// TODO: rename this module to auth use std::collections::HashMap; 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::{UserAccountEntity}; pub const LOGIN_PORT: u16 = 12000; pub const COMMUNICATION_PORT: u16 = 12123; #[derive(thiserror::Error, Debug)] #[error("")] pub enum LoginError { DbError } #[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(), } } } // TODO: MORE impl EntityGateway? pub async fn get_login_status(entity_gateway: &mut 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).await.map_err(|_| AccountStatus::InvalidUser)?; if !user.activated { return Err(AccountStatus::PayUp) } let verified = bcrypt::verify(password, user.password.as_str()).map_err(|_err| AccountStatus::Error)?; match verified { true => if user.banned_until.map(|banned| banned > chrono::Utc::now()).unwrap_or(false) { Err(AccountStatus::Banned) } else { Ok(user) }, false => Err(AccountStatus::InvalidPassword) } } pub fn check_if_already_online(user: UserAccountEntity) -> Result { Ok(user) /* if user.is_currently_online() { Err(AccountStatus::PayUp) } else { Ok(user) } */ } #[derive(Clone)] pub struct LoginServerState { character_server_ip: net::Ipv4Addr, entity_gateway: EG, clients: HashMap, } impl LoginServerState { pub fn new(entity_gateway: EG, character_server_ip: net::Ipv4Addr) -> LoginServerState { LoginServerState { entity_gateway, character_server_ip, clients: HashMap::new(), } } async fn validate_login(&mut self, id: ClientId, pkt: &Login) -> Result, anyhow::Error> { match get_login_status(&mut self.entity_gateway, pkt).await.and_then(check_if_already_online) { Ok(mut user) => { user.at_login = true; self.entity_gateway.save_user(&user).await.map_err(|_| LoginError::DbError)?; self.clients.insert(id, user.username.clone()); let response = SendLoginPacket::LoginResponse(LoginResponse::by_status(AccountStatus::Ok, pkt.session)); let ip = u32::from_ne_bytes(self.character_server_ip.octets()); Ok(vec![response, SendLoginPacket::RedirectClient(RedirectClient::new(ip, crate::login::character::CHARACTER_PORT))]) }, Err(err) => { Ok(vec![SendLoginPacket::LoginResponse(LoginResponse::by_status(err, pkt.session))]) } } } } #[async_trait::async_trait] impl ServerState for LoginServerState { type SendPacket = SendLoginPacket; type RecvPacket = RecvLoginPacket; type Cipher = PSOBBCipher; //type PacketError = LoginError; type PacketError = anyhow::Error; async fn on_connect(&mut self, _id: ClientId) -> Result>, anyhow::Error> { 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[..]); Ok(vec![OnConnect::Packet(SendLoginPacket::LoginWelcome(LoginWelcome::new(server_key, client_key))), OnConnect::Cipher(PSOBBCipher::new(ELSEWHERE_PARRAY, ELSEWHERE_PRIVATE_KEY, client_key), PSOBBCipher::new(ELSEWHERE_PARRAY, ELSEWHERE_PRIVATE_KEY, server_key)) ]) } async fn handle(&mut self, id: ClientId, pkt: Self::RecvPacket) -> Result, anyhow::Error> { Ok(match pkt { RecvLoginPacket::Login(login) => { self.validate_login(id, &login).await? .into_iter() .map(move |pkt| { (id, pkt) }) .collect() } }) } async fn on_disconnect(&mut self, id: ClientId) -> Result, anyhow::Error> { if let Some(username) = self.clients.remove(&id) { if let Ok(mut user) = self.entity_gateway.get_user_by_name(username).await { user.at_login = false; self.entity_gateway.save_user(&user).await?; } } Ok(Vec::new()) } } #[cfg(test)] mod test { use super::*; use crate::entity::account::{UserAccountId}; use crate::entity::gateway::GatewayError; 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, } }); #[async_std::test] async fn test_correct_login() { #[derive(Clone)] struct TestData { } #[async_trait::async_trait] impl EntityGateway for TestData { async fn get_user_by_name(&mut self, name: String) -> Result { assert!(name == "testuser"); Ok(UserAccountEntity { id: UserAccountId(1), username: "testuser".to_owned(), password: bcrypt::hash("mypassword", 5).unwrap(), guildcard: 0, team_id: None, banned_until: None, muted_until: None, created_at: chrono::Utc::now(), flags: 0, activated: true, at_login: false, at_character: false, at_ship: false, }) } async fn save_user(&mut self, _user: &UserAccountEntity) -> Result<(), GatewayError> { Ok(()) } } let mut server = LoginServerState::new(TestData {}, "127.0.0.1".parse().unwrap()); let send = server.handle(ClientId(1), LOGIN_PACKET).await.unwrap(); 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, }))]) } #[async_std::test] async fn test_login_bad_username() { #[derive(Clone)] struct TestData { } #[async_trait::async_trait] impl EntityGateway for TestData { async fn get_user_by_name(&mut self, _name: String) -> Result { Err(GatewayError::Error) } } let mut server = LoginServerState::new(TestData {}, "127.0.0.1".parse().unwrap()); let send = server.handle(ClientId(1), LOGIN_PACKET).await.unwrap(); 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 }))]) } #[async_std::test] async fn test_login_bad_password() { #[derive(Clone)] struct TestData { } #[async_trait::async_trait] impl EntityGateway for TestData { async fn get_user_by_name(&mut self, name: String) -> Result { assert!(name == "testuser"); Ok(UserAccountEntity { id: UserAccountId(1), username: "testuser".to_owned(), password: bcrypt::hash("notpassword", 5).unwrap(), guildcard: 0, team_id: None, banned_until: None, muted_until: None, created_at: chrono::Utc::now(), flags: 0, activated: true, at_login: false, at_character: false, at_ship: false, }) } } let mut server = LoginServerState::new(TestData {}, "127.0.0.1".parse().unwrap()); let send = server.handle(ClientId(1), LOGIN_PACKET).await.unwrap(); 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 }))]) } #[async_std::test] async fn test_banned_user() { #[derive(Clone)] struct TestData { } #[async_trait::async_trait] impl EntityGateway for TestData { async fn get_user_by_name(&mut self, name: String) -> Result { assert!(name == "testuser"); Ok(UserAccountEntity { id: UserAccountId(1), username: "testuser".to_owned(), password: bcrypt::hash("mypassword", 5).unwrap(), guildcard: 0, team_id: None, banned_until: Some(chrono::Utc::now() + chrono::Duration::days(1)), muted_until: None, created_at: chrono::Utc::now(), flags: 0, activated: true, at_login: false, at_character: false, at_ship: false, }) } } let mut server = LoginServerState::new(TestData {}, "127.0.0.1".parse().unwrap()); let send = server.handle(ClientId(1), LOGIN_PACKET).await.unwrap(); 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 }))]) } }