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 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
// 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/>. //! HTTP Signatures, an implementation of [the http signatures specification](https://tools.ietf.org/html/draft-cavage-http-signatures-09) //! //! The base crate provides types for creating and verifying signatures, and the features //! `use_hyper`, `use_reqwest`, and `use_rocket` provide implementations of required traits for //! easily using HTTP Signatures with web applications. //! //! # Creating an HTTP Signature //! //! To get a string that would be the contents of an HTTP Request's Authorization header, a few //! steps must be taken. The method, path, and query must be known, furthermore, there must be at //! least one item in the headers hashmap, if there is not, the HTTP Signature creation will fail. //! //! ```rust //! # extern crate ring; //! # extern crate http_signatures; //! # //! # use ring::signature::RSAKeyPair; //! use http_signatures::{ //! CreateKey, //! # Error, //! HttpSignature, //! # Input, //! ShaSize, //! # SignatureAlgorithm, //! REQUEST_TARGET, //! }; //! # //! # use std::{fs::File, collections::BTreeMap, io::Read}; //! # //! # fn run() -> Result<(), Error> { //! # let mut priv_key = File::open("tests/assets/private.der")?; //! # let mut priv_key_vec = Vec::new(); //! # priv_key.read_to_end(&mut priv_key_vec)?; //! # let priv_key_input = Input::from(&priv_key_vec); //! # let priv_key = RSAKeyPair::from_der(priv_key_input).unwrap(); //! //! let method = "GET"; //! let path = "/test"; //! let query = "key=value"; //! //! let mut headers: BTreeMap<String, Vec<String>> = BTreeMap::new(); //! headers.insert("Accept".into(), vec!["application/json".into()]); //! headers.insert( //! REQUEST_TARGET.into(), //! vec![format!("{} {}?{}", method.to_lowercase(), path, query)], //! ); //! //! let priv_creation_key = CreateKey::rsa(priv_key, ShaSize::SHA512); //! let key_id = "1".into(); //! //! let auth_header = HttpSignature::new(key_id, priv_creation_key, headers)? //! .authorization_header()?; //! //! println!("Authorization: {}", auth_header); //! # Ok(()) //! # } //! # fn main() { run().unwrap(); } //! ``` //! //! # Verifying an HTTP Signature //! //! ```rust //! # extern crate ring; //! # extern crate http_signatures; //! # //! # use ring::signature::RSAKeyPair; //! use http_signatures::{ //! prelude::*, //! # CreateKey, //! VerifyKey, //! # Error, //! # HttpSignature, //! # Input, //! # ShaSize, //! SignedHeader, //! # REQUEST_TARGET, //! }; //! # //! # use std::{fs::File, collections::BTreeMap, io::Read}; //! # //! # fn some_auth_header() -> Result<String, Error> { //! # //! # let mut priv_key_file = File::open("tests/assets/private.der")?; //! # let mut priv_key_vec = Vec::new(); //! # priv_key_file.read_to_end(&mut priv_key_vec)?; //! # let priv_key_input = Input::from(&priv_key_vec); //! # let priv_key = RSAKeyPair::from_der(priv_key_input).unwrap(); //! # let priv_creation_key = CreateKey::rsa(priv_key, ShaSize::SHA512); //! # //! # let method = "GET"; //! # let path = "/test"; //! # let query = "key=value"; //! # let mut headers: BTreeMap<String, Vec<String>> = BTreeMap::new(); //! # //! # headers.insert("Accept".into(), vec!["application/json".into()]); //! # headers.insert( //! # REQUEST_TARGET.into(), //! # vec![format!("{} {}?{}", method.to_lowercase(), path, query)], //! # ); //! # let key_id = "1".into(); //! # let auth_header = HttpSignature::new(key_id, priv_creation_key, headers)? //! # .authorization_header()?; //! # //! # Ok(auth_header) //! # } //! //! # fn run() -> Result<(), Error> { //! # let auth_header = some_auth_header()?; //! # let mut pub_key_file = File::open("tests/assets/public.der")?; //! # let mut pub_key_vec = Vec::new(); //! # pub_key_file.read_to_end(&mut pub_key_vec)?; //! //! let mut headers = Vec::new(); //! headers.push(("Accept".into(), "application/json".into())); //! //! let method = "GET"; //! let path = "/test"; //! let query = "key=value"; //! //! let auth_header = SignedHeader::new(&auth_header)?; //! auth_header //! .verify(&headers, method, path, Some(query), VerifyKey::unchecked_from_vec(pub_key_vec))?; //! //! # Ok(()) //! # } //! # fn main() { run().unwrap(); } //! ``` #[cfg(feature = "use_actix_web")] pub mod use_actix_web_client; #[cfg(feature = "use_actix_web")] pub mod use_actix_web_server; #[cfg(feature = "use_hyper")] pub mod use_hyper_client; #[cfg(feature = "use_hyper")] pub mod use_hyper_server; #[cfg(feature = "use_reqwest")] pub mod use_reqwest; #[cfg(feature = "use_rocket")] pub mod use_rocket; mod create; mod error; pub mod prelude; mod verify; use std::str::FromStr; use ring::{ digest::{Algorithm, SHA256, SHA384, SHA512}, signature::{ RSAEncoding, VerificationAlgorithm, RSA_PKCS1_2048_8192_SHA256, RSA_PKCS1_2048_8192_SHA384, RSA_PKCS1_2048_8192_SHA512, RSA_PKCS1_SHA256, RSA_PKCS1_SHA384, RSA_PKCS1_SHA512, }, }; use self::error::DecodeError; pub use self::{ create::{CreateKey, HttpSignature}, error::Error, verify::{SignedHeader, VerifyKey}, }; pub const REQUEST_TARGET: &str = "(request-target)"; /// Variations of the Sha hashing function. /// /// This stuct is used to tell the RSA and HMAC signature functions how big the sha hash should be. /// It currently offers three variations. #[derive(Clone, Copy, Debug)] pub enum ShaSize { /// SHA256 SHA256, /// SHA384 SHA384, /// SHA512 SHA512, } impl ShaSize { pub fn hmac_algorithm(self) -> &'static Algorithm { match self { ShaSize::SHA256 => &SHA256, ShaSize::SHA384 => &SHA384, ShaSize::SHA512 => &SHA512, } } pub fn rsa_algorithm(self) -> &'static dyn RSAEncoding { match self { ShaSize::SHA256 => &RSA_PKCS1_SHA256, ShaSize::SHA384 => &RSA_PKCS1_SHA384, ShaSize::SHA512 => &RSA_PKCS1_SHA512, } } pub fn verification_algorithm(self) -> &'static dyn VerificationAlgorithm { match self { ShaSize::SHA256 => &RSA_PKCS1_2048_8192_SHA256, ShaSize::SHA384 => &RSA_PKCS1_2048_8192_SHA384, ShaSize::SHA512 => &RSA_PKCS1_2048_8192_SHA512, } } } /// Which algorithm should be used to create an HTTP header. /// /// This library uses Ring 0.11.0 for creating and verifying hashes, so this determines whether the /// library will use Ring's RSA Signatures or Rings's HMAC signatures. #[derive(Clone, Copy, Debug)] pub enum SignatureAlgorithm { /// RSA RSA(ShaSize), /// HMAC HMAC(ShaSize), } /// Convert an `&str` into a `SignatureAlgorithm` impl FromStr for SignatureAlgorithm { type Err = DecodeError; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "rsa-sha256" => Ok(SignatureAlgorithm::RSA(ShaSize::SHA256)), "rsa-sha384" => Ok(SignatureAlgorithm::RSA(ShaSize::SHA384)), "rsa-sha512" => Ok(SignatureAlgorithm::RSA(ShaSize::SHA512)), "hmac-sha256" => Ok(SignatureAlgorithm::HMAC(ShaSize::SHA256)), "hmac-sha384" => Ok(SignatureAlgorithm::HMAC(ShaSize::SHA384)), "hmac-sha512" => Ok(SignatureAlgorithm::HMAC(ShaSize::SHA512)), e => Err(DecodeError::InvalidAlgorithm(e.into())), } } } /// Convert a `SignatureAlgorithm` into an `&str` impl From<SignatureAlgorithm> for &'static str { fn from(alg: SignatureAlgorithm) -> Self { match alg { SignatureAlgorithm::RSA(size) => match size { ShaSize::SHA256 => "rsa-sha256", ShaSize::SHA384 => "rsa-sha384", ShaSize::SHA512 => "rsa-sha512", }, SignatureAlgorithm::HMAC(size) => match size { ShaSize::SHA256 => "hmac-sha256", ShaSize::SHA384 => "hmac-sha384", ShaSize::SHA512 => "hmac-sha512", }, } } } #[cfg(test)] mod tests { use ring::{ hmac::{self, SigningKey}, rand, signature::RSAKeyPair, }; use untrusted::Input; use std::{collections::BTreeMap, fs::File}; use crate::{ create::{CreateKey, HttpSignature}, verify::{SignedHeader, VerifyKey}, ShaSize, REQUEST_TARGET, }; #[test] fn hmac_256_can_sign_and_verify() { hmac_can_sign_and_verify(ShaSize::SHA256); } #[test] fn hmac_384_can_sign_and_verify() { hmac_can_sign_and_verify(ShaSize::SHA384); } #[test] fn hmac_512_can_sign_and_verify() { hmac_can_sign_and_verify(ShaSize::SHA512); } #[test] fn rsa_256_can_sign_and_verify() { rsa_can_sign_and_verify(ShaSize::SHA256); } #[test] fn rsa_384_can_sign_and_verify() { rsa_can_sign_and_verify(ShaSize::SHA384); } #[test] fn rsa_512_can_sign_and_verify() { rsa_can_sign_and_verify(ShaSize::SHA512); } fn hmac_can_sign_and_verify(sha_size: ShaSize) { let algorithm = sha_size.hmac_algorithm(); let rng = rand::SystemRandom::new(); let len = hmac::recommended_key_len(&algorithm); let mut key_vec: Vec<u8> = Vec::new(); for _ in 0..len { key_vec.push(0); } let _ = SigningKey::generate_serializable(&algorithm, &rng, key_vec.as_mut_slice()).unwrap(); let key = SigningKey::new(&algorithm, key_vec.as_ref()); let creation_key = CreateKey::hmac(key, sha_size); let method = "GET"; let path = "/test"; let query = "key=value"; let mut headers_one: BTreeMap<String, Vec<String>> = BTreeMap::new(); headers_one.insert("Accept".into(), vec!["application/json".into()]); headers_one.insert( REQUEST_TARGET.into(), vec![format!("{} {}?{}", method.to_lowercase(), path, query)], ); let mut headers_two = Vec::new(); headers_two.push(("Accept".into(), "application/json".into())); let key_id = "1".into(); let auth_header = HttpSignature::new(key_id, creation_key, headers_one) .unwrap() .authorization_header() .unwrap(); let auth_header = SignedHeader::new(&auth_header).unwrap(); auth_header .verify( &headers_two, method, path, Some(query), VerifyKey::unchecked_from_vec(key_vec), ) .unwrap(); } fn rsa_can_sign_and_verify(sha_size: ShaSize) { use std::io::Read; let mut priv_key = File::open("tests/assets/private.der").unwrap(); let mut priv_key_vec = Vec::new(); priv_key.read_to_end(&mut priv_key_vec).unwrap(); let priv_key_input = Input::from(&priv_key_vec); let priv_key = RSAKeyPair::from_der(priv_key_input).unwrap(); let priv_creation_key = CreateKey::rsa(priv_key, sha_size); let mut pub_key = File::open("tests/assets/public.der").unwrap(); let mut pub_key_vec = Vec::new(); pub_key.read_to_end(&mut pub_key_vec).unwrap(); let method = "GET"; let path = "/test"; let query = "key=value"; let mut headers_one: BTreeMap<String, Vec<String>> = BTreeMap::new(); headers_one.insert("Accept".into(), vec!["application/json".into()]); headers_one.insert( REQUEST_TARGET.into(), vec![format!("{} {}?{}", method.to_lowercase(), path, query)], ); let mut headers_two = Vec::new(); headers_two.push(("Accept".into(), "application/json".into())); let key_id = "1".into(); let auth_header = HttpSignature::new(key_id, priv_creation_key, headers_one) .unwrap() .signature_header() .unwrap(); let auth_header = SignedHeader::new(&auth_header).unwrap(); auth_header .verify( &headers_two, method, path, Some(query), VerifyKey::unchecked_from_vec(pub_key_vec), ) .unwrap(); } }