Merge pull request #65 from dyc3/cleanup

Misc cleanup for rust code
This commit is contained in:
Carson McManus 2021-07-31 12:27:51 -04:00 committed by GitHub
commit ca93b7289c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 101 additions and 70 deletions

23
Cargo.lock generated
View file

@ -1,5 +1,7 @@
# This file is automatically @generated by Cargo. # This file is automatically @generated by Cargo.
# It is not intended for manual editing. # It is not intended for manual editing.
version = 3
[[package]] [[package]]
name = "adler" name = "adler"
version = "1.0.2" version = "1.0.2"
@ -1241,6 +1243,26 @@ version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "213701ba3370744dcd1a12960caa4843b3d68b4d1c0a5d575e0d65b2ee9d16c0" checksum = "213701ba3370744dcd1a12960caa4843b3d68b4d1c0a5d575e0d65b2ee9d16c0"
[[package]]
name = "steamguard"
version = "0.1.0"
dependencies = [
"anyhow",
"base64",
"cookie",
"hmac-sha1",
"lazy_static 1.4.0",
"log",
"rand",
"regex",
"reqwest",
"rsa",
"serde",
"serde_json",
"standback",
"uuid",
]
[[package]] [[package]]
name = "steamguard-cli" name = "steamguard-cli"
version = "0.2.0" version = "0.2.0"
@ -1261,6 +1283,7 @@ dependencies = [
"serde_json", "serde_json",
"standback", "standback",
"stderrlog", "stderrlog",
"steamguard",
"termion", "termion",
"text_io", "text_io",
"uuid", "uuid",

View file

@ -1,3 +1,9 @@
[workspace]
members = [
"steamguard"
]
[package] [package]
name = "steamguard-cli" name = "steamguard-cli"
version = "0.2.0" version = "0.2.0"
@ -26,3 +32,4 @@ regex = "1"
lazy_static = "1.4.0" lazy_static = "1.4.0"
uuid = { version = "0.8", features = ["v4"] } uuid = { version = "0.8", features = ["v4"] }
termion = "1.5.6" termion = "1.5.6"
steamguard = { path = "./steamguard" }

View file

@ -1,8 +1,8 @@
use std::collections::HashMap; use std::collections::HashMap;
use reqwest::{Url, cookie::{CookieStore}, header::COOKIE, header::{SET_COOKIE, USER_AGENT}}; use reqwest::{Url, cookie::{CookieStore}, header::COOKIE};
use serde::{Serialize, Deserialize}; use serde::Deserialize;
use serde_json::Value; use serde_json::Value;
use steamguard_cli::{SteamGuardAccount, steamapi::Session}; use steamguard::{SteamGuardAccount, steamapi::Session};
use log::*; use log::*;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]

View file

@ -3,7 +3,7 @@ use std::io::BufReader;
use std::path::Path; use std::path::Path;
use serde::{Serialize, Deserialize}; use serde::{Serialize, Deserialize};
use std::error::Error; use std::error::Error;
use steamguard_cli::SteamGuardAccount; use steamguard::SteamGuardAccount;
use log::*; use log::*;
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]

View file

