annotate src/ur/openid.ur @ 15:35bc4da563dd

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