Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add password hashing #1

Merged
merged 1 commit into from
Jan 4, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 106 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,7 @@ pic8259_simple = "0.1.1"
pc-keyboard = { version = "0.5.0", git = "https://github.com/vinc/pc-keyboard", branch = "feature/add-dvorak-layout" }
heapless = "0.5.1"
lazy_static = { version = "1.0", features = ["spin_no_std"] }
base64 = { version = "0.11", default-features = false }
pbkdf2 = { version = "0.3", default-features = false }
sha2 = { version = "0.8", default-features = false }
hmac = { version = "0.7", default-features = false }
1 change: 1 addition & 0 deletions dsk/cfg/passwords.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
root,1$AAAQAA$nvQAFYGhN1a4NmHS8ooWrA$7zOWQLxpmRF4AC3G3+F2OVJ9IejzdH52TXQFlbRAmLg
1 change: 1 addition & 0 deletions src/kernel/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@ pub mod console;
pub mod fs;
pub mod gdt;
pub mod interrupts;
pub mod random;
pub mod sleep;
pub mod vga;
8 changes: 8 additions & 0 deletions src/kernel/random.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
use x86_64::instructions::random::RdRand;

pub fn rand64() -> Option<u64> {
match RdRand::new() {
Some(rand) => rand.get_u64(),
None => None
}
}
1 change: 1 addition & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ fn main(_boot_info: &'static BootInfo) -> ! {
moros::init();
include_file("/cfg/boot.sh", include_str!("../dsk/cfg/boot.sh"));
include_file("/cfg/banner.txt", include_str!("../dsk/cfg/banner.txt"));
include_file("/cfg/passwords.csv", include_str!("../dsk/cfg/passwords.csv"));
loop {
user::shell::main(&["shell", "/cfg/boot.sh"]);
}
Expand Down
30 changes: 30 additions & 0 deletions src/user/base64.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
use crate::{print, user};
use heapless::{String, Vec};
use heapless::consts::*;

pub fn main(args: &[&str]) -> user::shell::ExitCode {
if args.len() != 2 {
user::shell::ExitCode::CommandError
} else {
let buf = encode(args[1].as_bytes());
let encoded = String::from_utf8(buf).unwrap();
print!("{}\n", encoded);
user::shell::ExitCode::CommandSuccessful
}
}

pub fn encode(s: &[u8]) -> Vec<u8, U1024> {
let mut buf = Vec::<u8, U1024>::new();
buf.resize(s.len() * 4 / 3 + 4, 0).unwrap(); // Resize to base64 + padding
let bytes_written = base64::encode_config_slice(s, base64::STANDARD_NO_PAD, &mut buf);
buf.resize(bytes_written, 0).unwrap(); // Resize back to actual size
buf
}

pub fn decode(s: &[u8]) -> Vec<u8, U1024> {
let mut buf = Vec::<u8, U1024>::new();
buf.resize(s.len(), 0).unwrap();
let bytes_written = base64::decode_config_slice(s, base64::STANDARD_NO_PAD, &mut buf).unwrap();
buf.resize(bytes_written, 0).unwrap();
buf
}
102 changes: 89 additions & 13 deletions src/user/login.rs
Original file line number Diff line number Diff line change
@@ -1,26 +1,102 @@
use crate::{print, kernel, user};
use heapless::{String, FnvIndexMap, Vec};
use heapless::consts::*;
use core::convert::TryInto;
use core::str;
use hmac::Hmac;
use sha2::Sha256;

pub fn main(_args: &[&str]) -> user::shell::ExitCode {
login()
}

// TODO: Add max number of attempts
pub fn login() -> user::shell::ExitCode {
print!("\nUsername: ");
let username = kernel::console::get_line();
if username != "root\n" {
kernel::sleep::sleep(1.0);
return login();
let mut hashed_passwords: FnvIndexMap<String<U256>, String<U1024>, U256> = FnvIndexMap::new();
if let Some(file) = kernel::fs::File::open("/cfg/passwords.csv") {
for line in file.read().split("\n") {
let mut rows = line.split(",");
if let Some(username) = rows.next() {
if let Some(hashed_password) = rows.next() {
hashed_passwords.insert(username.into(), hashed_password.into()).unwrap();
}
}
}
}

print!("Password: ");
kernel::console::disable_echo();
let password = kernel::console::get_line();
kernel::console::enable_echo();
print!("\n");
if password != "root\n" {
kernel::sleep::sleep(1.0);
return login();
print!("\nUsername: ");
let mut username = kernel::console::get_line();
username.pop(); // Trim end of string
match hashed_passwords.get(&username) {
None => {
kernel::sleep::sleep(1.0);
return login();
},
Some(hashed_password) => {
print!("Password: ");
kernel::console::disable_echo();
let mut password = kernel::console::get_line();
kernel::console::enable_echo();
print!("\n");
password.pop();
if !check(&password, hashed_password) {
kernel::sleep::sleep(1.0);
return login();
}
}
}
user::shell::ExitCode::CommandSuccessful
}

pub fn check(password: &str, hashed_password: &str) -> bool {
let fields: Vec<_, U4> = hashed_password.split('$').collect();
if fields.len() != 4 || fields[0] != "1" {
return false;
}

let decoded_field = user::base64::decode(&fields[1].as_bytes());
let c = u32::from_be_bytes(decoded_field[0..4].try_into().unwrap());

let decoded_field = user::base64::decode(&fields[2].as_bytes());
let salt: [u8; 16] = decoded_field[0..16].try_into().unwrap();

let mut hash = [0u8; 32];
pbkdf2::pbkdf2::<Hmac<Sha256>>(password.as_bytes(), &salt, c as usize, &mut hash);
let encoded_hash = String::from_utf8(user::base64::encode(&hash)).unwrap();

encoded_hash == fields[3]
}

// Password hashing version 1 => PBKDF2-HMAC-SHA256 + BASE64
// Fields: "<version>$<c>$<salt>$<hash>"
// Example: "1$AAAQAA$PDkXP0I8O7SxNOxvUKmHHQ$BwIUWBxKs50BTpH6i4ImF3SZOxADv7dh4xtu3IKc3o8"
pub fn hash(password: &str) -> String<U1024> {
let v = "1"; // Password hashing version
let c = 4096u32; // Number of iterations
let mut salt = [0u8; 16];
let mut hash = [0u8; 32];

// Generating salt
for i in 0..2 {
let num = kernel::random::rand64().unwrap();
let buf = num.to_be_bytes();
let n = buf.len();
for j in 0..n {
salt[i * n + j] = buf[j];
}
}

// Hashing password with PBKDF2-HMAC-SHA256
pbkdf2::pbkdf2::<Hmac<Sha256>>(password.as_bytes(), &salt, c as usize, &mut hash);

// Encoding in Base64 standard without padding
let c = c.to_be_bytes();
let mut res: String<U1024> = String::from(v);
res.push('$').unwrap();
res.push_str(&String::from_utf8(user::base64::encode(&c)).unwrap()).unwrap();
res.push('$').unwrap();
res.push_str(&String::from_utf8(user::base64::encode(&salt)).unwrap()).unwrap();
res.push('$').unwrap();
res.push_str(&String::from_utf8(user::base64::encode(&hash)).unwrap()).unwrap();
res
}
1 change: 1 addition & 0 deletions src/user/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod base64;
pub mod clear;
pub mod date;
pub mod editor;
Expand Down
1 change: 1 addition & 0 deletions src/user/shell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ impl Shell {
"sleep" => user::sleep::main(&args),
"clear" => user::clear::main(&args),
"login" => user::login::main(&args),
"base64" => user::base64::main(&args),
_ => ExitCode::CommandUnknown,
}
}
Expand Down
2 changes: 1 addition & 1 deletion x86_64-moros.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@
"panic-strategy": "abort",
"disable-redzone": true,
"features": "-mmx,-sse,+soft-float"
}
}