aboutsummaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 9fa1a72fa4cea1e98af392fd0ddc54ba750d75d4 (plain)
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
#![warn(missing_docs, rust_2018_compatibility, rust_2018_idioms, unused)]

//! Reads OTP configuration from a QR code and writes it to an OTP slot on a Nitrokey device.

use std::borrow;
use std::fmt;
use std::fs;
use std::io;
use std::path;
use std::process;
use std::str;

#[derive(Debug)]
enum Error {
    IoError(io::Error),
    Error(String),
    UrlParseError(url::ParseError),
    Utf8Error(str::Utf8Error),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            Error::IoError(ref err) => write!(f, "IO error: {}", err),
            Error::Error(ref string) => write!(f, "Error: {}", string),
            Error::UrlParseError(ref err) => write!(f, "URL parse error: {}", err),
            Error::Utf8Error(ref err) => write!(f, "UTF-8 error: {}", err),
        }
    }
}

impl From<&str> for Error {
    fn from(string: &str) -> Error {
        Error::Error(string.to_string())
    }
}

impl From<io::Error> for Error {
    fn from(error: io::Error) -> Error {
        Error::IoError(error)
    }
}

impl From<(&str, process::ExitStatus)> for Error {
    fn from(data: (&str, process::ExitStatus)) -> Error {
        let (command, status) = data;
        let msg = match status.code() {
            Some(code) => format!("{} failed with error code {}", command, code),
            None => format!("{} was terminated by a signal", command),
        };
        Error::Error(msg)
    }
}

impl From<url::ParseError> for Error {
    fn from(error: url::ParseError) -> Error {
        Error::UrlParseError(error)
    }
}

impl From<str::Utf8Error> for Error {
    fn from(error: str::Utf8Error) -> Error {
        Error::Utf8Error(error)
    }
}

#[derive(Debug, PartialEq)]
struct UrlData {
    otp_type: String,
    label: String,
    secret: String,
    issuer: Option<String>,
    digits: Option<String>,
    counter: Option<String>,
    period: Option<String>,
}

#[derive(Debug)]
struct Options {
    slot: u8,
    file: Option<String>,
    name: Option<String>,
}

fn parse_options() -> Result<Options, i32> {
    let mut options = Options {
        slot: 0,
        file: None,
        name: None,
    };
    let mut parser = argparse::ArgumentParser::new();
    parser.set_description(
        "Reads OTP configuration from a QR code and writes it to an OTP slot on a Nitrokey device.",
    );
    parser.refer(&mut options.slot).required().add_argument(
        "slot",
        argparse::Store,
        "The slot to write the OTP data to",
    );
    parser.refer(&mut options.file).add_argument(
        "file",
        argparse::StoreOption,
        "The file to read the QR code from",
    );
    parser.refer(&mut options.name).add_option(
        &["-n", "--name"],
        argparse::StoreOption,
        "The name to store in the OTP slot",
    );
    parser.parse_args()?;
    drop(parser);
    Ok(options)
}

fn import_qr_code() -> Result<path::PathBuf, Error> {
    let mut temp = mktemp::Temp::new_file()?;
    let path = temp.to_path_buf();

    let status = process::Command::new("import").arg(&path).status()?;

    if status.success() {
        temp.release();
        Ok(path)
    } else {
        Err(Error::from(("import", status)))
    }
}

fn decode_qr_code(path: &path::Path) -> Result<String, Error> {
    let output = process::Command::new("zbarimg")
        .arg("--quiet")
        .arg("--raw")
        .arg(path)
        .output()?;
    if output.status.success() {
        let output = String::from_utf8(output.stdout).map_err(|err| err.utf8_error())?;
        let urls = output
            .split("\n")
            .filter(|url| url.starts_with("otpauth://"))
            .collect::<Vec<&str>>();
        if urls.is_empty() {
            Err(Error::from("Could not find an otpauth QR code"))
        } else {
            if urls.len() > 1 {
                println!("Found more than otpauth QR code, using the first one.");
            }
            Ok(urls[0].to_string())
        }
    } else {
        Err(Error::from(("zbarimg", output.status)))
    }
}

