annotate src/ur/openid.ur @ 12:c778455fe570

Diffie-Hellman seems to be working
author Adam Chlipala <adam@chlipala.net>
date Sat, 01 Jan 2011 14:00:52 -0500
parents e637249abfd2
children de04a3fc6b72
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@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@12 143 secret <- OpenidFfi.compute dh pub;
adam@12 144 digest <- return (case stype of
adam@12 145 DH_SHA1 => OpenidFfi.sha1 secret
adam@12 146 | DH_SHA256 => OpenidFfi.sha256 secret
adam@12 147 | _ => error <xml>Non-DH stype in associateDh</xml>);
adam@12 148 key <- return (OpenidFfi.xor mac digest);
adam@8 149 tm <- now;
adam@8 150 dml (INSERT INTO associations (Endpoint, Handle, Typ, Key, Expires)
adam@8 151 VALUES ({[url]}, {[handle]}, {[serialize atype]}, {[key]}, {[addSeconds tm expires]}));
adam@8 152 return (Association {Handle = handle, Typ = atype, Key = key}))
adam@8 153 | (None, _, _, _) => return (AssError "Missing assoc_handle")
adam@8 154 | (_, None, _, _) => return (AssError "Missing dh_server_public")
adam@8 155 | (_, _, None, _) => return (AssError "Missing enc_mac_key")
adam@8 156 | _ => return (AssError "Missing expires_in")
adam@8 157
adam@8 158 fun oldAssociation url =
adam@8 159 secret <- oneOrNoRows1 (SELECT associations.Handle, associations.Typ, associations.Key
adam@7 160 FROM associations
adam@7 161 WHERE associations.Endpoint = {[url]});
adam@3 162 case secret of
adam@8 163 Some r => return (Some (r -- #Typ ++ {Typ = deserialize r.Typ}))
adam@8 164 | None => return None
adam@8 165
adam@8 166 fun newAssociation url atype stype =
adam@8 167 case stype of
adam@8 168 NoEncryption => associateNoEncryption url atype
adam@8 169 | _ => associateDh url atype stype
adam@8 170
adam@8 171 fun association atype stype url =
adam@8 172 secret <- oldAssociation url;
adam@8 173 case secret of
adam@4 174 Some r => return (Association r)
adam@3 175 | None =>
adam@8 176 stype <- return (case (stype, String.isPrefix {Full = url, Prefix = "https://"}) of
adam@8 177 (NoEncryption, False) => DH_SHA256
adam@8 178 | _ => stype);
adam@8 179 r <- newAssociation url atype stype;
adam@8 180 case r of
adam@8 181 AssAlternate alt =>
adam@8 182 if alt.Atype = atype && alt.Stype = stype then
adam@8 183 return (AssError "Suggested new modes match old ones!")
adam@8 184 else
adam@12 185 debug "Renegotiating protocol";
adam@8 186 newAssociation url alt.Atype alt.Stype
adam@8 187 | v => return v
adam@4 188
adam@6 189 fun eatFragment s =
adam@6 190 case String.split s #"#" of
adam@10 191 Some (s', _) => s'
adam@6 192 | _ => s
adam@6 193
adam@8 194 datatype handle_result = HandleOk of {Endpoint : string, Typ : association_type, Key : string} | HandleError of string
adam@6 195
adam@6 196 fun verifyHandle os id =
adam@10 197 id' <- return (eatFragment id);
adam@10 198 ep <- discover id';
adam@6 199 case ep of
adam@10 200 None => return (HandleError ("Discovery failed on returned identifier: " ^ id'))
adam@6 201 | Some ep =>
adam@6 202 case OpenidFfi.getOutput os "openid.assoc_handle" of
adam@6 203 None => return (HandleError "Missing association handle in response")
adam@6 204 | Some handle =>
adam@8 205 assoc <- oldAssociation ep;
adam@6 206 case assoc of
adam@8 207 None => return (HandleError "Couldn't find association handle")
adam@8 208 | Some assoc =>
adam@6 209 if assoc.Handle <> handle then
adam@6 210 return (HandleError "Association handles don't match")
adam@6 211 else
adam@8 212 return (HandleOk {Endpoint = ep, Typ = assoc.Typ, Key = assoc.Key})
adam@6 213
adam@6 214 table nonces : { Endpoint : string, Nonce : string, Expires : time }
adam@6 215 PRIMARY KEY (Endpoint, Nonce)
adam@6 216
adam@6 217 fun timeOfNonce s =
adam@6 218 case String.split s #"T" of
adam@6 219 None => None
adam@6 220 | Some (date, s) =>
adam@6 221 case String.split s #"Z" of
adam@6 222 None => None
adam@7 223 | Some (time, _) => readUtc (date ^ " " ^ time)
adam@6 224
adam@6 225 fun verifyNonce os ep =
adam@6 226 case OpenidFfi.getOutput os "openid.response_nonce" of
adam@6 227 None => return (Some "Missing nonce in OP response")
adam@6 228 | Some nonce =>
adam@6 229 case timeOfNonce nonce of
adam@6 230 None => return (Some "Invalid timestamp in nonce")
adam@6 231 | Some tm =>
adam@6 232 now <- now;
adam@9 233 if tm < addSeconds now (-nonceExpiry) then
adam@6 234 return (Some "Nonce timestamp is too old")
adam@9 235 else if tm > addSeconds now nonceSkew then
adam@11 236 return (Some "Nonce timestamp is too far in the future")
adam@6 237 else
adam@6 238 b <- oneRowE1 (SELECT COUNT( * ) > 0
adam@6 239 FROM nonces
adam@6 240 WHERE nonces.Endpoint = {[ep]}
adam@6 241 AND nonces.Nonce = {[nonce]});
adam@6 242
adam@6 243 if b then
adam@6 244 return (Some "Duplicate nonce")
adam@6 245 else
adam@6 246 dml (INSERT INTO nonces (Endpoint, Nonce, Expires)
adam@9 247 VALUES ({[ep]}, {[nonce]}, {[addSeconds now nonceExpiry]}));
adam@6 248 return None
adam@6 249
adam@8 250 fun verifySig os atype key =
adam@6 251 case OpenidFfi.getOutput os "openid.signed" of
adam@6 252 None => return (Some "Missing openid.signed in OP response")
adam@6 253 | Some signed =>
adam@6 254 case OpenidFfi.getOutput os "openid.sig" of
adam@6 255 None => return (Some "Missing openid.sig in OP response")
adam@6 256 | Some sign => let
adam@9 257 fun gatherNvps signed required acc =
adam@6 258 let
adam@6 259 val (this, next) =
adam@6 260 case String.split signed #"," of
adam@6 261 None => (signed, None)
adam@6 262 | Some (this, next) => (this, Some next)
adam@6 263 in
adam@6 264 case OpenidFfi.getOutput os ("openid." ^ this) of
adam@6 265 None => None
adam@6 266 | Some value =>
adam@6 267 let
adam@9 268 val required = List.filter (fn other => other <> this) required
adam@6 269 val acc = acc ^ this ^ ":" ^ value ^ "\n"
adam@6 270 in
adam@6 271 case next of
adam@9 272 None => Some (required, acc)
adam@9 273 | Some next => gatherNvps next required acc
adam@6 274 end
adam@6 275 end
adam@6 276 in
adam@9 277 case gatherNvps signed ("op_endpoint" :: "return_to" :: "response_nonce" :: "assoc_handle" :: "claimed_id" :: "identity" :: []) "" of
adam@6 278 None => return (Some "openid.signed mentions missing field")
adam@9 279 | Some ([], nvps) =>
adam@6 280 let
adam@8 281 val sign' = case atype of
adam@12 282 HMAC_SHA256 => OpenidFfi.hmac_sha256 key nvps
adam@12 283 | HMAC_SHA1 => OpenidFfi.hmac_sha1 key nvps
adam@6 284 in
adam@9 285 (*debug ("Fields: " ^ signed);
adam@6 286 debug ("Nvps: " ^ nvps);
adam@7 287 debug ("Key: " ^ key);
adam@6 288 debug ("His: " ^ sign);
adam@9 289 debug ("Mine: " ^ sign');*)
adam@6 290 if sign' = sign then
adam@6 291 return None
adam@6 292 else
adam@6 293 return (Some "Signatures don't match")
adam@6 294 end
adam@9 295 | Some (left, _) => return (Some ("openid.signed is missing required fields: " ^ show left))
adam@6 296 end
adam@6 297
adam@10 298 datatype authentication = AuthenticatedAs of string | Canceled | Failure of string
adam@10 299
adam@10 300 fun authenticate after r =
adam@10 301 let
adam@12 302 fun returnTo (qs : option queryString) =
adam@10 303 case qs of
adam@10 304 None => after (Failure "Empty query string for OpenID callback")
adam@10 305 | Some qs =>
adam@10 306 os <- OpenidFfi.indirect qs;
adam@10 307 case OpenidFfi.getOutput os "openid.error" of
adam@10 308 Some v => after (Failure "Authentication failed: {[v]}")
adam@10 309 | None =>
adam@10 310 case OpenidFfi.getOutput os "openid.mode" of
adam@10 311 None => after (Failure "No openid.mode in response")
adam@10 312 | Some mode =>
adam@10 313 case mode of
adam@10 314 "cancel" => after Canceled
adam@10 315 | "id_res" =>
adam@10 316 (case OpenidFfi.getOutput os "openid.claimed_id" of
adam@10 317 None => after (Failure "Missing identity in OP response")
adam@10 318 | Some id =>
adam@10 319 errO <- verifyHandle os id;
adam@6 320 case errO of
adam@10 321 HandleError s => after (Failure s)
adam@10 322 | HandleOk {Endpoint = ep, Typ = atype, Key = key} =>
adam@12 323 errO <- verifyReturnTo os;
adam@6 324 case errO of
adam@10 325 Some s => after (Failure s)
adam@10 326 | None =>
adam@10 327 errO <- verifyNonce os ep;
adam@10 328 case errO of
adam@10 329 Some s => after (Failure s)
adam@10 330 | None =>
adam@10 331 errO <- verifySig os atype key;
adam@10 332 case errO of
adam@10 333 Some s => after (Failure s)
adam@10 334 | None => after (AuthenticatedAs id))
adam@10 335 | _ => after (Failure ("Unexpected openid.mode: " ^ mode))
adam@4 336
adam@12 337 and verifyReturnTo os =
adam@10 338 case OpenidFfi.getOutput os "openid.return_to" of
adam@10 339 None => return (Some "Missing return_to in OP response")
adam@10 340 | Some rt =>
adam@12 341 if rt <> show (effectfulUrl returnTo) then
adam@10 342 return (Some "Wrong return_to in OP response")
adam@10 343 else
adam@10 344 return None
adam@10 345 in
adam@10 346 dy <- discover r.Identifier;
adam@10 347 case dy of
adam@10 348 None => return "Discovery failed"
adam@10 349 | Some dy =>
adam@10 350 assoc <- association r.AssociationType r.AssociationSessionType dy;
adam@10 351 case assoc of
adam@10 352 AssError msg => return ("Association failure: " ^ msg)
adam@10 353 | AssAlternate _ => return "Association failure: server didn't accept its own alternate association modes"
adam@10 354 | Association assoc =>
adam@10 355 redirect (bless (dy ^ "?openid.ns=http://specs.openid.net/auth/2.0&openid.mode=checkid_setup&openid.claimed_id="
adam@10 356 ^ r.Identifier ^ "&openid.identity=http://specs.openid.net/auth/2.0/identifier_select&openid.assoc_handle="
adam@12 357 ^ assoc.Handle ^ "&openid.return_to=" ^ show (effectfulUrl returnTo)))
adam@10 358 end
adam@6 359
adam@6 360 task periodic 1 = fn () =>
adam@6 361 dml (DELETE FROM discoveries WHERE Expires < CURRENT_TIMESTAMP);
adam@6 362 dml (DELETE FROM associations WHERE Expires < CURRENT_TIMESTAMP);
adam@6 363 dml (DELETE FROM nonces WHERE Expires < CURRENT_TIMESTAMP)