Merge pull request #72 from tilosp/rustfmt
Run cargo fmt and check it using github actions
This commit is contained in:
commit
258e758395
7 changed files with 1096 additions and 936 deletions
25
.github/workflows/rustfmt.yml
vendored
Normal file
25
.github/workflows/rustfmt.yml
vendored
Normal file
|
@ -0,0 +1,25 @@
|
||||||
|
on: [push, pull_request]
|
||||||
|
|
||||||
|
name: rustfmt
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
rustfmt:
|
||||||
|
name: rustfmt
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout sources
|
||||||
|
uses: actions/checkout@v2
|
||||||
|
|
||||||
|
- name: Install stable toolchain
|
||||||
|
uses: actions-rs/toolchain@v1
|
||||||
|
with:
|
||||||
|
profile: minimal
|
||||||
|
toolchain: stable
|
||||||
|
override: true
|
||||||
|
components: rustfmt
|
||||||
|
|
||||||
|
- name: Run cargo fmt
|
||||||
|
uses: actions-rs/cargo@v1
|
||||||
|
with:
|
||||||
|
command: fmt
|
||||||
|
args: --all -- --check
|
|
@ -1,86 +1,87 @@
|
||||||
use std::collections::HashMap;
|
use log::*;
|
||||||
use reqwest::{Url, cookie::{CookieStore}, header::COOKIE};
|
use reqwest::{cookie::CookieStore, header::COOKIE, Url};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
use steamguard::{SteamGuardAccount, steamapi::Session};
|
use std::collections::HashMap;
|
||||||
use log::*;
|
use steamguard::{steamapi::Session, SteamGuardAccount};
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct AccountLinker {
|
pub struct AccountLinker {
|
||||||
device_id: String,
|
device_id: String,
|
||||||
phone_number: String,
|
phone_number: String,
|
||||||
pub account: SteamGuardAccount,
|
pub account: SteamGuardAccount,
|
||||||
client: reqwest::blocking::Client,
|
client: reqwest::blocking::Client,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AccountLinker {
|
impl AccountLinker {
|
||||||
pub fn new() -> AccountLinker {
|
pub fn new() -> AccountLinker {
|
||||||
return AccountLinker{
|
return AccountLinker {
|
||||||
device_id: generate_device_id(),
|
device_id: generate_device_id(),
|
||||||
phone_number: String::from(""),
|
phone_number: String::from(""),
|
||||||
account: SteamGuardAccount::new(),
|
account: SteamGuardAccount::new(),
|
||||||
client: reqwest::blocking::ClientBuilder::new()
|
client: reqwest::blocking::ClientBuilder::new()
|
||||||
.cookie_store(true)
|
.cookie_store(true)
|
||||||
.build()
|
.build()
|
||||||
.unwrap(),
|
.unwrap(),
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn link(&self, session: &mut Session) {
|
pub fn link(&self, session: &mut Session) {
|
||||||
let mut params = HashMap::new();
|
let mut params = HashMap::new();
|
||||||
params.insert("access_token", session.token.clone());
|
params.insert("access_token", session.token.clone());
|
||||||
params.insert("steamid", session.steam_id.to_string());
|
params.insert("steamid", session.steam_id.to_string());
|
||||||
params.insert("device_identifier", self.device_id.clone());
|
params.insert("device_identifier", self.device_id.clone());
|
||||||
params.insert("authenticator_type", String::from("1"));
|
params.insert("authenticator_type", String::from("1"));
|
||||||
params.insert("sms_phone_id", String::from("1"));
|
params.insert("sms_phone_id", String::from("1"));
|
||||||
}
|
}
|
||||||
|
|
||||||
fn has_phone(&self, session: &Session) -> bool {
|
fn has_phone(&self, session: &Session) -> bool {
|
||||||
return self._phoneajax(session, "has_phone", "null");
|
return self._phoneajax(session, "has_phone", "null");
|
||||||
}
|
}
|
||||||
|
|
||||||
fn _phoneajax(&self, session: &Session, op: &str, arg: &str) -> bool {
|
fn _phoneajax(&self, session: &Session, op: &str, arg: &str) -> bool {
|
||||||
trace!("_phoneajax: op={}", op);
|
trace!("_phoneajax: op={}", op);
|
||||||
let url = "https://steamcommunity.com".parse::<Url>().unwrap();
|
let url = "https://steamcommunity.com".parse::<Url>().unwrap();
|
||||||
let cookies = reqwest::cookie::Jar::default();
|
let cookies = reqwest::cookie::Jar::default();
|
||||||
cookies.add_cookie_str("mobileClientVersion=0 (2.1.3)", &url);
|
cookies.add_cookie_str("mobileClientVersion=0 (2.1.3)", &url);
|
||||||
cookies.add_cookie_str("mobileClient=android", &url);
|
cookies.add_cookie_str("mobileClient=android", &url);
|
||||||
cookies.add_cookie_str("Steam_Language=english", &url);
|
cookies.add_cookie_str("Steam_Language=english", &url);
|
||||||
|
|
||||||
let mut params = HashMap::new();
|
let mut params = HashMap::new();
|
||||||
params.insert("op", op);
|
params.insert("op", op);
|
||||||
params.insert("arg", arg);
|
params.insert("arg", arg);
|
||||||
params.insert("sessionid", session.session_id.as_str());
|
params.insert("sessionid", session.session_id.as_str());
|
||||||
if op == "check_sms_code" {
|
if op == "check_sms_code" {
|
||||||
params.insert("checkfortos", "0");
|
params.insert("checkfortos", "0");
|
||||||
params.insert("skipvoip", "1");
|
params.insert("skipvoip", "1");
|
||||||
}
|
}
|
||||||
|
|
||||||
let resp = self.client
|
let resp = self
|
||||||
.post("https://steamcommunity.com/steamguard/phoneajax")
|
.client
|
||||||
.header(COOKIE, cookies.cookies(&url).unwrap())
|
.post("https://steamcommunity.com/steamguard/phoneajax")
|
||||||
.send()
|
.header(COOKIE, cookies.cookies(&url).unwrap())
|
||||||
.unwrap();
|
.send()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
let result: Value = resp.json().unwrap();
|
let result: Value = resp.json().unwrap();
|
||||||
if result["has_phone"] != Value::Null {
|
if result["has_phone"] != Value::Null {
|
||||||
trace!("found has_phone field");
|
trace!("found has_phone field");
|
||||||
return result["has_phone"].as_bool().unwrap();
|
return result["has_phone"].as_bool().unwrap();
|
||||||
} else if result["success"] != Value::Null {
|
} else if result["success"] != Value::Null {
|
||||||
trace!("found success field");
|
trace!("found success field");
|
||||||
return result["success"].as_bool().unwrap();
|
return result["success"].as_bool().unwrap();
|
||||||
} else {
|
} else {
|
||||||
trace!("did not find any expected field");
|
trace!("did not find any expected field");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn generate_device_id() -> String {
|
fn generate_device_id() -> String {
|
||||||
return format!("android:{}", uuid::Uuid::new_v4().to_string());
|
return format!("android:{}", uuid::Uuid::new_v4().to_string());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize)]
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
pub struct AddAuthenticatorResponse {
|
pub struct AddAuthenticatorResponse {
|
||||||
pub response: SteamGuardAccount
|
pub response: SteamGuardAccount,
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,81 +1,81 @@
|
||||||
|
use log::*;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::error::Error;
|
||||||
use std::fs::File;
|
use std::fs::File;
|
||||||
use std::io::BufReader;
|
use std::io::BufReader;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
use serde::{Serialize, Deserialize};
|
|
||||||
use std::error::Error;
|
|
||||||
use steamguard::SteamGuardAccount;
|
use steamguard::SteamGuardAccount;
|
||||||
use log::*;
|
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize)]
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
pub struct Manifest {
|
pub struct Manifest {
|
||||||
pub encrypted: bool,
|
pub encrypted: bool,
|
||||||
pub entries: Vec<ManifestEntry>,
|
pub entries: Vec<ManifestEntry>,
|
||||||
pub first_run: bool,
|
pub first_run: bool,
|
||||||
pub periodic_checking: bool,
|
pub periodic_checking: bool,
|
||||||
pub periodic_checking_interval: i32,
|
pub periodic_checking_interval: i32,
|
||||||
pub periodic_checking_checkall: bool,
|
pub periodic_checking_checkall: bool,
|
||||||
pub auto_confirm_market_transactions: bool,
|
pub auto_confirm_market_transactions: bool,
|
||||||
pub auto_confirm_trades: bool,
|
pub auto_confirm_trades: bool,
|
||||||
|
|
||||||
#[serde(skip)]
|
#[serde(skip)]
|
||||||
pub accounts: Vec<SteamGuardAccount>,
|
pub accounts: Vec<SteamGuardAccount>,
|
||||||
#[serde(skip)]
|
#[serde(skip)]
|
||||||
folder: String, // I wanted to use a Path here, but it was too hard to make it work...
|
folder: String, // I wanted to use a Path here, but it was too hard to make it work...
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct ManifestEntry {
|
pub struct ManifestEntry {
|
||||||
pub encryption_iv: Option<String>,
|
pub encryption_iv: Option<String>,
|
||||||
pub encryption_salt: Option<String>,
|
pub encryption_salt: Option<String>,
|
||||||
pub filename: String,
|
pub filename: String,
|
||||||
#[serde(rename = "steamid")]
|
#[serde(rename = "steamid")]
|
||||||
pub steam_id: u64,
|
pub steam_id: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Manifest {
|
impl Manifest {
|
||||||
pub fn load(path: &Path) -> Result<Manifest, Box<dyn Error>> {
|
pub fn load(path: &Path) -> Result<Manifest, Box<dyn Error>> {
|
||||||
debug!("loading manifest: {:?}", &path);
|
debug!("loading manifest: {:?}", &path);
|
||||||
match File::open(path) {
|
match File::open(path) {
|
||||||
Ok(file) => {
|
Ok(file) => {
|
||||||
let reader = BufReader::new(file);
|
let reader = BufReader::new(file);
|
||||||
match serde_json::from_reader(reader) {
|
match serde_json::from_reader(reader) {
|
||||||
Ok(m) => {
|
Ok(m) => {
|
||||||
let mut manifest: Manifest = m;
|
let mut manifest: Manifest = m;
|
||||||
manifest.folder = String::from(path.parent().unwrap().to_str().unwrap());
|
manifest.folder = String::from(path.parent().unwrap().to_str().unwrap());
|
||||||
return Ok(manifest);
|
return Ok(manifest);
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
return Err(Box::new(e));
|
return Err(Box::new(e));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
return Err(Box::new(e));
|
return Err(Box::new(e));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn load_accounts(&mut self) {
|
pub fn load_accounts(&mut self) {
|
||||||
for entry in &self.entries {
|
for entry in &self.entries {
|
||||||
let path = Path::new(&self.folder).join(&entry.filename);
|
let path = Path::new(&self.folder).join(&entry.filename);
|
||||||
debug!("loading account: {:?}", path);
|
debug!("loading account: {:?}", path);
|
||||||
match File::open(path) {
|
match File::open(path) {
|
||||||
Ok(f) => {
|
Ok(f) => {
|
||||||
let reader = BufReader::new(f);
|
let reader = BufReader::new(f);
|
||||||
match serde_json::from_reader(reader) {
|
match serde_json::from_reader(reader) {
|
||||||
Ok(a) => {
|
Ok(a) => {
|
||||||
let account: SteamGuardAccount = a;
|
let account: SteamGuardAccount = a;
|
||||||
self.accounts.push(account);
|
self.accounts.push(account);
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
error!("invalid json: {}", e)
|
error!("invalid json: {}", e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
error!("unable to open account: {}", e)
|
error!("unable to open account: {}", e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
619
src/main.rs
619
src/main.rs
|
@ -1,23 +1,32 @@
|
||||||
extern crate rpassword;
|
extern crate rpassword;
|
||||||
use steamguard::{SteamGuardAccount, Confirmation, ConfirmationType, steamapi};
|
use clap::{crate_version, App, Arg};
|
||||||
use std::collections::HashSet;
|
|
||||||
use std::{io::{Write, stdout, stdin}, path::Path};
|
|
||||||
use clap::{App, Arg, crate_version};
|
|
||||||
use log::*;
|
use log::*;
|
||||||
use regex::Regex;
|
use regex::Regex;
|
||||||
use termion::{raw::IntoRawMode, screen::AlternateScreen, event::{Key, Event}, input::{TermRead}};
|
use std::collections::HashSet;
|
||||||
|
use std::{
|
||||||
|
io::{stdin, stdout, Write},
|
||||||
|
path::Path,
|
||||||
|
};
|
||||||
|
use steamguard::{steamapi, Confirmation, ConfirmationType, SteamGuardAccount};
|
||||||
|
use termion::{
|
||||||
|
event::{Event, Key},
|
||||||
|
input::TermRead,
|
||||||
|
raw::IntoRawMode,
|
||||||
|
screen::AlternateScreen,
|
||||||
|
};
|
||||||
|
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate lazy_static;
|
extern crate lazy_static;
|
||||||
mod accountmanager;
|
|
||||||
mod accountlinker;
|
mod accountlinker;
|
||||||
|
mod accountmanager;
|
||||||
|
|
||||||
lazy_static! {
|
lazy_static! {
|
||||||
static ref CAPTCHA_VALID_CHARS: Regex = Regex::new("^([A-H]|[J-N]|[P-R]|[T-Z]|[2-4]|[7-9]|[@%&])+$").unwrap();
|
static ref CAPTCHA_VALID_CHARS: Regex =
|
||||||
|
Regex::new("^([A-H]|[J-N]|[P-R]|[T-Z]|[2-4]|[7-9]|[@%&])+$").unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let matches = App::new("steamguard-cli")
|
let matches = App::new("steamguard-cli")
|
||||||
.version(crate_version!())
|
.version(crate_version!())
|
||||||
.bin_name("steamguard")
|
.bin_name("steamguard")
|
||||||
.author("dyc3 (Carson McManus)")
|
.author("dyc3 (Carson McManus)")
|
||||||
|
@ -80,320 +89,362 @@ fn main() {
|
||||||
)
|
)
|
||||||
.get_matches();
|
.get_matches();
|
||||||
|
|
||||||
|
let verbosity = matches.occurrences_of("verbosity") as usize + 2;
|
||||||
|
stderrlog::new()
|
||||||
|
.verbosity(verbosity)
|
||||||
|
.module(module_path!())
|
||||||
|
.init()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
let verbosity = matches.occurrences_of("verbosity") as usize + 2;
|
if let Some(demo_matches) = matches.subcommand_matches("debug") {
|
||||||
stderrlog::new()
|
if demo_matches.is_present("demo-conf-menu") {
|
||||||
.verbosity(verbosity)
|
demo_confirmation_menu();
|
||||||
.module(module_path!()).init().unwrap();
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if let Some(demo_matches) = matches.subcommand_matches("debug") {
|
let path = Path::new(matches.value_of("mafiles-path").unwrap()).join("manifest.json");
|
||||||
if demo_matches.is_present("demo-conf-menu") {
|
let mut manifest: accountmanager::Manifest;
|
||||||
demo_confirmation_menu();
|
match accountmanager::Manifest::load(path.as_path()) {
|
||||||
}
|
Ok(m) => {
|
||||||
return;
|
manifest = m;
|
||||||
}
|
}
|
||||||
|
Err(e) => {
|
||||||
|
error!("Could not load manifest: {}", e);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let path = Path::new(matches.value_of("mafiles-path").unwrap()).join("manifest.json");
|
manifest.load_accounts();
|
||||||
let mut manifest: accountmanager::Manifest;
|
|
||||||
match accountmanager::Manifest::load(path.as_path()) {
|
|
||||||
Ok(m) => {
|
|
||||||
manifest = m;
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
error!("Could not load manifest: {}", e);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
manifest.load_accounts();
|
if matches.is_present("setup") {
|
||||||
|
info!("setup");
|
||||||
|
let mut linker = accountlinker::AccountLinker::new();
|
||||||
|
do_login(&mut linker.account);
|
||||||
|
// linker.link(linker.account.session.expect("no login session"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if matches.is_present("setup") {
|
let mut selected_accounts: Vec<SteamGuardAccount> = vec![];
|
||||||
info!("setup");
|
if matches.is_present("all") {
|
||||||
let mut linker = accountlinker::AccountLinker::new();
|
// manifest.accounts.iter().map(|a| selected_accounts.push(a.b));
|
||||||
do_login(&mut linker.account);
|
for account in manifest.accounts {
|
||||||
// linker.link(linker.account.session.expect("no login session"));
|
selected_accounts.push(account.clone());
|
||||||
return;
|
}
|
||||||
}
|
} else {
|
||||||
|
for account in manifest.accounts {
|
||||||
|
if !matches.is_present("username") {
|
||||||
|
selected_accounts.push(account.clone());
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if matches.value_of("username").unwrap() == account.account_name {
|
||||||
|
selected_accounts.push(account.clone());
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let mut selected_accounts: Vec<SteamGuardAccount> = vec![];
|
debug!(
|
||||||
if matches.is_present("all") {
|
"selected accounts: {:?}",
|
||||||
// manifest.accounts.iter().map(|a| selected_accounts.push(a.b));
|
selected_accounts
|
||||||
for account in manifest.accounts {
|
.iter()
|
||||||
selected_accounts.push(account.clone());
|
.map(|a| a.account_name.clone())
|
||||||
}
|
.collect::<Vec<String>>()
|
||||||
} else {
|
);
|
||||||
for account in manifest.accounts {
|
|
||||||
if !matches.is_present("username") {
|
|
||||||
selected_accounts.push(account.clone());
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
if matches.value_of("username").unwrap() == account.account_name {
|
|
||||||
selected_accounts.push(account.clone());
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
debug!("selected accounts: {:?}", selected_accounts.iter().map(|a| a.account_name.clone()).collect::<Vec<String>>());
|
if let Some(trade_matches) = matches.subcommand_matches("trade") {
|
||||||
|
info!("trade");
|
||||||
|
for a in selected_accounts.iter_mut() {
|
||||||
|
let mut account = a; // why is this necessary?
|
||||||
|
|
||||||
if let Some(trade_matches) = matches.subcommand_matches("trade") {
|
info!("Checking for trade confirmations");
|
||||||
info!("trade");
|
let confirmations: Vec<Confirmation>;
|
||||||
for a in selected_accounts.iter_mut() {
|
loop {
|
||||||
let mut account = a; // why is this necessary?
|
match account.get_trade_confirmations() {
|
||||||
|
Ok(confs) => {
|
||||||
|
confirmations = confs;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
info!("failed to get trade confirmations, asking user to log in");
|
||||||
|
do_login(&mut account);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
info!("Checking for trade confirmations");
|
if trade_matches.is_present("accept-all") {
|
||||||
let confirmations: Vec<Confirmation>;
|
info!("accepting all confirmations");
|
||||||
loop {
|
for conf in &confirmations {
|
||||||
match account.get_trade_confirmations() {
|
let result = account.accept_confirmation(conf);
|
||||||
Ok(confs) => {
|
debug!("accept confirmation result: {:?}", result);
|
||||||
confirmations = confs;
|
}
|
||||||
break;
|
} else {
|
||||||
}
|
if termion::is_tty(&stdout()) {
|
||||||
Err(_) => {
|
let (accept, deny) = prompt_confirmation_menu(confirmations);
|
||||||
info!("failed to get trade confirmations, asking user to log in");
|
for conf in &accept {
|
||||||
do_login(&mut account);
|
let result = account.accept_confirmation(conf);
|
||||||
}
|
debug!("accept confirmation result: {:?}", result);
|
||||||
}
|
}
|
||||||
}
|
for conf in &deny {
|
||||||
|
let result = account.deny_confirmation(conf);
|
||||||
if trade_matches.is_present("accept-all") {
|
debug!("deny confirmation result: {:?}", result);
|
||||||
info!("accepting all confirmations");
|
}
|
||||||
for conf in &confirmations {
|
} else {
|
||||||
let result = account.accept_confirmation(conf);
|
warn!("not a tty, not showing menu");
|
||||||
debug!("accept confirmation result: {:?}", result);
|
for conf in &confirmations {
|
||||||
}
|
println!("{}", conf.description());
|
||||||
}
|
}
|
||||||
else {
|
}
|
||||||
if termion::is_tty(&stdout()) {
|
}
|
||||||
let (accept, deny) = prompt_confirmation_menu(confirmations);
|
}
|
||||||
for conf in &accept {
|
} else {
|
||||||
let result = account.accept_confirmation(conf);
|
let server_time = steamapi::get_server_time();
|
||||||
debug!("accept confirmation result: {:?}", result);
|
for account in selected_accounts {
|
||||||
}
|
trace!("{:?}", account);
|
||||||
for conf in &deny {
|
let code = account.generate_code(server_time);
|
||||||
let result = account.deny_confirmation(conf);
|
println!("{}", code);
|
||||||
debug!("deny confirmation result: {:?}", result);
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
else {
|
|
||||||
warn!("not a tty, not showing menu");
|
|
||||||
for conf in &confirmations {
|
|
||||||
println!("{}", conf.description());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
let server_time = steamapi::get_server_time();
|
|
||||||
for account in selected_accounts {
|
|
||||||
trace!("{:?}", account);
|
|
||||||
let code = account.generate_code(server_time);
|
|
||||||
println!("{}", code);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn validate_captcha_text(text: &String) -> bool {
|
fn validate_captcha_text(text: &String) -> bool {
|
||||||
return CAPTCHA_VALID_CHARS.is_match(text);
|
return CAPTCHA_VALID_CHARS.is_match(text);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_validate_captcha_text() {
|
fn test_validate_captcha_text() {
|
||||||
assert!(validate_captcha_text(&String::from("2WWUA@")));
|
assert!(validate_captcha_text(&String::from("2WWUA@")));
|
||||||
assert!(validate_captcha_text(&String::from("3G8HT2")));
|
assert!(validate_captcha_text(&String::from("3G8HT2")));
|
||||||
assert!(validate_captcha_text(&String::from("3J%@X3")));
|
assert!(validate_captcha_text(&String::from("3J%@X3")));
|
||||||
assert!(validate_captcha_text(&String::from("2GCZ4A")));
|
assert!(validate_captcha_text(&String::from("2GCZ4A")));
|
||||||
assert!(validate_captcha_text(&String::from("3G8HT2")));
|
assert!(validate_captcha_text(&String::from("3G8HT2")));
|
||||||
assert!(!validate_captcha_text(&String::from("asd823")));
|
assert!(!validate_captcha_text(&String::from("asd823")));
|
||||||
assert!(!validate_captcha_text(&String::from("!PQ4RD")));
|
assert!(!validate_captcha_text(&String::from("!PQ4RD")));
|
||||||
assert!(!validate_captcha_text(&String::from("1GQ4XZ")));
|
assert!(!validate_captcha_text(&String::from("1GQ4XZ")));
|
||||||
assert!(!validate_captcha_text(&String::from("8GO4XZ")));
|
assert!(!validate_captcha_text(&String::from("8GO4XZ")));
|
||||||
assert!(!validate_captcha_text(&String::from("IPQ4RD")));
|
assert!(!validate_captcha_text(&String::from("IPQ4RD")));
|
||||||
assert!(!validate_captcha_text(&String::from("0PT4RD")));
|
assert!(!validate_captcha_text(&String::from("0PT4RD")));
|
||||||
assert!(!validate_captcha_text(&String::from("APTSRD")));
|
assert!(!validate_captcha_text(&String::from("APTSRD")));
|
||||||
assert!(!validate_captcha_text(&String::from("AP5TRD")));
|
assert!(!validate_captcha_text(&String::from("AP5TRD")));
|
||||||
assert!(!validate_captcha_text(&String::from("AP6TRD")));
|
assert!(!validate_captcha_text(&String::from("AP6TRD")));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Prompt the user for text input.
|
/// Prompt the user for text input.
|
||||||
fn prompt() -> String {
|
fn prompt() -> String {
|
||||||
let mut text = String::new();
|
let mut text = String::new();
|
||||||
let _ = std::io::stdout().flush();
|
let _ = std::io::stdout().flush();
|
||||||
stdin().read_line(&mut text).expect("Did not enter a correct string");
|
stdin()
|
||||||
return String::from(text.strip_suffix('\n').unwrap());
|
.read_line(&mut text)
|
||||||
|
.expect("Did not enter a correct string");
|
||||||
|
return String::from(text.strip_suffix('\n').unwrap());
|
||||||
}
|
}
|
||||||
|
|
||||||
fn prompt_captcha_text(captcha_gid: &String) -> String {
|
fn prompt_captcha_text(captcha_gid: &String) -> String {
|
||||||
println!("Captcha required. Open this link in your web browser: https://steamcommunity.com/public/captcha.php?gid={}", captcha_gid);
|
println!("Captcha required. Open this link in your web browser: https://steamcommunity.com/public/captcha.php?gid={}", captcha_gid);
|
||||||
let mut captcha_text;
|
let mut captcha_text;
|
||||||
loop {
|
loop {
|
||||||
print!("Enter captcha text: ");
|
print!("Enter captcha text: ");
|
||||||
captcha_text = prompt();
|
captcha_text = prompt();
|
||||||
if captcha_text.len() > 0 && validate_captcha_text(&captcha_text) {
|
if captcha_text.len() > 0 && validate_captcha_text(&captcha_text) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
warn!("Invalid chars for captcha text found in user's input. Prompting again...");
|
warn!("Invalid chars for captcha text found in user's input. Prompting again...");
|
||||||
}
|
}
|
||||||
return captcha_text;
|
return captcha_text;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns a tuple of (accepted, denied). Ignored confirmations are not included.
|
/// Returns a tuple of (accepted, denied). Ignored confirmations are not included.
|
||||||
fn prompt_confirmation_menu(confirmations: Vec<Confirmation>) -> (Vec<Confirmation>, Vec<Confirmation>) {
|
fn prompt_confirmation_menu(
|
||||||
println!("press a key other than enter to show the menu.");
|
confirmations: Vec<Confirmation>,
|
||||||
let mut to_accept_idx: HashSet<usize> = HashSet::new();
|
) -> (Vec<Confirmation>, Vec<Confirmation>) {
|
||||||
let mut to_deny_idx: HashSet<usize> = HashSet::new();
|
println!("press a key other than enter to show the menu.");
|
||||||
|
let mut to_accept_idx: HashSet<usize> = HashSet::new();
|
||||||
|
let mut to_deny_idx: HashSet<usize> = HashSet::new();
|
||||||
|
|
||||||
let mut screen = AlternateScreen::from(stdout().into_raw_mode().unwrap());
|
let mut screen = AlternateScreen::from(stdout().into_raw_mode().unwrap());
|
||||||
let stdin = stdin();
|
let stdin = stdin();
|
||||||
|
|
||||||
let mut selected_idx = 0;
|
let mut selected_idx = 0;
|
||||||
|
|
||||||
for c in stdin.events() {
|
for c in stdin.events() {
|
||||||
match c.expect("could not get events") {
|
match c.expect("could not get events") {
|
||||||
Event::Key(Key::Char('a')) => {
|
Event::Key(Key::Char('a')) => {
|
||||||
to_accept_idx.insert(selected_idx);
|
to_accept_idx.insert(selected_idx);
|
||||||
to_deny_idx.remove(&selected_idx);
|
to_deny_idx.remove(&selected_idx);
|
||||||
}
|
}
|
||||||
Event::Key(Key::Char('d')) => {
|
Event::Key(Key::Char('d')) => {
|
||||||
to_accept_idx.remove(&selected_idx);
|
to_accept_idx.remove(&selected_idx);
|
||||||
to_deny_idx.insert(selected_idx);
|
to_deny_idx.insert(selected_idx);
|
||||||
}
|
}
|
||||||
Event::Key(Key::Char('i')) => {
|
Event::Key(Key::Char('i')) => {
|
||||||
to_accept_idx.remove(&selected_idx);
|
to_accept_idx.remove(&selected_idx);
|
||||||
to_deny_idx.remove(&selected_idx);
|
to_deny_idx.remove(&selected_idx);
|
||||||
}
|
}
|
||||||
Event::Key(Key::Char('A')) => {
|
Event::Key(Key::Char('A')) => {
|
||||||
(0..confirmations.len()).for_each(|i| { to_accept_idx.insert(i); to_deny_idx.remove(&i); });
|
(0..confirmations.len()).for_each(|i| {
|
||||||
}
|
to_accept_idx.insert(i);
|
||||||
Event::Key(Key::Char('D')) => {
|
to_deny_idx.remove(&i);
|
||||||
(0..confirmations.len()).for_each(|i| { to_accept_idx.remove(&i); to_deny_idx.insert(i); });
|
});
|
||||||
}
|
}
|
||||||
Event::Key(Key::Char('I')) => {
|
Event::Key(Key::Char('D')) => {
|
||||||
(0..confirmations.len()).for_each(|i| { to_accept_idx.remove(&i); to_deny_idx.remove(&i); });
|
(0..confirmations.len()).for_each(|i| {
|
||||||
}
|
to_accept_idx.remove(&i);
|
||||||
Event::Key(Key::Up) if selected_idx > 0 => {
|
to_deny_idx.insert(i);
|
||||||
selected_idx -= 1;
|
});
|
||||||
}
|
}
|
||||||
Event::Key(Key::Down) if selected_idx < confirmations.len() - 1 => {
|
Event::Key(Key::Char('I')) => {
|
||||||
selected_idx += 1;
|
(0..confirmations.len()).for_each(|i| {
|
||||||
}
|
to_accept_idx.remove(&i);
|
||||||
Event::Key(Key::Char('\n')) => {
|
to_deny_idx.remove(&i);
|
||||||
break;
|
});
|
||||||
}
|
}
|
||||||
Event::Key(Key::Esc) | Event::Key(Key::Ctrl('c')) => {
|
Event::Key(Key::Up) if selected_idx > 0 => {
|
||||||
return (vec![], vec![]);
|
selected_idx -= 1;
|
||||||
}
|
}
|
||||||
_ => {}
|
Event::Key(Key::Down) if selected_idx < confirmations.len() - 1 => {
|
||||||
}
|
selected_idx += 1;
|
||||||
|
}
|
||||||
|
Event::Key(Key::Char('\n')) => {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
Event::Key(Key::Esc) | Event::Key(Key::Ctrl('c')) => {
|
||||||
|
return (vec![], vec![]);
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
|
||||||
write!(screen, "{}{}{}arrow keys to select, [a]ccept, [d]eny, [i]gnore, [enter] confirm choices\n\n", termion::clear::All, termion::cursor::Goto(1, 1), termion::color::Fg(termion::color::White)).unwrap();
|
write!(
|
||||||
for i in 0..confirmations.len() {
|
screen,
|
||||||
if selected_idx == i {
|
"{}{}{}arrow keys to select, [a]ccept, [d]eny, [i]gnore, [enter] confirm choices\n\n",
|
||||||
write!(screen, "\r{} >", termion::color::Fg(termion::color::LightYellow)).unwrap();
|
termion::clear::All,
|
||||||
}
|
termion::cursor::Goto(1, 1),
|
||||||
else {
|
termion::color::Fg(termion::color::White)
|
||||||
write!(screen, "\r{} ", termion::color::Fg(termion::color::White)).unwrap();
|
)
|
||||||
}
|
.unwrap();
|
||||||
|
for i in 0..confirmations.len() {
|
||||||
|
if selected_idx == i {
|
||||||
|
write!(
|
||||||
|
screen,
|
||||||
|
"\r{} >",
|
||||||
|
termion::color::Fg(termion::color::LightYellow)
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
} else {
|
||||||
|
write!(screen, "\r{} ", termion::color::Fg(termion::color::White)).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
if to_accept_idx.contains(&i) {
|
if to_accept_idx.contains(&i) {
|
||||||
write!(screen, "{}[a]", termion::color::Fg(termion::color::LightGreen)).unwrap();
|
write!(
|
||||||
}
|
screen,
|
||||||
else if to_deny_idx.contains(&i) {
|
"{}[a]",
|
||||||
write!(screen, "{}[d]", termion::color::Fg(termion::color::LightRed)).unwrap();
|
termion::color::Fg(termion::color::LightGreen)
|
||||||
}
|
)
|
||||||
else {
|
.unwrap();
|
||||||
write!(screen, "[ ]").unwrap();
|
} else if to_deny_idx.contains(&i) {
|
||||||
}
|
write!(
|
||||||
|
screen,
|
||||||
|
"{}[d]",
|
||||||
|
termion::color::Fg(termion::color::LightRed)
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
} else {
|
||||||
|
write!(screen, "[ ]").unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
if selected_idx == i {
|
if selected_idx == i {
|
||||||
write!(screen, "{}", termion::color::Fg(termion::color::LightYellow)).unwrap();
|
write!(
|
||||||
}
|
screen,
|
||||||
|
"{}",
|
||||||
|
termion::color::Fg(termion::color::LightYellow)
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
write!(screen, " {}\n", confirmations[i].description()).unwrap();
|
write!(screen, " {}\n", confirmations[i].description()).unwrap();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
to_accept_idx.iter().map(|i| confirmations[*i]).collect(),
|
to_accept_idx.iter().map(|i| confirmations[*i]).collect(),
|
||||||
to_deny_idx.iter().map(|i| confirmations[*i]).collect(),
|
to_deny_idx.iter().map(|i| confirmations[*i]).collect(),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn do_login(account: &mut SteamGuardAccount) {
|
fn do_login(account: &mut SteamGuardAccount) {
|
||||||
if account.account_name.len() > 0 {
|
if account.account_name.len() > 0 {
|
||||||
println!("Username: {}", account.account_name);
|
println!("Username: {}", account.account_name);
|
||||||
} else {
|
} else {
|
||||||
print!("Username: ");
|
print!("Username: ");
|
||||||
account.account_name = prompt();
|
account.account_name = prompt();
|
||||||
}
|
}
|
||||||
let _ = std::io::stdout().flush();
|
let _ = std::io::stdout().flush();
|
||||||
let password = rpassword::prompt_password_stdout("Password: ").unwrap();
|
let password = rpassword::prompt_password_stdout("Password: ").unwrap();
|
||||||
if password.len() > 0 {
|
if password.len() > 0 {
|
||||||
debug!("password is present");
|
debug!("password is present");
|
||||||
} else {
|
} else {
|
||||||
debug!("password is empty");
|
debug!("password is empty");
|
||||||
}
|
}
|
||||||
// TODO: reprompt if password is empty
|
// TODO: reprompt if password is empty
|
||||||
let mut login = steamapi::UserLogin::new(account.account_name.clone(), password);
|
let mut login = steamapi::UserLogin::new(account.account_name.clone(), password);
|
||||||
let mut loops = 0;
|
let mut loops = 0;
|
||||||
loop {
|
loop {
|
||||||
match login.login() {
|
match login.login() {
|
||||||
Ok(s) => {
|
Ok(s) => {
|
||||||
account.session = Option::Some(s);
|
account.session = Option::Some(s);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
Err(steamapi::LoginError::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);
|
||||||
}
|
}
|
||||||
Err(steamapi::LoginError::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);
|
||||||
}
|
}
|
||||||
Err(steamapi::LoginError::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();
|
||||||
}
|
}
|
||||||
r => {
|
r => {
|
||||||
error!("Fatal login result: {:?}", r);
|
error!("Fatal login result: {:?}", r);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
loops += 1;
|
loops += 1;
|
||||||
if loops > 2 {
|
if loops > 2 {
|
||||||
error!("Too many loops. Aborting login process, to avoid getting rate limited.");
|
error!("Too many loops. Aborting login process, to avoid getting rate limited.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn demo_confirmation_menu() {
|
fn demo_confirmation_menu() {
|
||||||
info!("showing demo menu");
|
info!("showing demo menu");
|
||||||
let (accept, deny) = prompt_confirmation_menu(vec![
|
let (accept, deny) = prompt_confirmation_menu(vec![
|
||||||
Confirmation {
|
Confirmation {
|
||||||
id: 1234,
|
id: 1234,
|
||||||
key: 12345,
|
key: 12345,
|
||||||
conf_type: ConfirmationType::Trade,
|
conf_type: ConfirmationType::Trade,
|
||||||
creator: 09870987,
|
creator: 09870987,
|
||||||
},
|
},
|
||||||
Confirmation {
|
Confirmation {
|
||||||
id: 1234,
|
id: 1234,
|
||||||
key: 12345,
|
key: 12345,
|
||||||
conf_type: ConfirmationType::MarketSell,
|
conf_type: ConfirmationType::MarketSell,
|
||||||
creator: 09870987,
|
creator: 09870987,
|
||||||
},
|
},
|
||||||
Confirmation {
|
Confirmation {
|
||||||
id: 1234,
|
id: 1234,
|
||||||
key: 12345,
|
key: 12345,
|
||||||
conf_type: ConfirmationType::AccountRecovery,
|
conf_type: ConfirmationType::AccountRecovery,
|
||||||
creator: 09870987,
|
creator: 09870987,
|
||||||
},
|
},
|
||||||
Confirmation {
|
Confirmation {
|
||||||
id: 1234,
|
id: 1234,
|
||||||
key: 12345,
|
key: 12345,
|
||||||
conf_type: ConfirmationType::Trade,
|
conf_type: ConfirmationType::Trade,
|
||||||
creator: 09870987,
|
creator: 09870987,
|
||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
println!("accept: {}, deny: {}", accept.len(), deny.len());
|
println!("accept: {}, deny: {}", accept.len(), deny.len());
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,37 +1,37 @@
|
||||||
/// A mobile confirmation. There are multiple things that can be confirmed, like trade offers.
|
/// A mobile confirmation. There are multiple things that can be confirmed, like trade offers.
|
||||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||||
pub struct Confirmation {
|
pub struct Confirmation {
|
||||||
pub id: u64,
|
pub id: u64,
|
||||||
pub key: u64,
|
pub key: u64,
|
||||||
/// Trade offer ID or market transaction ID
|
/// Trade offer ID or market transaction ID
|
||||||
pub creator: u64,
|
pub creator: u64,
|
||||||
pub conf_type: ConfirmationType,
|
pub conf_type: ConfirmationType,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Confirmation {
|
impl Confirmation {
|
||||||
/// Human readable representation of this confirmation.
|
/// Human readable representation of this confirmation.
|
||||||
pub fn description(&self) -> String {
|
pub fn description(&self) -> String {
|
||||||
format!("{:?} id={} key={}", self.conf_type, self.id, self.key)
|
format!("{:?} id={} key={}", self.conf_type, self.id, self.key)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub enum ConfirmationType {
|
pub enum ConfirmationType {
|
||||||
Generic = 1,
|
Generic = 1,
|
||||||
Trade = 2,
|
Trade = 2,
|
||||||
MarketSell = 3,
|
MarketSell = 3,
|
||||||
AccountRecovery = 6,
|
AccountRecovery = 6,
|
||||||
Unknown
|
Unknown,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<&str> for ConfirmationType {
|
impl From<&str> for ConfirmationType {
|
||||||
fn from(text: &str) -> Self {
|
fn from(text: &str) -> Self {
|
||||||
match text {
|
match text {
|
||||||
"1" => ConfirmationType::Generic,
|
"1" => ConfirmationType::Generic,
|
||||||
"2" => ConfirmationType::Trade,
|
"2" => ConfirmationType::Trade,
|
||||||
"3" => ConfirmationType::MarketSell,
|
"3" => ConfirmationType::MarketSell,
|
||||||
"6" => ConfirmationType::AccountRecovery,
|
"6" => ConfirmationType::AccountRecovery,
|
||||||
_ => ConfirmationType::Unknown,
|
_ => ConfirmationType::Unknown,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,18 +1,22 @@
|
||||||
use std::{collections::HashMap, convert::TryInto, thread, time};
|
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
pub use confirmation::{Confirmation, ConfirmationType};
|
pub use confirmation::{Confirmation, ConfirmationType};
|
||||||
use hmacsha1::hmac_sha1;
|
use hmacsha1::hmac_sha1;
|
||||||
use reqwest::{Url, cookie::CookieStore, header::{COOKIE, USER_AGENT}};
|
|
||||||
use serde::{Serialize, Deserialize};
|
|
||||||
use log::*;
|
use log::*;
|
||||||
|
use reqwest::{
|
||||||
|
cookie::CookieStore,
|
||||||
|
header::{COOKIE, USER_AGENT},
|
||||||
|
Url,
|
||||||
|
};
|
||||||
use scraper::{Html, Selector};
|
use scraper::{Html, Selector};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::{collections::HashMap, convert::TryInto, thread, time};
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate lazy_static;
|
extern crate lazy_static;
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate anyhow;
|
extern crate anyhow;
|
||||||
|
|
||||||
pub mod steamapi;
|
|
||||||
mod confirmation;
|
mod confirmation;
|
||||||
|
pub mod steamapi;
|
||||||
|
|
||||||
// const STEAMAPI_BASE: String = "https://api.steampowered.com";
|
// const STEAMAPI_BASE: String = "https://api.steampowered.com";
|
||||||
// const COMMUNITY_BASE: String = "https://steamcommunity.com";
|
// const COMMUNITY_BASE: String = "https://steamcommunity.com";
|
||||||
|
@ -21,125 +25,134 @@ mod confirmation;
|
||||||
// const TWO_FACTOR_BASE: String = STEAMAPI_BASE + "/ITwoFactorService/%s/v0001";
|
// const TWO_FACTOR_BASE: String = STEAMAPI_BASE + "/ITwoFactorService/%s/v0001";
|
||||||
// static TWO_FACTOR_TIME_QUERY: String = TWO_FACTOR_BASE.Replace("%s", "QueryTime");
|
// static TWO_FACTOR_TIME_QUERY: String = TWO_FACTOR_BASE.Replace("%s", "QueryTime");
|
||||||
|
|
||||||
extern crate hmacsha1;
|
|
||||||
extern crate base64;
|
extern crate base64;
|
||||||
extern crate cookie;
|
extern crate cookie;
|
||||||
|
extern crate hmacsha1;
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct SteamGuardAccount {
|
pub struct SteamGuardAccount {
|
||||||
pub account_name: String,
|
pub account_name: String,
|
||||||
pub serial_number: String,
|
pub serial_number: String,
|
||||||
pub revocation_code: String,
|
pub revocation_code: String,
|
||||||
pub shared_secret: String,
|
pub shared_secret: String,
|
||||||
pub token_gid: String,
|
pub token_gid: String,
|
||||||
pub identity_secret: String,
|
pub identity_secret: String,
|
||||||
pub server_time: u64,
|
pub server_time: u64,
|
||||||
pub uri: String,
|
pub uri: String,
|
||||||
pub fully_enrolled: bool,
|
pub fully_enrolled: bool,
|
||||||
pub device_id: String,
|
pub device_id: String,
|
||||||
#[serde(rename = "Session")]
|
#[serde(rename = "Session")]
|
||||||
pub session: Option<steamapi::Session>,
|
pub session: Option<steamapi::Session>,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn build_time_bytes(time: i64) -> [u8; 8] {
|
fn build_time_bytes(time: i64) -> [u8; 8] {
|
||||||
return time.to_be_bytes();
|
return time.to_be_bytes();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn parse_shared_secret(secret: String) -> anyhow::Result<[u8; 20]> {
|
pub fn parse_shared_secret(secret: String) -> anyhow::Result<[u8; 20]> {
|
||||||
ensure!(secret.len() != 0, "unable to parse empty shared secret");
|
ensure!(secret.len() != 0, "unable to parse empty shared secret");
|
||||||
let result = base64::decode(secret)?.try_into();
|
let result = base64::decode(secret)?.try_into();
|
||||||
return Ok(result.unwrap());
|
return Ok(result.unwrap());
|
||||||
}
|
}
|
||||||
|
|
||||||
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 {
|
||||||
let decode: &[u8] = &base64::decode(&identity_secret).unwrap();
|
let decode: &[u8] = &base64::decode(&identity_secret).unwrap();
|
||||||
let time_bytes = build_time_bytes(time);
|
let time_bytes = build_time_bytes(time);
|
||||||
let tag_bytes = tag.as_bytes();
|
let tag_bytes = tag.as_bytes();
|
||||||
let array = [&time_bytes, tag_bytes].concat();
|
let array = [&time_bytes, tag_bytes].concat();
|
||||||
let hash = hmac_sha1(decode, &array);
|
let hash = hmac_sha1(decode, &array);
|
||||||
let encoded = base64::encode(hash);
|
let encoded = base64::encode(hash);
|
||||||
return encoded;
|
return encoded;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SteamGuardAccount {
|
impl SteamGuardAccount {
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
return SteamGuardAccount{
|
return SteamGuardAccount {
|
||||||
account_name: String::from(""),
|
account_name: String::from(""),
|
||||||
serial_number: String::from(""),
|
serial_number: String::from(""),
|
||||||
revocation_code: String::from(""),
|
revocation_code: String::from(""),
|
||||||
shared_secret: String::from(""),
|
shared_secret: String::from(""),
|
||||||
token_gid: String::from(""),
|
token_gid: String::from(""),
|
||||||
identity_secret: String::from(""),
|
identity_secret: String::from(""),
|
||||||
server_time: 0,
|
server_time: 0,
|
||||||
uri: String::from(""),
|
uri: String::from(""),
|
||||||
fully_enrolled: false,
|
fully_enrolled: false,
|
||||||
device_id: String::from(""),
|
device_id: String::from(""),
|
||||||
session: Option::None,
|
session: Option::None,
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
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.
|
// 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()).unwrap();
|
let shared_secret: [u8; 20] = parse_shared_secret(self.shared_secret.clone()).unwrap();
|
||||||
let hashed_data = hmacsha1::hmac_sha1(&shared_secret, &time_bytes);
|
let hashed_data = hmacsha1::hmac_sha1(&shared_secret, &time_bytes);
|
||||||
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 = ((hashed_data[b] & 0x7F) as i32) << 24
|
||||||
((hashed_data[b] & 0x7F) as i32) << 24 |
|
| ((hashed_data[b + 1] & 0xFF) as i32) << 16
|
||||||
((hashed_data[b + 1] & 0xFF) as i32) << 16 |
|
| ((hashed_data[b + 2] & 0xFF) as i32) << 8
|
||||||
((hashed_data[b + 2] & 0xFF) as i32) << 8 |
|
| ((hashed_data[b + 3] & 0xFF) as i32);
|
||||||
((hashed_data[b + 3] & 0xFF) as i32);
|
|
||||||
|
|
||||||
for i in 0..5 {
|
for i in 0..5 {
|
||||||
code_array[i] = steam_guard_code_translations[code_point as usize % steam_guard_code_translations.len()];
|
code_array[i] = steam_guard_code_translations
|
||||||
code_point /= steam_guard_code_translations.len() as i32;
|
[code_point as usize % steam_guard_code_translations.len()];
|
||||||
}
|
code_point /= steam_guard_code_translations.len() as i32;
|
||||||
|
}
|
||||||
|
|
||||||
return String::from_utf8(code_array.iter().map(|c| *c).collect()).unwrap()
|
return String::from_utf8(code_array.iter().map(|c| *c).collect()).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_confirmation_query_params(&self, tag: &str) -> HashMap<&str, String> {
|
fn get_confirmation_query_params(&self, tag: &str) -> HashMap<&str, String> {
|
||||||
let session = self.session.clone().unwrap();
|
let session = self.session.clone().unwrap();
|
||||||
let time = steamapi::get_server_time();
|
let time = steamapi::get_server_time();
|
||||||
let mut params = HashMap::new();
|
let mut params = HashMap::new();
|
||||||
params.insert("p", self.device_id.clone());
|
params.insert("p", self.device_id.clone());
|
||||||
params.insert("a", session.steam_id.to_string());
|
params.insert("a", session.steam_id.to_string());
|
||||||
params.insert("k", generate_confirmation_hash_for_time(time, tag, &self.identity_secret));
|
params.insert(
|
||||||
params.insert("t", time.to_string());
|
"k",
|
||||||
params.insert("m", String::from("android"));
|
generate_confirmation_hash_for_time(time, tag, &self.identity_secret),
|
||||||
params.insert("tag", String::from(tag));
|
);
|
||||||
return params;
|
params.insert("t", time.to_string());
|
||||||
}
|
params.insert("m", String::from("android"));
|
||||||
|
params.insert("tag", String::from(tag));
|
||||||
|
return params;
|
||||||
|
}
|
||||||
|
|
||||||
fn build_cookie_jar(&self) -> reqwest::cookie::Jar {
|
fn build_cookie_jar(&self) -> reqwest::cookie::Jar {
|
||||||
let url = "https://steamcommunity.com".parse::<Url>().unwrap();
|
let url = "https://steamcommunity.com".parse::<Url>().unwrap();
|
||||||
let cookies = reqwest::cookie::Jar::default();
|
let cookies = reqwest::cookie::Jar::default();
|
||||||
let session = self.session.clone().unwrap();
|
let session = self.session.clone().unwrap();
|
||||||
let session_id = session.session_id;
|
let session_id = session.session_id;
|
||||||
cookies.add_cookie_str("mobileClientVersion=0 (2.1.3)", &url);
|
cookies.add_cookie_str("mobileClientVersion=0 (2.1.3)", &url);
|
||||||
cookies.add_cookie_str("mobileClient=android", &url);
|
cookies.add_cookie_str("mobileClient=android", &url);
|
||||||
cookies.add_cookie_str("Steam_Language=english", &url);
|
cookies.add_cookie_str("Steam_Language=english", &url);
|
||||||
cookies.add_cookie_str("dob=", &url);
|
cookies.add_cookie_str("dob=", &url);
|
||||||
cookies.add_cookie_str(format!("sessionid={}", session_id).as_str(), &url);
|
cookies.add_cookie_str(format!("sessionid={}", session_id).as_str(), &url);
|
||||||
cookies.add_cookie_str(format!("steamid={}", session.steam_id).as_str(), &url);
|
cookies.add_cookie_str(format!("steamid={}", session.steam_id).as_str(), &url);
|
||||||
cookies.add_cookie_str(format!("steamLogin={}", session.steam_login).as_str(), &url);
|
cookies.add_cookie_str(format!("steamLogin={}", session.steam_login).as_str(), &url);
|
||||||
cookies.add_cookie_str(format!("steamLoginSecure={}", session.steam_login_secure).as_str(), &url);
|
cookies.add_cookie_str(
|
||||||
return cookies;
|
format!("steamLoginSecure={}", session.steam_login_secure).as_str(),
|
||||||
}
|
&url,
|
||||||
|
);
|
||||||
|
return cookies;
|
||||||
|
}
|
||||||
|
|
||||||
pub fn get_trade_confirmations(&self) -> Result<Vec<Confirmation>, anyhow::Error> {
|
pub fn get_trade_confirmations(&self) -> Result<Vec<Confirmation>, anyhow::Error> {
|
||||||
// uri: "https://steamcommunity.com/mobileconf/conf"
|
// uri: "https://steamcommunity.com/mobileconf/conf"
|
||||||
// confirmation details:
|
// confirmation details:
|
||||||
let url = "https://steamcommunity.com".parse::<Url>().unwrap();
|
let url = "https://steamcommunity.com".parse::<Url>().unwrap();
|
||||||
let cookies = self.build_cookie_jar();
|
let cookies = self.build_cookie_jar();
|
||||||
let client = reqwest::blocking::ClientBuilder::new()
|
let client = reqwest::blocking::ClientBuilder::new()
|
||||||
.cookie_store(true)
|
.cookie_store(true)
|
||||||
.build()?;
|
.build()?;
|
||||||
|
|
||||||
let resp = client
|
let resp = client
|
||||||
.get("https://steamcommunity.com/mobileconf/conf".parse::<Url>().unwrap())
|
.get("https://steamcommunity.com/mobileconf/conf".parse::<Url>().unwrap())
|
||||||
.header("X-Requested-With", "com.valvesoftware.android.steam.community")
|
.header("X-Requested-With", "com.valvesoftware.android.steam.community")
|
||||||
.header(USER_AGENT, "Mozilla/5.0 (Linux; U; Android 4.1.1; en-us; Google Nexus 4 - 4.1.1 - API 16 - 768x1280 Build/JRO03S) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30")
|
.header(USER_AGENT, "Mozilla/5.0 (Linux; U; Android 4.1.1; en-us; Google Nexus 4 - 4.1.1 - API 16 - 768x1280 Build/JRO03S) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30")
|
||||||
|
@ -147,37 +160,37 @@ impl SteamGuardAccount {
|
||||||
.query(&self.get_confirmation_query_params("conf"))
|
.query(&self.get_confirmation_query_params("conf"))
|
||||||
.send()?;
|
.send()?;
|
||||||
|
|
||||||
trace!("{:?}", resp);
|
trace!("{:?}", resp);
|
||||||
let text = resp.text().unwrap();
|
let text = resp.text().unwrap();
|
||||||
trace!("text: {:?}", text);
|
trace!("text: {:?}", text);
|
||||||
println!("{}", text);
|
println!("{}", text);
|
||||||
return parse_confirmations(text);
|
return parse_confirmations(text);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Respond to a confirmation.
|
/// Respond to a confirmation.
|
||||||
///
|
///
|
||||||
/// Host: https://steamcommunity.com
|
/// Host: https://steamcommunity.com
|
||||||
/// Steam Endpoint: `GET /mobileconf/ajaxop`
|
/// Steam Endpoint: `GET /mobileconf/ajaxop`
|
||||||
fn send_confirmation_ajax(&self, conf: &Confirmation, operation: String) -> anyhow::Result<()> {
|
fn send_confirmation_ajax(&self, conf: &Confirmation, operation: String) -> anyhow::Result<()> {
|
||||||
ensure!(operation == "allow" || operation == "cancel");
|
ensure!(operation == "allow" || operation == "cancel");
|
||||||
|
|
||||||
let url = "https://steamcommunity.com".parse::<Url>().unwrap();
|
let url = "https://steamcommunity.com".parse::<Url>().unwrap();
|
||||||
let cookies = self.build_cookie_jar();
|
let cookies = self.build_cookie_jar();
|
||||||
let client = reqwest::blocking::ClientBuilder::new()
|
let client = reqwest::blocking::ClientBuilder::new()
|
||||||
.cookie_store(true)
|
.cookie_store(true)
|
||||||
.build()?;
|
.build()?;
|
||||||
|
|
||||||
let mut query_params = self.get_confirmation_query_params("conf");
|
let mut query_params = self.get_confirmation_query_params("conf");
|
||||||
query_params.insert("op", operation);
|
query_params.insert("op", operation);
|
||||||
query_params.insert("cid", conf.id.to_string());
|
query_params.insert("cid", conf.id.to_string());
|
||||||
query_params.insert("ck", conf.key.to_string());
|
query_params.insert("ck", conf.key.to_string());
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, Deserialize)]
|
#[derive(Debug, Clone, Copy, Deserialize)]
|
||||||
struct SendConfirmationResponse {
|
struct SendConfirmationResponse {
|
||||||
pub success: bool
|
pub success: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
let resp: SendConfirmationResponse = client.get("https://steamcommunity.com/mobileconf/ajaxop".parse::<Url>().unwrap())
|
let resp: SendConfirmationResponse = client.get("https://steamcommunity.com/mobileconf/ajaxop".parse::<Url>().unwrap())
|
||||||
.header("X-Requested-With", "com.valvesoftware.android.steam.community")
|
.header("X-Requested-With", "com.valvesoftware.android.steam.community")
|
||||||
.header(USER_AGENT, "Mozilla/5.0 (Linux; U; Android 4.1.1; en-us; Google Nexus 4 - 4.1.1 - API 16 - 768x1280 Build/JRO03S) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30")
|
.header(USER_AGENT, "Mozilla/5.0 (Linux; U; Android 4.1.1; en-us; Google Nexus 4 - 4.1.1 - API 16 - 768x1280 Build/JRO03S) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30")
|
||||||
.header(COOKIE, cookies.cookies(&url).unwrap())
|
.header(COOKIE, cookies.cookies(&url).unwrap())
|
||||||
|
@ -185,35 +198,35 @@ impl SteamGuardAccount {
|
||||||
.send()?
|
.send()?
|
||||||
.json()?;
|
.json()?;
|
||||||
|
|
||||||
ensure!(resp.success);
|
ensure!(resp.success);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn accept_confirmation(&self, conf: &Confirmation) -> anyhow::Result<()> {
|
pub fn accept_confirmation(&self, conf: &Confirmation) -> anyhow::Result<()> {
|
||||||
self.send_confirmation_ajax(conf, "allow".into())
|
self.send_confirmation_ajax(conf, "allow".into())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deny_confirmation(&self, conf: &Confirmation) -> anyhow::Result<()> {
|
pub fn deny_confirmation(&self, conf: &Confirmation) -> anyhow::Result<()> {
|
||||||
self.send_confirmation_ajax(conf, "cancel".into())
|
self.send_confirmation_ajax(conf, "cancel".into())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Steam Endpoint: `GET /mobileconf/details/:id`
|
/// Steam Endpoint: `GET /mobileconf/details/:id`
|
||||||
pub fn get_confirmation_details(&self, conf: &Confirmation) -> anyhow::Result<String> {
|
pub fn get_confirmation_details(&self, conf: &Confirmation) -> anyhow::Result<String> {
|
||||||
#[derive(Debug, Clone, Deserialize)]
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
struct ConfirmationDetailsResponse {
|
struct ConfirmationDetailsResponse {
|
||||||
pub success: bool,
|
pub success: bool,
|
||||||
pub html: String,
|
pub html: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
let url = "https://steamcommunity.com".parse::<Url>().unwrap();
|
let url = "https://steamcommunity.com".parse::<Url>().unwrap();
|
||||||
let cookies = self.build_cookie_jar();
|
let cookies = self.build_cookie_jar();
|
||||||
let client = reqwest::blocking::ClientBuilder::new()
|
let client = reqwest::blocking::ClientBuilder::new()
|
||||||
.cookie_store(true)
|
.cookie_store(true)
|
||||||
.build()?;
|
.build()?;
|
||||||
|
|
||||||
let query_params = self.get_confirmation_query_params("details");
|
let query_params = self.get_confirmation_query_params("details");
|
||||||
|
|
||||||
let resp: ConfirmationDetailsResponse = client.get(format!("https://steamcommunity.com/mobileconf/details/{}", conf.id).parse::<Url>().unwrap())
|
let resp: ConfirmationDetailsResponse = client.get(format!("https://steamcommunity.com/mobileconf/details/{}", conf.id).parse::<Url>().unwrap())
|
||||||
.header("X-Requested-With", "com.valvesoftware.android.steam.community")
|
.header("X-Requested-With", "com.valvesoftware.android.steam.community")
|
||||||
.header(USER_AGENT, "Mozilla/5.0 (Linux; U; Android 4.1.1; en-us; Google Nexus 4 - 4.1.1 - API 16 - 768x1280 Build/JRO03S) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30")
|
.header(USER_AGENT, "Mozilla/5.0 (Linux; U; Android 4.1.1; en-us; Google Nexus 4 - 4.1.1 - API 16 - 768x1280 Build/JRO03S) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30")
|
||||||
.header(COOKIE, cookies.cookies(&url).unwrap())
|
.header(COOKIE, cookies.cookies(&url).unwrap())
|
||||||
|
@ -221,94 +234,125 @@ impl SteamGuardAccount {
|
||||||
.send()?
|
.send()?
|
||||||
.json()?;
|
.json()?;
|
||||||
|
|
||||||
ensure!(resp.success);
|
ensure!(resp.success);
|
||||||
Ok(resp.html)
|
Ok(resp.html)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn parse_confirmations(text: String) -> anyhow::Result<Vec<Confirmation>> {
|
fn parse_confirmations(text: String) -> anyhow::Result<Vec<Confirmation>> {
|
||||||
// possible errors:
|
// possible errors:
|
||||||
//
|
//
|
||||||
// Invalid authenticator:
|
// Invalid authenticator:
|
||||||
// <div>Invalid authenticator</div>
|
// <div>Invalid authenticator</div>
|
||||||
// <div>It looks like your Steam Guard Mobile Authenticator is providing incorrect Steam Guard codes. This could be caused by an inaccurate clock or bad timezone settings on your device. If your time settings are correct, it could be that a different device has been set up to provide the Steam Guard codes for your account, which means the authenticator on this device is no longer valid.</div>
|
// <div>It looks like your Steam Guard Mobile Authenticator is providing incorrect Steam Guard codes. This could be caused by an inaccurate clock or bad timezone settings on your device. If your time settings are correct, it could be that a different device has been set up to provide the Steam Guard codes for your account, which means the authenticator on this device is no longer valid.</div>
|
||||||
//
|
//
|
||||||
// <div>Nothing to confirm</div>
|
// <div>Nothing to confirm</div>
|
||||||
|
|
||||||
let fragment = Html::parse_fragment(&text);
|
let fragment = Html::parse_fragment(&text);
|
||||||
let selector = Selector::parse(".mobileconf_list_entry").unwrap();
|
let selector = Selector::parse(".mobileconf_list_entry").unwrap();
|
||||||
let mut confirmations = vec![];
|
let mut confirmations = vec![];
|
||||||
for elem in fragment.select(&selector) {
|
for elem in fragment.select(&selector) {
|
||||||
let conf = Confirmation {
|
let conf = Confirmation {
|
||||||
id: elem.value().attr("data-confid").unwrap().parse()?,
|
id: elem.value().attr("data-confid").unwrap().parse()?,
|
||||||
key: elem.value().attr("data-key").unwrap().parse()?,
|
key: elem.value().attr("data-key").unwrap().parse()?,
|
||||||
conf_type: elem.value().attr("data-type").unwrap().try_into().unwrap_or(ConfirmationType::Unknown),
|
conf_type: elem
|
||||||
creator: elem.value().attr("data-creator").unwrap().parse()?,
|
.value()
|
||||||
};
|
.attr("data-type")
|
||||||
confirmations.push(conf);
|
.unwrap()
|
||||||
}
|
.try_into()
|
||||||
return Ok(confirmations);
|
.unwrap_or(ConfirmationType::Unknown),
|
||||||
|
creator: elem.value().attr("data-creator").unwrap().parse()?,
|
||||||
|
};
|
||||||
|
confirmations.push(conf);
|
||||||
|
}
|
||||||
|
return Ok(confirmations);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_build_time_bytes() {
|
fn test_build_time_bytes() {
|
||||||
let t1 = build_time_bytes(1617591917i64);
|
let t1 = build_time_bytes(1617591917i64);
|
||||||
let t2: [u8; 8] = [0, 0, 0, 0, 96, 106, 126, 109];
|
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);
|
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();
|
||||||
account.shared_secret = String::from("zvIayp3JPvtvX/QGHqsqKBk/44s=");
|
account.shared_secret = String::from("zvIayp3JPvtvX/QGHqsqKBk/44s=");
|
||||||
|
|
||||||
let code = account.generate_code(1616374841i64);
|
let code = account.generate_code(1616374841i64);
|
||||||
assert_eq!(code, "2F9J5")
|
assert_eq!(code, "2F9J5")
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_generate_confirmation_hash_for_time() {
|
fn test_generate_confirmation_hash_for_time() {
|
||||||
assert_eq!(generate_confirmation_hash_for_time(1617591917, "conf", &String::from("GQP46b73Ws7gr8GmZFR0sDuau5c=")), String::from("NaL8EIMhfy/7vBounJ0CvpKbrPk="));
|
assert_eq!(
|
||||||
}
|
generate_confirmation_hash_for_time(
|
||||||
|
1617591917,
|
||||||
|
"conf",
|
||||||
|
&String::from("GQP46b73Ws7gr8GmZFR0sDuau5c=")
|
||||||
|
),
|
||||||
|
String::from("NaL8EIMhfy/7vBounJ0CvpKbrPk=")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_parse_multiple_confirmations() {
|
fn test_parse_multiple_confirmations() {
|
||||||
let text = include_str!("fixtures/confirmations/multiple-confirmations.html");
|
let text = include_str!("fixtures/confirmations/multiple-confirmations.html");
|
||||||
let confirmations = parse_confirmations(text.into()).unwrap();
|
let confirmations = parse_confirmations(text.into()).unwrap();
|
||||||
assert_eq!(confirmations.len(), 5);
|
assert_eq!(confirmations.len(), 5);
|
||||||
assert_eq!(confirmations[0], Confirmation {
|
assert_eq!(
|
||||||
id: 9890792058,
|
confirmations[0],
|
||||||
key: 15509106087034649470,
|
Confirmation {
|
||||||
conf_type: ConfirmationType::MarketSell,
|
id: 9890792058,
|
||||||
creator: 3392884950693131245,
|
key: 15509106087034649470,
|
||||||
});
|
conf_type: ConfirmationType::MarketSell,
|
||||||
assert_eq!(confirmations[1], Confirmation {
|
creator: 3392884950693131245,
|
||||||
id: 9890791666,
|
}
|
||||||
key: 2661901169510258722,
|
);
|
||||||
conf_type: ConfirmationType::MarketSell,
|
assert_eq!(
|
||||||
creator: 3392884950693130525,
|
confirmations[1],
|
||||||
});
|
Confirmation {
|
||||||
assert_eq!(confirmations[2], Confirmation {
|
id: 9890791666,
|
||||||
id: 9890791241,
|
key: 2661901169510258722,
|
||||||
key: 15784514761287735229,
|
conf_type: ConfirmationType::MarketSell,
|
||||||
conf_type: ConfirmationType::MarketSell,
|
creator: 3392884950693130525,
|
||||||
creator: 3392884950693129565,
|
}
|
||||||
});
|
);
|
||||||
assert_eq!(confirmations[3], Confirmation {
|
assert_eq!(
|
||||||
id: 9890790828,
|
confirmations[2],
|
||||||
key: 5049250785011653560,
|
Confirmation {
|
||||||
conf_type: ConfirmationType::MarketSell,
|
id: 9890791241,
|
||||||
creator: 3392884950693128685,
|
key: 15784514761287735229,
|
||||||
});
|
conf_type: ConfirmationType::MarketSell,
|
||||||
assert_eq!(confirmations[4], Confirmation {
|
creator: 3392884950693129565,
|
||||||
id: 9890790159,
|
}
|
||||||
key: 6133112455066694993,
|
);
|
||||||
conf_type: ConfirmationType::MarketSell,
|
assert_eq!(
|
||||||
creator: 3392884950693127345,
|
confirmations[3],
|
||||||
});
|
Confirmation {
|
||||||
}
|
id: 9890790828,
|
||||||
|
key: 5049250785011653560,
|
||||||
|
conf_type: ConfirmationType::MarketSell,
|
||||||
|
creator: 3392884950693128685,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
confirmations[4],
|
||||||
|
Confirmation {
|
||||||
|
id: 9890790159,
|
||||||
|
key: 6133112455066694993,
|
||||||
|
conf_type: ConfirmationType::MarketSell,
|
||||||
|
creator: 3392884950693127345,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,103 +1,109 @@
|
||||||
use std::collections::HashMap;
|
|
||||||
use reqwest::{Url, cookie::{CookieStore}, header::COOKIE, header::{SET_COOKIE, USER_AGENT}};
|
|
||||||
use rsa::{PublicKey, RsaPublicKey};
|
|
||||||
use std::time::{SystemTime, UNIX_EPOCH};
|
|
||||||
use serde::{Serialize, Deserialize};
|
|
||||||
use log::*;
|
use log::*;
|
||||||
|
use reqwest::{
|
||||||
|
cookie::CookieStore,
|
||||||
|
header::COOKIE,
|
||||||
|
header::{SET_COOKIE, USER_AGENT},
|
||||||
|
Url,
|
||||||
|
};
|
||||||
|
use rsa::{PublicKey, RsaPublicKey};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize)]
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
struct LoginResponse {
|
struct LoginResponse {
|
||||||
success: bool,
|
success: bool,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
login_complete: bool,
|
login_complete: bool,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
captcha_needed: bool,
|
captcha_needed: bool,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
captcha_gid: String,
|
captcha_gid: String,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
emailsteamid: u64,
|
emailsteamid: u64,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
emailauth_needed: bool,
|
emailauth_needed: bool,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
requires_twofactor: bool,
|
requires_twofactor: bool,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
message: String,
|
message: String,
|
||||||
transfer_urls: Option<Vec<String>>,
|
transfer_urls: Option<Vec<String>>,
|
||||||
transfer_parameters: Option<LoginTransferParameters>,
|
transfer_parameters: Option<LoginTransferParameters>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
struct LoginTransferParameters {
|
struct LoginTransferParameters {
|
||||||
steamid: String,
|
steamid: String,
|
||||||
token_secure: String,
|
token_secure: String,
|
||||||
auth: String,
|
auth: String,
|
||||||
remember_login: bool,
|
remember_login: bool,
|
||||||
webcookie: String,
|
webcookie: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize)]
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
struct RsaResponse {
|
struct RsaResponse {
|
||||||
success: bool,
|
success: bool,
|
||||||
publickey_exp: String,
|
publickey_exp: String,
|
||||||
publickey_mod: String,
|
publickey_mod: String,
|
||||||
timestamp: String,
|
timestamp: String,
|
||||||
token_gid: String,
|
token_gid: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum LoginError {
|
pub enum LoginError {
|
||||||
BadRSA,
|
BadRSA,
|
||||||
BadCredentials,
|
BadCredentials,
|
||||||
NeedCaptcha{ captcha_gid: String },
|
NeedCaptcha { captcha_gid: String },
|
||||||
Need2FA,
|
Need2FA,
|
||||||
NeedEmail,
|
NeedEmail,
|
||||||
TooManyAttempts,
|
TooManyAttempts,
|
||||||
OtherFailure,
|
OtherFailure,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct UserLogin {
|
pub struct UserLogin {
|
||||||
pub username: String,
|
pub username: String,
|
||||||
pub password: String,
|
pub password: String,
|
||||||
pub captcha_required: bool,
|
pub captcha_required: bool,
|
||||||
pub captcha_gid: String,
|
pub captcha_gid: String,
|
||||||
pub captcha_text: String,
|
pub captcha_text: String,
|
||||||
pub twofactor_code: String,
|
pub twofactor_code: String,
|
||||||
pub email_code: String,
|
pub email_code: String,
|
||||||
pub steam_id: u64,
|
pub steam_id: u64,
|
||||||
|
|
||||||
cookies: reqwest::cookie::Jar,
|
cookies: reqwest::cookie::Jar,
|
||||||
client: reqwest::blocking::Client,
|
client: reqwest::blocking::Client,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl UserLogin {
|
impl UserLogin {
|
||||||
pub fn new(username: String, password: String) -> UserLogin {
|
pub fn new(username: String, password: String) -> UserLogin {
|
||||||
return UserLogin {
|
return UserLogin {
|
||||||
username,
|
username,
|
||||||
password,
|
password,
|
||||||
captcha_required: false,
|
captcha_required: false,
|
||||||
captcha_gid: String::from("-1"),
|
captcha_gid: String::from("-1"),
|
||||||
captcha_text: String::from(""),
|
captcha_text: String::from(""),
|
||||||
twofactor_code: String::from(""),
|
twofactor_code: String::from(""),
|
||||||
email_code: String::from(""),
|
email_code: String::from(""),
|
||||||
steam_id: 0,
|
steam_id: 0,
|
||||||
cookies: reqwest::cookie::Jar::default(),
|
cookies: reqwest::cookie::Jar::default(),
|
||||||
client: reqwest::blocking::ClientBuilder::new()
|
client: reqwest::blocking::ClientBuilder::new()
|
||||||
.cookie_store(true)
|
.cookie_store(true)
|
||||||
.build()
|
.build()
|
||||||
.unwrap(),
|
.unwrap(),
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Updates the cookie jar with the session cookies by pinging steam servers.
|
/// 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();
|
||||||
self.cookies.add_cookie_str("mobileClientVersion=0 (2.1.3)", &url);
|
self.cookies
|
||||||
self.cookies.add_cookie_str("mobileClient=android", &url);
|
.add_cookie_str("mobileClientVersion=0 (2.1.3)", &url);
|
||||||
self.cookies.add_cookie_str("Steam_Language=english", &url);
|
self.cookies.add_cookie_str("mobileClient=android", &url);
|
||||||
|
self.cookies.add_cookie_str("Steam_Language=english", &url);
|
||||||
|
|
||||||
let resp = self.client
|
let resp = self.client
|
||||||
.get("https://steamcommunity.com/login?oauth_client_id=DE45CD61&oauth_scope=read_profile%20write_profile%20read_client%20write_client".parse::<Url>().unwrap())
|
.get("https://steamcommunity.com/login?oauth_client_id=DE45CD61&oauth_scope=read_profile%20write_profile%20read_client%20write_client".parse::<Url>().unwrap())
|
||||||
.header("X-Requested-With", "com.valvesoftware.android.steam.community")
|
.header("X-Requested-With", "com.valvesoftware.android.steam.community")
|
||||||
.header(USER_AGENT, "Mozilla/5.0 (Linux; U; Android 4.1.1; en-us; Google Nexus 4 - 4.1.1 - API 16 - 768x1280 Build/JRO03S) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30")
|
.header(USER_AGENT, "Mozilla/5.0 (Linux; U; Android 4.1.1; en-us; Google Nexus 4 - 4.1.1 - API 16 - 768x1280 Build/JRO03S) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30")
|
||||||
|
@ -106,252 +112,285 @@ impl UserLogin {
|
||||||
// .header(COOKIE, "Steam_Language=english")
|
// .header(COOKIE, "Steam_Language=english")
|
||||||
.header(COOKIE, self.cookies.cookies(&url).unwrap())
|
.header(COOKIE, self.cookies.cookies(&url).unwrap())
|
||||||
.send();
|
.send();
|
||||||
trace!("{:?}", resp);
|
trace!("{:?}", resp);
|
||||||
|
|
||||||
trace!("cookies: {:?}", self.cookies);
|
trace!("cookies: {:?}", self.cookies);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn login(&mut self) -> anyhow::Result<Session, LoginError> {
|
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 Err(LoginError::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();
|
||||||
if self.cookies.cookies(&url) == Option::None {
|
if self.cookies.cookies(&url) == Option::None {
|
||||||
self.update_session()
|
self.update_session()
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut params = HashMap::new();
|
let mut params = HashMap::new();
|
||||||
params.insert("donotcache", format!("{}", SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() * 1000));
|
params.insert(
|
||||||
params.insert("username", self.username.clone());
|
"donotcache",
|
||||||
let resp = self.client
|
format!(
|
||||||
.post("https://steamcommunity.com/login/getrsakey")
|
"{}",
|
||||||
.form(¶ms)
|
SystemTime::now()
|
||||||
.send()
|
.duration_since(UNIX_EPOCH)
|
||||||
.unwrap();
|
.unwrap()
|
||||||
|
.as_secs()
|
||||||
|
* 1000
|
||||||
|
),
|
||||||
|
);
|
||||||
|
params.insert("username", self.username.clone());
|
||||||
|
let resp = self
|
||||||
|
.client
|
||||||
|
.post("https://steamcommunity.com/login/getrsakey")
|
||||||
|
.form(¶ms)
|
||||||
|
.send()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
let encrypted_password: String;
|
let encrypted_password: String;
|
||||||
let rsa_timestamp: String;
|
let rsa_timestamp: String;
|
||||||
match resp.json::<RsaResponse>() {
|
match resp.json::<RsaResponse>() {
|
||||||
Ok(rsa_resp) => {
|
Ok(rsa_resp) => {
|
||||||
rsa_timestamp = rsa_resp.timestamp.clone();
|
rsa_timestamp = rsa_resp.timestamp.clone();
|
||||||
encrypted_password = encrypt_password(rsa_resp, &self.password);
|
encrypted_password = encrypt_password(rsa_resp, &self.password);
|
||||||
}
|
}
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
error!("rsa error: {:?}", error);
|
error!("rsa error: {:?}", error);
|
||||||
return Err(LoginError::BadRSA);
|
return Err(LoginError::BadRSA);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
trace!("captchagid: {}", self.captcha_gid);
|
trace!("captchagid: {}", self.captcha_gid);
|
||||||
trace!("captcha_text: {}", self.captcha_text);
|
trace!("captcha_text: {}", self.captcha_text);
|
||||||
trace!("twofactorcode: {}", self.twofactor_code);
|
trace!("twofactorcode: {}", self.twofactor_code);
|
||||||
trace!("emailauth: {}", self.email_code);
|
trace!("emailauth: {}", self.email_code);
|
||||||
let mut params = HashMap::new();
|
let mut params = HashMap::new();
|
||||||
params.insert("donotcache", format!("{}", SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() * 1000));
|
params.insert(
|
||||||
params.insert("username", self.username.clone());
|
"donotcache",
|
||||||
params.insert("password", encrypted_password);
|
format!(
|
||||||
params.insert("twofactorcode", self.twofactor_code.clone());
|
"{}",
|
||||||
params.insert("emailauth", self.email_code.clone());
|
SystemTime::now()
|
||||||
params.insert("captchagid", self.captcha_gid.clone());
|
.duration_since(UNIX_EPOCH)
|
||||||
params.insert("captcha_text", self.captcha_text.clone());
|
.unwrap()
|
||||||
params.insert("rsatimestamp", rsa_timestamp);
|
.as_secs()
|
||||||
params.insert("remember_login", String::from("true"));
|
* 1000
|
||||||
params.insert("oauth_client_id", String::from("DE45CD61"));
|
),
|
||||||
params.insert("oauth_scope", String::from("read_profile write_profile read_client write_client"));
|
);
|
||||||
|
params.insert("username", self.username.clone());
|
||||||
|
params.insert("password", encrypted_password);
|
||||||
|
params.insert("twofactorcode", self.twofactor_code.clone());
|
||||||
|
params.insert("emailauth", self.email_code.clone());
|
||||||
|
params.insert("captchagid", self.captcha_gid.clone());
|
||||||
|
params.insert("captcha_text", self.captcha_text.clone());
|
||||||
|
params.insert("rsatimestamp", rsa_timestamp);
|
||||||
|
params.insert("remember_login", String::from("true"));
|
||||||
|
params.insert("oauth_client_id", String::from("DE45CD61"));
|
||||||
|
params.insert(
|
||||||
|
"oauth_scope",
|
||||||
|
String::from("read_profile write_profile read_client write_client"),
|
||||||
|
);
|
||||||
|
|
||||||
let login_resp: LoginResponse;
|
let login_resp: LoginResponse;
|
||||||
match self.client
|
match self
|
||||||
.post("https://steamcommunity.com/login/dologin")
|
.client
|
||||||
.form(¶ms)
|
.post("https://steamcommunity.com/login/dologin")
|
||||||
.send() {
|
.form(¶ms)
|
||||||
Ok(resp) => {
|
.send()
|
||||||
// https://stackoverflow.com/questions/49928648/rubys-mechanize-error-401-while-sending-a-post-request-steam-trade-offer-send
|
{
|
||||||
let text = resp.text().unwrap();
|
Ok(resp) => {
|
||||||
trace!("resp content: {}", text);
|
// https://stackoverflow.com/questions/49928648/rubys-mechanize-error-401-while-sending-a-post-request-steam-trade-offer-send
|
||||||
match serde_json::from_str(text.as_str()) {
|
let text = resp.text().unwrap();
|
||||||
Ok(lr) => {
|
trace!("resp content: {}", text);
|
||||||
info!("login resp: {:?}", lr);
|
match serde_json::from_str(text.as_str()) {
|
||||||
login_resp = lr;
|
Ok(lr) => {
|
||||||
}
|
info!("login resp: {:?}", lr);
|
||||||
Err(error) => {
|
login_resp = lr;
|
||||||
debug!("login response did not have normal schema");
|
}
|
||||||
error!("login parse error: {:?}", error);
|
Err(error) => {
|
||||||
return Err(LoginError::OtherFailure);
|
debug!("login response did not have normal schema");
|
||||||
}
|
error!("login parse error: {:?}", error);
|
||||||
}
|
return Err(LoginError::OtherFailure);
|
||||||
}
|
}
|
||||||
Err(error) => {
|
}
|
||||||
error!("login request error: {:?}", error);
|
}
|
||||||
return Err(LoginError::OtherFailure);
|
Err(error) => {
|
||||||
}
|
error!("login request error: {:?}", error);
|
||||||
}
|
return Err(LoginError::OtherFailure);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if login_resp.message.contains("too many login") {
|
if login_resp.message.contains("too many login") {
|
||||||
return Err(LoginError::TooManyAttempts);
|
return Err(LoginError::TooManyAttempts);
|
||||||
}
|
}
|
||||||
|
|
||||||
if login_resp.message.contains("Incorrect login") {
|
if login_resp.message.contains("Incorrect login") {
|
||||||
return Err(LoginError::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 Err(LoginError::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 Err(LoginError::NeedEmail);
|
return Err(LoginError::NeedEmail);
|
||||||
}
|
}
|
||||||
|
|
||||||
if login_resp.requires_twofactor {
|
if login_resp.requires_twofactor {
|
||||||
return Err(LoginError::Need2FA);
|
return Err(LoginError::Need2FA);
|
||||||
}
|
}
|
||||||
|
|
||||||
if !login_resp.login_complete {
|
if !login_resp.login_complete {
|
||||||
return Err(LoginError::BadCredentials);
|
return Err(LoginError::BadCredentials);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// transfer login parameters? Not completely sure what this is for.
|
||||||
|
// i guess steam changed their authentication scheme slightly
|
||||||
|
let oauth;
|
||||||
|
match (login_resp.transfer_urls, login_resp.transfer_parameters) {
|
||||||
|
(Some(urls), Some(params)) => {
|
||||||
|
debug!("received transfer parameters, relaying data...");
|
||||||
|
for url in urls {
|
||||||
|
trace!("posting transfer to {}", url);
|
||||||
|
let result = self.client.post(url).json(¶ms).send();
|
||||||
|
trace!("result: {:?}", result);
|
||||||
|
match result {
|
||||||
|
Ok(resp) => {
|
||||||
|
debug!("result status: {}", resp.status());
|
||||||
|
self.save_cookies_from_response(&resp);
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
error!("failed to transfer parameters: {:?}", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// transfer login parameters? Not completely sure what this is for.
|
oauth = OAuthData {
|
||||||
// i guess steam changed their authentication scheme slightly
|
oauth_token: params.auth,
|
||||||
let oauth;
|
steamid: params.steamid.parse().unwrap(),
|
||||||
match (login_resp.transfer_urls, login_resp.transfer_parameters) {
|
wgtoken: params.token_secure.clone(), // guessing
|
||||||
(Some(urls), Some(params)) => {
|
wgtoken_secure: params.token_secure,
|
||||||
debug!("received transfer parameters, relaying data...");
|
webcookie: params.webcookie,
|
||||||
for url in urls {
|
};
|
||||||
trace!("posting transfer to {}", url);
|
}
|
||||||
let result = self.client
|
_ => {
|
||||||
.post(url)
|
error!("did not receive transfer_urls and transfer_parameters");
|
||||||
.json(¶ms)
|
return Err(LoginError::OtherFailure);
|
||||||
.send();
|
}
|
||||||
trace!("result: {:?}", result);
|
}
|
||||||
match result {
|
|
||||||
Ok(resp) => {
|
|
||||||
debug!("result status: {}", resp.status());
|
|
||||||
self.save_cookies_from_response(&resp);
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
error!("failed to transfer parameters: {:?}", e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
oauth = OAuthData {
|
let url = "https://steamcommunity.com".parse::<Url>().unwrap();
|
||||||
oauth_token: params.auth,
|
let cookies = self.cookies.cookies(&url).unwrap();
|
||||||
steamid: params.steamid.parse().unwrap(),
|
let all_cookies = cookies.to_str().unwrap();
|
||||||
wgtoken: params.token_secure.clone(), // guessing
|
let mut session_id = String::from("");
|
||||||
wgtoken_secure: params.token_secure,
|
for cookie in all_cookies
|
||||||
webcookie: params.webcookie,
|
.split(";")
|
||||||
};
|
.map(|s| cookie::Cookie::parse(s).unwrap())
|
||||||
}
|
{
|
||||||
_ => {
|
if cookie.name() == "sessionid" {
|
||||||
error!("did not receive transfer_urls and transfer_parameters");
|
session_id = String::from(cookie.value());
|
||||||
return Err(LoginError::OtherFailure);
|
}
|
||||||
}
|
}
|
||||||
}
|
trace!("cookies {:?}", cookies);
|
||||||
|
let session = self.build_session(oauth, session_id);
|
||||||
|
|
||||||
let url = "https://steamcommunity.com".parse::<Url>().unwrap();
|
return Ok(session);
|
||||||
let cookies = self.cookies.cookies(&url).unwrap();
|
}
|
||||||
let all_cookies = cookies.to_str().unwrap();
|
|
||||||
let mut session_id = String::from("");
|
|
||||||
for cookie in all_cookies.split(";").map(|s| cookie::Cookie::parse(s).unwrap()) {
|
|
||||||
if cookie.name() == "sessionid" {
|
|
||||||
session_id = String::from(cookie.value());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
trace!("cookies {:?}", cookies);
|
|
||||||
let session = self.build_session(oauth, session_id);
|
|
||||||
|
|
||||||
return Ok(session);
|
fn build_session(&self, data: OAuthData, session_id: String) -> Session {
|
||||||
}
|
return Session {
|
||||||
|
token: data.oauth_token,
|
||||||
|
steam_id: data.steamid,
|
||||||
|
steam_login: format!("{}%7C%7C{}", data.steamid, data.wgtoken),
|
||||||
|
steam_login_secure: format!("{}%7C%7C{}", data.steamid, data.wgtoken_secure),
|
||||||
|
session_id: session_id,
|
||||||
|
web_cookie: data.webcookie,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
fn build_session(&self, data: OAuthData, session_id: String) -> Session {
|
fn save_cookies_from_response(&mut self, response: &reqwest::blocking::Response) {
|
||||||
return Session{
|
let set_cookie_iter = response.headers().get_all(SET_COOKIE);
|
||||||
token: data.oauth_token,
|
let url = "https://steamcommunity.com".parse::<Url>().unwrap();
|
||||||
steam_id: data.steamid,
|
|
||||||
steam_login: format!("{}%7C%7C{}", data.steamid, data.wgtoken),
|
|
||||||
steam_login_secure: format!("{}%7C%7C{}", data.steamid, data.wgtoken_secure),
|
|
||||||
session_id: session_id,
|
|
||||||
web_cookie: data.webcookie,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
fn save_cookies_from_response(&mut self, response: &reqwest::blocking::Response) {
|
for c in set_cookie_iter {
|
||||||
let set_cookie_iter = response.headers().get_all(SET_COOKIE);
|
c.to_str()
|
||||||
let url = "https://steamcommunity.com".parse::<Url>().unwrap();
|
.into_iter()
|
||||||
|
.for_each(|cookie_str| self.cookies.add_cookie_str(cookie_str, &url));
|
||||||
for c in set_cookie_iter {
|
}
|
||||||
c.to_str()
|
}
|
||||||
.into_iter()
|
|
||||||
.for_each(|cookie_str| {
|
|
||||||
self.cookies.add_cookie_str(cookie_str, &url)
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize)]
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
struct OAuthData {
|
struct OAuthData {
|
||||||
oauth_token: String,
|
oauth_token: String,
|
||||||
steamid: u64,
|
steamid: u64,
|
||||||
wgtoken: String,
|
wgtoken: String,
|
||||||
wgtoken_secure: String,
|
wgtoken_secure: String,
|
||||||
webcookie: String,
|
webcookie: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct Session {
|
pub struct Session {
|
||||||
#[serde(rename = "SessionID")]
|
#[serde(rename = "SessionID")]
|
||||||
pub session_id: String,
|
pub session_id: String,
|
||||||
#[serde(rename = "SteamLogin")]
|
#[serde(rename = "SteamLogin")]
|
||||||
pub steam_login: String,
|
pub steam_login: String,
|
||||||
#[serde(rename = "SteamLoginSecure")]
|
#[serde(rename = "SteamLoginSecure")]
|
||||||
pub steam_login_secure: String,
|
pub steam_login_secure: String,
|
||||||
#[serde(rename = "WebCookie")]
|
#[serde(rename = "WebCookie")]
|
||||||
pub web_cookie: String,
|
pub web_cookie: String,
|
||||||
#[serde(rename = "OAuthToken")]
|
#[serde(rename = "OAuthToken")]
|
||||||
pub token: String,
|
pub token: String,
|
||||||
#[serde(rename = "SteamID")]
|
#[serde(rename = "SteamID")]
|
||||||
pub steam_id: u64,
|
pub steam_id: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_server_time() -> i64 {
|
pub fn get_server_time() -> i64 {
|
||||||
let client = reqwest::blocking::Client::new();
|
let client = reqwest::blocking::Client::new();
|
||||||
let resp = client
|
let resp = client
|
||||||
.post("https://api.steampowered.com/ITwoFactorService/QueryTime/v0001")
|
.post("https://api.steampowered.com/ITwoFactorService/QueryTime/v0001")
|
||||||
.body("steamid=0")
|
.body("steamid=0")
|
||||||
.send();
|
.send();
|
||||||
let value: serde_json::Value = resp.unwrap().json().unwrap();
|
let value: serde_json::Value = resp.unwrap().json().unwrap();
|
||||||
|
|
||||||
return String::from(value["response"]["server_time"].as_str().unwrap()).parse().unwrap();
|
return String::from(value["response"]["server_time"].as_str().unwrap())
|
||||||
|
.parse()
|
||||||
|
.unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
fn encrypt_password(rsa_resp: RsaResponse, password: &String) -> String {
|
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();
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
let mut rng = rand::rngs::mock::StepRng::new(2, 1);
|
let mut rng = rand::rngs::mock::StepRng::new(2, 1);
|
||||||
#[cfg(not(test))]
|
#[cfg(not(test))]
|
||||||
let mut rng = rand::rngs::OsRng;
|
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(
|
||||||
return encrypted_password;
|
public_key
|
||||||
|
.encrypt(&mut rng, padding, password.as_bytes())
|
||||||
|
.unwrap(),
|
||||||
|
);
|
||||||
|
return encrypted_password;
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_encrypt_password() {
|
fn test_encrypt_password() {
|
||||||
let rsa_resp = RsaResponse{
|
let rsa_resp = RsaResponse{
|
||||||
success: true,
|
success: true,
|
||||||
publickey_exp: String::from("010001"),
|
publickey_exp: String::from("010001"),
|
||||||
publickey_mod: String::from("98f9088c1250b17fe19d2b2422d54a1eef0036875301731f11bd17900e215318eb6de1546727c0b7b61b86cefccdcb2f8108c813154d9a7d55631965eece810d4ab9d8a59c486bda778651b876176070598a93c2325c275cb9c17bdbcacf8edc9c18c0c5d59bc35703505ef8a09ed4c62b9f92a3fac5740ce25e490ab0e26d872140e4103d912d1e3958f844264211277ee08d2b4dd3ac58b030b25342bd5c949ae7794e46a8eab26d5a8deca683bfd381da6c305b19868b8c7cd321ce72c693310a6ebf2ecd43642518f825894602f6c239cf193cb4346ce64beac31e20ef88f934f2f776597734bb9eae1ebdf4a453973b6df9d5e90777bffe5db83dd1757b"),
|
publickey_mod: String::from("98f9088c1250b17fe19d2b2422d54a1eef0036875301731f11bd17900e215318eb6de1546727c0b7b61b86cefccdcb2f8108c813154d9a7d55631965eece810d4ab9d8a59c486bda778651b876176070598a93c2325c275cb9c17bdbcacf8edc9c18c0c5d59bc35703505ef8a09ed4c62b9f92a3fac5740ce25e490ab0e26d872140e4103d912d1e3958f844264211277ee08d2b4dd3ac58b030b25342bd5c949ae7794e46a8eab26d5a8deca683bfd381da6c305b19868b8c7cd321ce72c693310a6ebf2ecd43642518f825894602f6c239cf193cb4346ce64beac31e20ef88f934f2f776597734bb9eae1ebdf4a453973b6df9d5e90777bffe5db83dd1757b"),
|
||||||
timestamp: String::from("asdf"),
|
timestamp: String::from("asdf"),
|
||||||
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);
|
assert_eq!(result.len(), 344);
|
||||||
assert_eq!(result, "RUo/3IfbkVcJi1q1S5QlpKn1mEn3gNJoc/Z4VwxRV9DImV6veq/YISEuSrHB3885U5MYFLn1g94Y+cWRL6HGXoV+gOaVZe43m7O92RwiVz6OZQXMfAv3UC/jcqn/xkitnj+tNtmx55gCxmGbO2KbqQ0TQqAyqCOOw565B+Cwr2OOorpMZAViv9sKA/G3Q6yzscU6rhua179c8QjC1Hk3idUoSzpWfT4sHNBW/EREXZ3Dkjwu17xzpfwIUpnBVIlR8Vj3coHgUCpTsKVRA3T814v9BYPlvLYwmw5DW3ddx+2SyTY0P5uuog36TN2PqYS7ioF5eDe16gyfRR4Nzn/7wA==");
|
assert_eq!(result, "RUo/3IfbkVcJi1q1S5QlpKn1mEn3gNJoc/Z4VwxRV9DImV6veq/YISEuSrHB3885U5MYFLn1g94Y+cWRL6HGXoV+gOaVZe43m7O92RwiVz6OZQXMfAv3UC/jcqn/xkitnj+tNtmx55gCxmGbO2KbqQ0TQqAyqCOOw565B+Cwr2OOorpMZAViv9sKA/G3Q6yzscU6rhua179c8QjC1Hk3idUoSzpWfT4sHNBW/EREXZ3Dkjwu17xzpfwIUpnBVIlR8Vj3coHgUCpTsKVRA3T814v9BYPlvLYwmw5DW3ddx+2SyTY0P5uuog36TN2PqYS7ioF5eDe16gyfRR4Nzn/7wA==");
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue