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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
// This file is part of HTTP Signatures

// HTTP Signatures 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.

// HTTP Signatures 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 HTTP Signatures  If not, see <http://www.gnu.org/licenses/>.

//! This module defines types and traits for creating HTTP Signatures.

use std::collections::HashMap;
use std::convert::{TryFrom, TryInto};
use std::sync::Arc;
use std::io::Read;

use ring::{rand, signature, digest, hmac};
use base64::encode;
use untrusted::Input;

use super::{SignatureAlgorithm, ShaSize};
use error::{Error, CreationError};

/// `AsHttpSignature` defines a trait for getting an Authorization Header string from any type that
/// implements it. It provides two methods: as_http_signature, which implementors must define, and
/// authorization_header, which uses as_http_signature to create the header string.
pub trait AsHttpSignature<T>
where
    T: Read,
{
    /// Gets an `HttpSignature` struct from an immutably borrowed Self
    fn as_http_signature(
        &self,
        key_id: String,
        key: T,
        algorithm: SignatureAlgorithm,
    ) -> Result<HttpSignature<T>, Error>;

    /// Generates the Authorization Header from an immutably borrowed Self
    fn authorization_header(
        &self,
        key_id: String,
        key: T,
        algorithm: SignatureAlgorithm,
    ) -> Result<String, Error> {
        Ok(self.as_http_signature(key_id, key, algorithm)?
            .authorization_header()?)
    }
}

/// `WithHttpSignature` defines a trait for adding an Authorization header to another library's
/// request or response object.
pub trait WithHttpSignature<T>: AsHttpSignature<T>
where
    T: Read,
{
    fn with_http_signature(
        &mut self,
        key_id: String,
        key: T,
        algorithm: SignatureAlgorithm,
    ) -> Result<&mut Self, Error>;
}

/// The `HttpSignature` struct, this is the entry point for creating an Authorization header. It
/// contains all the values required for generation.
pub struct HttpSignature<T>
where
    T: Read,
{
    /// The keyId field in the Authorization header
    key_id: String,
    /// The key (implementing `Read`) used to sign the request
    key: T,
    /// The algorithm used to sign the request
    algorithm: SignatureAlgorithm,
    /// The headers that will be included in the signature
    headers: HashMap<String, Vec<String>>,
}

impl<T> HttpSignature<T>
where
    T: Read,
{
    /// Create a new HttpSignature from its components.
    ///
    /// This method will Error if `headers` is empty.
    ///
    /// ### Example
    /// ```rust
    /// # use std::fs::File;
    /// # use std::collections::HashMap;
    /// # use http_signatures::Error;
    /// use http_signatures::{HttpSignature, SignatureAlgorithm, ShaSize, REQUEST_TARGET};
    ///
    /// # fn run() -> Result<(), Error> {
    /// let key_id = "test/assets/public.der".into();
    /// let priv_key = File::open("test/assets/private.der")?;
    ///
    /// let alg = SignatureAlgorithm::RSA(ShaSize::FiveTwelve);
    ///
    /// let mut headers = HashMap::new();
    /// headers.insert(REQUEST_TARGET.into(), vec!["get /".into()]);
    ///
    /// let http_sig = HttpSignature::new(key_id, priv_key, alg, headers)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(
        key_id: String,
        key: T,
        algorithm: SignatureAlgorithm,
        headers: HashMap<String, Vec<String>>,
    ) -> Result<Self, CreationError> {
        if headers.is_empty() {
            return Err(CreationError::NoHeaders);
        }

        Ok(HttpSignature {
            key_id,
            key,
            algorithm,
            headers,
        })
    }

    pub fn key_id(&self) -> &str {
        &self.key_id
    }

    pub fn algorithm(&self) -> &SignatureAlgorithm {
        &self.algorithm
    }

    pub fn headers(&self) -> &HashMap<String, Vec<String>> {
        &self.headers
    }

    /// Generate the Authorization Header from the `HttpSignature`
    ///
    /// This method errors if signing the signing-string fails.
    ///
    /// ### Example
    /// ```rust
    /// # use std::fs::File;
    /// # use std::collections::HashMap;
    /// # use http_signatures::{Error, SignatureAlgorithm, ShaSize, REQUEST_TARGET};
    /// use http_signatures::HttpSignature;
    /// # fn run() -> Result<(), Error> {
    /// # let key_id = "test/assets/public.der".into();
    /// # let priv_key = File::open("test/assets/private.der")?;
    /// # let alg = SignatureAlgorithm::RSA(ShaSize::FiveTwelve);
    /// # let mut headers = HashMap::new();
    /// # headers.insert(REQUEST_TARGET.into(), vec!["get /".into()]);
    /// # let http_signature = HttpSignature::new(key_id, priv_key, alg, headers)?;
    ///
    /// let auth_header = http_signature.authorization_header()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn authorization_header(self) -> Result<String, CreationError> {
        let signing_string: SigningString<T> = self.into();
        let signature: Signature = signing_string.try_into()?;

        Ok(signature.authorization())
    }
}

/// A default implementation of `AsHttpSignature` for `HttpSignature`.
///
/// This only works if type `T` is `Clone` in addition to `Read`, which is normally required. This
/// implementation doesn't serve much of a purpose.
impl<T> AsHttpSignature<T> for HttpSignature<T>
where
    T: Read + Clone,
{
    fn as_http_signature(&self, _: String, _: T, _: SignatureAlgorithm) -> Result<Self, Error> {
        Ok(HttpSignature {
            key_id: self.key_id.clone(),
            key: self.key.clone(),
            algorithm: self.algorithm.clone(),
            headers: self.headers.clone(),
        })
    }
}

/// The `SigningString<T>` struct uses what was given in the `HttpSignature` struct, but also has a
/// plaintext field called `signing_string` which holds the string used to sign the request.
///
/// Since `From<HttpSignature<T>>` was implemented for `SigningString<T>`, the transition is as
/// simple as calling `http_signature.into()`.
///
/// This struct does not have public fields, and does not have a constructor since it should only
/// be used as an intermediate point from `HttpSignature<T>` to the signed string.
pub struct SigningString<T> {
    key_id: String,
    key: T,
    headers: Vec<String>,
    algorithm: SignatureAlgorithm,
    // The plaintext string used to sign the request
    signing_string: String,
}

impl<T> From<HttpSignature<T>> for SigningString<T>
where
    T: Read,
{
    fn from(http_signature: HttpSignature<T>) -> Self {
        let (header_keys, signing_vec): (Vec<_>, Vec<_>) = http_signature
            .headers
            .iter()
            .map(|(header, values)| {
                (
                    header.to_lowercase(),
                    format!("{}: {}", header.to_lowercase(), values.join(", ")),
                )
            })
            .unzip();

        SigningString {
            key_id: http_signature.key_id,
            key: http_signature.key,
            headers: header_keys,
            algorithm: http_signature.algorithm,
            signing_string: signing_vec.join("\n"),
        }
    }
}

/// `Signature` is the result of using the `key: T` of `SigningString<T>` to sign the
/// `signing_string`.
///
/// To get the Authorization Header String from the Signature, the `authorization` method is
/// provided.
pub struct Signature {
    sig: String,
    key_id: String,
    headers: Vec<String>,
    algorithm: SignatureAlgorithm,
}

impl Signature {
    /// Get the Authorization Header String.
    pub fn authorization(self) -> String {
        let alg: &str = self.algorithm.into();

        format!("Signature: keyId=\"{}\",algorithm=\"{}\",headers=\"{}\",signature=\"{}\"",
                self.key_id,
                alg,
                self.headers.join(" "),
                self.sig,
        )
    }

    fn rsa<T>(mut key: T, size: &ShaSize, signing_string: &[u8]) -> Result<String, CreationError>
    where
        T: Read,
    {
        let mut private_key_der = Vec::new();
        key.read_to_end(&mut private_key_der)?;
        let private_key_der = Input::from(&private_key_der);

        let key_pair = signature::RSAKeyPair::from_der(private_key_der).map_err(
            |_| {
                CreationError::BadPrivateKey
            },
        )?;
        let key_pair = Arc::new(key_pair);

        let mut signing_state = signature::RSASigningState::new(key_pair).map_err(|_| {
            CreationError::SigningError
        })?;

        let rng = rand::SystemRandom::new();
        let mut signature = vec![0; signing_state.key_pair().public_modulus_len()];
        signing_state
            .sign(
                match *size {
                    ShaSize::TwoFiftySix => &signature::RSA_PKCS1_SHA256,
                    ShaSize::ThreeEightyFour => &signature::RSA_PKCS1_SHA384,
                    ShaSize::FiveTwelve => &signature::RSA_PKCS1_SHA512,
                },
                &rng,
                signing_string,
                signature.as_mut_slice(),
            )
            .map_err(|_| CreationError::SigningError)?;

        Ok(encode(signature.as_slice()))
    }

    fn hmac<T>(mut key: T, size: &ShaSize, signing_string: &[u8]) -> Result<String, CreationError>
    where
        T: Read,
    {
        let mut hmac_key = Vec::new();
        key.read_to_end(&mut hmac_key)?;
        let hmac_key = hmac::SigningKey::new(
            match *size {
                ShaSize::TwoFiftySix => &digest::SHA256,
                ShaSize::ThreeEightyFour => &digest::SHA384,
                ShaSize::FiveTwelve => &digest::SHA512,
            },
            &hmac_key,
        );
        let signature = hmac::sign(&hmac_key, signing_string);

        Ok(encode(signature.as_ref()))
    }
}

impl<T> TryFrom<SigningString<T>> for Signature
where
    T: Read,
{
    type Error = CreationError;

    /// Attempt to sign the signing_string. If signing fails, a `Signature` will not be created and
    /// an `Error` will be returned.
    fn try_from(signing_string: SigningString<T>) -> Result<Self, Self::Error> {
        Ok(match signing_string.algorithm {
            SignatureAlgorithm::RSA(size) => {
                Signature {
                    sig: Signature::rsa(
                        signing_string.key,
                        &size,
                        signing_string.signing_string.as_ref(),
                    )?,
                    key_id: signing_string.key_id,
                    headers: signing_string.headers,
                    algorithm: SignatureAlgorithm::RSA(size),
                }
            }
            SignatureAlgorithm::HMAC(size) => {
                Signature {
                    sig: Signature::hmac(
                        signing_string.key,
                        &size,
                        signing_string.signing_string.as_ref(),
                    )?,
                    key_id: signing_string.key_id,
                    headers: signing_string.headers,
                    algorithm: SignatureAlgorithm::HMAC(size),
                }
            }
        })
    }
}