2019-01-07 11:33:07 +01:00
|
|
|
// Copyright 2015-2019 Parity Technologies (UK) Ltd.
|
|
|
|
// This file is part of Parity Ethereum.
|
2016-06-07 17:21:19 +02:00
|
|
|
|
2019-01-07 11:33:07 +01:00
|
|
|
// Parity Ethereum is free software: you can redistribute it and/or modify
|
2016-06-07 17:21:19 +02:00
|
|
|
// it under the terms of the GNU General Public License as published by
|
|
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
|
|
// (at your option) any later version.
|
|
|
|
|
2019-01-07 11:33:07 +01:00
|
|
|
// Parity Ethereum is distributed in the hope that it will be useful,
|
2016-06-07 17:21:19 +02:00
|
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
// GNU General Public License for more details.
|
|
|
|
|
|
|
|
// You should have received a copy of the GNU General Public License
|
2019-01-07 11:33:07 +01:00
|
|
|
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
2016-06-07 17:21:19 +02:00
|
|
|
|
2016-11-14 11:56:01 +01:00
|
|
|
use std::io::{self, Read, Write};
|
2016-06-07 17:21:19 +02:00
|
|
|
use std::path::Path;
|
2016-11-14 11:56:01 +01:00
|
|
|
use std::{fs, time, mem};
|
2017-05-24 12:24:07 +02:00
|
|
|
|
2017-08-17 16:05:26 +02:00
|
|
|
use itertools::Itertools;
|
2019-06-03 15:36:21 +02:00
|
|
|
use rand::{Rng, rngs::OsRng, distributions::Alphanumeric};
|
2017-08-31 11:35:41 +02:00
|
|
|
use hash::keccak;
|
2018-01-10 13:35:18 +01:00
|
|
|
use ethereum_types::H256;
|
2016-06-07 17:21:19 +02:00
|
|
|
|
|
|
|
/// Providing current time in seconds
|
|
|
|
pub trait TimeProvider {
|
|
|
|
/// Returns timestamp (in seconds since epoch)
|
|
|
|
fn now(&self) -> u64;
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<F : Fn() -> u64> TimeProvider for F {
|
|
|
|
fn now(&self) -> u64 {
|
|
|
|
self()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Default implementation of `TimeProvider` using system time.
|
|
|
|
#[derive(Default)]
|
|
|
|
pub struct DefaultTimeProvider;
|
|
|
|
|
|
|
|
impl TimeProvider for DefaultTimeProvider {
|
|
|
|
fn now(&self) -> u64 {
|
|
|
|
time::UNIX_EPOCH.elapsed().expect("Valid time has to be set in your system.").as_secs()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// No of seconds the hash is valid
|
2016-08-08 17:03:25 +02:00
|
|
|
const TIME_THRESHOLD: u64 = 7;
|
2016-11-14 11:56:01 +01:00
|
|
|
/// minimal length of hash
|
2016-06-07 17:21:19 +02:00
|
|
|
const TOKEN_LENGTH: usize = 16;
|
2016-11-14 11:56:01 +01:00
|
|
|
/// Separator between fields in serialized tokens file.
|
2019-03-22 12:01:11 +01:00
|
|
|
const SEPARATOR: &str = ";";
|
2016-11-14 11:56:01 +01:00
|
|
|
/// Number of seconds to keep unused tokens.
|
|
|
|
const UNUSED_TOKEN_TIMEOUT: u64 = 3600 * 24; // a day
|
|
|
|
|
|
|
|
struct Code {
|
|
|
|
code: String,
|
|
|
|
/// Duration since unix_epoch
|
|
|
|
created_at: time::Duration,
|
|
|
|
/// Duration since unix_epoch
|
|
|
|
last_used_at: Option<time::Duration>,
|
|
|
|
}
|
|
|
|
|
|
|
|
fn decode_time(val: &str) -> Option<time::Duration> {
|
|
|
|
let time = val.parse::<u64>().ok();
|
|
|
|
time.map(time::Duration::from_secs)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn encode_time(time: time::Duration) -> String {
|
|
|
|
format!("{}", time.as_secs())
|
|
|
|
}
|
2016-06-07 17:21:19 +02:00
|
|
|
|
|
|
|
/// Manages authorization codes for `SignerUIs`
|
|
|
|
pub struct AuthCodes<T: TimeProvider = DefaultTimeProvider> {
|
2016-11-14 11:56:01 +01:00
|
|
|
codes: Vec<Code>,
|
2016-06-07 17:21:19 +02:00
|
|
|
now: T,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl AuthCodes<DefaultTimeProvider> {
|
|
|
|
|
|
|
|
/// Reads `AuthCodes` from file and creates new instance using `DefaultTimeProvider`.
|
|
|
|
pub fn from_file(file: &Path) -> io::Result<AuthCodes> {
|
|
|
|
let content = {
|
|
|
|
if let Ok(mut file) = fs::File::open(file) {
|
|
|
|
let mut s = String::new();
|
2016-12-27 12:53:56 +01:00
|
|
|
let _ = file.read_to_string(&mut s)?;
|
2016-06-07 17:21:19 +02:00
|
|
|
s
|
|
|
|
} else {
|
|
|
|
"".into()
|
|
|
|
}
|
|
|
|
};
|
2016-11-14 11:56:01 +01:00
|
|
|
let time_provider = DefaultTimeProvider::default();
|
|
|
|
|
2016-06-07 17:21:19 +02:00
|
|
|
let codes = content.lines()
|
2016-11-14 11:56:01 +01:00
|
|
|
.filter_map(|line| {
|
|
|
|
let mut parts = line.split(SEPARATOR);
|
|
|
|
let token = parts.next();
|
|
|
|
let created = parts.next();
|
|
|
|
let used = parts.next();
|
|
|
|
|
|
|
|
match token {
|
|
|
|
None => None,
|
|
|
|
Some(token) if token.len() < TOKEN_LENGTH => None,
|
|
|
|
Some(token) => {
|
|
|
|
Some(Code {
|
|
|
|
code: token.into(),
|
|
|
|
last_used_at: used.and_then(decode_time),
|
|
|
|
created_at: created.and_then(decode_time)
|
|
|
|
.unwrap_or_else(|| time::Duration::from_secs(time_provider.now())),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
2016-06-07 17:21:19 +02:00
|
|
|
.collect();
|
|
|
|
Ok(AuthCodes {
|
2019-03-22 12:01:11 +01:00
|
|
|
codes,
|
2016-11-14 11:56:01 +01:00
|
|
|
now: time_provider,
|
2016-06-07 17:21:19 +02:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T: TimeProvider> AuthCodes<T> {
|
|
|
|
|
|
|
|
/// Writes all `AuthCodes` to a disk.
|
|
|
|
pub fn to_file(&self, file: &Path) -> io::Result<()> {
|
2016-12-27 12:53:56 +01:00
|
|
|
let mut file = fs::File::create(file)?;
|
2016-11-14 11:56:01 +01:00
|
|
|
let content = self.codes.iter().map(|code| {
|
2019-03-22 12:01:11 +01:00
|
|
|
let mut data = vec![code.code.clone(), encode_time(code.created_at)];
|
2016-11-28 13:20:49 +01:00
|
|
|
if let Some(used_at) = code.last_used_at {
|
2016-11-14 11:56:01 +01:00
|
|
|
data.push(encode_time(used_at));
|
|
|
|
}
|
|
|
|
data.join(SEPARATOR)
|
|
|
|
}).join("\n");
|
2016-06-07 17:21:19 +02:00
|
|
|
file.write_all(content.as_bytes())
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Creates a new `AuthCodes` store with given `TimeProvider`.
|
|
|
|
pub fn new(codes: Vec<String>, now: T) -> Self {
|
|
|
|
AuthCodes {
|
2016-11-14 11:56:01 +01:00
|
|
|
codes: codes.into_iter().map(|code| Code {
|
2019-03-22 12:01:11 +01:00
|
|
|
code,
|
2016-11-14 11:56:01 +01:00
|
|
|
created_at: time::Duration::from_secs(now.now()),
|
|
|
|
last_used_at: None,
|
|
|
|
}).collect(),
|
2019-03-22 12:01:11 +01:00
|
|
|
now,
|
2016-06-07 17:21:19 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-11-14 11:56:01 +01:00
|
|
|
/// Checks if given hash is correct authcode of `SignerUI`
|
|
|
|
/// Updates this hash last used field in case it's valid.
|
2016-09-21 12:44:49 +02:00
|
|
|
pub fn is_valid(&mut self, hash: &H256, time: u64) -> bool {
|
2016-06-07 17:21:19 +02:00
|
|
|
let now = self.now.now();
|
|
|
|
// check time
|
|
|
|
if time >= now + TIME_THRESHOLD || time <= now - TIME_THRESHOLD {
|
2016-08-08 17:03:25 +02:00
|
|
|
warn!(target: "signer", "Received old authentication request. ({} vs {})", now, time);
|
2016-06-07 17:21:19 +02:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2017-08-31 11:35:41 +02:00
|
|
|
let as_token = |code| keccak(format!("{}:{}", code, time));
|
2016-09-21 12:44:49 +02:00
|
|
|
|
2016-06-07 17:21:19 +02:00
|
|
|
// look for code
|
2017-10-15 15:11:07 +02:00
|
|
|
for code in &mut self.codes {
|
2016-11-14 11:56:01 +01:00
|
|
|
if &as_token(&code.code) == hash {
|
|
|
|
code.last_used_at = Some(time::Duration::from_secs(now));
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
false
|
2016-06-07 17:21:19 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Generates and returns a new code that can be used by `SignerUIs`
|
|
|
|
pub fn generate_new(&mut self) -> io::Result<String> {
|
2016-12-27 12:53:56 +01:00
|
|
|
let mut rng = OsRng::new()?;
|
2019-06-03 15:36:21 +02:00
|
|
|
let code = rng.sample_iter(&Alphanumeric).take(TOKEN_LENGTH).collect::<String>();
|
2016-06-07 17:21:19 +02:00
|
|
|
let readable_code = code.as_bytes()
|
|
|
|
.chunks(4)
|
|
|
|
.filter_map(|f| String::from_utf8(f.to_vec()).ok())
|
|
|
|
.collect::<Vec<String>>()
|
|
|
|
.join("-");
|
2016-06-29 17:50:27 +02:00
|
|
|
trace!(target: "signer", "New authentication token generated.");
|
2016-11-14 11:56:01 +01:00
|
|
|
self.codes.push(Code {
|
2019-03-22 12:01:11 +01:00
|
|
|
code,
|
2016-11-14 11:56:01 +01:00
|
|
|
created_at: time::Duration::from_secs(self.now.now()),
|
|
|
|
last_used_at: None,
|
|
|
|
});
|
2016-06-07 17:21:19 +02:00
|
|
|
Ok(readable_code)
|
|
|
|
}
|
2016-09-21 12:44:49 +02:00
|
|
|
|
|
|
|
/// Returns true if there are no tokens in this store
|
|
|
|
pub fn is_empty(&self) -> bool {
|
|
|
|
self.codes.is_empty()
|
|
|
|
}
|
2016-06-07 17:21:19 +02:00
|
|
|
|
2016-11-14 11:56:01 +01:00
|
|
|
/// Removes old tokens that have not been used since creation.
|
|
|
|
pub fn clear_garbage(&mut self) {
|
|
|
|
let now = self.now.now();
|
|
|
|
let threshold = time::Duration::from_secs(now.saturating_sub(UNUSED_TOKEN_TIMEOUT));
|
|
|
|
|
|
|
|
let codes = mem::replace(&mut self.codes, Vec::new());
|
|
|
|
for code in codes {
|
|
|
|
// Skip codes that are old and were never used.
|
|
|
|
if code.last_used_at.is_none() && code.created_at <= threshold {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
self.codes.push(code);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2016-06-07 17:21:19 +02:00
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
2016-11-14 11:56:01 +01:00
|
|
|
use std::io::{Read, Write};
|
|
|
|
use std::{time, fs};
|
|
|
|
use std::cell::Cell;
|
2018-01-19 17:32:53 +01:00
|
|
|
use tempdir::TempDir;
|
2017-08-31 11:35:41 +02:00
|
|
|
use hash::keccak;
|
2016-11-14 11:56:01 +01:00
|
|
|
|
2018-01-10 13:35:18 +01:00
|
|
|
use ethereum_types::H256;
|
2016-06-07 17:21:19 +02:00
|
|
|
use super::*;
|
|
|
|
|
|
|
|
fn generate_hash(val: &str, time: u64) -> H256 {
|
2017-08-31 11:35:41 +02:00
|
|
|
keccak(format!("{}:{}", val, time))
|
2016-06-07 17:21:19 +02:00
|
|
|
}
|
|
|
|
|
2016-09-21 12:44:49 +02:00
|
|
|
#[test]
|
2018-09-13 10:58:52 +02:00
|
|
|
fn should_return_false_even_if_code_is_initial_and_store_is_empty() {
|
2016-09-21 12:44:49 +02:00
|
|
|
// given
|
|
|
|
let code = "initial";
|
|
|
|
let time = 99;
|
|
|
|
let mut codes = AuthCodes::new(vec![], || 100);
|
|
|
|
|
|
|
|
// when
|
|
|
|
let res1 = codes.is_valid(&generate_hash(code, time), time);
|
|
|
|
let res2 = codes.is_valid(&generate_hash(code, time), time);
|
|
|
|
|
|
|
|
// then
|
2018-09-13 10:58:52 +02:00
|
|
|
assert_eq!(res1, false);
|
2016-09-21 12:44:49 +02:00
|
|
|
assert_eq!(res2, false);
|
|
|
|
}
|
|
|
|
|
2016-06-07 17:21:19 +02:00
|
|
|
#[test]
|
|
|
|
fn should_return_true_if_hash_is_valid() {
|
|
|
|
// given
|
|
|
|
let code = "23521352asdfasdfadf";
|
|
|
|
let time = 99;
|
2016-09-21 12:44:49 +02:00
|
|
|
let mut codes = AuthCodes::new(vec![code.into()], || 100);
|
2016-06-07 17:21:19 +02:00
|
|
|
|
|
|
|
// when
|
|
|
|
let res = codes.is_valid(&generate_hash(code, time), time);
|
|
|
|
|
|
|
|
// then
|
|
|
|
assert_eq!(res, true);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn should_return_false_if_code_is_unknown() {
|
|
|
|
// given
|
|
|
|
let code = "23521352asdfasdfadf";
|
|
|
|
let time = 99;
|
2016-09-21 12:44:49 +02:00
|
|
|
let mut codes = AuthCodes::new(vec!["1".into()], || 100);
|
2016-06-07 17:21:19 +02:00
|
|
|
|
|
|
|
// when
|
|
|
|
let res = codes.is_valid(&generate_hash(code, time), time);
|
|
|
|
|
|
|
|
// then
|
|
|
|
assert_eq!(res, false);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn should_return_false_if_hash_is_valid_but_time_is_invalid() {
|
|
|
|
// given
|
|
|
|
let code = "23521352asdfasdfadf";
|
2016-08-08 22:53:54 +02:00
|
|
|
let time = 107;
|
|
|
|
let time2 = 93;
|
2016-09-21 12:44:49 +02:00
|
|
|
let mut codes = AuthCodes::new(vec![code.into()], || 100);
|
2016-06-07 17:21:19 +02:00
|
|
|
|
|
|
|
// when
|
|
|
|
let res1 = codes.is_valid(&generate_hash(code, time), time);
|
|
|
|
let res2 = codes.is_valid(&generate_hash(code, time2), time2);
|
|
|
|
|
|
|
|
// then
|
|
|
|
assert_eq!(res1, false);
|
|
|
|
assert_eq!(res2, false);
|
|
|
|
}
|
|
|
|
|
2016-11-14 11:56:01 +01:00
|
|
|
#[test]
|
|
|
|
fn should_read_old_format_from_file() {
|
|
|
|
// given
|
2018-01-19 17:32:53 +01:00
|
|
|
let tempdir = TempDir::new("").unwrap();
|
|
|
|
let file_path = tempdir.path().join("file");
|
2016-11-14 11:56:01 +01:00
|
|
|
let code = "23521352asdfasdfadf";
|
|
|
|
{
|
2018-01-19 17:32:53 +01:00
|
|
|
let mut file = fs::File::create(&file_path).unwrap();
|
2016-11-14 11:56:01 +01:00
|
|
|
file.write_all(b"a\n23521352asdfasdfadf\nb\n").unwrap();
|
|
|
|
}
|
|
|
|
|
|
|
|
// when
|
2018-01-19 17:32:53 +01:00
|
|
|
let mut authcodes = AuthCodes::from_file(&file_path).unwrap();
|
2016-11-14 11:56:01 +01:00
|
|
|
let time = time::UNIX_EPOCH.elapsed().unwrap().as_secs();
|
|
|
|
|
|
|
|
// then
|
|
|
|
assert!(authcodes.is_valid(&generate_hash(code, time), time), "Code should be read from file");
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn should_remove_old_unused_tokens() {
|
|
|
|
// given
|
2018-01-19 17:32:53 +01:00
|
|
|
let tempdir = TempDir::new("").unwrap();
|
|
|
|
let file_path = tempdir.path().join("file");
|
2016-11-14 11:56:01 +01:00
|
|
|
let code1 = "11111111asdfasdf111";
|
|
|
|
let code2 = "22222222asdfasdf222";
|
|
|
|
let code3 = "33333333asdfasdf333";
|
|
|
|
|
|
|
|
let time = Cell::new(100);
|
|
|
|
let mut codes = AuthCodes::new(vec![code1.into(), code2.into(), code3.into()], || time.get());
|
|
|
|
// `code2` should not be removed (we never remove tokens that were used)
|
|
|
|
codes.is_valid(&generate_hash(code2, time.get()), time.get());
|
|
|
|
|
|
|
|
// when
|
|
|
|
time.set(100 + 10_000_000);
|
|
|
|
// mark `code1` as used now
|
|
|
|
codes.is_valid(&generate_hash(code1, time.get()), time.get());
|
|
|
|
|
|
|
|
let new_code = codes.generate_new().unwrap().replace('-', "");
|
|
|
|
codes.clear_garbage();
|
2018-01-19 17:32:53 +01:00
|
|
|
codes.to_file(&file_path).unwrap();
|
2016-11-14 11:56:01 +01:00
|
|
|
|
|
|
|
// then
|
|
|
|
let mut content = String::new();
|
2018-01-19 17:32:53 +01:00
|
|
|
let mut file = fs::File::open(&file_path).unwrap();
|
2016-11-14 11:56:01 +01:00
|
|
|
file.read_to_string(&mut content).unwrap();
|
|
|
|
|
|
|
|
assert_eq!(content, format!("{};100;10000100\n{};100;100\n{};10000100", code1, code2, new_code));
|
|
|
|
}
|
|
|
|
|
2016-06-07 17:21:19 +02:00
|
|
|
}
|