// TODO: rename this module to auth use std::net; use rand::Rng; use bcrypt; use libpso::packet::login::*; use libpso::{PacketParseError, PSOPacket}; use libpso::crypto::bb::PSOBBCipher; use libpso::util::array_to_utf8; use crate::common::cipherkeys::{ELSEWHERE_PRIVATE_KEY, ELSEWHERE_PARRAY}; use crate::common::serverstate::{SendServerPacket, RecvServerPacket, ServerState, OnConnect, ClientId}; use crate::entity::gateway::EntityGateway; use crate::entity::account::UserAccount; pub const LOGIN_PORT: u16 = 12000; #[derive(Debug)] pub enum LoginError { } #[derive(Debug, PartialEq)] pub enum RecvLoginPacket { Login(Login), } impl RecvServerPacket for RecvLoginPacket { fn from_bytes(data: &[u8]) -> Result { match data[2] { 0x93 => Ok(RecvLoginPacket::Login(Login::from_bytes(data)?)), _ => Err(PacketParseError::WrongPacketForServerType(u16::from_le_bytes([data[2], data[3]]), data.to_vec())) } } } #[derive(Debug, PartialEq)] pub enum SendLoginPacket { LoginResponse(LoginResponse), LoginWelcome(LoginWelcome), RedirectClient(RedirectClient), } impl SendServerPacket for SendLoginPacket { fn as_bytes(&self) -> Vec { match self { SendLoginPacket::LoginResponse(pkt) => pkt.as_bytes(), SendLoginPacket::LoginWelcome(pkt) => pkt.as_bytes(), SendLoginPacket::RedirectClient(pkt) => pkt.as_bytes(), } } } pub fn get_login_status(entity_gateway: &impl EntityGateway, pkt: &Login) -> Result { let username = array_to_utf8(pkt.username).map_err(|_err| AccountStatus::Error)?; let password = array_to_utf8(pkt.password).map_err(|_err| AccountStatus::Error)?; let user = entity_gateway.get_user_by_name(username).ok_or(AccountStatus::InvalidUser)?; let verified = bcrypt::verify(password, user.password.as_str()).map_err(|_err| AccountStatus::Error)?; match verified { true => if user.banned { Err(AccountStatus::Banned) } else { Ok(user) }, false => Err(AccountStatus::InvalidPassword) } } pub struct LoginServerState { entity_gateway: EG, } impl LoginServerState { pub fn new(entity_gateway: EG) -> LoginServerState { LoginServerState { entity_gateway: entity_gateway, } } fn validate_login(&mut self, pkt: &Login) -> Vec { match get_login_status(&self.entity_gateway, pkt) { Ok(_user) => { let response = SendLoginPacket::LoginResponse(LoginResponse::by_status(AccountStatus::Ok, pkt.session)); let ip = net::Ipv4Addr::new(127,0,0,1); let ip = u32::from_ne_bytes(ip.octets()); vec![response, SendLoginPacket::RedirectClient(RedirectClient::new(ip, crate::login::character::CHARACTER_PORT))] }, Err(err) => { vec![SendLoginPacket::LoginResponse(LoginResponse::by_status(err, pkt.session))] } } } } impl ServerState for LoginServerState { type SendPacket = SendLoginPacket; type RecvPacket = RecvLoginPacket; type PacketError = LoginError; fn on_connect(&mut self, _id: ClientId) -> Vec> { let mut rng = rand::thread_rng(); let mut server_key = [0u8; 48]; let mut client_key = [0u8; 48]; rng.fill(&mut server_key[..]); rng.fill(&mut client_key[..]); vec![OnConnect::Packet(SendLoginPacket::LoginWelcome(LoginWelcome::new(server_key, client_key))), OnConnect::Cipher((Box::new(PSOBBCipher::new(ELSEWHERE_PARRAY, ELSEWHERE_PRIVATE_KEY, client_key)), Box::new(PSOBBCipher::new(ELSEWHERE_PARRAY, ELSEWHERE_PRIVATE_KEY, server_key)))) ] } fn handle(&mut self, id: ClientId, pkt: &Self::RecvPacket) -> Result + Send>, LoginError> { Ok(match pkt { RecvLoginPacket::Login(login) => { Box::new(self.validate_login(login) .into_iter() .map(move |pkt| { (id, pkt) })) } }) } fn on_disconnect(&mut self, id: ClientId) -> Vec<(ClientId, SendLoginPacket)> { Vec::new() } } #[cfg(test)] mod test { use std::time::SystemTime; use super::*; const LOGIN_PACKET: RecvLoginPacket = RecvLoginPacket::Login(Login { tag: 65536, guildcard: 0, version: 65, unknown1: [0, 0, 0, 255, 0, 14], team: 0, username: [116, 101, 115, 116, 117, 115, 101, 114, 0, 0, 0, 0, 0, 0, 0, 0], // utf8_to_array!("testuser", 16), unknown2: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], password: [109, 121, 112, 97, 115, 115, 119, 111, 114, 100, 0, 0, 0, 0, 0, 0], // utf8_to_array!("mypassword", 16), unknown3: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], hwinfo: [129, 1, 1, 1, 1, 1, 1, 1], session: Session { version: [69, 108, 115, 101, 119, 97, 114, 101, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // utf8_to_array!("Elseware", 30), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], session_id: 0, interserver_checksum: 0, action: SessionAction::None, character_slot: 0, } }); #[test] fn test_correct_login() { struct TestData { } impl EntityGateway for TestData { fn get_user_by_name(&self, name: String) -> Option { assert!(name == "testuser"); Some(UserAccount { id: 1, username: "testuser".to_owned(), password: bcrypt::hash("mypassword", 5).unwrap(), guildcard: 0, team_id: None, banned: false, muted_until: SystemTime::now(), created_at: SystemTime::now(), flags: 0, }) } } let mut server = LoginServerState::new(TestData {}); let send = server.handle(ClientId(1), &LOGIN_PACKET).unwrap().collect::>(); assert!(send == vec![ (ClientId(1), SendLoginPacket::LoginResponse(LoginResponse { status: AccountStatus::Ok, tag: 65536, guildcard: 0, team_id: 0, session: Session { version: [69, 108, 115, 101, 119, 97, 114, 101, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // utf8_to_array!("Elseware", 30), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], session_id: 0, interserver_checksum: 0, action: SessionAction::None, character_slot: 0, }, caps: 258 })), (ClientId(1), SendLoginPacket::RedirectClient(RedirectClient { ip: 16777343, port: 12001, padding: 0, }))]) } #[test] fn test_login_bad_username() { struct TestData { } impl EntityGateway for TestData { fn get_user_by_name(&self, _name: String) -> Option { None } } let mut server = LoginServerState::new(TestData {}); let send = server.handle(ClientId(1), &LOGIN_PACKET).unwrap().collect::>(); assert!(send == vec![ (ClientId(1), SendLoginPacket::LoginResponse(LoginResponse { status: AccountStatus::InvalidUser, tag: 65536, guildcard: 0, team_id: 0, session: Session { version: [69, 108, 115, 101, 119, 97, 114, 101, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // utf8_to_array!("Elseware", 30), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], session_id: 0, interserver_checksum: 0, action: SessionAction::None, character_slot: 0, }, caps: 258 }))]) } #[test] fn test_login_bad_password() { struct TestData { } impl EntityGateway for TestData { fn get_user_by_name(&self, name: String) -> Option { assert!(name == "testuser"); Some(UserAccount { id: 1, username: "testuser".to_owned(), password: bcrypt::hash("notpassword", 5).unwrap(), guildcard: 0, team_id: None, banned: false, muted_until: SystemTime::now(), created_at: SystemTime::now(), flags: 0, }) } } let mut server = LoginServerState::new(TestData {}); let send = server.handle(ClientId(1), &LOGIN_PACKET).unwrap().collect::>(); assert!(send == vec![ (ClientId(1), SendLoginPacket::LoginResponse(LoginResponse { status: AccountStatus::InvalidPassword, tag: 65536, guildcard: 0, team_id: 0, session: Session { version: [69, 108, 115, 101, 119, 97, 114, 101, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // utf8_to_array!("Elseware", 30), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], session_id: 0, interserver_checksum: 0, action: SessionAction::None, character_slot: 0, }, caps: 258 }))]) } #[test] fn test_banned_user() { struct TestData { } impl EntityGateway for TestData { fn get_user_by_name(&self, name: String) -> Option { assert!(name == "testuser"); Some(UserAccount { id: 1, username: "testuser".to_owned(), password: bcrypt::hash("mypassword", 5).unwrap(), guildcard: 0, team_id: None, banned: true, muted_until: SystemTime::now(), created_at: SystemTime::now(), flags: 0, }) } } let mut server = LoginServerState::new(TestData {}); let send = server.handle(ClientId(1), &LOGIN_PACKET).unwrap().collect::>(); assert!(send == vec![ (ClientId(1), SendLoginPacket::LoginResponse(LoginResponse { status: AccountStatus::Banned, tag: 65536, guildcard: 0, team_id: 0, session: Session { version: [69, 108, 115, 101, 119, 97, 114, 101, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // utf8_to_array!("Elseware", 30), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], session_id: 0, interserver_checksum: 0, action: SessionAction::None, character_slot: 0, }, caps: 258 }))]) } }