aboutsummaryrefslogtreecommitdiffstats
path: root/src/main.rs
blob: b742d950a9e70c2a17132bda7f023c880a682910 (plain) (blame)
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
// checkpw - Check passwords against pwnedpasswords.com
// Copyright (C) 2018  Harald Eilertsen <haraldei@anduin.net>
//
// This program is free software: you can redistribute it and/or modify
// 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.
//
// This program is distributed in the hope that it will be useful,
// 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
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

extern crate futures;
extern crate hyper;
extern crate hyper_tls;
extern crate ring;
extern crate tokio_core;

use futures::{Future, Stream};
use hyper::Client;
use hyper_tls::HttpsConnector;
use ring::digest;
use std::env;
use tokio_core::reactor::Core;

//
// Convert a slice of bytes into a string of hex values
//
fn to_hex(data: &[u8]) -> String {
    data.into_iter()
        .map(|b| format!("{:02X}", b))
        .collect()
}

#[test]
fn test_to_hex() {
    let input = [0x01, 0x00, 0xff, 0xaa, 0x10, 0x07];
    assert_eq!(to_hex(&input), "0100FFAA1007");
}

///
/// Split the digest into the range and rest parts for k-anonymity
///
fn to_k_anon(d: digest::Digest) -> (String, String) {
    let mut hash = to_hex(d.as_ref());
    let rest = hash.split_off(5);
    (hash, rest)
}

#[test]
fn test_k_anon() {
    let input = digest::digest(&digest::SHA1, "Passw0rd".as_bytes());
    let res = to_k_anon(input);
    assert_eq!(res, (String::from("EBFC7"), String::from("910077770C8340F63CD2DCA2AC1F120444F")));
}

struct Password {
    pw: String,
    pub range: String,
    pub rest: String,
}

impl Password {
    pub fn new(pw: &str) -> Password {
        let (range, rest) = to_k_anon(digest::digest(&digest::SHA1, &pw.as_bytes()));

        Password {
            pw: String::from(pw),
            range: range,
            rest: rest,
        }
    }
}

#[test]
fn test_creating_new_password() {
    let pw = Password::new("Passw0rd");
    assert_eq!(&pw.range, "EBFC7");
    assert_eq!(&pw.rest, "910077770C8340F63CD2DCA2AC1F120444F");
}

fn check(pw: Password) -> Result<(), Box<::std::error::Error>> {
    let mut core = Core::new()?;
    let client = Client::configure()
        .connector(HttpsConnector::new(4, &core.handle())?)
        .build(&core.handle());

    let uri = format!("https://api.pwnedpasswords.com/range/{}", pw.range).parse()?;

    let req = client.get(uri).and_then(|res| {
        res.body().concat2().and_then(move |body| {
            let hashes = std::str::from_utf8(&body)?;
            if let Some(pos) = hashes.find(&pw.rest) {
                println!("Password is PWNED!");
                if let Some(res) = hashes[pos..].lines().take(1).collect::<Vec<_>>().pop() {
                    let count = res.split(':').skip(1).collect::<Vec<_>>().pop().unwrap();
                    println!("The password {} was found in {} breaches", pw.pw, count);
                }
            }
            Ok(())
        })
    });

    core.run(req)?;

    Ok(())
}

fn print_usage() {
    println!("Usage: checkpw <pw>...");
}

fn main() {
    let (args, passwords) : (Vec<String>, Vec<String>) = env::args()
        .skip(1)
        .partition(|arg| arg.starts_with('-'));

    if args.is_empty() && passwords.is_empty() {
        print_usage();
        return;
    }

    for pw in passwords {
        check(Password::new(&pw)).unwrap();
    }
}