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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
|
namespace Janrain.OpenId.Consumer
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using Org.Mentalis.Security.Cryptography;
using Janrain.OpenId;
using Janrain.OpenId.Store;
using System.Web;
using System.IO;
public class GenericConsumer
{
private static uint TOKEN_LIFETIME = 120;
private IAssociationStore store;
private Fetcher fetcher;
public GenericConsumer(IAssociationStore store, Fetcher fetcher)
{
this.store = store;
this.fetcher = fetcher;
}
public AuthRequest Begin(ServiceEndpoint service_endpoint)
{
string nonce = CryptUtil.CreateNonce();
string token = new Token(service_endpoint).Serialize(store.AuthKey);
Association assoc = this.GetAssociation(service_endpoint.ServerUrl);
AuthRequest request = new AuthRequest(token, assoc, service_endpoint);
request.ReturnToArgs.Add(QueryStringArgs.nonce, nonce);
return request;
}
public ConsumerResponse Complete(NameValueCollection query, string tokenString)
{
string mode = query[QueryStringArgs.openid.mode];
if (mode == null)
mode = "<no mode specified>";
Token token = Token.Deserialize(tokenString, store.AuthKey);
if (mode == QueryStringArgs.Modes.cancel)
throw new CancelException(token.IdentityUrl);
if (mode == QueryStringArgs.Modes.error)
{
string error = query[QueryStringArgs.openid.error];
throw new FailureException(token.IdentityUrl, error);
}
if (mode == QueryStringArgs.Modes.id_res)
{
if (token.IdentityUrl == null)
throw new FailureException(token.IdentityUrl, "No session state found");
ConsumerResponse response = DoIdRes(query, token.IdentityUrl, token.ServerId, token.ServerUrl);
CheckNonce(response, query[QueryStringArgs.nonce]);
return response;
}
throw new FailureException(token.IdentityUrl, "Invalid openid.mode: " + mode);
}
private bool CheckAuth(NameValueCollection query, Uri server_url)
{
NameValueCollection request = CreateCheckAuthRequest(query);
if (request == null)
return false;
IDictionary response = MakeKVPost(request, server_url);
if (response == null)
return false;
return ProcessCheckAuthResponse(response, server_url);
}
private void CheckNonce(ConsumerResponse response, string nonce)
{
NameValueCollection nvc = HttpUtility.ParseQueryString(response.ReturnTo.Query);
string value = nvc[QueryStringArgs.nonce];
if (String.IsNullOrEmpty(value))
throw new FailureException(response.IdentityUrl,
"Nonce missing from return_to: " +
response.ReturnTo.AbsoluteUri);
if (value != nonce)
throw new FailureException(response.IdentityUrl, "Nonce mismatch");
}
private IDictionary MakeKVPost(NameValueCollection args, Uri server_url)
{
byte[] body = ASCIIEncoding.ASCII.GetBytes(UriUtil.CreateQueryString(args));
try
{
FetchResponse resp = this.fetcher.Post(server_url, body);
return KVUtil.KVToDict(resp.data);
}
catch // (FetchException e)
{
//if (e.response == null)
// return null;
//else (if e.response.code == HttpStatusCode.BadRequest)
// # XXX: log this
// pass
//else:
// # XXX: log this
// pass
return null;
}
}
private ConsumerResponse DoIdRes(NameValueCollection query, Uri consumer_id, Uri server_id, Uri server_url)
{
Converter<string, string> getRequired = delegate(string key)
{
string val = query[key];
if (val == null)
throw new FailureException(consumer_id, "Missing required field: " + key);
return val;
};
string user_setup_url = query[QueryStringArgs.openid.user_setup_url];
if (user_setup_url != null)
throw new SetupNeededException(consumer_id, new Uri(user_setup_url));
string return_to = getRequired(QueryStringArgs.openid.return_to);
string server_id2 = getRequired(QueryStringArgs.openid.identity);
string assoc_handle = getRequired(QueryStringArgs.openid.assoc_handle);
if (server_id.AbsoluteUri != server_id.ToString())
throw new FailureException(consumer_id, "Server ID (delegate) mismatch");
Association assoc = this.store.GetAssociation(server_url, assoc_handle);
if (assoc == null)
{
// It's not an association we know about. Dumb mode is our
// only possible path for recovery.
if (!CheckAuth(query, server_url))
throw new FailureException(consumer_id, "check_authentication failed");
return new ConsumerResponse(consumer_id, query, query[QueryStringArgs.openid.signed]);
}
if (assoc.ExpiresIn <= 0)
{
throw new FailureException(consumer_id, String.Format("Association with {0} expired", server_url));
}
// Check the signature
string sig = getRequired(QueryStringArgs.openid.sig);
string signed = getRequired(QueryStringArgs.openid.signed);
string[] signed_array = signed.Split(',');
string v_sig = assoc.SignDict(signed_array, query, QueryStringArgs.openid.Prefix);
if (v_sig != sig)
throw new FailureException(consumer_id, "Bad signature");
return new ConsumerResponse(consumer_id, query, signed);
}
private static AssociationRequest CreateAssociationRequest(Uri server_url)
{
NameValueCollection args = new NameValueCollection();
args.Add(QueryStringArgs.openid.mode, QueryStringArgs.Modes.associate);
args.Add(QueryStringArgs.openid.assoc_type, QueryStringArgs.HMAC_SHA1);
DiffieHellman dh = null;
if (server_url.Scheme != Uri.UriSchemeHttps)
{
// Initiate Diffie-Hellman Exchange
dh = CryptUtil.CreateDiffieHellman();
byte[] dhPublic = dh.CreateKeyExchange();
string cpub = CryptUtil.UnsignedToBase64(dhPublic);
args.Add(QueryStringArgs.openid.session_type, QueryStringArgs.DH_SHA1);
args.Add(QueryStringArgs.openid.dh_consumer_public, cpub);
DHParameters dhps = dh.ExportParameters(true);
if (dhps.P != CryptUtil.DEFAULT_MOD || dhps.G != CryptUtil.DEFAULT_GEN)
{
args.Add(QueryStringArgs.openid.dh_modulus, CryptUtil.UnsignedToBase64(dhps.P));
args.Add(QueryStringArgs.openid.dh_gen, CryptUtil.UnsignedToBase64(dhps.G));
}
}
return new AssociationRequest(dh, args);
}
private NameValueCollection CreateCheckAuthRequest(NameValueCollection query)
{
string signed = query[QueryStringArgs.openid.signed];
if (signed == null)
// #XXX: oidutil.log('No signature present; checkAuth aborted')
return null;
// Arguments that are always passed to the server and not
// included in the signature.
string[] whitelist = new string[] { QueryStringArgs.openidnp.assoc_handle, QueryStringArgs.openidnp.sig, QueryStringArgs.openidnp.signed, QueryStringArgs.openidnp.invalidate_handle };
string[] splitted = signed.Split(',');
// combine the previous 2 arrays (whitelist + splitted) into a new array: signed_array
string[] signed_array = new string[whitelist.Length + splitted.Length];
Array.Copy(whitelist, signed_array, whitelist.Length);
Array.Copy(splitted, 0, signed_array, whitelist.Length, splitted.Length);
NameValueCollection check_args = new NameValueCollection();
foreach (string key in query.AllKeys)
{
if (key.StartsWith(QueryStringArgs.openid.Prefix)
&& Array.IndexOf(signed_array, key.Substring(QueryStringArgs.openid.Prefix.Length)) > -1)
check_args.Add(key, query[key]);
check_args[QueryStringArgs.openid.mode] = QueryStringArgs.Modes.check_authentication;
}
return check_args;
}
private Association GetAssociation(Uri server_url)
{
if (this.store.IsDumb)
return null;
Association assoc = this.store.GetAssociation(server_url);
if (assoc == null || assoc.ExpiresIn < TOKEN_LIFETIME)
{
AssociationRequest req = CreateAssociationRequest(server_url);
IDictionary response = MakeKVPost(req.Args, server_url);
if (response == null)
assoc = null;
else
assoc = ParseAssociation(response, req.DH, server_url);
}
return assoc;
}
protected HMACSHA1Association ParseAssociation(IDictionary results, DiffieHellman dh, Uri server_url)
{
Converter<string, string> getParameter = delegate(string key)
{
string val = (string)results[key];
if (val == null)
throw new MissingParameterException("Query args missing key: " + key);
return val;
};
Converter<string, byte[]> getDecoded = delegate(string key)
{
try
{
return Convert.FromBase64String(getParameter(key));
}
catch (FormatException)
{
throw new MissingParameterException("Query argument is not base64: " + key);
}
};
try
{
if (getParameter(QueryStringArgs.openidnp.assoc_type) != QueryStringArgs.HMAC_SHA1)
// XXX: log this
return null;
byte[] secret;
string session_type = (string)results[QueryStringArgs.openidnp.session_type];
if (string.IsNullOrEmpty(session_type) || session_type == "plaintext")
secret = getDecoded(QueryStringArgs.mac_key);
else if (session_type == QueryStringArgs.DH_SHA1)
{
byte[] dh_server_public = getDecoded(QueryStringArgs.openidnp.dh_server_public);
byte[] enc_mac_key = getDecoded(QueryStringArgs.enc_mac_key);
secret = CryptUtil.SHA1XorSecret(dh, dh_server_public, enc_mac_key);
}
else // # XXX: log this
return null;
string assocHandle = getParameter(QueryStringArgs.openidnp.assoc_handle);
TimeSpan expiresIn = new TimeSpan(0, 0, Convert.ToInt32(getParameter(QueryStringArgs.openidnp.expires_in)));
HMACSHA1Association assoc = new HMACSHA1Association(assocHandle, secret, expiresIn);
this.store.StoreAssociation(server_url, assoc);
return assoc;
}
catch (MissingParameterException)
{
return null;
}
}
public class MissingParameterException : ApplicationException
{
public MissingParameterException(string key)
: base("Query missing key: " + key)
{
}
}
private bool ProcessCheckAuthResponse(IDictionary response, Uri server_url)
{
string is_valid = (string)response[QueryStringArgs.openidnp.is_valid];
if (is_valid == "true")
{
string invalidate_handle = (string)response[QueryStringArgs.openidnp.invalidate_handle];
if (invalidate_handle != null)
this.store.RemoveAssociation(server_url, invalidate_handle);
return true;
}
// XXX: Log this
return false;
}
class AssociationRequest
{
public AssociationRequest(DiffieHellman dh, NameValueCollection nvc)
{
this.DH = dh;
this.Args = nvc;
}
public readonly DiffieHellman DH;
public readonly NameValueCollection Args;
}
}
}
|