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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
|
// This file tests authentication prompt callbacks
// TODO NIT use do_check_eq(expected, actual) consistently, not sometimes eq(actual, expected)
"use strict";
const { HttpServer } = ChromeUtils.import("resource://testing-common/httpd.js");
// Turn off the authentication dialog blocking for this test.
var prefs = Services.prefs;
prefs.setIntPref("network.auth.subresource-http-auth-allow", 2);
function URL(domain, path = "") {
if (path.startsWith("/")) {
path = path.substring(1);
}
return `http://${domain}:${httpserv.identity.primaryPort}/${path}`;
}
XPCOMUtils.defineLazyGetter(this, "PORT", function () {
return httpserv.identity.primaryPort;
});
const FLAG_RETURN_FALSE = 1 << 0;
const FLAG_WRONG_PASSWORD = 1 << 1;
const FLAG_BOGUS_USER = 1 << 2;
// const FLAG_PREVIOUS_FAILED = 1 << 3;
const CROSS_ORIGIN = 1 << 4;
// const FLAG_NO_REALM = 1 << 5;
const FLAG_NON_ASCII_USER_PASSWORD = 1 << 6;
function AuthPrompt1(flags) {
this.flags = flags;
}
AuthPrompt1.prototype = {
user: "guest",
pass: "guest",
expectedRealm: "secret",
QueryInterface: ChromeUtils.generateQI(["nsIAuthPrompt"]),
prompt: function ap1_prompt(title, text, realm, save, defaultText, result) {
do_throw("unexpected prompt call");
},
promptUsernameAndPassword: function ap1_promptUP(
title,
text,
realm,
savePW,
user,
pw
) {
if (!(this.flags & CROSS_ORIGIN)) {
if (!text.includes(this.expectedRealm)) {
do_throw("Text must indicate the realm");
}
} else if (text.includes(this.expectedRealm)) {
do_throw("There should not be realm for cross origin");
}
if (!text.includes("localhost")) {
do_throw("Text must indicate the hostname");
}
if (!text.includes(String(PORT))) {
do_throw("Text must indicate the port");
}
if (text.includes("-1")) {
do_throw("Text must contain negative numbers");
}
if (this.flags & FLAG_RETURN_FALSE) {
return false;
}
if (this.flags & FLAG_BOGUS_USER) {
this.user = "foo\nbar";
} else if (this.flags & FLAG_NON_ASCII_USER_PASSWORD) {
this.user = "é";
}
user.value = this.user;
if (this.flags & FLAG_WRONG_PASSWORD) {
pw.value = this.pass + ".wrong";
// Now clear the flag to avoid an infinite loop
this.flags &= ~FLAG_WRONG_PASSWORD;
} else if (this.flags & FLAG_NON_ASCII_USER_PASSWORD) {
pw.value = "é";
} else {
pw.value = this.pass;
}
return true;
},
promptPassword: function ap1_promptPW(title, text, realm, save, pwd) {
do_throw("unexpected promptPassword call");
},
};
function AuthPrompt2(flags) {
this.flags = flags;
}
AuthPrompt2.prototype = {
user: "guest",
pass: "guest",
expectedRealm: "secret",
QueryInterface: ChromeUtils.generateQI(["nsIAuthPrompt2"]),
promptAuth: function ap2_promptAuth(channel, level, authInfo) {
authInfo.username = this.user;
authInfo.password = this.pass;
return true;
},
asyncPromptAuth: function ap2_async(chan, cb, ctx, lvl, info) {
throw Components.Exception("", Cr.NS_ERROR_NOT_IMPLEMENTED);
},
};
function Requestor(flags, versions) {
this.flags = flags;
this.versions = versions;
}
Requestor.prototype = {
QueryInterface: ChromeUtils.generateQI(["nsIInterfaceRequestor"]),
getInterface: function requestor_gi(iid) {
if (this.versions & 1 && iid.equals(Ci.nsIAuthPrompt)) {
// Allow the prompt to store state by caching it here
if (!this.prompt1) {
this.prompt1 = new AuthPrompt1(this.flags);
}
return this.prompt1;
}
if (this.versions & 2 && iid.equals(Ci.nsIAuthPrompt2)) {
// Allow the prompt to store state by caching it here
if (!this.prompt2) {
this.prompt2 = new AuthPrompt2(this.flags);
}
return this.prompt2;
}
throw Components.Exception("", Cr.NS_ERROR_NO_INTERFACE);
},
prompt1: null,
prompt2: null,
};
function RealmTestRequestor() {}
RealmTestRequestor.prototype = {
QueryInterface: ChromeUtils.generateQI([
"nsIInterfaceRequestor",
"nsIAuthPrompt2",
]),
getInterface: function realmtest_interface(iid) {
if (iid.equals(Ci.nsIAuthPrompt2)) {
return this;
}
throw Components.Exception("", Cr.NS_ERROR_NO_INTERFACE);
},
promptAuth: function realmtest_checkAuth(channel, level, authInfo) {
Assert.equal(authInfo.realm, '"foo_bar');
return false;
},
asyncPromptAuth: function realmtest_async(chan, cb, ctx, lvl, info) {
throw Components.Exception("", Cr.NS_ERROR_NOT_IMPLEMENTED);
},
};
function makeChan(url) {
let loadingUrl = Services.io
.newURI(url)
.mutate()
.setPathQueryRef("")
.finalize();
var principal = Services.scriptSecurityManager.createContentPrincipal(
loadingUrl,
{}
);
return NetUtil.newChannel({
uri: url,
loadingPrincipal: principal,
securityFlags: Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL,
contentPolicyType: Ci.nsIContentPolicy.TYPE_OTHER,
});
}
function ntlm_auth(metadata, response) {
let challenge = metadata.getHeader("Authorization");
if (!challenge.startsWith("NTLM ")) {
response.setStatusLine(metadata.httpVersion, 401, "Unauthorized");
return;
}
let decoded = atob(challenge.substring(5));
info(decoded);
if (!decoded.startsWith("NTLMSSP\0")) {
response.setStatusLine(metadata.httpVersion, 401, "Unauthorized");
return;
}
let isNegotiate = decoded.substring(8).startsWith("\x01\x00\x00\x00");
let isAuthenticate = decoded.substring(8).startsWith("\x03\x00\x00\x00");
if (isNegotiate) {
response.setStatusLine(metadata.httpVersion, 401, "Unauthorized");
response.setHeader(
"WWW-Authenticate",
"NTLM TlRMTVNTUAACAAAAAAAAAAAoAAABggAAASNFZ4mrze8AAAAAAAAAAAAAAAAAAAAA",
false
);
return;
}
if (isAuthenticate) {
let body = "OK";
response.bodyOutputStream.write(body, body.length);
return;
}
// Something else went wrong.
response.setStatusLine(metadata.httpVersion, 401, "Unauthorized");
}
function basic_auth(metadata, response) {
let challenge = metadata.getHeader("Authorization");
if (!challenge.startsWith("Basic ")) {
response.setStatusLine(metadata.httpVersion, 401, "Unauthorized");
return;
}
if (challenge == "Basic Z3Vlc3Q6Z3Vlc3Q=") {
response.setStatusLine(metadata.httpVersion, 200, "OK, authorized");
response.setHeader("WWW-Authenticate", 'Basic realm="secret"', false);
let body = "success";
response.bodyOutputStream.write(body, body.length);
return;
}
response.setStatusLine(metadata.httpVersion, 401, "Unauthorized");
response.setHeader("WWW-Authenticate", 'Basic realm="secret"', false);
}
//
// Digest functions
//
function bytesFromString(str) {
const encoder = new TextEncoder();
return encoder.encode(str);
}
// return the two-digit hexadecimal code for a byte
function toHexString(charCode) {
return ("0" + charCode.toString(16)).slice(-2);
}
function H(str) {
var data = bytesFromString(str);
var ch = Cc["@mozilla.org/security/hash;1"].createInstance(Ci.nsICryptoHash);
ch.init(Ci.nsICryptoHash.MD5);
ch.update(data, data.length);
var hash = ch.finish(false);
return Array.from(hash, (c, i) => toHexString(hash.charCodeAt(i))).join("");
}
const nonce = "6f93719059cf8d568005727f3250e798";
const opaque = "1234opaque1234";
const digestChallenge = `Digest realm="secret", domain="/", qop=auth,algorithm=MD5, nonce="${nonce}" opaque="${opaque}"`;
//
// Digest handler
//
// /auth/digest
function authDigest(metadata, response) {
var cnonceRE = /cnonce="(\w+)"/;
var responseRE = /response="(\w+)"/;
var usernameRE = /username="(\w+)"/;
var body = "";
// check creds if we have them
if (metadata.hasHeader("Authorization")) {
var auth = metadata.getHeader("Authorization");
var cnonce = auth.match(cnonceRE)[1];
var clientDigest = auth.match(responseRE)[1];
var username = auth.match(usernameRE)[1];
var nc = "00000001";
if (username != "guest") {
response.setStatusLine(metadata.httpVersion, 400, "bad request");
body = "should never get here";
} else {
// see RFC2617 for the description of this calculation
var A1 = "guest:secret:guest";
var A2 = "GET:/path";
var noncebits = [nonce, nc, cnonce, "auth", H(A2)].join(":");
var digest = H([H(A1), noncebits].join(":"));
if (clientDigest == digest) {
response.setStatusLine(metadata.httpVersion, 200, "OK, authorized");
body = "digest";
} else {
info(clientDigest);
info(digest);
handle_unauthorized(metadata, response);
return;
}
}
} else {
// no header, send one
handle_unauthorized(metadata, response);
return;
}
response.bodyOutputStream.write(body, body.length);
}
let challenges = ["NTLM", `Basic realm="secret"`, digestChallenge];
function handle_unauthorized(metadata, response) {
response.setStatusLine(metadata.httpVersion, 401, "Unauthorized");
for (let ch of challenges) {
response.setHeader("WWW-Authenticate", ch, true);
}
}
// /path
function auth_handler(metadata, response) {
if (!metadata.hasHeader("Authorization")) {
handle_unauthorized(metadata, response);
return;
}
let challenge = metadata.getHeader("Authorization");
if (challenge.startsWith("NTLM ")) {
ntlm_auth(metadata, response);
return;
}
if (challenge.startsWith("Basic ")) {
basic_auth(metadata, response);
return;
}
if (challenge.startsWith("Digest ")) {
authDigest(metadata, response);
return;
}
handle_unauthorized(metadata, response);
}
let httpserv;
add_setup(() => {
Services.prefs.setBoolPref("network.auth.force-generic-ntlm", true);
Services.prefs.setBoolPref("network.auth.force-generic-ntlm-v1", true);
Services.prefs.setBoolPref("network.dns.native-is-localhost", true);
Services.prefs.setBoolPref("network.http.sanitize-headers-in-logs", false);
httpserv = new HttpServer();
httpserv.registerPathHandler("/path", auth_handler);
httpserv.start(-1);
registerCleanupFunction(async () => {
Services.prefs.clearUserPref("network.auth.force-generic-ntlm");
Services.prefs.clearUserPref("network.auth.force-generic-ntlm-v1");
Services.prefs.clearUserPref("network.dns.native-is-localhost");
Services.prefs.clearUserPref("network.http.sanitize-headers-in-logs");
await httpserv.stop();
});
});
add_task(async function test_ntlm_first() {
Services.prefs.setBoolPref(
"network.auth.choose_most_secure_challenge",
false
);
challenges = ["NTLM", `Basic realm="secret"`, digestChallenge];
httpserv.identity.add("http", "ntlm.com", httpserv.identity.primaryPort);
let chan = makeChan(URL("ntlm.com", "/path"));
chan.notificationCallbacks = new Requestor(FLAG_RETURN_FALSE, 2);
let [req, buf] = await new Promise(resolve => {
chan.asyncOpen(
new ChannelListener((req, buf) => resolve([req, buf]), null)
);
});
Assert.equal(buf, "OK");
Assert.equal(req.QueryInterface(Ci.nsIHttpChannel).responseStatus, 200);
});
add_task(async function test_basic_first() {
Services.prefs.setBoolPref(
"network.auth.choose_most_secure_challenge",
false
);
challenges = [`Basic realm="secret"`, "NTLM", digestChallenge];
httpserv.identity.add("http", "basic.com", httpserv.identity.primaryPort);
let chan = makeChan(URL("basic.com", "/path"));
chan.notificationCallbacks = new Requestor(FLAG_RETURN_FALSE, 2);
let [req, buf] = await new Promise(resolve => {
chan.asyncOpen(
new ChannelListener((req, buf) => resolve([req, buf]), null)
);
});
Assert.equal(buf, "success");
Assert.equal(req.QueryInterface(Ci.nsIHttpChannel).responseStatus, 200);
});
add_task(async function test_digest_first() {
Services.prefs.setBoolPref(
"network.auth.choose_most_secure_challenge",
false
);
challenges = [digestChallenge, `Basic realm="secret"`, "NTLM"];
httpserv.identity.add("http", "digest.com", httpserv.identity.primaryPort);
let chan = makeChan(URL("digest.com", "/path"));
chan.notificationCallbacks = new Requestor(FLAG_RETURN_FALSE, 2);
let [req, buf] = await new Promise(resolve => {
chan.asyncOpen(
new ChannelListener((req, buf) => resolve([req, buf]), null)
);
});
Assert.equal(req.QueryInterface(Ci.nsIHttpChannel).responseStatus, 200);
Assert.equal(buf, "digest");
});
add_task(async function test_choose_most_secure() {
// When the pref is true, we rank the challenges by how secure they are.
// In this case, NTLM should be the most secure.
Services.prefs.setBoolPref("network.auth.choose_most_secure_challenge", true);
challenges = [digestChallenge, `Basic realm="secret"`, "NTLM"];
httpserv.identity.add(
"http",
"ntlmstrong.com",
httpserv.identity.primaryPort
);
let chan = makeChan(URL("ntlmstrong.com", "/path"));
chan.notificationCallbacks = new Requestor(FLAG_RETURN_FALSE, 2);
let [req, buf] = await new Promise(resolve => {
chan.asyncOpen(
new ChannelListener((req, buf) => resolve([req, buf]), null)
);
});
Assert.equal(req.QueryInterface(Ci.nsIHttpChannel).responseStatus, 200);
Assert.equal(buf, "OK");
});
|