annotate src/ur/openid.ur @ 10:194577b60771

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