@ -1,18 +1,11 @@
extern crate rpassword; extern crate rpassword;
use borrow::BorrowMut; use steamguard::{SteamGuardAccount, Confirmation, ConfirmationType, steamapi};
use collections::HashSet; use std::collections::HashSet;
use io::{Write, stdout}; use std::{io::{Write, stdout, stdin}, path::Path};
use steamapi::Session;
use steamguard_cli::*;
use termion::{color::Color, raw::IntoRawMode, screen::AlternateScreen};
use ::std::*;
use text_io::read;
use std::{convert::TryInto, io::stdin, path::Path, sync::Arc};
use clap::{App, Arg, crate_version}; use clap::{App, Arg, crate_version};
use log::*; use log::*;
use regex::Regex; use regex::Regex;
use termion::event::{Key, Event}; use termion::{raw::IntoRawMode, screen::AlternateScreen, event::{Key, Event}, input::{TermRead}};
use termion::input::{TermRead};
#[macro_use] #[macro_use]
extern crate lazy_static; extern crate lazy_static;
@ -345,18 +338,18 @@ fn do_login(account: &mut SteamGuardAccount) {
let mut loops = 0; let mut loops = 0;
loop { loop {
match login.login() { match login.login() {
steamapi::LoginResult::Ok(s) => { Ok(s) => {
account.session = Option::Some(s); account.session = Option::Some(s);
break; break;
} }
steamapi::LoginResult::Need2FA => { Err(steamapi::LoginError::Need2FA) => {
let server_time = steamapi::get_server_time(); let server_time = steamapi::get_server_time();
login.twofactor_code = account.generate_code(server_time); login.twofactor_code = account.generate_code(server_time);
} }
steamapi::LoginResult::NeedCaptcha{ captcha_gid } => { Err(steamapi::LoginError::NeedCaptcha{ captcha_gid }) => {
login.captcha_text = prompt_captcha_text(&captcha_gid); login.captcha_text = prompt_captcha_text(&captcha_gid);
} }
steamapi::LoginResult::NeedEmail => { Err(steamapi::LoginError::NeedEmail) => {
println!("You should have received an email with a code."); println!("You should have received an email with a code.");
print!("Enter code"); print!("Enter code");
login.email_code = prompt(); login.email_code = prompt();

23
steamguard/Cargo.toml Normal file
View file

@ -0,0 +1,23 @@
[package]
name = "steamguard"
version = "0.1.0"
edition = "2018"
description = "Library for generating 2fa codes for Steam and responding to mobile confirmations."
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
anyhow = "^1.0"
hmac-sha1 = "^0.1"
base64 = "0.13.0"
reqwest = { version = "0.11", features = ["blocking", "json", "cookies", "gzip"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
rsa = "0.5.0"
rand = "0.8.4"
standback = "0.2.17" # required to fix a compilation error on a transient dependency
cookie = "0.14"
regex = "1"
lazy_static = "1.4.0"
uuid = { version = "0.8", features = ["v4"] }
log = "0.4.14"

View file

@ -46,27 +46,14 @@ pub struct SteamGuardAccount {
pub session: Option<steamapi::Session>, pub session: Option<steamapi::Session>,
} }
fn build_time_bytes(mut time: i64) -> [u8; 8] { fn build_time_bytes(time: i64) -> [u8; 8] {
let mut bytes: [u8; 8] = [0; 8]; return time.to_be_bytes();
for i in (0..8).rev() {
bytes[i] = time as u8;
time >>= 8;
}
return bytes
} }
pub fn parse_shared_secret(secret: String) -> [u8; 20] { pub fn parse_shared_secret(secret: String) -> anyhow::Result<[u8; 20]> {
if secret.len() == 0 { ensure!(secret.len() != 0, "unable to parse empty shared secret");
panic!("unable to parse empty shared secret") let result = base64::decode(secret)?.try_into();
} return Ok(result.unwrap());
match base64::decode(secret) {
Result::Ok(v) => {
return v.try_into().unwrap()
}
_ => {
panic!("unable to parse shared secret")
}
}
} }
fn generate_confirmation_hash_for_time(time: i64, tag: &str, identity_secret: &String) -> String { fn generate_confirmation_hash_for_time(time: i64, tag: &str, identity_secret: &String) -> String {
@ -99,11 +86,10 @@ impl SteamGuardAccount {
pub fn generate_code(&self, time: i64) -> String { pub fn generate_code(&self, time: i64) -> String {
let steam_guard_code_translations: [u8; 26] = [50, 51, 52, 53, 54, 55, 56, 57, 66, 67, 68, 70, 71, 72, 74, 75, 77, 78, 80, 81, 82, 84, 86, 87, 88, 89]; let steam_guard_code_translations: [u8; 26] = [50, 51, 52, 53, 54, 55, 56, 57, 66, 67, 68, 70, 71, 72, 74, 75, 77, 78, 80, 81, 82, 84, 86, 87, 88, 89];
// this effectively makes it so that it creates a new code every 30 seconds.
let time_bytes: [u8; 8] = build_time_bytes(time / 30i64); let time_bytes: [u8; 8] = build_time_bytes(time / 30i64);
let shared_secret: [u8; 20] = parse_shared_secret(self.shared_secret.clone()); let shared_secret: [u8; 20] = parse_shared_secret(self.shared_secret.clone()).unwrap();
// println!("time_bytes: {:?}", time_bytes);
let hashed_data = hmacsha1::hmac_sha1(&shared_secret, &time_bytes); let hashed_data = hmacsha1::hmac_sha1(&shared_secret, &time_bytes);
// println!("hashed_data: {:?}", hashed_data);
let mut code_array: [u8; 5] = [0; 5]; let mut code_array: [u8; 5] = [0; 5];
let b = (hashed_data[19] & 0xF) as usize; let b = (hashed_data[19] & 0xF) as usize;
let mut code_point: i32 = let mut code_point: i32 =
@ -117,8 +103,6 @@ impl SteamGuardAccount {
code_point /= steam_guard_code_translations.len() as i32; code_point /= steam_guard_code_translations.len() as i32;
} }
// println!("code_array: {:?}", code_array);
return String::from_utf8(code_array.iter().map(|c| *c).collect()).unwrap() return String::from_utf8(code_array.iter().map(|c| *c).collect()).unwrap()
} }
@ -283,6 +267,13 @@ impl SteamGuardAccount {
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn test_build_time_bytes() {
let t1 = build_time_bytes(1617591917i64);
let t2: [u8; 8] = [0, 0, 0, 0, 96, 106, 126, 109];
assert!(t1.iter().zip(t2.iter()).all(|(a,b)| a == b), "Arrays are not equal, got {:?}", t1);
}
#[test] #[test]
fn test_generate_code() { fn test_generate_code() {
let mut account = SteamGuardAccount::new(); let mut account = SteamGuardAccount::new();

View file

@ -3,9 +3,6 @@ use reqwest::{Url, cookie::{CookieStore}, header::COOKIE, header::{SET_COOKIE, U
use rsa::{PublicKey, RsaPublicKey}; use rsa::{PublicKey, RsaPublicKey};
use std::time::{SystemTime, UNIX_EPOCH}; use std::time::{SystemTime, UNIX_EPOCH};
use serde::{Serialize, Deserialize}; use serde::{Serialize, Deserialize};
use serde::de::{Visitor};
use rand::rngs::OsRng;
use std::fmt;
use log::*; use log::*;
#[derive(Debug, Clone, Deserialize)] #[derive(Debug, Clone, Deserialize)]
@ -13,8 +10,6 @@ struct LoginResponse {
success: bool, success: bool,
#[serde(default)] #[serde(default)]
login_complete: bool, login_complete: bool,
// #[serde(default)]
// oauth: String,
#[serde(default)] #[serde(default)]
captcha_needed: bool, captcha_needed: bool,
#[serde(default)] #[serde(default)]
@ -50,8 +45,7 @@ struct RsaResponse {
} }
#[derive(Debug)] #[derive(Debug)]
pub enum LoginResult { pub enum LoginError {
Ok(Session),
BadRSA, BadRSA,
BadCredentials, BadCredentials,
NeedCaptcha{ captcha_gid: String }, NeedCaptcha{ captcha_gid: String },
@ -73,7 +67,6 @@ pub struct UserLogin {
pub steam_id: u64, pub steam_id: u64,
cookies: reqwest::cookie::Jar, cookies: reqwest::cookie::Jar,
// cookies: Arc<reqwest::cookie::Jar>,
client: reqwest::blocking::Client, client: reqwest::blocking::Client,
} }
@ -89,7 +82,6 @@ impl UserLogin {
email_code: String::from(""), email_code: String::from(""),
steam_id: 0, steam_id: 0,
cookies: reqwest::cookie::Jar::default(), cookies: reqwest::cookie::Jar::default(),
// cookies: Arc::<reqwest::cookie::Jar>::new(reqwest::cookie::Jar::default()),
client: reqwest::blocking::ClientBuilder::new() client: reqwest::blocking::ClientBuilder::new()
.cookie_store(true) .cookie_store(true)
.build() .build()
@ -97,6 +89,7 @@ impl UserLogin {
} }
} }
/// Updates the cookie jar with the session cookies by pinging steam servers.
fn update_session(&self) { fn update_session(&self) {
trace!("UserLogin::update_session"); trace!("UserLogin::update_session");
let url = "https://steamcommunity.com".parse::<Url>().unwrap(); let url = "https://steamcommunity.com".parse::<Url>().unwrap();
@ -118,10 +111,10 @@ impl UserLogin {
trace!("cookies: {:?}", self.cookies); trace!("cookies: {:?}", self.cookies);
} }
pub fn login(&mut self) -> LoginResult { pub fn login(&mut self) -> anyhow::Result<Session, LoginError> {
trace!("UserLogin::login"); trace!("UserLogin::login");
if self.captcha_required && self.captcha_text.len() == 0 { if self.captcha_required && self.captcha_text.len() == 0 {
return LoginResult::NeedCaptcha{captcha_gid: self.captcha_gid.clone()}; return Err(LoginError::NeedCaptcha{captcha_gid: self.captcha_gid.clone()});
} }
let url = "https://steamcommunity.com".parse::<Url>().unwrap(); let url = "https://steamcommunity.com".parse::<Url>().unwrap();
@ -147,7 +140,7 @@ impl UserLogin {
} }
Err(error) => { Err(error) => {
error!("rsa error: {:?}", error); error!("rsa error: {:?}", error);
return LoginResult::BadRSA return Err(LoginError::BadRSA);
} }
} }
@ -185,40 +178,40 @@ impl UserLogin {
Err(error) => { Err(error) => {
debug!("login response did not have normal schema"); debug!("login response did not have normal schema");
error!("login parse error: {:?}", error); error!("login parse error: {:?}", error);
return LoginResult::OtherFailure; return Err(LoginError::OtherFailure);
} }
} }
} }
Err(error) => { Err(error) => {
error!("login request error: {:?}", error); error!("login request error: {:?}", error);
return LoginResult::OtherFailure; return Err(LoginError::OtherFailure);
} }
} }
if login_resp.message.contains("too many login") { if login_resp.message.contains("too many login") {
return LoginResult::TooManyAttempts; return Err(LoginError::TooManyAttempts);
} }
if login_resp.message.contains("Incorrect login") { if login_resp.message.contains("Incorrect login") {
return LoginResult::BadCredentials; return Err(LoginError::BadCredentials);
} }
if login_resp.captcha_needed { if login_resp.captcha_needed {
self.captcha_gid = login_resp.captcha_gid.clone(); self.captcha_gid = login_resp.captcha_gid.clone();
return LoginResult::NeedCaptcha{ captcha_gid: self.captcha_gid.clone() }; return Err(LoginError::NeedCaptcha{ captcha_gid: self.captcha_gid.clone() });
} }
if login_resp.emailauth_needed { if login_resp.emailauth_needed {
self.steam_id = login_resp.emailsteamid.clone(); self.steam_id = login_resp.emailsteamid.clone();
return LoginResult::NeedEmail; return Err(LoginError::NeedEmail);
} }
if login_resp.requires_twofactor { if login_resp.requires_twofactor {
return LoginResult::Need2FA; return Err(LoginError::Need2FA);
} }
if !login_resp.login_complete { if !login_resp.login_complete {
return LoginResult::BadCredentials; return Err(LoginError::BadCredentials);
} }
@ -256,11 +249,10 @@ impl UserLogin {
} }
_ => { _ => {
error!("did not receive transfer_urls and transfer_parameters"); error!("did not receive transfer_urls and transfer_parameters");
return LoginResult::OtherFailure; return Err(LoginError::OtherFailure);
} }
} }
// let oauth: OAuthData = serde_json::from_str(login_resp.oauth.as_str()).unwrap();
let url = "https://steamcommunity.com".parse::<Url>().unwrap(); let url = "https://steamcommunity.com".parse::<Url>().unwrap();
let cookies = self.cookies.cookies(&url).unwrap(); let cookies = self.cookies.cookies(&url).unwrap();
let all_cookies = cookies.to_str().unwrap(); let all_cookies = cookies.to_str().unwrap();
@ -273,7 +265,7 @@ impl UserLogin {
trace!("cookies {:?}", cookies); trace!("cookies {:?}", cookies);
let session = self.build_session(oauth, session_id); let session = self.build_session(oauth, session_id);
return LoginResult::Ok(session); return Ok(session);
} }
fn build_session(&self, data: OAuthData, session_id: String) -> Session { fn build_session(&self, data: OAuthData, session_id: String) -> Session {
@ -334,8 +326,6 @@ pub fn get_server_time() -> i64 {
.send(); .send();
let value: serde_json::Value = resp.unwrap().json().unwrap(); let value: serde_json::Value = resp.unwrap().json().unwrap();
// println!("{}", value["response"]);
return String::from(value["response"]["server_time"].as_str().unwrap()).parse().unwrap(); return String::from(value["response"]["server_time"].as_str().unwrap()).parse().unwrap();
} }
@ -343,7 +333,10 @@ fn encrypt_password(rsa_resp: RsaResponse, password: &String) -> String {
let rsa_exponent = rsa::BigUint::parse_bytes(rsa_resp.publickey_exp.as_bytes(), 16).unwrap(); let rsa_exponent = rsa::BigUint::parse_bytes(rsa_resp.publickey_exp.as_bytes(), 16).unwrap();
let rsa_modulus = rsa::BigUint::parse_bytes(rsa_resp.publickey_mod.as_bytes(), 16).unwrap(); let rsa_modulus = rsa::BigUint::parse_bytes(rsa_resp.publickey_mod.as_bytes(), 16).unwrap();
let public_key = RsaPublicKey::new(rsa_modulus, rsa_exponent).unwrap(); let public_key = RsaPublicKey::new(rsa_modulus, rsa_exponent).unwrap();
let mut rng = OsRng; #[cfg(test)]
let mut rng = rand::rngs::mock::StepRng::new(2, 1);
#[cfg(not(test))]
let mut rng = rand::rngs::OsRng;
let padding = rsa::PaddingScheme::new_pkcs1v15_encrypt(); let padding = rsa::PaddingScheme::new_pkcs1v15_encrypt();
let encrypted_password = base64::encode(public_key.encrypt(&mut rng, padding, password.as_bytes()).unwrap()); let encrypted_password = base64::encode(public_key.encrypt(&mut rng, padding, password.as_bytes()).unwrap());
return encrypted_password; return encrypted_password;
@ -359,5 +352,6 @@ fn test_encrypt_password() {
token_gid: String::from("asdf"), token_gid: String::from("asdf"),
}; };
let result = encrypt_password(rsa_resp, &String::from("kelwleofpsm3n4ofc")); let result = encrypt_password(rsa_resp, &String::from("kelwleofpsm3n4ofc"));
assert_eq!(result.len(), 344); // can't test exact match because the result is different every time (because of OsRng) assert_eq!(result.len(), 344);
assert_eq!(result, "RUo/3IfbkVcJi1q1S5QlpKn1mEn3gNJoc/Z4VwxRV9DImV6veq/YISEuSrHB3885U5MYFLn1g94Y+cWRL6HGXoV+gOaVZe43m7O92RwiVz6OZQXMfAv3UC/jcqn/xkitnj+tNtmx55gCxmGbO2KbqQ0TQqAyqCOOw565B+Cwr2OOorpMZAViv9sKA/G3Q6yzscU6rhua179c8QjC1Hk3idUoSzpWfT4sHNBW/EREXZ3Dkjwu17xzpfwIUpnBVIlR8Vj3coHgUCpTsKVRA3T814v9BYPlvLYwmw5DW3ddx+2SyTY0P5uuog36TN2PqYS7ioF5eDe16gyfRR4Nzn/7wA==");
} }