From 5a852e5d2c8b3f2cec2e592fe542531802a53ba5 Mon Sep 17 00:00:00 2001 From: fplust Date: Sat, 28 May 2022 04:13:57 +0800 Subject: [PATCH 1/2] upgrade to edition 2021 and dependencies upgrade --- Cargo.toml | 21 +++++++++++---------- src/bin/mstsc-rs.rs | 10 ---------- src/codec/rle.rs | 2 +- src/core/capability.rs | 6 +++--- src/core/client.rs | 22 +++++++++++----------- src/core/event.rs | 4 ++-- src/core/gcc.rs | 8 ++++---- src/core/global.rs | 16 ++++++++-------- src/core/license.rs | 4 ++-- src/core/mcs.rs | 14 +++++++------- src/core/per.rs | 4 ++-- src/core/sec.rs | 12 ++++++------ src/core/tpkt.rs | 14 +++++++------- src/core/x224.rs | 8 ++++---- src/model/data.rs | 2 +- src/model/link.rs | 4 ++-- src/model/unicode.rs | 2 +- src/nla/asn1.rs | 2 +- src/nla/cssp.rs | 12 ++++++------ src/nla/ntlm.rs | 25 +++++++++++++------------ src/nla/sspi.rs | 2 +- 21 files changed, 93 insertions(+), 101 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 07d020c..c11ab53 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,6 +9,7 @@ keywords = ["rdp", "security", "network", "windows"] categories = ["network"] license = "MIT" documentation = "https://docs.rs/rdp-rs" +edition = "2021" [lib] name = "rdp" @@ -27,17 +28,17 @@ mstsc-rs = ["hex", "winapi", "minifb", "clap", "libc"] [dependencies] native-tls = "^0.2" -byteorder = "^1.3" +byteorder = "^1.4" bufstream = "0.1" -indexmap = "^1.3" -yasna = { version = "^0.3" } -md4 = "^0.8" -hmac = "^0.7" -md-5 = "^0.8" -rand = "^0.7" -num-bigint = "^0.2" -x509-parser = "0.6.5" -num_enum = "0.4.3" +indexmap = "^1.8" +yasna = { version = "^0.5" } +md4 = "^0.10" +hmac = "^0.12" +md-5 = "^0.10" +rand = "^0.8" +num-bigint = "^0.4" +x509-parser = "0.13" +num_enum = "0.5" # for mtsc-rs hex = { version = "^0.4", optional = true } diff --git a/src/bin/mstsc-rs.rs b/src/bin/mstsc-rs.rs index e9328e1..81934a3 100644 --- a/src/bin/mstsc-rs.rs +++ b/src/bin/mstsc-rs.rs @@ -1,13 +1,3 @@ -#[cfg(target_os = "windows")] -extern crate winapi; -#[cfg(any(target_os = "linux", target_os = "macos"))] -extern crate libc; -extern crate minifb; -extern crate rdp; -extern crate hex; -extern crate clap; -extern crate hmac; - use minifb::{Key, Window, WindowOptions, MouseMode, MouseButton, KeyRepeat}; use std::net::{SocketAddr, TcpStream}; use std::io::{Read, Write}; diff --git a/src/codec/rle.rs b/src/codec/rle.rs index 8e7f684..ab909d0 100644 --- a/src/codec/rle.rs +++ b/src/codec/rle.rs @@ -1,4 +1,4 @@ -use model::error::{RdpResult, Error, RdpError, RdpErrorKind}; +use crate::model::error::{RdpResult, Error, RdpError, RdpErrorKind}; use std::io::{Cursor, Read}; use byteorder::{ReadBytesExt, LittleEndian}; diff --git a/src/core/capability.rs b/src/core/capability.rs index a3cf40e..b84d261 100644 --- a/src/core/capability.rs +++ b/src/core/capability.rs @@ -1,7 +1,7 @@ -use model::data::{Component, U16, U32, DynOption, MessageOption, Message, DataType, Check, Trame, to_vec}; -use model::error::{RdpResult, Error, RdpError, RdpErrorKind}; +use crate::model::data::{Component, U16, U32, DynOption, MessageOption, Message, DataType, Check, Trame, to_vec}; +use crate::model::error::{RdpResult, Error, RdpError, RdpErrorKind}; use std::io::Cursor; -use core::gcc::{KeyboardLayout, KeyboardType}; +use crate::core::gcc::{KeyboardLayout, KeyboardType}; use num_enum::TryFromPrimitive; use std::convert::TryFrom; diff --git a/src/core/client.rs b/src/core/client.rs index 91ab8ed..0216a41 100644 --- a/src/core/client.rs +++ b/src/core/client.rs @@ -1,15 +1,15 @@ -use core::x224; -use core::gcc::KeyboardLayout; -use core::mcs; -use core::tpkt; -use core::sec; -use core::global; +use crate::core::x224; +use crate::core::gcc::KeyboardLayout; +use crate::core::mcs; +use crate::core::tpkt; +use crate::core::sec; +use crate::core::global; use std::io::{Read, Write}; -use model::error::{RdpResult, Error, RdpError, RdpErrorKind}; -use model::link::{Link, Stream}; -use core::event::{RdpEvent, PointerButton}; -use core::global::{ts_pointer_event, PointerFlag, ts_keyboard_event, KeyboardFlag}; -use nla::ntlm::Ntlm; +use crate::model::error::{RdpResult, Error, RdpError, RdpErrorKind}; +use crate::model::link::{Link, Stream}; +use crate::core::event::{RdpEvent, PointerButton}; +use crate::core::global::{ts_pointer_event, PointerFlag, ts_keyboard_event, KeyboardFlag}; +use crate::nla::ntlm::Ntlm; impl From<&str> for KeyboardLayout { fn from(e: &str) -> Self { diff --git a/src/core/event.rs b/src/core/event.rs index b379171..73d3a1d 100644 --- a/src/core/event.rs +++ b/src/core/event.rs @@ -1,6 +1,6 @@ -use model::error::{RdpResult, Error, RdpError, RdpErrorKind}; +use crate::model::error::{RdpResult, Error, RdpError, RdpErrorKind}; use num_enum::TryFromPrimitive; -use codec::rle::{rle_32_decompress, rle_16_decompress, rgb565torgb32}; +use crate::codec::rle::{rle_32_decompress, rle_16_decompress, rgb565torgb32}; /// A bitmap event is used /// to notify client that it received diff --git a/src/core/gcc.rs b/src/core/gcc.rs index 6ca719f..188f312 100644 --- a/src/core/gcc.rs +++ b/src/core/gcc.rs @@ -1,7 +1,7 @@ -use model::data::{Component, U32, U16, Trame, to_vec, Message, DataType, DynOption, MessageOption, Check, Array}; -use model::unicode::Unicode; -use model::error::{RdpResult, RdpError, RdpErrorKind, Error}; -use core::per; +use crate::model::data::{Component, U32, U16, Trame, to_vec, Message, DataType, DynOption, MessageOption, Check, Array}; +use crate::model::unicode::Unicode; +use crate::model::error::{RdpResult, RdpError, RdpErrorKind, Error}; +use crate::core::per; use std::io::{Cursor, Read}; use std::collections::HashMap; diff --git a/src/core/global.rs b/src/core/global.rs index 8d9cf69..27f02ca 100644 --- a/src/core/global.rs +++ b/src/core/global.rs @@ -1,14 +1,14 @@ -use core::mcs; -use core::tpkt; +use crate::core::mcs; +use crate::core::tpkt; use std::io::{Read, Write, Cursor}; -use model::error::{RdpResult, Error, RdpErrorKind, RdpError}; -use model::data::{Component, MessageOption, U32, DynOption, U16, DataType, Message, Array, Trame, Check, to_vec}; -use core::event::{RdpEvent, BitmapEvent}; +use crate::model::error::{RdpResult, Error, RdpErrorKind, RdpError}; +use crate::model::data::{Component, MessageOption, U32, DynOption, U16, DataType, Message, Array, Trame, Check, to_vec}; +use crate::core::event::{RdpEvent, BitmapEvent}; use num_enum::TryFromPrimitive; use std::convert::TryFrom; -use core::capability::{Capability, capability_set}; -use core::capability; -use core::gcc::KeyboardLayout; +use crate::core::capability::{Capability, capability_set}; +use crate::core::capability; +use crate::core::gcc::KeyboardLayout; /// Raw PDU type use by the protocol diff --git a/src/core/license.rs b/src/core/license.rs index 960c6b1..be2974d 100644 --- a/src/core/license.rs +++ b/src/core/license.rs @@ -1,5 +1,5 @@ -use model::data::{Component, Check, DynOption, U16, MessageOption, U32, DataType, Message}; -use model::error::{RdpResult, Error, RdpError, RdpErrorKind}; +use crate::model::data::{Component, Check, DynOption, U16, MessageOption, U32, DataType, Message}; +use crate::model::error::{RdpResult, Error, RdpError, RdpErrorKind}; use std::io::{Cursor, Read}; use num_enum::TryFromPrimitive; use std::convert::TryFrom; diff --git a/src/core/mcs.rs b/src/core/mcs.rs index 8fd6128..1c2439e 100644 --- a/src/core/mcs.rs +++ b/src/core/mcs.rs @@ -1,12 +1,12 @@ -use core::x224; -use core::tpkt; -use model::error::{RdpResult, Error, RdpError, RdpErrorKind}; -use core::gcc::{KeyboardLayout, client_core_data, ClientData, ServerData, client_security_data, client_network_data, block_header, write_conference_create_request, MessageType, read_conference_create_response, Version}; -use model::data::{Trame, to_vec, Message, DataType, U16}; -use nla::asn1::{Sequence, ImplicitTag, OctetString, Enumerate, ASN1Type, Integer, to_der, from_ber}; +use crate::core::x224; +use crate::core::tpkt; +use crate::model::error::{RdpResult, Error, RdpError, RdpErrorKind}; +use crate::core::gcc::{KeyboardLayout, client_core_data, ClientData, ServerData, client_security_data, client_network_data, block_header, write_conference_create_request, MessageType, read_conference_create_response, Version}; +use crate::model::data::{Trame, to_vec, Message, DataType, U16}; +use crate::nla::asn1::{Sequence, ImplicitTag, OctetString, Enumerate, ASN1Type, Integer, to_der, from_ber}; use yasna::{Tag}; use std::io::{Write, Read, BufRead, Cursor}; -use core::per; +use crate::core::per; use std::collections::HashMap; #[allow(dead_code)] diff --git a/src/core/per.rs b/src/core/per.rs index 453073c..b6bd5f2 100644 --- a/src/core/per.rs +++ b/src/core/per.rs @@ -1,6 +1,6 @@ -use model::data::{Message, U16, Trame, U32}; +use crate::model::data::{Message, U16, Trame, U32}; use std::io::{Read, Write}; -use model::error::{RdpResult, Error, RdpError, RdpErrorKind}; +use crate::model::error::{RdpResult, Error, RdpError, RdpErrorKind}; /// PER encoding length diff --git a/src/core/sec.rs b/src/core/sec.rs index 606cd05..8ec936b 100644 --- a/src/core/sec.rs +++ b/src/core/sec.rs @@ -1,10 +1,10 @@ -use core::mcs; -use core::license; -use core::tpkt; -use model::error::{RdpResult, Error, RdpError, RdpErrorKind}; -use model::data::{Message, Component, U16, U32, DynOption, MessageOption, Trame, DataType}; +use crate::core::mcs; +use crate::core::license; +use crate::core::tpkt; +use crate::model::error::{RdpResult, Error, RdpError, RdpErrorKind}; +use crate::model::data::{Message, Component, U16, U32, DynOption, MessageOption, Trame, DataType}; use std::io::{Write, Read}; -use model::unicode::Unicode; +use crate::model::unicode::Unicode; /// Security flag send as header flage in core ptotocol /// https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/e13405c5-668b-4716-94b2-1c2654ca1ad4?redirectedfrom=MSDN diff --git a/src/core/tpkt.rs b/src/core/tpkt.rs index cb06e37..909074f 100644 --- a/src/core/tpkt.rs +++ b/src/core/tpkt.rs @@ -1,9 +1,9 @@ -use model::link::{Link}; -use model::data::{Message, U16, Component, Trame}; -use model::error::{RdpResult, RdpError, RdpErrorKind, Error}; +use crate::model::link::{Link}; +use crate::model::data::{Message, U16, Component, Trame}; +use crate::model::error::{RdpResult, RdpError, RdpErrorKind, Error}; use std::io::{Cursor, Write, Read}; -use nla::cssp::cssp_connect; -use nla::sspi::AuthenticationProtocol; +use crate::nla::cssp::cssp_connect; +use crate::nla::sspi::AuthenticationProtocol; /// TPKT must implement this two kind of payload pub enum Payload { @@ -223,8 +223,8 @@ impl Client { mod test { use super::*; use std::io::Cursor; - use model::data::{U32, DataType}; - use model::link::Stream; + use crate::model::data::{U32, DataType}; + use crate::model::link::Stream; /// Test the tpkt header type in write context #[test] diff --git a/src/core/x224.rs b/src/core/x224.rs index 9a19062..ec2659d 100644 --- a/src/core/x224.rs +++ b/src/core/x224.rs @@ -1,9 +1,9 @@ -use core::tpkt; -use model::data::{Message, Check, U16, U32, Component, DataType, Trame}; -use model::error::{Error, RdpError, RdpResult, RdpErrorKind}; +use crate::core::tpkt; +use crate::model::data::{Message, Check, U16, U32, Component, DataType, Trame}; +use crate::model::error::{Error, RdpError, RdpResult, RdpErrorKind}; use std::io::{Read, Write}; use std::option::{Option}; -use nla::sspi::AuthenticationProtocol; +use crate::nla::sspi::AuthenticationProtocol; use num_enum::TryFromPrimitive; use std::convert::TryFrom; diff --git a/src/model/data.rs b/src/model/data.rs index 98ed3c8..5555e3d 100644 --- a/src/model/data.rs +++ b/src/model/data.rs @@ -1,5 +1,5 @@ use std::io::{Write, Read, Cursor}; -use model::error::{RdpResult, RdpErrorKind, RdpError, Error}; +use crate::model::error::{RdpResult, RdpErrorKind, RdpError, Error}; use byteorder::{WriteBytesExt, ReadBytesExt, LittleEndian, BigEndian}; use indexmap::IndexMap; use std::collections::{HashSet, HashMap}; diff --git a/src/model/link.rs b/src/model/link.rs index 424a1c2..e6b5a8f 100644 --- a/src/model/link.rs +++ b/src/model/link.rs @@ -1,9 +1,9 @@ extern crate native_tls; -use model::error::{RdpResult, Error, RdpError, RdpErrorKind}; +use crate::model::error::{RdpResult, Error, RdpError, RdpErrorKind}; use std::io::{Cursor, Read, Write}; use self::native_tls::{TlsConnector, TlsStream, Certificate}; -use model::data::{Message}; +use crate::model::data::{Message}; /// This a wrapper to work equals /// for a stream and a TLS stream diff --git a/src/model/unicode.rs b/src/model/unicode.rs index 5246a71..3729767 100644 --- a/src/model/unicode.rs +++ b/src/model/unicode.rs @@ -1,4 +1,4 @@ -use model::data::{Message, U16}; +use crate::model::data::{Message, U16}; use std::io::Cursor; /// Use to to_unicode function for String diff --git a/src/nla/asn1.rs b/src/nla/asn1.rs index 5b09bae..aee8d5a 100644 --- a/src/nla/asn1.rs +++ b/src/nla/asn1.rs @@ -1,5 +1,5 @@ use yasna::{Tag, DERWriter, BERReader}; -use model::error::{RdpResult, Error}; +use crate::model::error::{RdpResult, Error}; use indexmap::map::IndexMap; /// Enum all possible value diff --git a/src/nla/cssp.rs b/src/nla/cssp.rs index d327106..b75d2c0 100644 --- a/src/nla/cssp.rs +++ b/src/nla/cssp.rs @@ -1,10 +1,10 @@ -use nla::asn1::{ASN1, Sequence, ExplicitTag, SequenceOf, ASN1Type, OctetString, Integer, to_der}; -use model::error::{RdpError, RdpErrorKind, Error, RdpResult}; +use crate::nla::asn1::{ASN1, Sequence, ExplicitTag, SequenceOf, ASN1Type, OctetString, Integer, to_der}; +use crate::model::error::{RdpError, RdpErrorKind, Error, RdpResult}; use num_bigint::{BigUint}; use yasna::Tag; -use x509_parser::{parse_x509_der, X509Certificate}; -use nla::sspi::AuthenticationProtocol; -use model::link::Link; +use x509_parser::prelude::{parse_x509_certificate, X509Certificate}; +use crate::nla::sspi::AuthenticationProtocol; +use crate::model::link::Link; use std::io::{Read, Write}; /// Create a ts request as expected by the specification @@ -100,7 +100,7 @@ pub fn create_ts_authenticate(nego: Vec, pub_key_auth: Vec) -> Vec { } pub fn read_public_certificate(stream: &[u8]) -> RdpResult { - let res = parse_x509_der(stream).unwrap(); + let res = parse_x509_certificate(stream).unwrap(); Ok(res.1) } diff --git a/src/nla/ntlm.rs b/src/nla/ntlm.rs index 3680c69..55a9cb8 100644 --- a/src/nla/ntlm.rs +++ b/src/nla/ntlm.rs @@ -1,13 +1,13 @@ -use nla::sspi::{AuthenticationProtocol, GenericSecurityService}; -use model::data::{Message, Component, U16, U32, Trame, DynOption, Check, DataType, MessageOption, to_vec}; +use crate::nla::sspi::{AuthenticationProtocol, GenericSecurityService}; +use crate::model::data::{Message, Component, U16, U32, Trame, DynOption, Check, DataType, MessageOption, to_vec}; use std::io::{Cursor}; -use model::error::{RdpResult, RdpError, RdpErrorKind, Error}; +use crate::model::error::{RdpResult, RdpError, RdpErrorKind, Error}; use std::collections::HashMap; use md4::{Md4, Digest}; use hmac::{Hmac, Mac}; use md5::{Md5}; -use model::rnd::{random}; -use nla::rc4::{Rc4}; +use crate::model::rnd::{random}; +use crate::nla::rc4::{Rc4}; use num_enum::TryFromPrimitive; use std::convert::TryFrom; @@ -264,8 +264,8 @@ fn z(m: usize) -> Vec { /// ``` fn md4(data: &[u8]) -> Vec { let mut hasher = Md4::new(); - hasher.input(data); - hasher.result().to_vec() + hasher.update(data); + hasher.finalize().to_vec() } /// Compute the MD5 Hash of input vector @@ -279,8 +279,8 @@ fn md4(data: &[u8]) -> Vec { /// ``` fn md5(data: &[u8]) -> Vec { let mut hasher = Md5::new(); - hasher.input(data); - hasher.result().to_vec() + hasher.update(data); + hasher.finalize().to_vec() } /// Encode a string into utf-16le @@ -310,9 +310,10 @@ fn unicode(data: &String) -> Vec { /// let signature = hmac_md5(b"foo", b"bar"); /// ``` fn hmac_md5(key: &[u8], data: &[u8]) -> Vec { - let mut stream = Hmac::::new_varkey(key).unwrap(); - stream.input(data); - stream.result().code().to_vec() + type HmacMd5 = Hmac::; + let mut stream = HmacMd5::new_from_slice(key).unwrap(); + stream.update(data); + stream.finalize().into_bytes().to_vec() } /// This function is used to compute init key of another hmac_md5 diff --git a/src/nla/sspi.rs b/src/nla/sspi.rs index 4c8f848..26b16ea 100644 --- a/src/nla/sspi.rs +++ b/src/nla/sspi.rs @@ -1,4 +1,4 @@ -use model::error::RdpResult; +use crate::model::error::RdpResult; /// This is a trait use by authentication /// protocol to provide a context From 4135fbb37ade02eb1a1173449456e75c18aff6d8 Mon Sep 17 00:00:00 2001 From: fplust Date: Sat, 28 May 2022 05:37:49 +0800 Subject: [PATCH 2/2] clippy fix clippy fix --- src/codec/rle.rs | 14 +++++++------- src/core/capability.rs | 14 +++++++------- src/core/client.rs | 6 ++++++ src/core/event.rs | 6 +++--- src/core/gcc.rs | 14 +++++++------- src/core/global.rs | 32 ++++++++++++++++---------------- src/core/license.rs | 2 +- src/core/mcs.rs | 20 ++++++++++---------- src/core/per.rs | 14 +++++++------- src/core/sec.rs | 4 ++-- src/core/tpkt.rs | 12 +++++------- src/core/x224.rs | 6 +++--- src/model/data.rs | 13 +++++++------ src/model/link.rs | 5 +++-- src/model/unicode.rs | 4 ++-- src/nla/asn1.rs | 8 +++++++- src/nla/ntlm.rs | 36 ++++++++++++++++++------------------ src/nla/rc4.rs | 6 +++--- 18 files changed, 114 insertions(+), 102 deletions(-) diff --git a/src/codec/rle.rs b/src/codec/rle.rs index ab909d0..5af6c7d 100644 --- a/src/codec/rle.rs +++ b/src/codec/rle.rs @@ -31,7 +31,7 @@ fn process_plane(input: &mut dyn Read, width: u32, height: u32, output: &mut [u8 replen = code & 0xf; collen = (code >> 4) & 0xf; revcode = (replen << 4) | collen; - if (revcode <= 47) && (revcode >= 16) { + if (16..=47).contains(&revcode) { replen = revcode; collen = 0; } @@ -57,20 +57,20 @@ fn process_plane(input: &mut dyn Read, width: u32, height: u32, output: &mut [u8 replen = code & 0xf; collen = (code >> 4) & 0xf; revcode = (replen << 4) | collen; - if (revcode <= 47) && (revcode >= 16) { + if (16..=47).contains(&revcode) { replen = revcode; collen = 0; } while collen > 0 { x = input.read_u8()?; if x & 1 != 0{ - x = x >> 1; - x = x + 1; + x >>= 1; + x += 1; color = -(x as i32) as i8; } else { - x = x >> 1; + x >>= 1; color = x as i8; } x = (output[(last_line + (indexw * 4)) as usize] as i32 + color as i32) as u8; @@ -227,7 +227,7 @@ pub fn rle_16_decompress(input: &[u8], width: usize, mut height: usize, output: while count > 0 { if x >= width { - if height <= 0 { + if height == 0 { return Err(Error::RdpError(RdpError::new(RdpErrorKind::InvalidData, "error during decompress"))) } x = 0; @@ -331,7 +331,7 @@ pub fn rle_16_decompress(input: &[u8], width: usize, mut height: usize, output: pub fn rgb565torgb32(input: &[u16], width: usize, height: usize) -> Vec { - let mut result_32_bpp = vec![0 as u8; width as usize * height as usize * 4]; + let mut result_32_bpp = vec![0_u8; width as usize * height as usize * 4]; for i in 0..height { for j in 0..width { let index = (i * width + j) as usize; diff --git a/src/core/capability.rs b/src/core/capability.rs index b84d261..bd67fd5 100644 --- a/src/core/capability.rs +++ b/src/core/capability.rs @@ -187,8 +187,8 @@ pub fn ts_general_capability_set(extra_flags: Option) -> Capability { "updateCapabilityFlag" => Check::new(U16::LE(0)), "remoteUnshareFlag" => Check::new(U16::LE(0)), "generalCompressionLevel" => Check::new(U16::LE(0)), - "refreshRectSupport" => 0 as u8, - "suppressOutputSupport" => 0 as u8 + "refreshRectSupport" => 0_u8, + "suppressOutputSupport" => 0_u8 ] } } @@ -219,8 +219,8 @@ pub fn ts_bitmap_capability_set(preferred_bits_per_pixel: Option, desktop_w "pad2octets" => U16::LE(0), "desktopResizeFlag" => U16::LE(0), "bitmapCompressionFlag" => Check::new(U16::LE(0x0001)), - "highColorFlags" => Check::new(0 as u8), - "drawingFlags" => 0 as u8, + "highColorFlags" => Check::new(0_u8), + "drawingFlags" => 0_u8, "multipleRectangleSupport" => Check::new(U16::LE(0x0001)), "pad2octetsB" => U16::LE(0) ] @@ -253,7 +253,7 @@ pub fn ts_order_capability_set(order_flags: Option) -> Capability { Capability { cap_type: CapabilitySetType::CapstypeOrder, message: component![ - "terminalDescriptor" => vec![0 as u8; 16], + "terminalDescriptor" => vec![0_u8; 16], "pad4octetsA" => U32::LE(0), "desktopSaveXGranularity" => U16::LE(1), "desktopSaveYGranularity" => U16::LE(20), @@ -261,7 +261,7 @@ pub fn ts_order_capability_set(order_flags: Option) -> Capability { "maximumOrderLevel" => U16::LE(1), "numberFonts" => U16::LE(0), "orderFlags" => U16::LE(order_flags.unwrap_or(OrderFlag::NEGOTIATEORDERSUPPORT as u16)), - "orderSupport" => vec![0 as u8; 32], + "orderSupport" => vec![0_u8; 32], "textFlags" => U16::LE(0), "orderSupportExFlags" => U16::LE(0), "pad4octetsB" => U32::LE(0), @@ -375,7 +375,7 @@ pub fn ts_input_capability_set(input_flags: Option, keyboard_layout: Option "keyboardType" => U32::LE(KeyboardType::Ibm101102Keys as u32), "keyboardSubType" => U32::LE(0), "keyboardFunctionKey" => U32::LE(12), - "imeFileName" => vec![0 as u8; 64] + "imeFileName" => vec![0_u8; 64] ] } } diff --git a/src/core/client.rs b/src/core/client.rs index 0216a41..d7e5ee9 100644 --- a/src/core/client.rs +++ b/src/core/client.rs @@ -348,4 +348,10 @@ impl Connector { self.use_nla = use_nla; self } +} + +impl Default for Connector { + fn default() -> Self { + Self::new() + } } \ No newline at end of file diff --git a/src/core/event.rs b/src/core/event.rs index 73d3a1d..fd78b51 100644 --- a/src/core/event.rs +++ b/src/core/event.rs @@ -67,7 +67,7 @@ impl BitmapEvent { // 32 bpp is straight forward Ok( if self.is_compress { - let mut result = vec![0 as u8; self.width as usize * self.height as usize * 4]; + let mut result = vec![0_u8; self.width as usize * self.height as usize * 4]; rle_32_decompress(&self.data, self.width as u32, self.height as u32, &mut result)?; result } else { @@ -78,11 +78,11 @@ impl BitmapEvent { 16 => { // 16 bpp is more consumer let result_16bpp = if self.is_compress { - let mut result = vec![0 as u16; self.width as usize * self.height as usize * 2]; + let mut result = vec![0_u16; self.width as usize * self.height as usize * 2]; rle_16_decompress(&self.data, self.width as usize, self.height as usize, &mut result)?; result } else { - let mut result = vec![0 as u16; self.width as usize * self.height as usize]; + let mut result = vec![0_u16; self.width as usize * self.height as usize]; for i in 0..self.height { for j in 0..self.width { let src = (((self.height - i - 1) * self.width + j) * 2) as usize; diff --git a/src/core/gcc.rs b/src/core/gcc.rs index 188f312..4b98952 100644 --- a/src/core/gcc.rs +++ b/src/core/gcc.rs @@ -223,11 +223,11 @@ pub fn client_core_data(parameter: Option) -> Component { "sasSequence" => U16::LE(Sequence::RnsUdSasDel as u16), "kbdLayout" => U32::LE(client_parameter.layout as u32), "clientBuild" => U32::LE(3790), - "clientName" => client_name.to_string().to_unicode(), + "clientName" => client_name.to_unicode(), "keyboardType" => U32::LE(KeyboardType::Ibm101102Keys as u32), "keyboardSubType" => U32::LE(0), "keyboardFnKeys" => U32::LE(12), - "imeFileName" => vec![0 as u8; 64], + "imeFileName" => vec![0_u8; 64], "postBeta2ColorDepth" => U16::LE(ColorDepth::RnsUdColor8BPP as u16), "clientProductId" => U16::LE(1), "serialNumber" => U32::LE(0), @@ -240,8 +240,8 @@ pub fn client_core_data(parameter: Option) -> Component { ), "earlyCapabilityFlags" => U16::LE(CapabilityFlag::RnsUdCsSupportErrinfoPDU as u16), "clientDigProductId" => vec![0; 64], - "connectionType" => 0 as u8, - "pad1octet" => 0 as u8, + "connectionType" => 0_u8, + "pad1octet" => 0_u8, "serverSelectedProtocol" => U32::LE(client_parameter.server_selected_protocol) ] } @@ -277,7 +277,7 @@ pub fn server_security_data() -> Component { } /// Actually we have no more classic channel -pub fn channel_def(name: &String, options: u32) -> Component { +pub fn channel_def(name: &str, options: u32) -> Component { component![ "name"=> name.as_bytes().to_vec(), "options" => U32::LE(options) @@ -352,7 +352,7 @@ pub fn read_conference_create_response(cc_response: &mut dyn Read) -> RdpResult< break; } - let mut buffer = vec![0 as u8; (cast!(DataType::U16, header["length"])? - header.length() as u16) as usize]; + let mut buffer = vec![0_u8; (cast!(DataType::U16, header["length"])? - header.length() as u16) as usize]; sub.read_exact(&mut buffer)?; match MessageType::from(cast!(DataType::U16, header["type"])?) { @@ -377,7 +377,7 @@ pub fn read_conference_create_response(cc_response: &mut dyn Read) -> RdpResult< // All section are important Ok(ServerData{ - channel_ids: cast!(DataType::Trame, result[&MessageType::ScNet]["channelIdArray"])?.into_iter().map(|x| cast!(DataType::U16, x).unwrap()).collect(), + channel_ids: cast!(DataType::Trame, result[&MessageType::ScNet]["channelIdArray"])?.iter().map(|x| cast!(DataType::U16, x).unwrap()).collect(), rdp_version: Version::from(cast!(DataType::U32, result[&MessageType::ScCore]["rdpVersion"])?) }) } \ No newline at end of file diff --git a/src/core/global.rs b/src/core/global.rs index 27f02ca..976a6cd 100644 --- a/src/core/global.rs +++ b/src/core/global.rs @@ -80,8 +80,8 @@ fn ts_demand_active_pdu() -> PDU { /// /// https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/4e9722c3-ad83-43f5-af5a-529f73d88b48 fn ts_confirm_active_pdu(share_id: Option, source: Option>, capabilities_set: Option>) -> PDU { - let default_capabilities_set = capabilities_set.unwrap_or(Array::new(|| capability_set(None))); - let default_source = source.unwrap_or(vec![]); + let default_capabilities_set = capabilities_set.unwrap_or_else(|| Array::new(|| capability_set(None))); + let default_source = source.unwrap_or_default(); PDU { pdu_type: PDUType::PdutypeConfirmactivepdu, message: component![ @@ -113,16 +113,16 @@ fn ts_deactivate_all_pdu() -> PDU { /// All Data PDU share the same layout fn share_data_header(share_id: Option, pdu_type_2: Option, message: Option>) -> PDU { - let default_message = message.unwrap_or(vec![]); + let default_message = message.unwrap_or_default(); PDU { pdu_type: PDUType::PdutypeDatapdu, message: component![ "shareId" => U32::LE(share_id.unwrap_or(0)), - "pad1" => 0 as u8, - "streamId" => 1 as u8, + "pad1" => 0_u8, + "streamId" => 1_u8, "uncompressedLength" => DynOption::new(U16::LE(default_message.length() as u16 + 18), | size | MessageOption::Size("payload".to_string(), size.inner() as usize - 18)), "pduType2" => pdu_type_2.unwrap_or(PDUType2::Pdutype2ArcStatusPdu) as u8, - "compressedType" => 0 as u8, + "compressedType" => 0_u8, "compressedLength" => U16::LE(0), "payload" => default_message ] @@ -133,7 +133,7 @@ fn share_data_header(share_id: Option, pdu_type_2: Option, messag /// This is the main PDU payload format /// It use the share control header to dispatch between all PDU fn share_control_header(pdu_type: Option, pdu_source: Option, message: Option>) -> Component { - let default_message = message.unwrap_or(vec![]); + let default_message = message.unwrap_or_default(); component![ "totalLength" => DynOption::new(U16::LE(default_message.length() as u16 + 6), |total| MessageOption::Size("pduMessage".to_string(), total.inner() as usize - 6)), "pduType" => U16::LE(pdu_type.unwrap_or(PDUType::PdutypeDemandactivepdu) as u16), @@ -277,7 +277,7 @@ fn ts_font_map_pdu() -> DataPDU { /// Send input event as slow path fn ts_input_pdu_data(events: Option>) -> DataPDU { - let default_events = events.unwrap_or(Array::new(|| ts_input_event(None, None))); + let default_events = events.unwrap_or_else(|| Array::new(|| ts_input_event(None, None))); DataPDU { pdu_type: PDUType2::Pdutype2Input, message: component![ @@ -293,7 +293,7 @@ fn ts_input_event(message_type: Option, data: Option>) - component![ "eventTime" => U32::LE(0), "messageType" => U16::LE(message_type.unwrap_or(InputEventType::InputEventMouse) as u16), - "slowPathInputData" => data.unwrap_or(vec![]) + "slowPathInputData" => data.unwrap_or_default() ] } @@ -371,15 +371,15 @@ pub fn ts_keyboard_event(flags: Option, key_code: Option) -> TSInputEv /// https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/a1c4caa8-00ed-45bb-a06e-5177473766d3 fn ts_fp_update() -> Component { component![ - "updateHeader" => DynOption::new(0 as u8, |header| { - if (header >> 4) & 0x2 as u8 == 0 as u8 { + "updateHeader" => DynOption::new(0_u8, |header| { + if (header >> 4) & 0x2_u8 == 0_u8 { MessageOption::SkipField("compressionFlags".to_string()) } else { MessageOption::None } }), - "compressionFlags" => 0 as u8, + "compressionFlags" => 0_u8, "size" => DynOption::new(U16::LE(0), | size | MessageOption::Size("updateData".to_string(), size.inner() as usize)), "updateData" => Vec::::new() ] @@ -469,7 +469,7 @@ fn ts_fp_update_bitmap() -> FastPathUpdate { message: component![ "header" => Check::new(U16::LE(FastPathUpdateType::FastpathUpdatetypeBitmap as u16)), "numberRectangles" => U16::LE(0), - "rectangles" => Array::new(|| ts_bitmap_data()) + "rectangles" => Array::new(ts_bitmap_data) ] } } @@ -489,7 +489,7 @@ fn ts_colorpointerattribute() -> FastPathUpdate { "lengthXorMask" => DynOption::new(U16::LE(0), |length| MessageOption::Size("xorMaskData".to_string(), length.inner() as usize)), "xorMaskData" => Vec::::new(), "andMaskData" => Vec::::new(), - "pad" => Some(0 as u8) + "pad" => Some(0_u8) ] } } @@ -602,7 +602,7 @@ impl Client { self.share_id = Some(cast!(DataType::U32, pdu.message["shareId"])?); return Ok(true) } - return Ok(false) + Ok(false) } /// Read server synchronize pdu @@ -696,7 +696,7 @@ impl Client { fn read_fast_path(&mut self, stream: &mut dyn Read, mut callback: T) -> RdpResult<()> where T: FnMut(RdpEvent) { // it could be have one or more fast path payload - let mut fp_messages = Array::new(|| ts_fp_update()); + let mut fp_messages = Array::new(ts_fp_update); fp_messages.read(stream)?; for fp_message in fp_messages.inner().iter() { diff --git a/src/core/license.rs b/src/core/license.rs index be2974d..0ffad78 100644 --- a/src/core/license.rs +++ b/src/core/license.rs @@ -68,7 +68,7 @@ pub enum StateTransition { /// https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/73170ca2-5f82-4a2d-9d1b-b439f3d8dadc fn preamble() -> Component { component![ - "bMsgtype" => 0 as u8, + "bMsgtype" => 0_u8, "flag" => Check::new(Preambule::PreambleVersion30 as u8), "wMsgSize" => DynOption::new(U16::LE(0), |size| MessageOption::Size("message".to_string(), size.inner() as usize - 4)), "message" => Vec::::new() diff --git a/src/core/mcs.rs b/src/core/mcs.rs index 1c2439e..e8b2cc0 100644 --- a/src/core/mcs.rs +++ b/src/core/mcs.rs @@ -45,13 +45,13 @@ fn domain_parameters(max_channel_ids: u32, maw_user_ids: u32, max_token_ids: u32 /// http://www.itu.int/rec/T-REC-T.125-199802-I/en page 25 fn connect_initial(user_data: Option) -> ImplicitTag { ImplicitTag::new(Tag::application(101), sequence![ - "callingDomainSelector" => vec![1 as u8] as OctetString, - "calledDomainSelector" => vec![1 as u8] as OctetString, + "callingDomainSelector" => vec![1_u8] as OctetString, + "calledDomainSelector" => vec![1_u8] as OctetString, "upwardFlag" => true, "targetParameters" => domain_parameters(34, 2, 0, 1, 0, 1, 0xffff, 2), "minimumParameters" => domain_parameters(1, 1, 1, 1, 0, 1, 0x420, 2), "maximumParameters" => domain_parameters(0xffff, 0xfc17, 0xffff, 1, 0, 1, 0xffff, 2), - "userData" => user_data.unwrap_or(Vec::new()) + "userData" => user_data.unwrap_or_default() ]) } @@ -62,7 +62,7 @@ sequence![ "result" => 0 as Enumerate, "calledConnectId" => 0 as Integer, "domainParameters" => domain_parameters(22, 3, 0, 1, 0, 1,0xfff8, 2), - "userData" => user_data.unwrap_or(Vec::new()) + "userData" => user_data.unwrap_or_default() ]) } @@ -75,7 +75,7 @@ fn mcs_pdu_header(pdu: Option, options: Option) -> u8 { /// Client -- attach_user_request -> Server /// Client <- attach_user_confirm -- Server fn read_attach_user_confirm(buffer: &mut dyn Read) -> RdpResult { - let mut confirm = trame![0 as u8, Vec::::new()]; + let mut confirm = trame![0_u8, Vec::::new()]; confirm.read(buffer)?; if cast!(DataType::U8, confirm[0])? >> 2 != mcs_pdu_header(Some(DomainMCSPDU::AttachUserConfirm), None) >> 2 { return Err(Error::RdpError(RdpError::new(RdpErrorKind::InvalidData, "MCS: unexpected header on recv_attach_user_confirm"))); @@ -85,7 +85,7 @@ fn read_attach_user_confirm(buffer: &mut dyn Read) -> RdpResult { if per::read_enumerates(&mut request)? != 0 { return Err(Error::RdpError(RdpError::new(RdpErrorKind::RejectedByServer, "MCS: recv_attach_user_confirm user rejected by server"))); } - Ok(per::read_integer_16(1001, &mut request)?) + per::read_integer_16(1001, &mut request) } /// Create a session for the current user @@ -133,7 +133,7 @@ fn channel_join_request(user_id: Option, channel_id: Option) -> RdpRes /// Client -- channel_join_request -> Server /// Client <- channel_join_confirm -- Server fn read_channel_join_confirm(user_id: u16, channel_id: u16, buffer: &mut dyn Read) -> RdpResult { - let mut confirm = trame![0 as u8, Vec::::new()]; + let mut confirm = trame![0_u8, Vec::::new()]; confirm.read(buffer)?; if cast!(DataType::U8, confirm[0])? >> 2 != mcs_pdu_header(Some(DomainMCSPDU::ChannelJoinConfirm), None) >> 2 { return Err(Error::RdpError(RdpError::new(RdpErrorKind::InvalidData, "MCS: unexpected header on read_channel_join_confirm"))); @@ -257,13 +257,13 @@ impl Client { /// mcs.connect(800, 600, KeyboardLayout::French).unwrap(); /// mcs.write("global".to_string(), trame![U16::LE(0)]) /// ``` - pub fn write(&mut self, channel_name: &String, message: T) -> RdpResult<()> + pub fn write(&mut self, channel_name: &str, message: T) -> RdpResult<()> where T: Message { self.x224.write(trame![ mcs_pdu_header(Some(DomainMCSPDU::SendDataRequest), None), U16::BE(self.user_id.unwrap() - 1001), U16::BE(self.channel_ids[channel_name]), - 0x70 as u8, + 0x70_u8, per::write_length(message.length() as u16)?, message ]) @@ -301,7 +301,7 @@ impl Client { per::read_integer_16(1001, &mut payload)?; let channel_id = per::read_integer_16(0, &mut payload)?; - let channel = self.channel_ids.iter().find(|x| *x.1 == channel_id).ok_or(Error::RdpError(RdpError::new(RdpErrorKind::Unknown, "MCS: unknown channel")))?; + let channel = self.channel_ids.iter().find(|x| *x.1 == channel_id).ok_or_else(|| Error::RdpError(RdpError::new(RdpErrorKind::Unknown, "MCS: unknown channel")))?; per::read_enumerates(&mut payload)?; per::read_length(&mut payload)?; diff --git a/src/core/per.rs b/src/core/per.rs index b6bd5f2..9949b24 100644 --- a/src/core/per.rs +++ b/src/core/per.rs @@ -18,7 +18,7 @@ pub fn read_length(s: &mut dyn Read) -> RdpResult { let mut byte: u8 = 0; byte.read(s)?; if byte & 0x80 != 0 { - byte = byte & !0x80; + byte &= !0x80; let mut size = (byte as u16) << 8 ; byte.read(s)?; size += byte as u16; @@ -329,7 +329,7 @@ pub fn write_object_identifier(oid: &[u8], s: &mut dyn Write) ->RdpResult<()> { } trame![ - 5 as u8, + 5_u8, oid[0] << 4 | oid[1] & 0xF, oid[2], oid[3], @@ -349,7 +349,7 @@ pub fn write_object_identifier(oid: &[u8], s: &mut dyn Write) ->RdpResult<()> { /// ``` pub fn read_numeric_string(minimum: usize, s: &mut dyn Read) -> RdpResult> { let length = read_length(s)?; - let mut result = vec![0 as u8; length as usize + minimum + 1]; + let mut result = vec![0_u8; length as usize + minimum + 1]; result.read(s)?; Ok(result) } @@ -380,13 +380,13 @@ pub fn write_numeric_string(string: &[u8], minimum: usize, s: &mut dyn Write) - /// Read exactly a number of bytes pub fn read_padding(length: usize, s: &mut dyn Read) -> RdpResult<()> { let mut padding = vec![0; length]; - s.read(&mut padding)?; + s.read_exact(&mut padding)?; Ok(()) } /// Write length zero bytes pub fn write_padding(length: usize, s: &mut dyn Write) -> RdpResult<()> { - vec![0 as u8; length].write(s)?; + vec![0_u8; length].write(s)?; Ok(()) } @@ -406,10 +406,10 @@ pub fn read_octet_stream(octet_stream: &[u8], minimum: usize, s: &mut dyn Read) if length != octet_stream.len() { return Err(Error::RdpError(RdpError::new(RdpErrorKind::InvalidSize, "PER: source octet string have an invalid size"))); } - for i in 0..length { + for i in octet_stream.iter() { let mut c: u8 = 0; c.read(s)?; - if c != octet_stream[i] { + if c != *i { return Err(Error::RdpError(RdpError::new(RdpErrorKind::InvalidData, "PER: source octet string have an invalid char"))); } } diff --git a/src/core/sec.rs b/src/core/sec.rs index 8ec936b..c7098d1 100644 --- a/src/core/sec.rs +++ b/src/core/sec.rs @@ -77,7 +77,7 @@ fn rdp_extended_infos() -> Component { /// When CSSP is not used /// interactive logon used credentials /// present in this payload -fn rdp_infos(is_extended_info: bool, domain: &String, username: &String, password: &String, auto_logon: bool) -> Component { +fn rdp_infos(is_extended_info: bool, domain: &str, username: &str, password: &str, auto_logon: bool) -> Component { let mut domain_format = domain.to_unicode(); domain_format.push(0); domain_format.push(0); @@ -136,7 +136,7 @@ fn security_header() -> Component { /// let mut mcs = mcs::Client(...).unwrap(); /// sec::connect(&mut mcs).unwrap(); /// ``` -pub fn connect(mcs: &mut mcs::Client, domain: &String, username: &String, password: &String, auto_logon: bool) -> RdpResult<()> { +pub fn connect(mcs: &mut mcs::Client, domain: &str, username: &str, password: &str, auto_logon: bool) -> RdpResult<()> { mcs.write( &"global".to_string(), trame![ diff --git a/src/core/tpkt.rs b/src/core/tpkt.rs index 909074f..30c236d 100644 --- a/src/core/tpkt.rs +++ b/src/core/tpkt.rs @@ -26,7 +26,7 @@ pub enum Action { fn tpkt_header(size: u16) -> Component { component![ "action" => Action::FastPathActionX224 as u8, - "flag" => 0 as u8, + "flag" => 0_u8, "size" => U16::BE(size + 4) ] } @@ -161,12 +161,10 @@ impl Client { Ok(Payload::FastPath(sec_flag, Cursor::new(self.transport.read(length as usize - 3)?))) } } - else { - if short_length < 2 { - Err(Error::RdpError(RdpError::new(RdpErrorKind::InvalidSize, "Invalid minimal size for TPKT"))) - } else { - Ok(Payload::FastPath(sec_flag, Cursor::new(self.transport.read(short_length as usize - 2)?))) - } + else if short_length < 2 { + Err(Error::RdpError(RdpError::new(RdpErrorKind::InvalidSize, "Invalid minimal size for TPKT"))) + } else { + Ok(Payload::FastPath(sec_flag, Cursor::new(self.transport.read(short_length as usize - 2)?))) } } } diff --git a/src/core/x224.rs b/src/core/x224.rs index ec2659d..b4ef517 100644 --- a/src/core/x224.rs +++ b/src/core/x224.rs @@ -77,7 +77,7 @@ fn x224_crq(len: u8, code: MessageType) -> Component { component! [ "len" => (len + 6) as u8, "code" => code as u8, - "padding" => trame! [U16::LE(0), U16::LE(0), 0 as u8] + "padding" => trame! [U16::LE(0), U16::LE(0), 0_u8] ] } @@ -103,9 +103,9 @@ fn x224_connection_pdu( /// X224 header fn x224_header() -> Component { component![ - "header" => 2 as u8, + "header" => 2_u8, "messageType" => MessageType::X224TPDUData as u8, - "separator" => Check::new(0x80 as u8) + "separator" => Check::new(0x80_u8) ] } diff --git a/src/model/data.rs b/src/model/data.rs index 5555e3d..6f50a91 100644 --- a/src/model/data.rs +++ b/src/model/data.rs @@ -543,7 +543,7 @@ impl Value { impl PartialEq for Value { /// Equality between all type fn eq(&self, other: &Self) -> bool { - return self.inner() == other.inner() + self.inner() == other.inner() } } @@ -805,12 +805,12 @@ impl Message for Check { impl Message for Vec { fn write(&self, writer: &mut dyn Write) -> RdpResult<()> { - writer.write(self)?; + writer.write_all(self)?; Ok(()) } fn read(&mut self, reader: &mut dyn Read) -> RdpResult<()> { - if self.len() == 0 { + if self.is_empty() { reader.read_to_end(self)?; } else { @@ -993,9 +993,10 @@ impl Message for Option { /// assert_eq!(s2.into_inner(), []) /// ``` fn write(&self, writer: &mut dyn Write) -> RdpResult<()> { - Ok(if let Some(value) = self { + if let Some(value) = self { value.write(writer)? - }) + }; + Ok(()) } /// Read an optional field @@ -1210,7 +1211,7 @@ mod test { #[test] fn test_data_u8_write() { let mut stream = Cursor::new(Vec::::new()); - let x = 1 as u8; + let x = 1_u8; x.write(&mut stream).unwrap(); assert_eq!(stream.get_ref().as_slice(), [1]) } diff --git a/src/model/link.rs b/src/model/link.rs index e6b5a8f..1e062eb 100644 --- a/src/model/link.rs +++ b/src/model/link.rs @@ -78,10 +78,11 @@ impl Stream { /// Shutdown the stream /// Only works when stream is a SSL stream pub fn shutdown(&mut self) -> RdpResult<()> { - Ok(match self { + match self { Stream::Ssl(e) => e.shutdown()?, _ => () - }) + }; + Ok(()) } } diff --git a/src/model/unicode.rs b/src/model/unicode.rs index 3729767..8fe931c 100644 --- a/src/model/unicode.rs +++ b/src/model/unicode.rs @@ -6,7 +6,7 @@ pub trait Unicode { fn to_unicode(&self) -> Vec; } -impl Unicode for String { +impl Unicode for str { /// Convert any string into utf-16le string /// /// # Example @@ -21,6 +21,6 @@ impl Unicode for String { let encode_char = U16::LE(c); encode_char.write(&mut result).unwrap(); } - return result.into_inner() + result.into_inner() } } \ No newline at end of file diff --git a/src/nla/asn1.rs b/src/nla/asn1.rs index aee8d5a..0069022 100644 --- a/src/nla/asn1.rs +++ b/src/nla/asn1.rs @@ -41,6 +41,12 @@ pub struct SequenceOf { factory: Option Box>> } +impl Default for SequenceOf { + fn default() -> Self { + Self::new() + } +} + impl SequenceOf { /// Create an empty sequenceof /// @@ -49,7 +55,7 @@ impl SequenceOf { /// use rdp::nla::asn1::SequenceOf; /// let so = SequenceOf::new(); /// ``` - pub fn new() -> Self{ + pub fn new() -> Self { SequenceOf { inner: Vec::new(), factory : None diff --git a/src/nla/ntlm.rs b/src/nla/ntlm.rs index 55a9cb8..cf7555a 100644 --- a/src/nla/ntlm.rs +++ b/src/nla/ntlm.rs @@ -63,7 +63,7 @@ fn version() -> Component { "ProductMajorVersion" => MajorVersion::WindowsMajorVersion6 as u8, "ProductMinorVersion" => MinorVersion::WindowsMinorVersion0 as u8, "ProductBuild" => U16::LE(6002), - "Reserved" => trame![U16::LE(0), 0 as u8], + "Reserved" => trame![U16::LE(0), 0_u8], "NTLMRevisionCurrent" => NTLMRevision::NtlmSspRevisionW2K3 as u8 ) } @@ -78,7 +78,7 @@ fn negotiate_message(flags: u32) -> Component { if node.inner() & (Negotiate::NtlmsspNegociateVersion as u32) == 0 { return MessageOption::SkipField("Version".to_string()) } - return MessageOption::None + MessageOption::None }), "DomainNameLen" => U16::LE(0), "DomainNameMaxLen" => U16::LE(0), @@ -104,7 +104,7 @@ fn challenge_message() -> Component { if node.inner() & (Negotiate::NtlmsspNegociateVersion as u32) == 0 { return MessageOption::SkipField("Version".to_string()) } - return MessageOption::None + MessageOption::None }), "ServerChallenge" => vec![0; 8], "Reserved" => vec![0; 8], @@ -153,7 +153,7 @@ fn authenticate_message(lm_challenge_response: &[u8], nt_challenge_response:&[u8 if node.inner() & (Negotiate::NtlmsspNegociateVersion as u32) == 0 { return MessageOption::SkipField("Version".to_string()) } - return MessageOption::None + MessageOption::None }), "Version" => version() ] , payload) @@ -237,7 +237,7 @@ fn read_target_info(data: &[u8]) -> RdpResult>> { result.insert(av_id, cast!(DataType::Slice, element["Value"])?.to_vec()); } - return Ok(result); + Ok(result) } /// Zero filled array @@ -292,13 +292,13 @@ fn md5(data: &[u8]) -> Vec { /// ```rust, ignore /// let encoded_string = unicode("foo".to_string()); /// ``` -fn unicode(data: &String) -> Vec { +fn unicode(data: &str) -> Vec { let mut result = Cursor::new(Vec::new()); for c in data.encode_utf16() { let encode_char = U16::LE(c); encode_char.write(&mut result).unwrap(); } - return result.into_inner() + result.into_inner() } /// Compute HMAC with MD5 hash algorithm @@ -325,8 +325,8 @@ fn hmac_md5(key: &[u8], data: &[u8]) -> Vec { /// ```rust, ignore /// let key = ntowfv2("hello123".to_string(), "user".to_string(), "domain".to_string()) /// ``` -fn ntowfv2(password: &String, user: &String, domain: &String) -> Vec { - hmac_md5(&md4(&unicode(password)), &unicode(&(user.to_uppercase() + &domain))) +fn ntowfv2(password: &str, user: &str, domain: &str) -> Vec { + hmac_md5(&md4(&unicode(password)), &unicode(&(user.to_uppercase() + domain))) } /// This function is used to compute init key of another hmac_md5 @@ -339,8 +339,8 @@ fn ntowfv2(password: &String, user: &String, domain: &String) -> Vec { /// ```rust, ignore /// let key = ntowfv2("hello123".to_string(), "user".to_string(), "domain".to_string()) /// ``` -fn ntowfv2_hash(hash: &[u8], user: &String, domain: &String) -> Vec { - hmac_md5(hash, &unicode(&(user.to_uppercase() + &domain))) +fn ntowfv2_hash(hash: &[u8], user: &str, domain: &str) -> Vec { + hmac_md5(hash, &unicode(&(user.to_uppercase() + domain))) } /// This function is used to compute init key of another hmac_md5 @@ -350,7 +350,7 @@ fn ntowfv2_hash(hash: &[u8], user: &String, domain: &String) -> Vec { /// ```rust, ignore /// let key = lmowfv2("hello123".to_string(), "user".to_string(), "domain".to_string()) /// ``` -fn lmowfv2(password: &String, user: &String, domain: &String) -> Vec { +fn lmowfv2(password: &str, user: &str, domain: &str) -> Vec { ntowfv2(password, user, domain) } @@ -375,7 +375,7 @@ fn compute_response_v2( let temp = [response_version.to_vec(), hi_response_version.to_vec(), z(6), time.to_vec(), client_challenge.to_vec(), z(4), server_name.to_vec()].concat(); let nt_proof_str = hmac_md5(response_key_nt, &[server_challenge.to_vec(), temp.clone()].concat()); - let nt_challenge_response = [nt_proof_str.clone(), temp.clone()].concat(); + let nt_challenge_response = [nt_proof_str.clone(), temp].concat(); let lm_challenge_response = [hmac_md5(response_key_lm, &[server_challenge.to_vec(), client_challenge.to_vec()].concat()), client_challenge.to_vec()].concat(); let session_base_key = hmac_md5(response_key_nt, &nt_proof_str); @@ -396,7 +396,7 @@ fn kx_key_v2(session_base_key: &[u8], _lm_challenge_response: &[u8], _server_cha fn rc4k(key: &[u8], plaintext: &[u8]) -> Vec { let mut result = vec![0; plaintext.len()]; let mut rc4_handle = Rc4::new(key); - rc4_handle.process(&plaintext, &mut result); + rc4_handle.process(plaintext, &mut result); result } @@ -523,7 +523,7 @@ impl AuthenticationProtocol for Ntlm { Negotiate::NtlmsspNegociateUnicode as u32 )); self.negotiate_message = Some(buffer.clone()); - return Ok(buffer) + Ok(buffer) } /// Read the server challenge @@ -560,11 +560,11 @@ impl AuthenticationProtocol for Ntlm { // generate client challenge let client_challenge = random(8); - let response = compute_response_v2(&self.response_key_nt, &self.response_key_lm, &server_challenge, &client_challenge, ×tamp, &target_name); + let response = compute_response_v2(&self.response_key_nt, &self.response_key_lm, server_challenge, &client_challenge, ×tamp, target_name); let nt_challenge_response = response.0; let lm_challenge_response = response.1; let session_base_key = response.2; - let key_exchange_key = kx_key_v2(&session_base_key, &lm_challenge_response, &server_challenge); + let key_exchange_key = kx_key_v2(&session_base_key, &lm_challenge_response, server_challenge); self.exported_session_key = Some(random(16)); let encrypted_random_session_key = rc4k(&key_exchange_key, self.exported_session_key.as_ref().unwrap()); @@ -683,7 +683,7 @@ impl GenericSecurityService for NTLMv2SecurityInterface { let mut encrypted_data = vec![0; data.len()]; self.encrypt.process(data, &mut encrypted_data); let signature = mac(&mut self.encrypt, &self.signing_key, self.seq_num, data); - self.seq_num = self.seq_num + 1; + self.seq_num += 1; Ok(to_vec(&trame![signature, encrypted_data])) } diff --git a/src/nla/rc4.rs b/src/nla/rc4.rs index 1197a2e..d18f528 100644 --- a/src/nla/rc4.rs +++ b/src/nla/rc4.rs @@ -6,7 +6,7 @@ pub struct Rc4 { impl Rc4 { pub fn new(key: &[u8]) -> Rc4 { - assert!(key.len() >= 1 && key.len() <= 256); + assert!(!key.is_empty() && key.len() <= 256); let mut rc4 = Rc4 { i: 0, j: 0, state: [0; 256] }; for (i, x) in rc4.state.iter_mut().enumerate() { *x = i as u8; @@ -22,8 +22,8 @@ impl Rc4 { self.i = self.i.wrapping_add(1); self.j = self.j.wrapping_add(self.state[self.i as usize]); self.state.swap(self.i as usize, self.j as usize); - let k = self.state[(self.state[self.i as usize].wrapping_add(self.state[self.j as usize])) as usize]; - k + + self.state[(self.state[self.i as usize].wrapping_add(self.state[self.j as usize])) as usize] } pub fn process(&mut self, input: &[u8], output: &mut [u8]) {