elseware/src/login/login.rs

347 lines
12 KiB
Rust
Raw Normal View History

2019-08-23 23:01:36 -07:00
// TODO: rename this module to auth
use std::net;
2019-09-15 15:14:19 -07:00
use rand::Rng;
2019-08-25 04:51:12 -07:00
use bcrypt;
use libpso::packet::login::*;
use libpso::{PacketParseError, PSOPacket};
use libpso::crypto::bb::PSOBBCipher;
2019-11-04 20:33:10 -08:00
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(Debug)]
pub enum LoginError {
}
#[derive(Debug, PartialEq)]
pub enum RecvLoginPacket {
Login(Login),
}
impl RecvServerPacket for RecvLoginPacket {
2019-09-04 09:17:22 -07:00
fn from_bytes(data: &[u8]) -> Result<RecvLoginPacket, PacketParseError> {
match data[2] {
0x93 => Ok(RecvLoginPacket::Login(Login::from_bytes(data)?)),
2019-11-09 22:58:13 -08:00
_ => 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<u8> {
match self {
SendLoginPacket::LoginResponse(pkt) => pkt.as_bytes(),
SendLoginPacket::LoginWelcome(pkt) => pkt.as_bytes(),
SendLoginPacket::RedirectClient(pkt) => pkt.as_bytes(),
}
}
}
2020-06-02 18:51:18 -06:00
pub async fn get_login_status(entity_gateway: &impl EntityGateway, pkt: &Login) -> Result<UserAccountEntity, AccountStatus> {
2019-08-23 23:01:36 -07:00
let username = array_to_utf8(pkt.username).map_err(|_err| AccountStatus::Error)?;
let password = array_to_utf8(pkt.password).map_err(|_err| AccountStatus::Error)?;
2020-06-02 18:51:18 -06:00
let user = entity_gateway.get_user_by_name(username).await.ok_or(AccountStatus::InvalidUser)?;
2019-08-23 23:01:36 -07:00
let verified = bcrypt::verify(password, user.password.as_str()).map_err(|_err| AccountStatus::Error)?;
match verified {
2020-10-03 17:13:29 -06:00
true => if user.banned_until.map(|banned| banned > chrono::Utc::now()).unwrap_or(false) {
2019-11-09 12:57:42 -04:00
Err(AccountStatus::Banned)
}
else {
Ok(user)
},
2019-08-23 23:01:36 -07:00
false => Err(AccountStatus::InvalidPassword)
}
}
2019-08-23 23:01:36 -07:00
pub struct LoginServerState<EG: EntityGateway> {
entity_gateway: EG,
2019-09-15 15:14:19 -07:00
}
impl<EG: EntityGateway> LoginServerState<EG> {
pub fn new(entity_gateway: EG) -> LoginServerState<EG> {
LoginServerState {
entity_gateway: entity_gateway,
}
}
2020-06-02 18:51:18 -06:00
async fn validate_login(&mut self, pkt: &Login) -> Vec<SendLoginPacket> {
match get_login_status(&self.entity_gateway, pkt).await {
Ok(_user) => {
2019-11-04 20:28:50 -08:00
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) => {
2019-11-04 20:28:50 -08:00
vec![SendLoginPacket::LoginResponse(LoginResponse::by_status(err, pkt.session))]
}
}
}
}
2020-06-02 18:51:18 -06:00
#[async_trait::async_trait]
impl<EG: EntityGateway> ServerState for LoginServerState<EG> {
type SendPacket = SendLoginPacket;
type RecvPacket = RecvLoginPacket;
type PacketError = LoginError;
2019-09-15 15:14:19 -07:00
fn on_connect(&mut self, _id: ClientId) -> Vec<OnConnect<Self::SendPacket>> {
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))))
]
}
2020-06-02 18:51:18 -06:00
async fn handle(&mut self, id: ClientId, pkt: &Self::RecvPacket)
2020-01-23 18:00:34 -08:00
-> Result<Box<dyn Iterator<Item = (ClientId, Self::SendPacket)> + Send>, LoginError> {
Ok(match pkt {
RecvLoginPacket::Login(login) => {
2020-06-02 18:51:18 -06:00
Box::new(self.validate_login(login).await
2019-09-04 09:17:22 -07:00
.into_iter()
.map(move |pkt| {
(id, pkt)
}))
}
})
}
2020-01-08 22:02:51 -08:00
fn on_disconnect(&mut self, _id: ClientId) -> Vec<(ClientId, SendLoginPacket)> {
2020-01-08 22:02:51 -08:00
Vec::new()
}
}
#[cfg(test)]
mod test {
use std::time::SystemTime;
use super::*;
use crate::entity::account::{UserAccountId};
2019-09-15 16:14:12 -07:00
const LOGIN_PACKET: RecvLoginPacket = RecvLoginPacket::Login(Login {
2019-11-04 20:28:50 -08:00
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,
}
});
2020-06-02 19:02:06 -06:00
#[async_std::test]
async fn test_correct_login() {
#[derive(Clone)]
struct TestData {
}
2020-06-02 19:02:06 -06:00
#[async_trait::async_trait]
impl EntityGateway for TestData {
2020-06-02 19:02:06 -06:00
async fn get_user_by_name(&self, name: String) -> Option<UserAccountEntity> {
assert!(name == "testuser");
Some(UserAccountEntity {
id: UserAccountId(1),
username: "testuser".to_owned(),
password: bcrypt::hash("mypassword", 5).unwrap(),
2020-03-22 22:40:40 -03:00
guildcard: 0,
team_id: None,
2020-10-03 20:12:11 -06:00
banned_until: None,
muted_until: None,
created_at: chrono::Utc::now(),
2019-09-23 22:24:51 -07:00
flags: 0,
})
}
2020-06-02 19:02:06 -06:00
};
2019-09-04 09:17:22 -07:00
let mut server = LoginServerState::new(TestData {});
2020-06-02 19:02:06 -06:00
let send = server.handle(ClientId(1), &LOGIN_PACKET).await.unwrap().collect::<Vec<_>>();
assert!(send == vec![
2019-09-14 11:43:02 -07:00
(ClientId(1), SendLoginPacket::LoginResponse(LoginResponse {
status: AccountStatus::Ok,
tag: 65536,
guildcard: 0,
team_id: 0,
2019-11-04 20:28:50 -08:00
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
2019-09-04 09:17:22 -07:00
})),
2019-09-14 11:43:02 -07:00
(ClientId(1), SendLoginPacket::RedirectClient(RedirectClient {
ip: 16777343,
port: 12001,
padding: 0,
2019-09-04 09:17:22 -07:00
}))])
}
2019-09-15 16:00:30 -07:00
2020-06-02 19:02:06 -06:00
#[async_std::test]
async fn test_login_bad_username() {
#[derive(Clone)]
2019-09-15 16:00:30 -07:00
struct TestData {
}
2020-06-02 19:02:06 -06:00
#[async_trait::async_trait]
impl EntityGateway for TestData {
2020-06-02 19:02:06 -06:00
async fn get_user_by_name(&self, _name: String) -> Option<UserAccountEntity> {
2019-09-15 16:00:30 -07:00
None
}
}
let mut server = LoginServerState::new(TestData {});
2020-06-02 19:02:06 -06:00
let send = server.handle(ClientId(1), &LOGIN_PACKET).await.unwrap().collect::<Vec<_>>();
2019-09-15 16:00:30 -07:00
assert!(send == vec![
(ClientId(1), SendLoginPacket::LoginResponse(LoginResponse {
status: AccountStatus::InvalidUser,
tag: 65536,
guildcard: 0,
team_id: 0,
2019-11-04 20:28:50 -08:00
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,
},
2019-09-15 16:00:30 -07:00
caps: 258
}))])
}
2020-06-02 19:02:06 -06:00
#[async_std::test]
async fn test_login_bad_password() {
#[derive(Clone)]
2019-09-15 16:00:30 -07:00
struct TestData {
}
2020-06-02 19:02:06 -06:00
#[async_trait::async_trait]
impl EntityGateway for TestData {
2020-06-02 19:02:06 -06:00
async fn get_user_by_name(&self, name: String) -> Option<UserAccountEntity> {
2019-09-15 16:00:30 -07:00
assert!(name == "testuser");
Some(UserAccountEntity {
id: UserAccountId(1),
2019-09-15 16:00:30 -07:00
username: "testuser".to_owned(),
password: bcrypt::hash("notpassword", 5).unwrap(),
2020-03-22 22:40:40 -03:00
guildcard: 0,
2019-09-15 16:00:30 -07:00
team_id: None,
2020-10-03 20:12:11 -06:00
banned_until: None,
muted_until: None,
created_at: chrono::Utc::now(),
2019-09-23 22:24:51 -07:00
flags: 0,
2019-09-15 16:00:30 -07:00
})
}
}
let mut server = LoginServerState::new(TestData {});
2020-06-02 19:02:06 -06:00
let send = server.handle(ClientId(1), &LOGIN_PACKET).await.unwrap().collect::<Vec<_>>();
2019-09-15 16:00:30 -07:00
assert!(send == vec![
(ClientId(1), SendLoginPacket::LoginResponse(LoginResponse {
status: AccountStatus::InvalidPassword,
tag: 65536,
guildcard: 0,
team_id: 0,
2019-11-04 20:28:50 -08:00
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,
},
2019-09-15 16:00:30 -07:00
caps: 258
}))])
}
2019-11-09 12:57:42 -04:00
2020-06-02 19:02:06 -06:00
#[async_std::test]
async fn test_banned_user() {
#[derive(Clone)]
2019-11-09 12:57:42 -04:00
struct TestData {
}
2020-06-02 19:02:06 -06:00
#[async_trait::async_trait]
2019-11-09 12:57:42 -04:00
impl EntityGateway for TestData {
2020-06-02 19:02:06 -06:00
async fn get_user_by_name(&self, name: String) -> Option<UserAccountEntity> {
2019-11-09 12:57:42 -04:00
assert!(name == "testuser");
Some(UserAccountEntity {
id: UserAccountId(1),
2019-11-09 12:57:42 -04:00
username: "testuser".to_owned(),
password: bcrypt::hash("mypassword", 5).unwrap(),
2020-03-22 22:40:40 -03:00
guildcard: 0,
2019-11-09 12:57:42 -04:00
team_id: None,
2020-10-03 20:12:11 -06:00
banned_until: Some(chrono::Utc::now() + chrono::Duration::days(1)),
muted_until: None,
created_at: chrono::Utc::now(),
2019-11-09 12:57:42 -04:00
flags: 0,
})
}
2019-11-26 01:00:38 -04:00
}
2019-11-09 12:57:42 -04:00
let mut server = LoginServerState::new(TestData {});
2020-06-02 19:02:06 -06:00
let send = server.handle(ClientId(1), &LOGIN_PACKET).await.unwrap().collect::<Vec<_>>();
2019-11-09 12:57:42 -04:00
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
}))])
2019-11-26 01:00:38 -04:00
}
}