This repository has been archived by the owner on Feb 24, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 455
/
AuthenticationHelper.js
319 lines (277 loc) · 9.33 KB
/
AuthenticationHelper.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
/*!
* Copyright 2016 Amazon.com,
* Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Amazon Software License (the "License").
* You may not use this file except in compliance with the
* License. A copy of the License is located at
*
* http://aws.amazon.com/asl/
*
* or in the "license" file accompanying this file. This file is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, express or implied. See the License
* for the specific language governing permissions and
* limitations under the License.
*/
import { util } from 'aws-sdk/global';
import BigInteger from './BigInteger';
const initN = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1'
+ '29024E088A67CC74020BBEA63B139B22514A08798E3404DD'
+ 'EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245'
+ 'E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED'
+ 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D'
+ 'C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F'
+ '83655D23DCA3AD961C62F356208552BB9ED529077096966D'
+ '670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B'
+ 'E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9'
+ 'DE2BCBF6955817183995497CEA956AE515D2261898FA0510'
+ '15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64'
+ 'ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7'
+ 'ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B'
+ 'F12FFA06D98A0864D87602733EC86A64521F2B18177B200C'
+ 'BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31'
+ '43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF';
const newPasswordRequiredChallengeUserAttributePrefix = 'userAttributes.';
/** @class */
export default class AuthenticationHelper {
/**
* Constructs a new AuthenticationHelper object
* @param {string} PoolName Cognito user pool name.
*/
constructor(PoolName) {
this.N = new BigInteger(initN, 16);
this.g = new BigInteger('2', 16);
this.k = new BigInteger(this.hexHash(`00${this.N.toString(16)}0${this.g.toString(16)}`), 16);
this.smallAValue = this.generateRandomSmallA();
this.getLargeAValue(() => {});
this.infoBits = new util.Buffer('Caldera Derived Key', 'utf8');
this.poolName = PoolName;
}
/**
* @returns {BigInteger} small A, a random number
*/
getSmallAValue() {
return this.smallAValue;
}
/**
* @param {nodeCallback<BigInteger>} callback Called with (err, largeAValue)
* @returns {void}
*/
getLargeAValue(callback) {
if (this.largeAValue) {
callback(null, this.largeAValue);
} else {
this.calculateA(this.smallAValue, (err, largeAValue) => {
if (err) {
callback(err, null);
}
this.largeAValue = largeAValue;
callback(null, this.largeAValue);
});
}
}
/**
* helper function to generate a random big integer
* @returns {BigInteger} a random value.
* @private
*/
generateRandomSmallA() {
const hexRandom = util.crypto.lib.randomBytes(128).toString('hex');
const randomBigInt = new BigInteger(hexRandom, 16);
const smallABigInt = randomBigInt.mod(this.N);
return smallABigInt;
}
/**
* helper function to generate a random string
* @returns {string} a random value.
* @private
*/
generateRandomString() {
return util.crypto.lib.randomBytes(40).toString('base64');
}
/**
* @returns {string} Generated random value included in password hash.
*/
getRandomPassword() {
return this.randomPassword;
}
/**
* @returns {string} Generated random value included in devices hash.
*/
getSaltDevices() {
return this.SaltToHashDevices;
}
/**
* @returns {string} Value used to verify devices.
*/
getVerifierDevices() {
return this.verifierDevices;
}
/**
* Generate salts and compute verifier.
* @param {string} deviceGroupKey Devices to generate verifier for.
* @param {string} username User to generate verifier for.
* @param {nodeCallback<null>} callback Called with (err, null)
* @returns {void}
*/
generateHashDevice(deviceGroupKey, username, callback) {
this.randomPassword = this.generateRandomString();
const combinedString = `${deviceGroupKey}${username}:${this.randomPassword}`;
const hashedString = this.hash(combinedString);
const hexRandom = util.crypto.lib.randomBytes(16).toString('hex');
this.SaltToHashDevices = this.padHex(new BigInteger(hexRandom, 16));
this.g.modPow(
new BigInteger(this.hexHash(this.SaltToHashDevices + hashedString), 16),
this.N,
(err, verifierDevicesNotPadded) => {
if (err) {
callback(err, null);
}
this.verifierDevices = this.padHex(verifierDevicesNotPadded);
callback(null, null);
});
}
/**
* Calculate the client's public value A = g^a%N
* with the generated random number a
* @param {BigInteger} a Randomly generated small A.
* @param {nodeCallback<BigInteger>} callback Called with (err, largeAValue)
* @returns {void}
* @private
*/
calculateA(a, callback) {
this.g.modPow(a, this.N, (err, A) => {
if (err) {
callback(err, null);
}
if (A.mod(this.N).equals(BigInteger.ZERO)) {
callback(new Error('Illegal paramater. A mod N cannot be 0.'), null);
}
callback(null, A);
});
}
/**
* Calculate the client's value U which is the hash of A and B
* @param {BigInteger} A Large A value.
* @param {BigInteger} B Server B value.
* @returns {BigInteger} Computed U value.
* @private
*/
calculateU(A, B) {
this.UHexHash = this.hexHash(this.padHex(A) + this.padHex(B));
const finalU = new BigInteger(this.UHexHash, 16);
return finalU;
}
/**
* Calculate a hash from a bitArray
* @param {Buffer} buf Value to hash.
* @returns {String} Hex-encoded hash.
* @private
*/
hash(buf) {
const hashHex = util.crypto.sha256(buf, 'hex');
return (new Array(64 - hashHex.length).join('0')) + hashHex;
}
/**
* Calculate a hash from a hex string
* @param {String} hexStr Value to hash.
* @returns {String} Hex-encoded hash.
* @private
*/
hexHash(hexStr) {
return this.hash(new util.Buffer(hexStr, 'hex'));
}
/**
* Standard hkdf algorithm
* @param {Buffer} ikm Input key material.
* @param {Buffer} salt Salt value.
* @returns {Buffer} Strong key material.
* @private
*/
computehkdf(ikm, salt) {
const prk = util.crypto.hmac(salt, ikm, 'buffer', 'sha256');
const infoBitsUpdate = util.buffer.concat([
this.infoBits,
new util.Buffer(String.fromCharCode(1), 'utf8'),
]);
const hmac = util.crypto.hmac(prk, infoBitsUpdate, 'buffer', 'sha256');
return hmac.slice(0, 16);
}
/**
* Calculates the final hkdf based on computed S value, and computed U value and the key
* @param {String} username Username.
* @param {String} password Password.
* @param {BigInteger} serverBValue Server B value.
* @param {BigInteger} salt Generated salt.
* @param {nodeCallback<Buffer>} callback Called with (err, hkdfValue)
* @returns {void}
*/
getPasswordAuthenticationKey(username, password, serverBValue, salt, callback) {
if (serverBValue.mod(this.N).equals(BigInteger.ZERO)) {
throw new Error('B cannot be zero.');
}
this.UValue = this.calculateU(this.largeAValue, serverBValue);
if (this.UValue.equals(BigInteger.ZERO)) {
throw new Error('U cannot be zero.');
}
const usernamePassword = `${this.poolName}${username}:${password}`;
const usernamePasswordHash = this.hash(usernamePassword);
const xValue = new BigInteger(this.hexHash(this.padHex(salt) + usernamePasswordHash), 16);
this.calculateS(xValue, serverBValue, (err, sValue) => {
if (err) {
callback(err, null);
}
const hkdf = this.computehkdf(
new util.Buffer(this.padHex(sValue), 'hex'),
new util.Buffer(this.padHex(this.UValue.toString(16)), 'hex'));
callback(null, hkdf);
});
}
/**
* Calculates the S value used in getPasswordAuthenticationKey
* @param {BigInteger} xValue Salted password hash value.
* @param {BigInteger} serverBValue Server B value.
* @param {nodeCallback<string>} callback Called on success or error.
* @returns {void}
*/
calculateS(xValue, serverBValue, callback) {
this.g.modPow(xValue, this.N, (err, gModPowXN) => {
if (err) {
callback(err, null);
}
const intValue2 = serverBValue.subtract(this.k.multiply(gModPowXN));
intValue2.modPow(
this.smallAValue.add(this.UValue.multiply(xValue)),
this.N,
(err2, result) => {
if (err2) {
callback(err2, null);
}
callback(null, result.mod(this.N));
}
);
});
}
/**
* Return constant newPasswordRequiredChallengeUserAttributePrefix
* @return {newPasswordRequiredChallengeUserAttributePrefix} constant prefix value
*/
getNewPasswordRequiredChallengeUserAttributePrefix() {
return newPasswordRequiredChallengeUserAttributePrefix;
}
/**
* Converts a BigInteger (or hex string) to hex format padded with zeroes for hashing
* @param {BigInteger|String} bigInt Number or string to pad.
* @returns {String} Padded hex string.
*/
padHex(bigInt) {
let hashStr = bigInt.toString(16);
if (hashStr.length % 2 === 1) {
hashStr = `0${hashStr}`;
} else if ('89ABCDEFabcdef'.indexOf(hashStr[0]) !== -1) {
hashStr = `00${hashStr}`;
}
return hashStr;
}
}