annotate src/ur/openid.ur @ 22:70ab0230649b

Fix calculation of URL to return to after sign-up
author Adam Chlipala <adam@chlipala.net>
date Sat, 15 Jan 2011 15:24:42 -0500
parents df2eb629f21a
children ee97bc0e08fa
rev   line source
adam@6 1 val discoveryExpiry = 3600
adam@11 2 val nonceExpiry = 600
adam@11 3 val nonceSkew = 600
adam@6 4
adam@0 5 task initialize = fn () => OpenidFfi.init
adam@1 6
adam@6 7 table discoveries : { Identifier : string, Endpoint : string, Expires : time }
adam@6 8 PRIMARY KEY Identifier
adam@6 9
adam@17 10 fun eatFragment s =
adam@17 11 case String.split s #"#" of
adam@17 12 Some (s', _) => s'
adam@17 13 | _ => s
adam@17 14
adam@2 15 fun discover s =
adam@17 16 s <- return (eatFragment s);
adam@6 17 endpoint <- oneOrNoRowsE1 (SELECT (discoveries.Endpoint)
adam@6 18 FROM discoveries
adam@6 19 WHERE discoveries.Identifier = {[s]});
adam@6 20 case endpoint of
adam@6 21 Some ep => return (Some ep)
adam@6 22 | None =>
adam@6 23 r <- OpenidFfi.discover s;
adam@6 24 case r of
adam@6 25 None => return None
adam@6 26 | Some r =>
adam@6 27 tm <- now;
adam@6 28 dml (INSERT INTO discoveries (Identifier, Endpoint, Expires)
adam@6 29 VALUES ({[s]}, {[OpenidFfi.endpoint r]}, {[addSeconds tm discoveryExpiry]}));
adam@6 30 return (Some (OpenidFfi.endpoint r))
adam@3 31
adam@3 32 val createInputs =
adam@3 33 is <- OpenidFfi.createInputs;
adam@3 34 OpenidFfi.addInput is "openid.ns" "http://specs.openid.net/auth/2.0";
adam@3 35 return is
adam@3 36
adam@8 37 datatype association_type = HMAC_SHA1 | HMAC_SHA256
adam@8 38 datatype association_session_type = NoEncryption | DH_SHA1 | DH_SHA256
adam@13 39 datatype association_mode =
adam@13 40 Stateless
adam@13 41 | Stateful of {AssociationType : association_type,
adam@13 42 AssociationSessionType : association_session_type}
adam@8 43
adam@8 44 table associations : { Endpoint : string, Handle : string, Typ : serialized association_type, Key : string, Expires : time }
adam@3 45 PRIMARY KEY Endpoint
adam@3 46
adam@8 47 datatype association = Association of {Handle : string, Typ : association_type, Key : string}
adam@8 48 | AssError of string
adam@8 49 | AssAlternate of {Atype : association_type, Stype : association_session_type}
adam@3 50
adam@8 51 fun atype_show v =
adam@8 52 case v of
adam@8 53 HMAC_SHA1 => "HMAC-SHA1"
adam@8 54 | HMAC_SHA256 => "HMAC-SHA256"
adam@8 55
adam@8 56 val show_atype = mkShow atype_show
adam@8 57
adam@8 58 fun stype_show v =
adam@8 59 case v of
adam@8 60 NoEncryption => "no-encryption"
adam@8 61 | DH_SHA1 => "DH-SHA1"
adam@8 62 | DH_SHA256 => "DH-SHA256"
adam@8 63
adam@8 64 val show_stype = mkShow stype_show
adam@8 65
adam@8 66 fun atype_read s =
adam@8 67 case s of
adam@8 68 "HMAC-SHA1" => Some HMAC_SHA1
adam@8 69 | "HMAC-SHA256" => Some HMAC_SHA256
adam@8 70 | _ => None
adam@8 71
adam@8 72 val read_atype = mkRead' atype_read "association type"
adam@8 73
adam@8 74 fun stype_read s =
adam@8 75 case s of
adam@8 76 "no-encryption" => Some NoEncryption
adam@8 77 | "DH-SHA1" => Some DH_SHA1
adam@8 78 | "DH-SHA256" => Some DH_SHA256
adam@8 79 | _ => None
adam@8 80
adam@8 81 val read_stype = mkRead' stype_read "association session type"
adam@8 82
adam@8 83 fun atype_eq v1 v2 =
adam@8 84 case (v1, v2) of
adam@8 85 (HMAC_SHA1, HMAC_SHA1) => True
adam@8 86 | (HMAC_SHA256, HMAC_SHA256) => True
adam@8 87 | _ => False
adam@8 88
adam@8 89 val eq_atype = mkEq atype_eq
adam@8 90
adam@8 91 fun stype_eq v1 v2 =
adam@8 92 case (v1, v2) of
adam@8 93 (NoEncryption, NoEncryption) => True
adam@8 94 | (DH_SHA1, DH_SHA1) => True
adam@8 95 | (DH_SHA256, DH_SHA256) => True
adam@8 96 | _ => False
adam@8 97
adam@8 98 val eq_stype = mkEq stype_eq
adam@8 99
adam@8 100 fun errorResult atype stype os =
adam@8 101 case OpenidFfi.getOutput os "error" of
adam@8 102 Some v =>
adam@8 103 (case (OpenidFfi.getOutput os "error_code", OpenidFfi.getOutput os "assoc_type", OpenidFfi.getOutput os "session_type") of
adam@8 104 (Some "unsupported-type", at, st) => Some (AssAlternate {Atype = Option.get atype (Option.bind read at),
adam@8 105 Stype = Option.get stype (Option.bind read st)})
adam@8 106 | _ => Some (AssError ("OP error during association: " ^ v)))
adam@8 107 | None => None
adam@8 108
adam@8 109 fun associateNoEncryption url atype =
adam@8 110 is <- createInputs;
adam@8 111 OpenidFfi.addInput is "openid.mode" "associate";
adam@8 112 OpenidFfi.addInput is "openid.assoc_type" (show atype);
adam@8 113 OpenidFfi.addInput is "openid.session_type" (show NoEncryption);
adam@8 114
adam@8 115 os <- OpenidFfi.direct url is;
adam@8 116 case errorResult atype NoEncryption os of
adam@8 117 Some v => return v
adam@8 118 | None =>
adam@8 119 case (OpenidFfi.getOutput os "assoc_handle", OpenidFfi.getOutput os "mac_key", OpenidFfi.getOutput os "expires_in") of
adam@8 120 (Some handle, Some key, Some expires) =>
adam@8 121 (case read expires of
adam@8 122 None => return (AssError "Invalid 'expires_in' field")
adam@8 123 | Some expires =>
adam@8 124 tm <- now;
adam@8 125 dml (INSERT INTO associations (Endpoint, Handle, Typ, Key, Expires)
adam@8 126 VALUES ({[url]}, {[handle]}, {[serialize atype]}, {[key]}, {[addSeconds tm expires]}));
adam@8 127 return (Association {Handle = handle, Typ = atype, Key = key}))
adam@8 128 | (None, _, _) => return (AssError "Missing assoc_handle")
adam@8 129 | (_, None, _) => return (AssError "Missing mac_key")
adam@8 130 | _ => return (AssError "Missing expires_in")
adam@8 131
adam@8 132 fun associateDh url atype stype =
adam@8 133 dh <- OpenidFfi.generate;
adam@8 134
adam@8 135 is <- createInputs;
adam@8 136 OpenidFfi.addInput is "openid.mode" "associate";
adam@8 137 OpenidFfi.addInput is "openid.assoc_type" (show atype);
adam@8 138 OpenidFfi.addInput is "openid.session_type" (show stype);
adam@8 139 OpenidFfi.addInput is "openid.dh_modulus" (OpenidFfi.modulus dh);
adam@8 140 OpenidFfi.addInput is "openid.dh_gen" (OpenidFfi.generator dh);
adam@8 141 OpenidFfi.addInput is "openid.dh_consumer_public" (OpenidFfi.public dh);
adam@8 142
adam@8 143 os <- OpenidFfi.direct url is;
adam@8 144 case errorResult atype stype os of
adam@8 145 Some v => return v
adam@8 146 | None =>
adam@8 147 case (OpenidFfi.getOutput os "assoc_handle", OpenidFfi.getOutput os "dh_server_public",
adam@8 148 OpenidFfi.getOutput os "enc_mac_key", OpenidFfi.getOutput os "expires_in") of
adam@8 149 (Some handle, Some pub, Some mac, Some expires) =>
adam@8 150 (case read expires of
adam@8 151 None => return (AssError "Invalid 'expires_in' field")
adam@8 152 | Some expires =>
adam@12 153 secret <- OpenidFfi.compute dh pub;
adam@12 154 digest <- return (case stype of
adam@12 155 DH_SHA1 => OpenidFfi.sha1 secret
adam@12 156 | DH_SHA256 => OpenidFfi.sha256 secret
adam@12 157 | _ => error <xml>Non-DH stype in associateDh</xml>);
adam@12 158 key <- return (OpenidFfi.xor mac digest);
adam@8 159 tm <- now;
adam@8 160 dml (INSERT INTO associations (Endpoint, Handle, Typ, Key, Expires)
adam@8 161 VALUES ({[url]}, {[handle]}, {[serialize atype]}, {[key]}, {[addSeconds tm expires]}));
adam@8 162 return (Association {Handle = handle, Typ = atype, Key = key}))
adam@8 163 | (None, _, _, _) => return (AssError "Missing assoc_handle")
adam@8 164 | (_, None, _, _) => return (AssError "Missing dh_server_public")
adam@8 165 | (_, _, None, _) => return (AssError "Missing enc_mac_key")
adam@8 166 | _ => return (AssError "Missing expires_in")
adam@8 167
adam@8 168 fun oldAssociation url =
adam@8 169 secret <- oneOrNoRows1 (SELECT associations.Handle, associations.Typ, associations.Key
adam@7 170 FROM associations
adam@7 171 WHERE associations.Endpoint = {[url]});
adam@3 172 case secret of
adam@8 173 Some r => return (Some (r -- #Typ ++ {Typ = deserialize r.Typ}))
adam@8 174 | None => return None
adam@8 175
adam@8 176 fun newAssociation url atype stype =
adam@8 177 case stype of
adam@8 178 NoEncryption => associateNoEncryption url atype
adam@8 179 | _ => associateDh url atype stype
adam@8 180
adam@8 181 fun association atype stype url =
adam@8 182 secret <- oldAssociation url;
adam@8 183 case secret of
adam@4 184 Some r => return (Association r)
adam@3 185 | None =>
adam@8 186 stype <- return (case (stype, String.isPrefix {Full = url, Prefix = "https://"}) of
adam@8 187 (NoEncryption, False) => DH_SHA256
adam@8 188 | _ => stype);
adam@8 189 r <- newAssociation url atype stype;
adam@8 190 case r of
adam@8 191 AssAlternate alt =>
adam@8 192 if alt.Atype = atype && alt.Stype = stype then
adam@8 193 return (AssError "Suggested new modes match old ones!")
adam@8 194 else
adam@12 195 debug "Renegotiating protocol";
adam@8 196 newAssociation url alt.Atype alt.Stype
adam@8 197 | v => return v
adam@4 198
adam@13 199 datatype handle_result = HandleOk of {Endpoint : string, Typ : association_type, Key : string} | NoAssociation of string | HandleError of string
adam@13 200
adam@13 201 datatype authentication = AuthenticatedAs of string | Canceled | Failure of string
adam@6 202
adam@6 203 fun verifyHandle os id =
adam@10 204 id' <- return (eatFragment id);
adam@10 205 ep <- discover id';
adam@6 206 case ep of
adam@10 207 None => return (HandleError ("Discovery failed on returned identifier: " ^ id'))
adam@6 208 | Some ep =>
adam@6 209 case OpenidFfi.getOutput os "openid.assoc_handle" of
adam@6 210 None => return (HandleError "Missing association handle in response")
adam@6 211 | Some handle =>
adam@8 212 assoc <- oldAssociation ep;
adam@6 213 case assoc of
adam@13 214 None => return (NoAssociation ep)
adam@8 215 | Some assoc =>
adam@6 216 if assoc.Handle <> handle then
adam@6 217 return (HandleError "Association handles don't match")
adam@6 218 else
adam@8 219 return (HandleOk {Endpoint = ep, Typ = assoc.Typ, Key = assoc.Key})
adam@6 220
adam@14 221 fun verifyStateless os ep id expectInvalidation =
adam@13 222 os' <- OpenidFfi.direct ep (OpenidFfi.remode os "check_authentication");
adam@13 223 case OpenidFfi.getOutput os' "error" of
adam@13 224 Some msg => return (Failure ("Failure confirming message contents with OP: " ^ msg))
adam@13 225 | None =>
adam@14 226 let
adam@14 227 fun finish () = case OpenidFfi.getOutput os' "is_valid" of
adam@14 228 Some "true" => return (AuthenticatedAs id)
adam@14 229 | _ => return (Failure "OP does not confirm message contents")
adam@14 230 in
adam@14 231 case OpenidFfi.getOutput os' "invalidate_handle" of
adam@14 232 None =>
adam@14 233 if expectInvalidation then
adam@14 234 return (Failure "Claimed invalidate_handle is not confirmed")
adam@14 235 else
adam@14 236 finish ()
adam@14 237 | Some handle =>
adam@14 238 dml (DELETE FROM associations
adam@14 239 WHERE Endpoint = {[ep]} AND Handle = {[handle]});
adam@14 240 finish ()
adam@14 241 end
adam@13 242
adam@6 243 table nonces : { Endpoint : string, Nonce : string, Expires : time }
adam@6 244 PRIMARY KEY (Endpoint, Nonce)
adam@6 245
adam@6 246 fun timeOfNonce s =
adam@6 247 case String.split s #"T" of
adam@6 248 None => None
adam@6 249 | Some (date, s) =>
adam@6 250 case String.split s #"Z" of
adam@6 251 None => None
adam@7 252 | Some (time, _) => readUtc (date ^ " " ^ time)
adam@6 253
adam@6 254 fun verifyNonce os ep =
adam@6 255 case OpenidFfi.getOutput os "openid.response_nonce" of
adam@6 256 None => return (Some "Missing nonce in OP response")
adam@6 257 | Some nonce =>
adam@6 258 case timeOfNonce nonce of
adam@6 259 None => return (Some "Invalid timestamp in nonce")
adam@6 260 | Some tm =>
adam@6 261 now <- now;
adam@9 262 if tm < addSeconds now (-nonceExpiry) then
adam@6 263 return (Some "Nonce timestamp is too old")
adam@9 264 else if tm > addSeconds now nonceSkew then
adam@11 265 return (Some "Nonce timestamp is too far in the future")
adam@6 266 else
adam@6 267 b <- oneRowE1 (SELECT COUNT( * ) > 0
adam@6 268 FROM nonces
adam@6 269 WHERE nonces.Endpoint = {[ep]}
adam@6 270 AND nonces.Nonce = {[nonce]});
adam@6 271
adam@6 272 if b then
adam@6 273 return (Some "Duplicate nonce")
adam@6 274 else
adam@6 275 dml (INSERT INTO nonces (Endpoint, Nonce, Expires)
adam@9 276 VALUES ({[ep]}, {[nonce]}, {[addSeconds now nonceExpiry]}));
adam@6 277 return None
adam@6 278
adam@8 279 fun verifySig os atype key =
adam@6 280 case OpenidFfi.getOutput os "openid.signed" of
adam@6 281 None => return (Some "Missing openid.signed in OP response")
adam@6 282 | Some signed =>
adam@6 283 case OpenidFfi.getOutput os "openid.sig" of
adam@6 284 None => return (Some "Missing openid.sig in OP response")
adam@6 285 | Some sign => let
adam@9 286 fun gatherNvps signed required acc =
adam@6 287 let
adam@6 288 val (this, next) =
adam@6 289 case String.split signed #"," of
adam@6 290 None => (signed, None)
adam@6 291 | Some (this, next) => (this, Some next)
adam@6 292 in
adam@6 293 case OpenidFfi.getOutput os ("openid." ^ this) of
adam@6 294 None => None
adam@6 295 | Some value =>
adam@6 296 let
adam@9 297 val required = List.filter (fn other => other <> this) required
adam@6 298 val acc = acc ^ this ^ ":" ^ value ^ "\n"
adam@6 299 in
adam@6 300 case next of
adam@9 301 None => Some (required, acc)
adam@9 302 | Some next => gatherNvps next required acc
adam@6 303 end
adam@6 304 end
adam@6 305 in
adam@9 306 case gatherNvps signed ("op_endpoint" :: "return_to" :: "response_nonce" :: "assoc_handle" :: "claimed_id" :: "identity" :: []) "" of
adam@6 307 None => return (Some "openid.signed mentions missing field")
adam@9 308 | Some ([], nvps) =>
adam@6 309 let
adam@8 310 val sign' = case atype of
adam@12 311 HMAC_SHA256 => OpenidFfi.hmac_sha256 key nvps
adam@12 312 | HMAC_SHA1 => OpenidFfi.hmac_sha1 key nvps
adam@6 313 in
adam@6 314 if sign' = sign then
adam@6 315 return None
adam@6 316 else
adam@6 317 return (Some "Signatures don't match")
adam@6 318 end
adam@9 319 | Some (left, _) => return (Some ("openid.signed is missing required fields: " ^ show left))
adam@6 320 end
adam@6 321
adam@10 322 fun authenticate after r =
adam@10 323 let
adam@12 324 fun returnTo (qs : option queryString) =
adam@10 325 case qs of
adam@10 326 None => after (Failure "Empty query string for OpenID callback")
adam@10 327 | Some qs =>
adam@10 328 os <- OpenidFfi.indirect qs;
adam@10 329 case OpenidFfi.getOutput os "openid.error" of
adam@13 330 Some v => after (Failure ("Authentication failed: " ^ v))
adam@10 331 | None =>
adam@10 332 case OpenidFfi.getOutput os "openid.mode" of
adam@10 333 None => after (Failure "No openid.mode in response")
adam@10 334 | Some mode =>
adam@10 335 case mode of
adam@10 336 "cancel" => after Canceled
adam@10 337 | "id_res" =>
adam@10 338 (case OpenidFfi.getOutput os "openid.claimed_id" of
adam@10 339 None => after (Failure "Missing identity in OP response")
adam@10 340 | Some id =>
adam@13 341 errO <- verifyReturnTo os;
adam@6 342 case errO of
adam@13 343 Some s => after (Failure s)
adam@13 344 | None =>
adam@13 345 errO <- verifyHandle os id;
adam@6 346 case errO of
adam@13 347 HandleError s => after (Failure s)
adam@13 348 | NoAssociation ep =>
adam@14 349 r <- verifyStateless os ep id False;
adam@13 350 after r
adam@13 351 | HandleOk {Endpoint = ep, Typ = atype, Key = key} =>
adam@14 352 case OpenidFfi.getOutput os "openid.invalidate_handle" of
adam@14 353 Some _ =>
adam@14 354 r <- verifyStateless os ep id True;
adam@14 355 after r
adam@10 356 | None =>
adam@14 357 errO <- verifyNonce os ep;
adam@10 358 case errO of
adam@10 359 Some s => after (Failure s)
adam@14 360 | None =>
adam@14 361 errO <- verifySig os atype key;
adam@14 362 case errO of
adam@14 363 Some s => after (Failure s)
adam@14 364 | None => after (AuthenticatedAs id))
adam@10 365 | _ => after (Failure ("Unexpected openid.mode: " ^ mode))
adam@4 366
adam@12 367 and verifyReturnTo os =
adam@10 368 case OpenidFfi.getOutput os "openid.return_to" of
adam@10 369 None => return (Some "Missing return_to in OP response")
adam@10 370 | Some rt =>
adam@12 371 if rt <> show (effectfulUrl returnTo) then
adam@10 372 return (Some "Wrong return_to in OP response")
adam@10 373 else
adam@10 374 return None
adam@15 375
adam@15 376 val realmString = case r.Realm of
adam@15 377 None => ""
adam@15 378 | Some realm => "&openid.realm=" ^ realm
adam@10 379 in
adam@10 380 dy <- discover r.Identifier;
adam@10 381 case dy of
adam@10 382 None => return "Discovery failed"
adam@10 383 | Some dy =>
adam@13 384 case r.Association of
adam@13 385 Stateless =>
adam@10 386 redirect (bless (dy ^ "?openid.ns=http://specs.openid.net/auth/2.0&openid.mode=checkid_setup&openid.claimed_id="
adam@17 387 ^ eatFragment r.Identifier
adam@17 388 ^ "&openid.identity=http://specs.openid.net/auth/2.0/identifier_select&openid.return_to="
adam@15 389 ^ show (effectfulUrl returnTo) ^ realmString))
adam@13 390 | Stateful ar =>
adam@13 391 assoc <- association ar.AssociationType ar.AssociationSessionType dy;
adam@13 392 case assoc of
adam@13 393 AssError msg => return ("Association failure: " ^ msg)
adam@13 394 | AssAlternate _ => return "Association failure: server didn't accept its own alternate association modes"
adam@13 395 | Association assoc =>
adam@13 396 redirect (bless (dy ^ "?openid.ns=http://specs.openid.net/auth/2.0&openid.mode=checkid_setup&openid.claimed_id="
adam@17 397 ^ eatFragment r.Identifier
adam@17 398 ^ "&openid.identity=http://specs.openid.net/auth/2.0/identifier_select&openid.assoc_handle="
adam@15 399 ^ assoc.Handle ^ "&openid.return_to=" ^ show (effectfulUrl returnTo) ^ realmString))
adam@10 400 end
adam@6 401
adam@22 402 task periodic 60 = fn () =>
adam@22 403 dml (DELETE FROM discoveries WHERE Expires < CURRENT_TIMESTAMP);
adam@22 404 dml (DELETE FROM associations WHERE Expires < CURRENT_TIMESTAMP);
adam@22 405 dml (DELETE FROM nonces WHERE Expires < CURRENT_TIMESTAMP)