Home

rs-spectre @b6c2bb2b608f9b5738fa3f57e3b8267d76deffc7 - refs - log -
-
https://git.jolheiser.com/rs-spectre.git
Rust implementation for Spectre/Masterpassword
rs-spectre / spectre / src / lib.rs
- raw
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
use hmac::{Hmac, Mac};
use scrypt::{Params, scrypt};
use sha2::Sha256;

type HmacSha256 = Hmac<Sha256>;

pub mod scope;
pub mod template;

/// Spectre implements the Spectre/Masterpassword cipher
/// 
/// # Examples
/// 
/// ```
/// use spectre::{scope, SiteOptions, Spectre};
/// let s = Spectre::new(
///     "Robert Lee Mitchell",
///     "banana colored duckling",
///     scope::SimpleScoper::default(),
///  );
///  let pw = s.site("masterpasswordapp.com", SiteOptions::default());
///  assert_eq!(pw, "Jejr5[RepuSosp")
/// ```
#[derive(Debug)]
pub struct Spectre {
    key: String,
    scoper: Box<dyn scope::Scoper>,
}

impl Spectre {
    /// Create a new Spectre instance that can be used to generate site passwords.
    pub fn new(name: impl Into<String>, secret: impl Into<String>, scoper: impl scope::Scoper + 'static) -> Self {
        let key = user_key(name, secret, &scoper);
        Self {
            scoper: Box::new(scoper),
            key,
        }
    }

    fn site_key(&self, name: String, counter: u32, scope: scope::Scope) -> Vec<u8> {
        let key = self.scoper.scope(scope);
        let hmac_key = hex::decode(&self.key).unwrap();
        let mut hmac = HmacSha256::new_from_slice(&hmac_key).unwrap();
        let mut seed = Vec::new();
        seed.extend_from_slice(key.as_bytes());
        seed.extend_from_slice(&(name.len() as u32).to_be_bytes());
        seed.extend_from_slice(name.as_bytes());
        seed.extend_from_slice(&counter.to_be_bytes());
        hmac.update(&seed);
        let result = hmac.finalize();
        result.into_bytes().to_vec()
    }

    /// Generate a site password for a given site_name 
    /// 
    /// Generally this is the domain, e.g. `example.com`
    pub fn site(&self, site_name: impl Into<String>, opts: SiteOptions) -> String {
        let scope = opts.scope.unwrap_or(scope::Scope::AUTHENTICATION);
        let template_type = opts.template.unwrap_or(scope.default_template());
        let templates = template::templates(template_type);
        let counter = opts.counter.unwrap_or(1);
        let site_key = self.site_key(site_name.into(), counter, scope);
        let site_byte = site_key[0] as u32;
        let templates_len = templates.len() as u32;
        let template_idx = site_byte % templates_len;
        let template = templates[template_idx as usize];
        let mut out = String::new();
        for (i, b) in template.as_bytes().iter().enumerate() {
            let chars = template::chars(b).to_string();
            let chars_len = chars.len() as u32;
            let site_key_byte = site_key[i + 1] as u32;
            let char_idx = site_key_byte % chars_len;
            let char = chars.chars().nth(char_idx as usize).unwrap();
            out.push(char);
        }
        out
    }
}

#[derive(Default)]
pub struct SiteOptions {
    pub scope: Option<scope::Scope>,
    pub template: Option<template::Template>,
    pub counter: Option<u32>,
}

fn user_key(name: impl Into<String>, secret: impl Into<String>, scoper: &impl scope::Scoper) -> String {
    let name = name.into();
    let key = scoper.scope(scope::Scope::AUTHENTICATION);
    let out: &mut [u8] = &mut [0u8; 64];
    let mut salt = Vec::new();
    salt.extend_from_slice(key.as_bytes());
    salt.extend_from_slice(&(name.len() as u32).to_be_bytes());
    salt.extend_from_slice(name.as_bytes());
    scrypt(
        secret.into().as_bytes(),
        &salt,
        &Params::new(15, 8, 2, 64).unwrap(),
        out,
    )
    .unwrap();
    hex::encode(out)
}

#[cfg(test)]
mod spectre_tests {
    use super::*;
    use serde::Deserialize;
    use crate::scope::{Scope, SimpleScoper};
    use crate::template::Template;

    #[test]
    fn custom() {
        let scoper = SimpleScoper::new("com.jojodev.jolheiser");
        let s = Spectre::new(
            "Robert Lee Mitchell",
            "banana colored duckling",
            scoper,
        );
        let pw = s.site(
            "jojodev.com",
            SiteOptions {
                scope: Some(Scope::IDENTIFICATION),
                template: Some(Template::Maximum),
                counter: Some(2),
            },
        );
        assert_eq!(pw, "Ig^JIcxD!*)TbefJBi6-")
    }

    #[derive(Debug, Deserialize)]
    struct Tests {
        #[serde(rename = "case")]
        cases: Vec<Case>,
    }

    #[derive(Debug, Deserialize)]
    struct Case {
        #[serde(rename = "@id")]
        id: String,
        // algorithm: Option<i32>,
        #[serde(rename = "userName")]
        user_name: Option<String>,
        #[serde(rename = "userSecret")]
        user_secret: Option<String>,
        #[serde(rename = "siteName")]
        site_name: Option<String>,
        #[serde(rename = "resultType")]
        result_type: Option<String>,
        #[serde(rename = "keyCounter")]
        key_counter: Option<u32>,
        #[serde(rename = "keyPurpose")]
        key_purpose: Option<String>,
        result: Option<String>,
    }

    #[test]
    fn spectre() {
        let xml = include_str!("spectre_tests.xml");
        let tests: Tests = quick_xml::de::from_str(xml).unwrap();

        let mut i = 0;
        let total = tests.cases.len() - 1;
        for case in tests.cases {
            if case.id == "default" {
                continue;
            }
            i += 1;
            println!("[{}/{}] {}", i, total, case.id);
            let s = Spectre::new(
                case.user_name.unwrap_or("Robert Lee Mitchell".to_string()),
                case.user_secret
                    .unwrap_or("banana colored duckling".to_string()),
                scope::SimpleScoper::default(),
            );
            let pw = s.site(
                case.site_name.unwrap_or("spectre.app".to_string()),
                SiteOptions {
                    scope: Some(
                        case.key_purpose
                            .unwrap_or("Authentication".to_string())
                            .parse::<Scope>()
                            .unwrap(),
                    ),
                    template: Some(
                        case.result_type
                            .unwrap_or("Long".to_string())
                            .parse::<Template>()
                            .unwrap(),
                    ),
                    counter: Some(case.key_counter.unwrap_or(1)),
                },
            );
            assert_eq!(pw, case.result.unwrap());
        }
    }
}