| 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 | use hmac::{Hmac, Mac}; |
| 56 | use serde::Deserialize; |
| 57 | use sha2::Sha256; |
| 58 | use subtle::ConstantTimeEq; |
| 59 | use topcoat::{ |
| 60 | Result, |
| 61 | context::{Cx, app_context}, |
| 62 | router::{Body, Response, StatusCode, header::ORIGIN, headers}, |
| 63 | session, |
| 64 | view::{component, view}, |
| 65 | }; |
| 66 | |
| 67 | type HmacSha256 = Hmac<Sha256>; |
| 68 | |
| 69 | |
| 70 | pub const CSRF_FIELD: &str = "csrf_token"; |
| 71 | |
| 72 | |
| 73 | |
| 74 | |
| 75 | pub const REFUSED: &str = "This form was submitted from somewhere else. Go back and try again."; |
| 76 | |
| 77 | |
| 78 | |
| 79 | |
| 80 | |
| 81 | |
| 82 | pub const EXEMPT: &[(&str, &str)] = &[ |
| 83 | ( |
| 84 | "/{handle}/repos/{repo}/git-upload-pack", |
| 85 | "git transport: HTTP Basic per request, no cookie and no form", |
| 86 | ), |
| 87 | ( |
| 88 | "/{handle}/repos/{repo}/git-receive-pack", |
| 89 | "git transport: HTTP Basic per request, no cookie and no form", |
| 90 | ), |
| 91 | ( |
| 92 | "/api/setup", |
| 93 | "JSON a provisioner POSTs, never a browser carrying a session", |
| 94 | ), |
| 95 | ( |
| 96 | "/auth/setup", |
| 97 | "submitted signed out: no session to bind a token to", |
| 98 | ), |
| 99 | ( |
| 100 | "/auth/forgot", |
| 101 | "submitted signed out: no session to bind a token to", |
| 102 | ), |
| 103 | ( |
| 104 | "/auth/reset/{token}", |
| 105 | "submitted signed out, and the URL's own token is the unguessable part", |
| 106 | ), |
| 107 | ]; |
| 108 | |
| 109 | |
| 110 | |
| 111 | |
| 112 | |
| 113 | pub struct CsrfSecret([u8; 32]); |
| 114 | |
| 115 | impl CsrfSecret { |
| 116 | |
| 117 | #[must_use] |
| 118 | pub fn generate() -> Self { |
| 119 | use rand::Rng; |
| 120 | |
| 121 | let mut bytes = [0u8; 32]; |
| 122 | rand::rng().fill_bytes(&mut bytes); |
| 123 | |
| 124 | Self(bytes) |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | impl std::fmt::Debug for CsrfSecret { |
| 129 | |
| 130 | |
| 131 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 132 | f.write_str("CsrfSecret(redacted)") |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | |
| 137 | |
| 138 | |
| 139 | fn derive(secret: &CsrfSecret, session: &[u8]) -> String { |
| 140 | |
| 141 | let mut mac = HmacSha256::new_from_slice(&secret.0).expect("hmac takes any key"); |
| 142 | mac.update(session); |
| 143 | |
| 144 | mac.finalize() |
| 145 | .into_bytes() |
| 146 | .iter() |
| 147 | .map(|byte| format!("{byte:02x}")) |
| 148 | .collect() |
| 149 | } |
| 150 | |
| 151 | |
| 152 | |
| 153 | |
| 154 | |
| 155 | fn matches(expected: &str, presented: &str) -> bool { |
| 156 | expected.as_bytes().ct_eq(presented.as_bytes()).unwrap_u8() == 1 |
| 157 | } |
| 158 | |
| 159 | |
| 160 | async fn token(cx: &Cx) -> Result<Option<String>> { |
| 161 | let Some(hash) = session::token_hash(cx).await? else { |
| 162 | return Ok(None); |
| 163 | }; |
| 164 | |
| 165 | Ok(Some(derive(app_context::<CsrfSecret>(cx), &*hash))) |
| 166 | } |
| 167 | |
| 168 | |
| 169 | |
| 170 | |
| 171 | |
| 172 | |
| 173 | |
| 174 | |
| 175 | #[component] |
| 176 | pub async fn csrf_field(cx: &Cx) -> Result { |
| 177 | let token = token(cx).await?.unwrap_or_default(); |
| 178 | |
| 179 | view! { <input type="hidden" name=(CSRF_FIELD) value=(token.as_str()) /> } |
| 180 | } |
| 181 | |
| 182 | |
| 183 | |
| 184 | |
| 185 | |
| 186 | |
| 187 | |
| 188 | |
| 189 | |
| 190 | |
| 191 | |
| 192 | |
| 193 | |
| 194 | pub async fn csrf_verified(cx: &Cx, presented: &str) -> Result<()> { |
| 195 | match token(cx).await? { |
| 196 | Some(expected) if matches(&expected, presented) => Ok(()), |
| 197 | _ => { |
| 198 | eprintln!("steid: refused a form submission with no valid CSRF token"); |
| 199 | Err(CsrfRefused.into()) |
| 200 | } |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | |
| 205 | |
| 206 | |
| 207 | |
| 208 | |
| 209 | |
| 210 | |
| 211 | |
| 212 | |
| 213 | |
| 214 | |
| 215 | |
| 216 | |
| 217 | |
| 218 | |
| 219 | |
| 220 | pub async fn csrf_verified_response(cx: &Cx, presented: &str) -> Result<Option<Response>> { |
| 221 | match csrf_verified(cx, presented).await { |
| 222 | Ok(()) => Ok(None), |
| 223 | Err(error) => { |
| 224 | if error.downcast_ref::<CsrfRefused>().is_some() { |
| 225 | Ok(Some(refused())) |
| 226 | } else { |
| 227 | Err(error) |
| 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 | pub fn csrf_verified_signed_out(cx: &Cx) -> Option<Response> { |
| 256 | let headers = headers(cx); |
| 257 | let says_where = headers.contains_key("sec-fetch-site") || headers.contains_key(ORIGIN); |
| 258 | |
| 259 | if says_where && session::verify_origin(cx).is_ok() { |
| 260 | return None; |
| 261 | } |
| 262 | |
| 263 | eprintln!("steid: refused a signed-out form submission that did not say where it came from"); |
| 264 | Some(refused()) |
| 265 | } |
| 266 | |
| 267 | |
| 268 | |
| 269 | fn refused() -> Response { |
| 270 | let mut response = Response::new(Body::from(format!("{REFUSED}\n"))); |
| 271 | *response.status_mut() = StatusCode::FORBIDDEN; |
| 272 | response |
| 273 | } |
| 274 | |
| 275 | |
| 276 | |
| 277 | |
| 278 | |
| 279 | |
| 280 | #[derive(Debug)] |
| 281 | pub struct CsrfRefused; |
| 282 | |
| 283 | impl std::fmt::Display for CsrfRefused { |
| 284 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 285 | f.write_str("the form did not carry this session's CSRF token") |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | impl std::error::Error for CsrfRefused {} |
| 290 | |
| 291 | |
| 292 | |
| 293 | |
| 294 | |
| 295 | |
| 296 | #[derive(Debug, Deserialize)] |
| 297 | pub struct CsrfGuard { |
| 298 | |
| 299 | |
| 300 | |
| 301 | #[serde(default)] |
| 302 | pub csrf_token: String, |
| 303 | } |
| 304 | |
| 305 | #[cfg(test)] |
| 306 | mod tests { |
| 307 | use super::*; |
| 308 | |
| 309 | |
| 310 | |
| 311 | fn secret(byte: u8) -> CsrfSecret { |
| 312 | CsrfSecret([byte; 32]) |
| 313 | } |
| 314 | |
| 315 | #[test] |
| 316 | fn a_token_is_the_hmac_of_the_session_under_the_secret() { |
| 317 | |
| 318 | |
| 319 | assert_eq!( |
| 320 | derive(&secret(0x01), b"sess"), |
| 321 | "8a705977f42fbbc2a31942039d841760ec5de4c812f88e983674c0a5b44f61f7" |
| 322 | ); |
| 323 | } |
| 324 | |
| 325 | #[test] |
| 326 | fn two_sessions_get_different_tokens_under_one_secret() { |
| 327 | |
| 328 | |
| 329 | assert_ne!(derive(&secret(0x01), b"one"), derive(&secret(0x01), b"two")); |
| 330 | } |
| 331 | |
| 332 | #[test] |
| 333 | fn two_boots_get_different_tokens_for_one_session() { |
| 334 | |
| 335 | |
| 336 | assert_ne!(derive(&secret(0x01), b"one"), derive(&secret(0x02), b"one")); |
| 337 | } |
| 338 | |
| 339 | #[test] |
| 340 | fn a_token_verifies_against_itself_and_nothing_else() { |
| 341 | let token = derive(&secret(0x01), b"sess"); |
| 342 | |
| 343 | assert!(matches(&token, &token)); |
| 344 | assert!(!matches(&token, "")); |
| 345 | assert!(!matches(&token, &token[..token.len() - 1])); |
| 346 | assert!(!matches(&token, &format!("{token}0"))); |
| 347 | assert!(!matches(&token, &derive(&secret(0x01), b"other"))); |
| 348 | } |
| 349 | |
| 350 | #[test] |
| 351 | fn the_secret_does_not_print_itself() { |
| 352 | |
| 353 | assert_eq!(format!("{:?}", secret(0x01)), "CsrfSecret(redacted)"); |
| 354 | } |
| 355 | |
| 356 | #[test] |
| 357 | fn every_exemption_says_why() { |
| 358 | for (route, reason) in EXEMPT { |
| 359 | assert!(route.starts_with('/'), "{route} is not a route"); |
| 360 | assert!(!reason.is_empty(), "{route} is exempt for no stated reason"); |
| 361 | } |
| 362 | } |
| 363 | } |