-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdigestAuthMemory.js
395 lines (352 loc) · 15 KB
/
digestAuthMemory.js
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
// RFC 7616 HTTP Digest Authentication
// Adapted from https://github.com/inorganik/digest-auth-request
// Using forge library from https://github.com/digitalbazaar/forge
// 2023 Bagus Saputra
var digestAuthRequest = function (method, url, username, password){
if(!method){method='GET'}; if(!url){url='./'};
if(!username){username=null}; if(!password){password=null};
let statusCode = 401; // change status code to avoid browser sign in prompt
let scheme = null; // we just echo the scheme, to allow for 'Digest', 'X-Digest', 'JDigest' etc
let nonce = null; // uniquely generated by the server each time a 401 response is made
let realm = null; // string indicating which username/password to use
let qop = null; // quality of protection supported by the server 'auth' or 'auth-int'
let opaque = null; // quoted string that should be returned unchanged
let nc = 1; // nonce count, increments with each request used with the same nonce
let cnonce = null; // client nonce
let algorithm = null; // algorithm used to hash 'MD5', 'SHA-256', 'SHA-512-256' and session
let userhash = false; // specify if username hashing is required
let timeout = 10000; // connection timeout
let sendData = false; // determine wether or not to send data
let sendJSON = false; // determine wether or not to send data as JSON
let logging = true; // toggle console logging
if(method.toLowerCase() === 'post' || method.toLowerCase() === 'put'){
sendData = true;
}
this.request = function(successFn, errorFn, data){
if(data && typeof data === 'object'){
data = JSON.stringify(data);
sendJSON = true;
}
self.successFn = successFn;
self.errorFn = errorFn;
if(getLocalToken()){
setDigestParamLocal();
cnonce = generateCnonce();
}
if(!nonce){
makeUnauthenticatedRequest(data);
}else{
makeAuthenticatedRequest(data);
}
}
function makeUnauthenticatedRequest(data){
let unauthenticatedRequest = new XMLHttpRequest();
unauthenticatedRequest.withCredentials = true;
unauthenticatedRequest.open(method, url, true);
unauthenticatedRequest.timeout = timeout;
unauthenticatedRequest.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
if(sendData){
if(sendJSON){
unauthenticatedRequest.setRequestHeader('Content-type', 'application/json');
}else{
unauthenticatedRequest.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
}
}
unauthenticatedRequest.onreadystatechange = function() {
if(unauthenticatedRequest.readyState === 2){
let digestHeaders = null;
let responseHeaders = unauthenticatedRequest.getAllResponseHeaders();
responseHeaders = responseHeaders.split('\n');
responseHeaders.reverse();
for(let i=0; i<responseHeaders.length; i++){
if(responseHeaders[i].match(/www-authenticate/i) != null){
digestHeaders = responseHeaders[i];
log(digestHeaders);
} // https://datatracker.ietf.org/doc/html/rfc7616#section-3.7 using the first challenge
}
if(digestHeaders != null){
unauthenticatedRequest.abort();
setDigestParam(digestHeaders);
nc++; cnonce = generateCnonce();
makeAuthenticatedRequest(data);
}
}
if(unauthenticatedRequest.readyState === 4){
if(unauthenticatedRequest.status === 200){
log('Authentication not required for '+url);
let unauthenticatedResponse = unauthenticatedRequest.responseText;
if(unauthenticatedResponse !== 'undefined'){
if(unauthenticatedResponse.length > 0){
if(isJson(unauthenticatedResponse)){
successFn(JSON.parse(unauthenticatedResponse));
}else{
successFn(unauthenticatedResponse);
}
}
}else{
successFn();
}
}
}
}
unauthenticatedRequest.onerror = function(){
if(unauthenticatedRequest.status !== statusCode){
log("ERROR! "+unauthenticatedRequest.status+" "+url);
errorFn(unauthenticatedRequest.status);
}
}
if(sendData){
unauthenticatedRequest.send(data);
}else{
unauthenticatedRequest.send();
}
}
function makeAuthenticatedRequest(data){
let authenticatedRequest = new XMLHttpRequest();
authenticatedRequest.withCredentials = true;
authenticatedRequest.open(method, url, true);
authenticatedRequest.timeout = timeout;
let digestAuthHeader = generateDigestAuthHeader(data);
authenticatedRequest.setRequestHeader('Authorization', digestAuthHeader);
authenticatedRequest.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
if(sendData){
if(sendJSON){
authenticatedRequest.setRequestHeader('Content-type', 'application/json');
}else{
authenticatedRequest.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
}
}
authenticatedRequest.onreadystatechange = function() {
if(authenticatedRequest.readyState === 2){
let digestHeaders = null;
let responseHeaders = authenticatedRequest.getAllResponseHeaders();
responseHeaders = responseHeaders.split('\n');
responseHeaders.reverse();
for(let i=0; i<responseHeaders.length; i++){
if(responseHeaders[i].match(/www-authenticate/i) != null){
digestHeaders = responseHeaders[i];
log(digestHeaders);
}
} // https://datatracker.ietf.org/doc/html/rfc7616#section-3.7 using the first challenge
if(digestHeaders != null && checkNonceStale(digestHeaders)){
authenticatedRequest.abort();
setDigestParam(digestHeaders);
nc = 1; nc++; cnonce = generateCnonce();
makeAuthenticatedRequest(data);
} // If nonce used is too old (stale)
}
}
authenticatedRequest.onload = function(){
let authenticatedResponse = authenticatedRequest.responseText;
if(authenticatedRequest.status >= 200 && authenticatedRequest.status < 400){
nc++; refreshTokenStamp();
if(authenticatedResponse !== 'undefined' && authenticatedResponse.length > 0){
if(isJson(authenticatedResponse)){
successFn(JSON.parse(authenticatedResponse));
}else{
successFn(authenticatedResponse);
}
}else{
successFn();
}
}else{
nonce = null; clrLocalToken();
errorFn(authenticatedRequest.status);
}
}
authenticatedRequest.onerror = function(){
nonce = null; clrLocalToken();
log("ERROR! "+authenticatedRequest.status+" "+url);
errorFn(authenticatedRequest.status);
}
if(sendData){
authenticatedRequest.send(data);
}else{
authenticatedRequest.send();
}
}
function checkNonceStale(digestHeader){
let stale = false;
let split = digestHeader.replace(/"/g,'').replace(/,|\r/g,'').split(' ');
for(let i=0 ; i<split.length; i++){
let testVal = split[i].split('=');
if(testVal.indexOf("stale") > -1 &&
testVal[1].toLowerCase() == "true"){
stale = true;
log("Nonce Had Gone Stale");
}
}
return stale;
}
function setDigestParam(digestHeader){
let split = digestHeader.replace(/"/g,'').replace(/,|\r/g,'').split(' ');
scheme = split[1];
for(let i=0 ; i<split.length; i++){
let testVal = split[i].split('=');
if(testVal.indexOf("realm") > -1){
realm = testVal[1];
}else if(testVal.indexOf("nonce") > -1){
nonce = testVal[1];
}else if(testVal.indexOf("algorithm") > -1){
if(["md5", "sha-256", "sha-512-256", "md5-sess", "sha-256-sess",
"sha-512-256-sess"].indexOf(testVal[1].toLowerCase())){
algorithm = testVal[1];
}else{
algorithm = "MD5";
} // https://datatracker.ietf.org/doc/html/rfc7616#section-3.7
}else if(testVal.indexOf("opaque") > -1){
opaque = testVal[1];
}else if(testVal.indexOf("qop") > -1){
qop = testVal[1];
}else if(testVal.indexOf("userhash") > -1 &&
testVal[1].toLowerCase() == "true"){
userhash = true;
}
}
}
function setDigestParamLocal(){
let localToken = getLocalToken();
if(localToken){
scheme = localToken.scheme;
username = localToken.username;
realm = localToken.realm;
algorithm = localToken.algorithm;
nonce = localToken.nonce;
nc = localToken.nc;
qop = localToken.qop;
opaque = localToken.opaque;
}
}
function generateDigestAuthHeader(data){
let authHeader = "";
authHeader = authHeader.concat(scheme," ");
if(userhash){
authHeader = authHeader.concat('username="',generateHash(username+':'+realm),'", ');
}else{
authHeader = authHeader.concat('username="',username,'", ');
} // https://datatracker.ietf.org/doc/html/rfc7616#section-3.4.4
authHeader = authHeader.concat('realm="',realm,'", ');
authHeader = authHeader.concat('uri="',url,'", ');
if(algorithm){
authHeader = authHeader.concat('algorithm="',algorithm,'", ');
} // using Quoted-String: algorithm="<algorithm>"
authHeader = authHeader.concat('nonce="',nonce,'", ');
authHeader = authHeader.concat('nc=',('00000000' + nc).slice(-8),', ');
authHeader = authHeader.concat('cnonce="',cnonce,'", ');
authHeader = authHeader.concat('qop=',qop,', ');
authHeader = authHeader.concat('response="',generateResponse(data),'", ');
authHeader = authHeader.concat('opaque="',opaque,'"');
if(userhash){
authHeader = authHeader.concat(', userhash=true');
} // https://datatracker.ietf.org/doc/html/rfc7616#section-3.4.4
log(authHeader);
return authHeader;
}
function generateResponse(data){
let HA1 = ""; let HA2 = "";
let response = "";
if(getLocalToken()){
log("Using Stored Local Token");
HA1 = getLocalToken().token;
}else if(username != null && password != null){
log("Using Specified Credentials");
HA1 = HA1.concat(username,':',realm,':',password);
HA1 = generateHash(HA1);
setLocalToken(username, HA1);
}else{
log("Credentials Not Specified and No Local Token Found!");
}
if(algorithm && ['md5-sess', 'sha-256-sess',
'sha-512-256-sess'].indexOf(algorithm.toLowerCase()) > -1){
HA1 = HA1.concat(HA1,':',realm,':',cnonce);
HA1 = generateHash(HA1);
} // https://datatracker.ietf.org/doc/html/rfc7616#section-3.4.2
if(qop.toLowerCase() == "auth-int" && data){
HA2 = HA2.concat(method,':',url,':',generateHash(data));
HA2 = generateHash(HA2);
}else{
HA2 = HA2.concat(method,':',url);
HA2 = generateHash(HA2);
} // https://datatracker.ietf.org/doc/html/rfc7616#section-3.4.3
response = response.concat(HA1,':',nonce,':');
response = response.concat(('00000000' + nc).slice(-8),':');
response = response.concat(cnonce,':',qop,':',HA2);
response = generateHash(response);
return response;
}
function generateHash(input){
let output;
if(algorithm && ['sha-256', 'sha-256-sess'].indexOf(algorithm.toLowerCase()) > -1){
output = forge.md.sha256.create();
}else if(algorithm && ['sha-512-256', 'sha-512-256-sess'].indexOf(algorithm.toLowerCase()) > -1){
output = forge.md.sha512.sha256.create();
}else{
output = forge.md.md5.create();
}
output.update(input);
return output.digest().toHex().toString();
}
function generateCnonce(){
let charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
let token = "";
for(let i=0; i<44; i++){
if(i==3 || i==25){
token += "/";
}else{
token += charset.charAt(Math.floor(Math.random() * charset.length));
}
}
return token;
}
function isJson(str){
try{JSON.parse(str);
}catch(e){return false;
}return true;
}
function log(str){
if(logging){console.log("[Digest] "+str);}
}
function setLocalToken(username, HA1){
if(username && HA1){
let localToken = {stamp:Math.floor(Date.now() / 1000),
scheme:scheme, username:username, realm:realm, algorithm:algorithm,
nonce:nonce, nc:nc, qop:qop, token:HA1, opaque:opaque};
kettle.SetKettleVariable(btoa(JSON.stringify(localToken)));
}
}
function getLocalToken(){
let localToken = kettle.getKettleVariable();
if(localToken){
return JSON.parse(atob(localToken));
}
return false;
}
function clrLocalToken(){
kettle.SetKettleVariable(null);
}
this.clrLocalToken = function(){
log("Local Token Cleared");
return clrLocalToken();
} // for logout functionality
function refreshTokenStamp(){
let localToken = getLocalToken();
if(localToken){
let newToken = {stamp:Math.floor(Date.now() / 1000), scheme:scheme,
username:localToken.username, realm:realm, algorithm:algorithm,
nonce:nonce, nc:nc, qop:qop, token:localToken.token, opaque:opaque};
clrLocalToken();
kettle.SetKettleVariable(btoa(JSON.stringify(newToken)));
}
}
}
const kettle = (function(){
let _kettleVariable = null;
return {
SetKettleVariable:(value) => {
_kettleVariable = value;
},
getKettleVariable:() => {
return _kettleVariable;
}
}
})();