fn strip_issuer_prefix(label: String, issuer: &str) -> String {
    let prefix = format!("{}:", issuer);
    if label.starts_with(&prefix) {
        let label = label.trim_left_matches(&prefix);
        let label = label.trim_left_matches(" ");
        label.to_string()
    } else {
        label
    }
}

fn parse_url(url: &str) -> Result<UrlData, Error> {
    let url = url::Url::parse(url)?;
    let scheme = url.scheme();
    if scheme != "otpauth" {
        return Err(Error::Error(format!("Unexpected URL scheme: {}", scheme)));
    }
    let otp_type = match url.host_str() {
        Some(host) => host.to_string(),
        None => return Err(Error::from("otpauth URL does not contain type")),
    };
    let label = url.path();
    let label = percent_encoding::percent_decode(label.as_bytes()).decode_utf8()?;
    let label = label.trim_start_matches("/").to_string();
    let mut secret: Option<String> = None;
    let mut issuer: Option<String> = None;
    let mut digits: Option<String> = None;
    let mut counter: Option<String> = None;
    let mut period: Option<String> = None;
    for (key, value) in url.query_pairs() {
        let field = match key {
            borrow::Cow::Borrowed("secret") => Some(&mut secret),
            borrow::Cow::Borrowed("issuer") => Some(&mut issuer),
            borrow::Cow::Borrowed("digits") => Some(&mut digits),
            borrow::Cow::Borrowed("counter") => Some(&mut counter),
            borrow::Cow::Borrowed("period") => Some(&mut period),
            _ => None,
        };
        if let Some(field) = field {
            *field = Some(value.into_owned());
        }
    }
    let label = match issuer {
        Some(ref issuer) => strip_issuer_prefix(label, issuer),
        None => label,
    };
    match secret {
        Some(secret) => Ok(UrlData {
            otp_type,
            label,
            secret,
            issuer,
            digits,
            counter,
            period,
        }),
        None => Err(Error::from("otpauth URL did not contain a secret")),
    }
}

fn run(options: Options) -> Result<(), Error> {
    let path = match options.file {
        Some(ref file) => path::PathBuf::from(file),
        None => import_qr_code()?,
    };
    let url = decode_qr_code(&path)?;
    let url_data = parse_url(&url)?;
    println!("{:?}", url_data);
    if options.file.is_none() {
        fs::remove_file(&path)?;
    }
    Ok(())
}

fn main() {
    let status = match parse_options() {
        Ok(options) => match run(options) {
            Ok(()) => 0,
            Err(err) => {
                println!("{}", err);
                1
            }
        },
        Err(err) => err,
    };
    process::exit(status);
}

#[cfg(test)]
mod tests {
    #[test]
    fn parse_url() -> Result<(), super::Error> {
        let result = super::parse_url(
            "otpauth://totp/Example:alice@google.com?secret=JBSWY3DPEHPK3PXP&issuer=Example",
        )?;
        let expected = super::UrlData {
            otp_type: "totp".to_string(),
            label: "alice@google.com".to_string(),
            secret: "JBSWY3DPEHPK3PXP".to_string(),
            issuer: Some("Example".to_string()),
            digits: None,
            counter: None,
            period: None,
        };
        assert_eq!(result, expected);

        let result = super::parse_url("otpauth://totp/ACME%20Co:john.doe@email.com?secret=HXDMVJECJJWSRB3HWIZR4IFUGFTMXBOZ&issuer=ACME%20Co&algorithm=SHA1&digits=6&period=30")?;
        let expected = super::UrlData {
            otp_type: "totp".to_string(),
            label: "john.doe@email.com".to_string(),
            secret: "HXDMVJECJJWSRB3HWIZR4IFUGFTMXBOZ".to_string(),
            issuer: Some("ACME Co".to_string()),
            digits: Some("6".to_string()),
            counter: None,
            period: Some("30".to_string()),
        };
        assert_eq!(result, expected);

        assert!(super::parse_url("otpauth://totp/test?secret=blubb").is_ok());
        assert!(super::parse_url("otauth://totp/test?secret=blubb").is_err());
        assert!(super::parse_url("otpauth://totp/test").is_err());

        Ok(())
    }
}