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
use credentials::Key;
use base64;
use ring::constant_time;
use std::io::Write;
use std::ops::Deref;
use error::*;
use time;

/// The kind of MAC calcuation (corresponding to the first line of the message)
pub enum MacType {
    Header,
    Response,
    Bewit,
}

/// Mac represents a message authentication code, the signature in a Hawk transaction.
///
/// This class supports creating Macs using the Hawk specification, and comparing Macs
/// using a cosntant-time comparison (thus preventing timing side-channel attacks).
#[derive(Debug, Clone)]
pub struct Mac(Vec<u8>);

impl Mac {
    pub fn new(mac_type: MacType,
               key: &Key,
               ts: time::Timespec,
               nonce: &str,
               method: &str,
               host: &str,
               port: u16,
               path: &str,
               hash: Option<&[u8]>,
               ext: Option<&str>)
               -> Result<Mac> {
        let mut buffer: Vec<u8> = vec![];

        write!(buffer,
               "{}\n",
               match mac_type {
                   MacType::Header => "hawk.1.header",
                   MacType::Response => "hawk.1.response",
                   MacType::Bewit => "hawk.1.bewit",
               })?;
        write!(buffer, "{}\n", ts.sec)?;
        write!(buffer, "{}\n", nonce)?;
        write!(buffer, "{}\n", method)?;
        write!(buffer, "{}\n", path)?;
        write!(buffer, "{}\n", host)?;
        write!(buffer, "{}\n", port)?;

        if let Some(ref h) = hash {
            write!(buffer, "{}\n", base64::encode(h))?;
        } else {
            write!(buffer, "\n")?;
        }

        match ext {
            Some(ref e) => write!(buffer, "{}\n", e)?,
            None => write!(buffer, "\n")?,
        };

        return Ok(Mac(key.sign(buffer.as_ref())));
    }
}

impl AsRef<[u8]> for Mac {
    fn as_ref(&self) -> &[u8] {
        &self.0[..]
    }
}

impl From<Vec<u8>> for Mac {
    fn from(original: Vec<u8>) -> Self {
        Mac(original)
    }
}

impl Deref for Mac {
    type Target = Vec<u8>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl PartialEq for Mac {
    fn eq(&self, other: &Mac) -> bool {
        match constant_time::verify_slices_are_equal(&self.0[..], &other.0[..]) {
            Ok(_) => true,
            Err(_) => false,
        }
    }
}


#[cfg(test)]
mod test {
    use super::{Mac, MacType};
    use time::Timespec;
    use credentials::Key;
    use ring::digest;

    fn key() -> Key {
        Key::new(vec![11u8, 19, 228, 209, 79, 189, 200, 59, 166, 47, 86, 254, 235, 184, 120, 197,
                      75, 152, 201, 79, 115, 61, 111, 242, 219, 187, 173, 14, 227, 108, 60, 232],
                 &digest::SHA256)
    }

    #[test]
    fn test_make_mac() {
        let key = key();
        let mac = Mac::new(MacType::Header,
                           &key,
                           Timespec::new(1000, 100),
                           "nonny",
                           "POST",
                           "mysite.com",
                           443,
                           "/v1/api",
                           None,
                           None)
            .unwrap();
        println!("got {:?}", mac);
        assert!(mac.0 ==
                vec![192, 227, 235, 121, 157, 185, 197, 79, 189, 214, 235, 139, 9, 232, 99, 55,
                     67, 30, 68, 0, 150, 187, 192, 238, 21, 200, 209, 107, 245, 159, 243, 178]);
    }

    #[test]
    fn test_make_mac_hash() {
        let key = key();
        let hash = vec![1, 2, 3, 4, 5];
        let mac = Mac::new(MacType::Header,
                           &key,
                           Timespec::new(1000, 100),
                           "nonny",
                           "POST",
                           "mysite.com",
                           443,
                           "/v1/api",
                           Some(&hash),
                           None)
            .unwrap();
        println!("got {:?}", mac);
        assert!(mac.0 ==
                vec![61, 128, 208, 253, 88, 135, 190, 196, 1, 69, 153, 193, 124, 4, 195, 87, 38,
                     96, 181, 34, 65, 234, 58, 157, 175, 175, 145, 151, 61, 0, 57, 5]);
    }

    #[test]
    fn test_make_mac_ext() {
        let key = key();
        let ext = "ext-data".to_string();
        let mac = Mac::new(MacType::Header,
                           &key,
                           Timespec::new(1000, 100),
                           "nonny",
                           "POST",
                           "mysite.com",
                           443,
                           "/v1/api",
                           None,
                           Some(&ext))
            .unwrap();
        println!("got {:?}", mac);
        assert!(mac.0 ==
                vec![187, 104, 238, 100, 168, 112, 37, 68, 187, 141, 168, 155, 177, 193, 113, 0,
                     50, 105, 127, 36, 24, 117, 200, 251, 138, 199, 108, 14, 105, 123, 234, 119]);
    }
}