forked from fido-alliance/webauthn-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
350 lines (292 loc) · 13.4 KB
/
utils.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
const crypto = require('crypto');
const base64url = require('base64url');
const cbor = require('cbor');
const { Certificate } = require('@fidm/x509');
const iso_3166_1 = require('iso-3166-1');
/**
* U2F Presence constant
*/
let U2F_USER_PRESENTED = 0x01;
/**
* Takes signature, data and PEM public key and tries to verify signature
* @param {Buffer} signature
* @param {Buffer} data
* @param {String} publicKey - PEM encoded public key
* @return {Boolean}
*/
let verifySignature = (signature, data, publicKey) => {
return crypto.createVerify('SHA256')
.update(data)
.verify(publicKey, signature);
}
/**
* Returns base64url encoded buffer of the given length
* @param {Number} len - length of the buffer
* @return {String} - base64url random buffer
*/
let randomBase64URLBuffer = (len) => {
len = len || 32;
let buff = crypto.randomBytes(len);
return base64url(buff);
}
/**
* Generates makeCredentials request
* @param {String} username - username
* @param {String} displayName - user's personal display name
* @param {String} id - user's base64url encoded id
* @return {MakePublicKeyCredentialOptions} - server encoded make credentials request
*/
let generateServerMakeCredRequest = (username, displayName, id) => {
return {
challenge: randomBase64URLBuffer(32),
rp: {
name: "FIDO Examples Corporation"
},
user: {
id: id,
name: username,
displayName: displayName
},
attestation: 'direct',
pubKeyCredParams: [
{
type: "public-key", alg: -7 // "ES256" IANA COSE Algorithms registry
}
]
}
}
/**
* Generates getAssertion request
* @param {Array} authenticators - list of registered authenticators
* @return {PublicKeyCredentialRequestOptions} - server encoded get assertion request
*/
let generateServerGetAssertion = (authenticators) => {
let allowCredentials = [];
for(let authr of authenticators) {
allowCredentials.push({
type: 'public-key',
id: authr.credID,
transports: ['usb', 'nfc', 'ble']
})
}
return {
challenge: randomBase64URLBuffer(32),
allowCredentials: allowCredentials
}
}
/**
* Returns SHA-256 digest of the given data.
* @param {Buffer} data - data to hash
* @return {Buffer} - the hash
*/
let hash = (data) => {
return crypto.createHash('SHA256').update(data).digest();
}
/**
* Takes COSE encoded public key and converts it to RAW PKCS ECDHA key
* @param {Buffer} COSEPublicKey - COSE encoded public key
* @return {Buffer} - RAW PKCS encoded public key
*/
let COSEECDHAtoPKCS = (COSEPublicKey) => {
/*
+------+-------+-------+---------+----------------------------------+
| name | key | label | type | description |
| | type | | | |
+------+-------+-------+---------+----------------------------------+
| crv | 2 | -1 | int / | EC Curve identifier - Taken from |
| | | | tstr | the COSE Curves registry |
| | | | | |
| x | 2 | -2 | bstr | X Coordinate |
| | | | | |
| y | 2 | -3 | bstr / | Y Coordinate |
| | | | bool | |
| | | | | |
| d | 2 | -4 | bstr | Private key |
+------+-------+-------+---------+----------------------------------+
*/
let coseStruct = cbor.decodeAllSync(COSEPublicKey)[0];
let tag = Buffer.from([0x04]);
let x = coseStruct.get(-2);
let y = coseStruct.get(-3);
return Buffer.concat([tag, x, y])
}
/**
* Convert binary certificate or public key to an OpenSSL-compatible PEM text format.
* @param {Buffer} buffer - Cert or PubKey buffer
* @return {String} - PEM
*/
let ASN1toPEM = (pkBuffer) => {
if (!Buffer.isBuffer(pkBuffer))
throw new Error("ASN1toPEM: pkBuffer must be Buffer.")
let type;
if (pkBuffer.length == 65 && pkBuffer[0] == 0x04) {
/*
If needed, we encode rawpublic key to ASN structure, adding metadata:
SEQUENCE {
SEQUENCE {
OBJECTIDENTIFIER 1.2.840.10045.2.1 (ecPublicKey)
OBJECTIDENTIFIER 1.2.840.10045.3.1.7 (P-256)
}
BITSTRING <raw public key>
}
Luckily, to do that, we just need to prefix it with constant 26 bytes (metadata is constant).
*/
pkBuffer = Buffer.concat([
new Buffer.from("3059301306072a8648ce3d020106082a8648ce3d030107034200", "hex"),
pkBuffer
]);
type = 'PUBLIC KEY';
} else {
type = 'CERTIFICATE';
}
let b64cert = pkBuffer.toString('base64');
let PEMKey = '';
for(let i = 0; i < Math.ceil(b64cert.length / 64); i++) {
let start = 64 * i;
PEMKey += b64cert.substr(start, 64) + '\n';
}
PEMKey = `-----BEGIN ${type}-----\n` + PEMKey + `-----END ${type}-----\n`;
return PEMKey
}
/**
* Parses authenticatorData buffer.
* @param {Buffer} buffer - authenticatorData buffer
* @return {Object} - parsed authenticatorData struct
*/
let parseMakeCredAuthData = (buffer) => {
let rpIdHash = buffer.slice(0, 32); buffer = buffer.slice(32);
let flagsBuf = buffer.slice(0, 1); buffer = buffer.slice(1);
let flags = flagsBuf[0];
let counterBuf = buffer.slice(0, 4); buffer = buffer.slice(4);
let counter = counterBuf.readUInt32BE(0);
let aaguid = buffer.slice(0, 16); buffer = buffer.slice(16);
let credIDLenBuf = buffer.slice(0, 2); buffer = buffer.slice(2);
let credIDLen = credIDLenBuf.readUInt16BE(0);
let credID = buffer.slice(0, credIDLen); buffer = buffer.slice(credIDLen);
let COSEPublicKey = buffer;
return {rpIdHash, flagsBuf, flags, counter, counterBuf, aaguid, credID, COSEPublicKey}
}
let verifyAuthenticatorAttestationResponse = (webAuthnResponse) => {
let attestationBuffer = base64url.toBuffer(webAuthnResponse.response.attestationObject);
let ctapMakeCredResp = cbor.decodeAllSync(attestationBuffer)[0];
let response = {'verified': false};
if(ctapMakeCredResp.fmt === 'fido-u2f') {
let authrDataStruct = parseMakeCredAuthData(ctapMakeCredResp.authData);
if(!(authrDataStruct.flags & U2F_USER_PRESENTED))
throw new Error('User was NOT presented durring authentication!');
let clientDataHash = hash(base64url.toBuffer(webAuthnResponse.response.clientDataJSON))
let reservedByte = Buffer.from([0x00]);
let publicKey = COSEECDHAtoPKCS(authrDataStruct.COSEPublicKey)
let signatureBase = Buffer.concat([reservedByte, authrDataStruct.rpIdHash, clientDataHash, authrDataStruct.credID, publicKey]);
let PEMCertificate = ASN1toPEM(ctapMakeCredResp.attStmt.x5c[0]);
let signature = ctapMakeCredResp.attStmt.sig;
response.verified = verifySignature(signature, signatureBase, PEMCertificate)
if(response.verified) {
response.authrInfo = {
fmt: 'fido-u2f',
publicKey: base64url.encode(publicKey),
counter: authrDataStruct.counter,
credID: base64url.encode(authrDataStruct.credID)
}
}
} else if(ctapMakeCredResp.fmt === 'packed' && ctapMakeCredResp.attStmt.hasOwnProperty('x5c')) {
let authrDataStruct = parseMakeCredAuthData(ctapMakeCredResp.authData);
if(!(authrDataStruct.flags & U2F_USER_PRESENTED))
throw new Error('User was NOT presented durring authentication!');
let clientDataHash = hash(base64url.toBuffer(webAuthnResponse.response.clientDataJSON))
let publicKey = COSEECDHAtoPKCS(authrDataStruct.COSEPublicKey)
let signatureBase = Buffer.concat([ctapMakeCredResp.authData, clientDataHash]);
let PEMCertificate = ASN1toPEM(ctapMakeCredResp.attStmt.x5c[0]);
let signature = ctapMakeCredResp.attStmt.sig;
let pem = Certificate.fromPEM(PEMCertificate);
// Getting requirements from https://www.w3.org/TR/webauthn/#packed-attestation
let aaguid_ext = pem.getExtension('1.3.6.1.4.1.45724.1.1.4')
response.verified = // Verify that sig is a valid signature over the concatenation of authenticatorData
// and clientDataHash using the attestation public key in attestnCert with the algorithm specified in alg.
verifySignature(signature, signatureBase, PEMCertificate) &&
// version must be 3 (which is indicated by an ASN.1 INTEGER with value 2)
pem.version == 3 &&
// ISO 3166 valid country
typeof iso_3166_1.whereAlpha2(pem.subject.countryName) !== 'undefined' &&
// Legal name of the Authenticator vendor (UTF8String)
pem.subject.organizationName &&
// Literal string “Authenticator Attestation” (UTF8String)
pem.subject.organizationalUnitName === 'Authenticator Attestation' &&
// A UTF8String of the vendor’s choosing
pem.subject.commonName &&
// The Basic Constraints extension MUST have the CA component set to false
!pem.extensions.isCA &&
// If attestnCert contains an extension with OID 1.3.6.1.4.1.45724.1.1.4 (id-fido-gen-ce-aaguid)
// verify that the value of this extension matches the aaguid in authenticatorData.
// The extension MUST NOT be marked as critical.
(aaguid_ext != null ?
(authrDataStruct.hasOwnProperty('aaguid') ?
!aaguid_ext.critical && aaguid_ext.value.slice(2).equals(authrDataStruct.aaguid) : false)
: true);
if(response.verified) {
response.authrInfo = {
fmt: 'fido-u2f',
publicKey: base64url.encode(publicKey),
counter: authrDataStruct.counter,
credID: base64url.encode(authrDataStruct.credID)
}
}
} else {
throw new Error('Unsupported attestation format! ' + ctapMakeCredResp.fmt);
}
return response
}
/**
* Takes an array of registered authenticators and find one specified by credID
* @param {String} credID - base64url encoded credential
* @param {Array} authenticators - list of authenticators
* @return {Object} - found authenticator
*/
let findAuthr = (credID, authenticators) => {
for(let authr of authenticators) {
if(authr.credID === credID)
return authr
}
throw new Error(`Unknown authenticator with credID ${credID}!`)
}
/**
* Parses AuthenticatorData from GetAssertion response
* @param {Buffer} buffer - Auth data buffer
* @return {Object} - parsed authenticatorData struct
*/
let parseGetAssertAuthData = (buffer) => {
let rpIdHash = buffer.slice(0, 32); buffer = buffer.slice(32);
let flagsBuf = buffer.slice(0, 1); buffer = buffer.slice(1);
let flags = flagsBuf[0];
let counterBuf = buffer.slice(0, 4); buffer = buffer.slice(4);
let counter = counterBuf.readUInt32BE(0);
return {rpIdHash, flagsBuf, flags, counter, counterBuf}
}
let verifyAuthenticatorAssertionResponse = (webAuthnResponse, authenticators) => {
let authr = findAuthr(webAuthnResponse.id, authenticators);
let authenticatorData = base64url.toBuffer(webAuthnResponse.response.authenticatorData);
let response = {'verified': false};
if(authr.fmt === 'fido-u2f') {
let authrDataStruct = parseGetAssertAuthData(authenticatorData);
if(!(authrDataStruct.flags & U2F_USER_PRESENTED))
throw new Error('User was NOT presented durring authentication!');
let clientDataHash = hash(base64url.toBuffer(webAuthnResponse.response.clientDataJSON))
let signatureBase = Buffer.concat([authrDataStruct.rpIdHash, authrDataStruct.flagsBuf, authrDataStruct.counterBuf, clientDataHash]);
let publicKey = ASN1toPEM(base64url.toBuffer(authr.publicKey));
let signature = base64url.toBuffer(webAuthnResponse.response.signature);
response.verified = verifySignature(signature, signatureBase, publicKey)
if(response.verified) {
if(response.counter <= authr.counter)
throw new Error('Authr counter did not increase!');
authr.counter = authrDataStruct.counter
}
}
return response
}
module.exports = {
randomBase64URLBuffer,
generateServerMakeCredRequest,
generateServerGetAssertion,
verifyAuthenticatorAttestationResponse,
verifyAuthenticatorAssertionResponse
}