authentication.rs 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. use base64;
  2. use byteorder::{BigEndian, ByteOrder};
  3. use aes::Aes192;
  4. use hmac::Hmac;
  5. use sha1::{Sha1, Digest};
  6. use pbkdf2::pbkdf2;
  7. use protobuf::ProtobufEnum;
  8. use serde;
  9. use serde_json;
  10. use std::fs::File;
  11. use std::io::{self, Read, Write};
  12. use std::ops::FnOnce;
  13. use std::path::Path;
  14. use protocol::authentication::AuthenticationType;
  15. #[derive(Debug, Clone, Serialize, Deserialize)]
  16. pub struct Credentials {
  17. pub username: String,
  18. #[serde(serialize_with = "serialize_protobuf_enum")]
  19. #[serde(deserialize_with = "deserialize_protobuf_enum")]
  20. pub auth_type: AuthenticationType,
  21. #[serde(serialize_with = "serialize_base64")]
  22. #[serde(deserialize_with = "deserialize_base64")]
  23. pub auth_data: Vec<u8>,
  24. }
  25. impl Credentials {
  26. pub fn with_password(username: String, password: String) -> Credentials {
  27. Credentials {
  28. username: username,
  29. auth_type: AuthenticationType::AUTHENTICATION_USER_PASS,
  30. auth_data: password.into_bytes(),
  31. }
  32. }
  33. pub fn with_blob(username: String, encrypted_blob: &str, device_id: &str) -> Credentials {
  34. fn read_u8<R: Read>(stream: &mut R) -> io::Result<u8> {
  35. let mut data = [0u8];
  36. try!(stream.read_exact(&mut data));
  37. Ok(data[0])
  38. }
  39. fn read_int<R: Read>(stream: &mut R) -> io::Result<u32> {
  40. let lo = try!(read_u8(stream)) as u32;
  41. if lo & 0x80 == 0 {
  42. return Ok(lo);
  43. }
  44. let hi = try!(read_u8(stream)) as u32;
  45. Ok(lo & 0x7f | hi << 7)
  46. }
  47. fn read_bytes<R: Read>(stream: &mut R) -> io::Result<Vec<u8>> {
  48. let length = try!(read_int(stream));
  49. let mut data = vec![0u8; length as usize];
  50. try!(stream.read_exact(&mut data));
  51. Ok(data)
  52. }
  53. let secret = Sha1::digest(device_id.as_bytes());
  54. let key = {
  55. let mut key = [0u8; 24];
  56. pbkdf2::<Hmac<Sha1>>(&secret, username.as_bytes(), 0x100, &mut key[0..20]);
  57. let hash = &Sha1::digest(&key[..20]);
  58. key[..20].copy_from_slice(hash);
  59. BigEndian::write_u32(&mut key[20..], 20);
  60. key
  61. };
  62. // decrypt data using ECB mode without padding
  63. let blob = {
  64. use aes::block_cipher_trait::BlockCipher;
  65. use aes::block_cipher_trait::generic_array::GenericArray;
  66. use aes::block_cipher_trait::generic_array::typenum::Unsigned;
  67. let mut data = base64::decode(encrypted_blob).unwrap();
  68. let cipher = Aes192::new(GenericArray::from_slice(&key));
  69. let block_size = <Aes192 as BlockCipher>::BlockSize::to_usize();
  70. assert_eq!(data.len() % block_size, 0);
  71. // replace to chunks_exact_mut with MSRV bump to 1.31
  72. for chunk in data.chunks_mut(block_size) {
  73. cipher.decrypt_block(GenericArray::from_mut_slice(chunk));
  74. }
  75. let l = data.len();
  76. for i in 0..l - 0x10 {
  77. data[l - i - 1] ^= data[l - i - 0x11];
  78. }
  79. data
  80. };
  81. let mut cursor = io::Cursor::new(&blob);
  82. read_u8(&mut cursor).unwrap();
  83. read_bytes(&mut cursor).unwrap();
  84. read_u8(&mut cursor).unwrap();
  85. let auth_type = read_int(&mut cursor).unwrap();
  86. let auth_type = AuthenticationType::from_i32(auth_type as i32).unwrap();
  87. read_u8(&mut cursor).unwrap();
  88. let auth_data = read_bytes(&mut cursor).unwrap();
  89. Credentials {
  90. username: username,
  91. auth_type: auth_type,
  92. auth_data: auth_data,
  93. }
  94. }
  95. fn from_reader<R: Read>(mut reader: R) -> Credentials {
  96. let mut contents = String::new();
  97. reader.read_to_string(&mut contents).unwrap();
  98. serde_json::from_str(&contents).unwrap()
  99. }
  100. pub(crate) fn from_file<P: AsRef<Path>>(path: P) -> Option<Credentials> {
  101. File::open(path).ok().map(Credentials::from_reader)
  102. }
  103. fn save_to_writer<W: Write>(&self, writer: &mut W) {
  104. let contents = serde_json::to_string(&self.clone()).unwrap();
  105. writer.write_all(contents.as_bytes()).unwrap();
  106. }
  107. pub(crate) fn save_to_file<P: AsRef<Path>>(&self, path: P) {
  108. let mut file = File::create(path).unwrap();
  109. self.save_to_writer(&mut file)
  110. }
  111. }
  112. fn serialize_protobuf_enum<T, S>(v: &T, ser: S) -> Result<S::Ok, S::Error>
  113. where
  114. T: ProtobufEnum,
  115. S: serde::Serializer,
  116. {
  117. serde::Serialize::serialize(&v.value(), ser)
  118. }
  119. fn deserialize_protobuf_enum<T, D>(de: D) -> Result<T, D::Error>
  120. where
  121. T: ProtobufEnum,
  122. D: serde::Deserializer,
  123. {
  124. let v: i32 = try!(serde::Deserialize::deserialize(de));
  125. T::from_i32(v).ok_or_else(|| serde::de::Error::custom("Invalid enum value"))
  126. }
  127. fn serialize_base64<T, S>(v: &T, ser: S) -> Result<S::Ok, S::Error>
  128. where
  129. T: AsRef<[u8]>,
  130. S: serde::Serializer,
  131. {
  132. serde::Serialize::serialize(&base64::encode(v.as_ref()), ser)
  133. }
  134. fn deserialize_base64<D>(de: D) -> Result<Vec<u8>, D::Error>
  135. where
  136. D: serde::Deserializer,
  137. {
  138. let v: String = try!(serde::Deserialize::deserialize(de));
  139. base64::decode(&v).map_err(|e| serde::de::Error::custom(e.to_string()))
  140. }
  141. pub fn get_credentials<F: FnOnce(&String) -> String>(
  142. username: Option<String>,
  143. password: Option<String>,
  144. cached_credentials: Option<Credentials>,
  145. prompt: F,
  146. ) -> Option<Credentials> {
  147. match (username, password, cached_credentials) {
  148. (Some(username), Some(password), _) => Some(Credentials::with_password(username, password)),
  149. (Some(ref username), _, Some(ref credentials)) if *username == credentials.username => {
  150. Some(credentials.clone())
  151. }
  152. (Some(username), None, _) => {
  153. Some(Credentials::with_password(username.clone(), prompt(&username)))
  154. }
  155. (None, _, Some(credentials)) => Some(credentials),
  156. (None, _, None) => None,
  157. }
  158. }