| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | use std::time::{SystemTime, UNIX_EPOCH}; |
| 6 | |
| 7 | use aes_gcm::Aes128Gcm; |
| 8 | use aes_gcm::KeyInit; |
| 9 | use aes_gcm::aead::Aead; |
| 10 | use base64::Engine; |
| 11 | use base64::engine::general_purpose::URL_SAFE_NO_PAD; |
| 12 | use hkdf::Hkdf; |
| 13 | use p256::ecdsa::signature::Signer; |
| 14 | use p256::ecdsa::{Signature, SigningKey}; |
| 15 | use p256::elliptic_curve::sec1::ToSec1Point; |
| 16 | use sha2::Sha256; |
| 17 | |
| 18 | use forge_core::{Error, Result}; |
| 19 | |
| 20 | |
| 21 | const POINT_LEN: usize = 65; |
| 22 | |
| 23 | const RECORD_SIZE: u32 = 4096; |
| 24 | |
| 25 | const VAPID_TTL: u64 = 12 * 60 * 60; |
| 26 | |
| 27 | const PUSH_TTL: &str = "43200"; |
| 28 | |
| 29 | |
| 30 | pub fn decode_b64(text: &str) -> Result<Vec<u8>> { |
| 31 | URL_SAFE_NO_PAD |
| 32 | .decode(text.trim_end_matches('=')) |
| 33 | .map_err(|_| Error::Invalid("not base64url".into())) |
| 34 | } |
| 35 | |
| 36 | |
| 37 | pub fn encode_b64(bytes: &[u8]) -> String { |
| 38 | URL_SAFE_NO_PAD.encode(bytes) |
| 39 | } |
| 40 | |
| 41 | |
| 42 | |
| 43 | fn random_secret() -> p256::SecretKey { |
| 44 | loop { |
| 45 | let mut bytes = [0u8; 32]; |
| 46 | rand::fill(&mut bytes); |
| 47 | if let Ok(secret) = p256::SecretKey::from_slice(&bytes) { |
| 48 | return secret; |
| 49 | } |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | |
| 54 | pub fn new_vapid_private() -> [u8; 32] { |
| 55 | let mut out = [0u8; 32]; |
| 56 | out.copy_from_slice(&random_secret().to_bytes()); |
| 57 | out |
| 58 | } |
| 59 | |
| 60 | |
| 61 | pub fn vapid_key_pair(private: &[u8; 32]) -> Result<SigningKey> { |
| 62 | SigningKey::from_slice(private).map_err(|_| Error::Crypto("bad VAPID key".into())) |
| 63 | } |
| 64 | |
| 65 | |
| 66 | |
| 67 | pub fn vapid_public_key(private: &[u8; 32]) -> Result<String> { |
| 68 | let secret = |
| 69 | p256::SecretKey::from_slice(private).map_err(|_| Error::Crypto("bad VAPID key".into()))?; |
| 70 | let point = secret.public_key().to_sec1_point(false); |
| 71 | Ok(encode_b64(point.as_bytes())) |
| 72 | } |
| 73 | |
| 74 | |
| 75 | |
| 76 | fn encrypt_body( |
| 77 | ua_public: &p256::PublicKey, |
| 78 | auth: &[u8], |
| 79 | as_secret: &p256::SecretKey, |
| 80 | salt: &[u8; 16], |
| 81 | payload: &[u8], |
| 82 | ) -> Result<Vec<u8>> { |
| 83 | let encryption_error = |
| 84 | |e: &dyn std::fmt::Display| Error::Crypto(format!("web push encryption failed: {e}")); |
| 85 | let as_public = as_secret.public_key().to_sec1_point(false); |
| 86 | let ua_point = ua_public.to_sec1_point(false); |
| 87 | let shared = p256::ecdh::diffie_hellman(as_secret.to_nonzero_scalar(), ua_public.as_affine()); |
| 88 | |
| 89 | |
| 90 | let mut key_info = b"WebPush: info\0".to_vec(); |
| 91 | key_info.extend_from_slice(ua_point.as_bytes()); |
| 92 | key_info.extend_from_slice(as_public.as_bytes()); |
| 93 | let mut ikm = [0u8; 32]; |
| 94 | Hkdf::<Sha256>::new(Some(auth), &shared.raw_secret_bytes()[..]) |
| 95 | .expand(&key_info, &mut ikm) |
| 96 | .map_err(|e| encryption_error(&e))?; |
| 97 | |
| 98 | |
| 99 | let mut cek = [0u8; 16]; |
| 100 | let mut nonce = [0u8; 12]; |
| 101 | let prk = Hkdf::<Sha256>::new(Some(salt), &ikm); |
| 102 | prk.expand(b"Content-Encoding: aes128gcm\0", &mut cek) |
| 103 | .map_err(|e| encryption_error(&e))?; |
| 104 | prk.expand(b"Content-Encoding: nonce\0", &mut nonce) |
| 105 | .map_err(|e| encryption_error(&e))?; |
| 106 | |
| 107 | |
| 108 | |
| 109 | if payload.len() + 1 + 16 > RECORD_SIZE as usize { |
| 110 | return Err(Error::Invalid("the push message is too large".into())); |
| 111 | } |
| 112 | let mut plaintext = payload.to_vec(); |
| 113 | plaintext.push(0x02); |
| 114 | let ciphertext = Aes128Gcm::new(&cek.into()) |
| 115 | .encrypt(&nonce.into(), plaintext.as_slice()) |
| 116 | .map_err(|e| encryption_error(&e))?; |
| 117 | |
| 118 | let mut body = Vec::with_capacity(salt.len() + 4 + 1 + POINT_LEN + ciphertext.len()); |
| 119 | body.extend_from_slice(salt); |
| 120 | body.extend_from_slice(&RECORD_SIZE.to_be_bytes()); |
| 121 | body.push(POINT_LEN as u8); |
| 122 | body.extend_from_slice(as_public.as_bytes()); |
| 123 | body.extend_from_slice(&ciphertext); |
| 124 | Ok(body) |
| 125 | } |
| 126 | |
| 127 | |
| 128 | |
| 129 | fn vapid_token(uri: &http::Uri, subject: &str, key_pair: &SigningKey) -> Result<String> { |
| 130 | let bad_endpoint = || Error::Invalid("bad push endpoint".into()); |
| 131 | let scheme = uri.scheme_str().ok_or_else(bad_endpoint)?; |
| 132 | let authority = uri.authority().ok_or_else(bad_endpoint)?; |
| 133 | let now = SystemTime::now() |
| 134 | .duration_since(UNIX_EPOCH) |
| 135 | .map_err(|_| Error::Crypto("the system clock is before 1970".into()))? |
| 136 | .as_secs(); |
| 137 | let header = URL_SAFE_NO_PAD.encode(r#"{"typ":"JWT","alg":"ES256"}"#); |
| 138 | let claims = serde_json::json!({ |
| 139 | "aud": format!("{scheme}://{authority}"), |
| 140 | "exp": now + VAPID_TTL, |
| 141 | "sub": subject, |
| 142 | }); |
| 143 | let input = format!("{header}.{}", URL_SAFE_NO_PAD.encode(claims.to_string())); |
| 144 | let signature: Signature = key_pair |
| 145 | .try_sign(input.as_bytes()) |
| 146 | .map_err(|e| Error::Crypto(format!("VAPID signing failed: {e}")))?; |
| 147 | Ok(format!( |
| 148 | "{input}.{}", |
| 149 | URL_SAFE_NO_PAD.encode(signature.to_bytes()) |
| 150 | )) |
| 151 | } |
| 152 | |
| 153 | |
| 154 | |
| 155 | |
| 156 | pub fn push_request( |
| 157 | endpoint: &str, |
| 158 | p256dh: &[u8], |
| 159 | auth: &[u8], |
| 160 | subject: &str, |
| 161 | key_pair: &SigningKey, |
| 162 | payload: Vec<u8>, |
| 163 | ) -> Result<http::Request<Vec<u8>>> { |
| 164 | if p256dh.len() != POINT_LEN { |
| 165 | return Err(Error::Invalid( |
| 166 | "the browser key is not a P-256 point".into(), |
| 167 | )); |
| 168 | } |
| 169 | let ua_public = p256::PublicKey::from_sec1_bytes(p256dh) |
| 170 | .map_err(|_| Error::Invalid("the browser key is not on the curve".into()))?; |
| 171 | if auth.len() != 16 { |
| 172 | return Err(Error::Invalid( |
| 173 | "the browser auth secret is not 16 bytes".into(), |
| 174 | )); |
| 175 | } |
| 176 | let uri: http::Uri = endpoint |
| 177 | .parse() |
| 178 | .map_err(|_| Error::Invalid("bad push endpoint".into()))?; |
| 179 | |
| 180 | let mut salt = [0u8; 16]; |
| 181 | rand::fill(&mut salt); |
| 182 | let body = encrypt_body(&ua_public, auth, &random_secret(), &salt, &payload)?; |
| 183 | |
| 184 | let token = vapid_token(&uri, subject, key_pair)?; |
| 185 | let public = key_pair.verifying_key().to_sec1_point(false); |
| 186 | http::Request::builder() |
| 187 | .method(http::Method::POST) |
| 188 | .uri(uri) |
| 189 | .header("content-encoding", "aes128gcm") |
| 190 | .header("content-type", "application/octet-stream") |
| 191 | .header("ttl", PUSH_TTL) |
| 192 | .header( |
| 193 | "authorization", |
| 194 | format!("vapid t={token}, k={}", encode_b64(public.as_bytes())), |
| 195 | ) |
| 196 | .body(body) |
| 197 | .map_err(|e| Error::Crypto(format!("web push request failed: {e}"))) |
| 198 | } |
| 199 | |
| 200 | #[cfg(test)] |
| 201 | mod tests { |
| 202 | use super::*; |
| 203 | |
| 204 | #[test] |
| 205 | fn a_browser_key_that_is_not_a_point_is_refused() { |
| 206 | let key_pair = vapid_key_pair(&new_vapid_private()).expect("key"); |
| 207 | let auth = [7u8; 16]; |
| 208 | let not_a_point = [4u8; 65]; |
| 209 | assert!( |
| 210 | push_request( |
| 211 | "https://push.example.test/x", |
| 212 | ¬_a_point, |
| 213 | &auth, |
| 214 | "mailto:tahinli@example.test", |
| 215 | &key_pair, |
| 216 | b"hi".to_vec() |
| 217 | ) |
| 218 | .is_err() |
| 219 | ); |
| 220 | assert!( |
| 221 | push_request( |
| 222 | "https://push.example.test/x", |
| 223 | &[0x04; 10], |
| 224 | &auth, |
| 225 | "mailto:tahinli@example.test", |
| 226 | &key_pair, |
| 227 | b"hi".to_vec() |
| 228 | ) |
| 229 | .is_err() |
| 230 | ); |
| 231 | } |
| 232 | |
| 233 | #[test] |
| 234 | fn the_request_is_an_encrypted_vapid_post_to_the_endpoint() { |
| 235 | let private = new_vapid_private(); |
| 236 | let key_pair = vapid_key_pair(&private).expect("key"); |
| 237 | let browser = p256::SecretKey::from_slice(&new_vapid_private()).expect("scalar"); |
| 238 | let point = browser |
| 239 | .public_key() |
| 240 | .to_sec1_point(false) |
| 241 | .as_bytes() |
| 242 | .to_vec(); |
| 243 | let auth = [9u8; 16]; |
| 244 | let endpoint = "https://push.example.test/send/abc"; |
| 245 | let payload = br#"{"title":"tahinli/forge#1"}"#.to_vec(); |
| 246 | let request = push_request( |
| 247 | endpoint, |
| 248 | &point, |
| 249 | &auth, |
| 250 | "mailto:tahinli@example.test", |
| 251 | &key_pair, |
| 252 | payload.clone(), |
| 253 | ) |
| 254 | .expect("request"); |
| 255 | |
| 256 | assert_eq!(request.method(), http::Method::POST); |
| 257 | assert_eq!(request.uri().to_string(), endpoint); |
| 258 | assert_eq!(request.headers()["content-encoding"], "aes128gcm"); |
| 259 | assert_eq!(request.headers()["ttl"], "43200"); |
| 260 | |
| 261 | |
| 262 | let auth_header = request.headers()["authorization"] |
| 263 | .to_str() |
| 264 | .expect("ascii") |
| 265 | .to_owned(); |
| 266 | assert!(auth_header.starts_with("vapid "), "{auth_header}"); |
| 267 | assert!(auth_header.contains(&format!( |
| 268 | "k={}", |
| 269 | vapid_public_key(&private).expect("public") |
| 270 | ))); |
| 271 | let token = auth_header |
| 272 | .split("t=") |
| 273 | .nth(1) |
| 274 | .and_then(|rest| rest.split(',').next()) |
| 275 | .expect("token"); |
| 276 | let claims = token.split('.').nth(1).expect("claims"); |
| 277 | let claims = decode_b64(claims).expect("base64"); |
| 278 | let claims: serde_json::Value = serde_json::from_slice(&claims).expect("json"); |
| 279 | assert_eq!(claims["aud"], "https://push.example.test"); |
| 280 | assert_eq!(claims["sub"], "mailto:tahinli@example.test"); |
| 281 | |
| 282 | |
| 283 | let body = request.body(); |
| 284 | assert!(body.len() > payload.len()); |
| 285 | assert!(!body.windows(payload.len()).any(|w| w == payload.as_slice())); |
| 286 | } |
| 287 | |
| 288 | #[test] |
| 289 | fn the_public_key_is_the_uncompressed_point() { |
| 290 | let public = vapid_public_key(&new_vapid_private()).expect("public"); |
| 291 | assert_eq!(decode_b64(&public).expect("b64").len(), POINT_LEN); |
| 292 | } |
| 293 | |
| 294 | #[test] |
| 295 | fn the_rfc_8291_appendix_a_vector_encrypts_to_the_published_body() { |
| 296 | let as_secret = p256::SecretKey::from_slice( |
| 297 | &decode_b64("yfWPiYE-n46HLnH0KqZOF1fJJU3MYrct3AELtAQ-oRw").expect("b64"), |
| 298 | ) |
| 299 | .expect("key"); |
| 300 | let ua_public = p256::PublicKey::from_sec1_bytes( |
| 301 | &decode_b64( |
| 302 | "BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4", |
| 303 | ) |
| 304 | .expect("b64"), |
| 305 | ) |
| 306 | .expect("point"); |
| 307 | let auth = decode_b64("BTBZMqHH6r4Tts7J_aSIgg").expect("b64"); |
| 308 | let salt: [u8; 16] = decode_b64("DGv6ra1nlYgDCS1FRnbzlw") |
| 309 | .expect("b64") |
| 310 | .try_into() |
| 311 | .expect("16 bytes"); |
| 312 | let body = encrypt_body( |
| 313 | &ua_public, |
| 314 | &auth, |
| 315 | &as_secret, |
| 316 | &salt, |
| 317 | b"When I grow up, I want to be a watermelon", |
| 318 | ) |
| 319 | .expect("body"); |
| 320 | assert_eq!( |
| 321 | encode_b64(&body), |
| 322 | "DGv6ra1nlYgDCS1FRnbzlwAAEABBBP4z9KsN6nGRTbVYI_c7VJSPQTBtkgcy27mlmlMoZIIgDll6e3vCYLocInmYWAmS6TlzAC8wEqKK6PBru3jl7A_yl95bQpu6cVPTpK4Mqgkf1CXztLVBSt2Ks3oZwbuwXPXLWyouBWLVWGNWQexSgSxsj_Qulcy4a-fN" |
| 323 | ); |
| 324 | } |
| 325 | } |