-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathCreateAuthChallengeFIDO2.js
More file actions
258 lines (219 loc) · 10.5 KB
/
CreateAuthChallengeFIDO2.js
File metadata and controls
258 lines (219 loc) · 10.5 KB
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
// ### About this Flow ###
// Using Custom Auth Flow through Amazon Cognito User Pools with Lambda Triggers to complete a 'CUSTOM_CHALLENGE'.
//
// ### About this function ###
// This CreateAuthChallengeFIDO2 function (2nd of 4 triggers) creates a 'CUSTOM_CHALLENGE'
// for REGISTRATION and AUTHENTICATION acting as a Web Authentication Relying Party (RP) in a WebAuthn flow.
// If a user does not exist or exists but has no credentials, this function will make this a registration. If user exists, get credentials and start authentication flow.
// ### Last Updated ###
// Updated: Nov 11, 2020
// Renamed networkPin to serverVerifiedPin
'use strict';
var crypto = require('crypto');
var AWS = require('aws-sdk');
AWS.config.region = process.env.Region;
var lambda = new AWS.Lambda();
const validate = require('validate.js');
var constraints = {
username: {
presence: true,
format: {
pattern: "[a-z0-9_\-]+",
flags: "i",
message: "can only contain a-z, 0-9, or _-"
},
length: {
minimum: 3,
maximum: 20
}
}
};
const authSelectorResolve = {
"PLATFORM": "platform",
"CROSS_PLATFORM": "cross-platform"
};
// Using npmjs.com/package/data-api-client package for accessing an Aurora Serverless Database with Data API enabled
const data = require('data-api-client')({
secretArn: process.env.DBSecretsStoreArn,
resourceArn: process.env.DBAuroraClusterArn,
database: process.env.DatabaseName
});
// Main async handler - Only called by Cognito User Pools for Custom Auth Flow
exports.handler = async (event = {}) => {
console.log('RECEIVED Event: ', JSON.stringify(event, null, 2));
const result = validate({username: event.userName}, constraints)
if(result){
console.error("invalid username: ", result);
return;
}
// Get known credentials for user. Always set username to lowerCase
let creds = await getAllowedCredentialsForUser(event.userName, event.request.userAttributes.sub);
console.log('User creds found: ' + creds.length);
console.log('User creds: ', + creds);
// IF credentials exist, authenticate...else register and return pinCode
if (creds.userCredentials === undefined || creds.userCredentials.length == 0) {
// Registration params
console.log('Entered registration ceremony');
var publicKeyCredentialCreationOptions = await getCreateCredentialsOptions(event, creds);
event.response.privateChallengeParameters = { "type": "webauthn.create" };
event.response.publicChallengeParameters = { "type": "webauthn.create", publicKeyCredentialCreationOptions, "pinCode": creds.pinCode };
} else {
// Authentication params
console.log('Entered authentication ceremony');
var publicKeyCredentialRequestOptions = await getCredentialsOptions(event.request.userAttributes.name);
event.response.privateChallengeParameters = { "type": "webauthn.get" };
event.response.publicChallengeParameters = { "type": "webauthn.get", publicKeyCredentialRequestOptions };
}
console.log('Returned event: ', JSON.stringify(event, null, 2));
return event;
};
// REGISTRATION
async function getCreateCredentialsOptions(event, creds) {
const cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider({
apiVersion: '2016-04-18'
});
cognitoidentityserviceprovider.adminUpdateUserAttributes(
{
UserAttributes: [
{
Name: 'preferred_username',
Value: event.request.userAttributes.sub
}
],
UserPoolId: event.userPoolId,
Username: event.userName
},
function(err, data) {
console.log("err: ", err);
console.log("data: ", data);
}
);
const payload = JSON.stringify({
"type": "startRegistration",
"username": event.request.userAttributes.name,
"displayName": event.request.userAttributes.name,
"credentialNickname": "Security Key",
"requireResidentKey": false,
"uid": event.request.userAttributes.sub
});
console.log("getCreateCredentialsOptions request payload: "+payload);
var params = {
FunctionName: process.env.WebAuthnLibFunction,
InvocationType: 'RequestResponse',
LogType: 'Tail',
Payload: JSON.stringify(payload)
};
try {
console.log("invoking java-webauthn-server");
let response = await lambda.invoke(params).promise();
console.log("response: "+response);
console.log("response payload: "+response.Payload);
console.log("response payload jsonparse: "+JSON.parse(response.Payload));
let startRegisterPayload = JSON.parse(JSON.parse(response.Payload));
console.log("response payload jsonparse2: "+startRegisterPayload);
const coseLookup = {"ES256": -7, "EdDSA": -8, "ES384": -35, "ES512": -36, "RS256": -257};
startRegisterPayload.requestId = startRegisterPayload.requestId.base64url;
startRegisterPayload.publicKeyCredentialCreationOptions.user.id = startRegisterPayload.publicKeyCredentialCreationOptions.user.id.base64url;
startRegisterPayload.publicKeyCredentialCreationOptions.challenge = startRegisterPayload.publicKeyCredentialCreationOptions.challenge.base64url;
startRegisterPayload.publicKeyCredentialCreationOptions.attestation = startRegisterPayload.publicKeyCredentialCreationOptions.attestation.toLowerCase();
startRegisterPayload.publicKeyCredentialCreationOptions.authenticatorSelection.userVerification = startRegisterPayload.publicKeyCredentialCreationOptions.authenticatorSelection.userVerification.toLowerCase();
startRegisterPayload.publicKeyCredentialCreationOptions.authenticatorSelection.authenticatorAttachment = authSelectorResolve[startRegisterPayload.publicKeyCredentialCreationOptions.authenticatorSelection.authenticatorAttachment];
startRegisterPayload.publicKeyCredentialCreationOptions.pubKeyCredParams = startRegisterPayload.publicKeyCredentialCreationOptions.pubKeyCredParams.map( (cred) => {
cred.type = cred.type.toLowerCase().replace('_','-');
cred.alg = coseLookup[cred.alg];
console.log("cred: "+ JSON.stringify(cred));
return cred;
});
console.log("response payload: ", startRegisterPayload);
return JSON.stringify(startRegisterPayload);
} catch (err) {
//context.fail(err);
console.log("error"+ err);
return "error";
}
}
// AUTHENTICATION
async function getCredentialsOptions(username) {
const payload = JSON.stringify({
"type": "startAuthentication",
"username": username
});
console.log("getCredentialsOptions request payload: "+payload);
var params = {
FunctionName: process.env.WebAuthnLibFunction,
InvocationType: 'RequestResponse',
LogType: 'Tail',
Payload: JSON.stringify(payload)
};
try {
console.log("invoking java-webauthn-server");
let response = await lambda.invoke(params).promise();
console.log("response: "+response);
console.log("response payload: "+response.Payload);
console.log("response payload jsonparse: "+JSON.parse(response.Payload));
let startAuthPayload = JSON.parse(JSON.parse(response.Payload));
console.log("startAuthPayload: ", startAuthPayload);
startAuthPayload.requestId = startAuthPayload.requestId.base64url;
console.log("requestId: ", startAuthPayload.requestId);
startAuthPayload.publicKeyCredentialRequestOptions.userVerification = startAuthPayload.publicKeyCredentialRequestOptions.userVerification.toLowerCase();
startAuthPayload.publicKeyCredentialRequestOptions.challenge = startAuthPayload.publicKeyCredentialRequestOptions.challenge.base64url;
console.log("challenge: ", startAuthPayload.publicKeyCredentialRequestOptions.challenge);
startAuthPayload.publicKeyCredentialRequestOptions.allowCredentials = startAuthPayload.publicKeyCredentialRequestOptions.allowCredentials.map( (cred) => {
cred.type = cred.type.toLowerCase().replace('_','-');
cred.id = cred.id.base64url;
return cred
});
console.log("response payload: ", startAuthPayload);
return JSON.stringify(startAuthPayload);
} catch (err) {
//context.fail(err);
console.log("error"+ err);
return "error";
}
}
// Get all WebAuthn credentials from DB for given user
// Returns: { "id:" <credentilaId>, "type:" "public-key" } as allowedCredentials
async function getAllowedCredentialsForUser(userName, cognitoId){
// Get credentials associated with a user
var userCredentials = [];
let userCreds = {};
const payload = JSON.stringify({
"type": "getCredentialIdsForUsername",
"username": userName,
});
console.log("getCredentialIdsForUsername payload: "+payload);
var params = {
FunctionName: process.env.WebAuthnLibFunction,
InvocationType: 'RequestResponse',
LogType: 'Tail',
Payload: JSON.stringify(payload)
};
try {
console.log("invoking java-webauthn-server");
let response = await lambda.invoke(params).promise();
let payload = JSON.parse(JSON.parse(response.Payload));
console.log("response payload: ", payload);
userCreds.records = payload;
} catch (err) {
console.log("error"+ err);
return "error";
}
console.log('userCreds: ', userCreds.records);
// Return empty credentials if none defined in db
if (userCreds.records === undefined || userCreds.records == 0) {
// Create new user with empty credentials
await data.query('INSERT IGNORE INTO user (userName, cognito_id) VALUES(:userName, :cognito_id)', { userName: userName, cognito_id: cognitoId });
let userCredentialObject = {
userName: userName,
cognitoId: cognitoId,
userCredentials: (userCredentials)
};
return userCredentialObject;
}
let userCredentialObject = {
userName: userName,
cognitoId: cognitoId,
userCredentials: (payload)
};
return userCredentialObject;
}