forked from mcguinness/saml-idp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
481 lines (411 loc) · 14 KB
/
app.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
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
/**
* Module dependencies.
*/
var express = require('express'),
os = require('os'),
fs = require('fs'),
http = require('http'),
https = require('https'),
path = require('path'),
extend = require('extend'),
hbs = require('hbs'),
logger = require('morgan'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
samlp = require('samlp'),
yargs = require('yargs'),
config = require('./config.js'),
SimpleProfileMapper = require('./lib/simpleProfileMapper.js');
/**
* Globals
*/
var app = express(),
blocks = {},
httpServer;
/**
* Arguments
*/
console.log();
console.log('loading configuration...');
var argv = yargs
.usage('\nSimple IdP for SAML 2.0 WebSSO Profile\n\n' +
'Launches Web Server that mints SAML assertions for a Service Provider (SP)\n\n' +
'Usage:\n\t$0 -acs {url} -aud {uri}', {
port: {
description: 'Web Server Listener Port',
required: true,
alias: 'p',
default: 7000
},
cert: {
description: 'IdP Signature PublicKey Certificate',
required: true,
default: './idp-public-cert.pem'
},
key: {
description: 'IdP Signature PrivateKey Certificate',
required: true,
default: './idp-private-key.pem'
},
issuer: {
description: 'IdP Issuer URI',
required: true,
alias: 'iss',
default: 'urn:example:idp'
},
acsUrl: {
description: 'SP Assertion Consumer URL',
required: true,
alias: 'acs'
},
audience: {
description: 'SP Audience URI',
required: true,
alias: 'aud'
},
relayState: {
description: 'Default SAML RelayState for SAMLResponse',
required: false,
alias: 'rs'
},
disableRequestAcsUrl: {
description: 'Disables ability for SP AuthnRequest to specify Assertion Consumer URL',
required: false,
boolean: true,
alias: 'static',
default: false
},
encryptionCert: {
description: 'SP Certificate (pem) for Assertion Encryption',
required: false,
string: true,
alias: 'encCert'
},
encryptionPublicKey: {
description: 'SP RSA Public Key (pem) for Assertion Encryption ' +
'(e.g. openssl x509 -pubkey -noout -in sp-cert.pem)',
required: false,
string: true,
alias: 'encKey'
},
httpsPrivateKey: {
description: 'Web Server TLS/SSL Private Key (pem)',
required: false,
string: true,
},
httpsCert: {
description: 'Web Server TLS/SSL Certificate (pem)',
required: false,
string: true,
},
https: {
description: 'Enables HTTPS Listener (requires httpsPrivateKey and httpsCert)',
required: true,
boolean: true,
default: false
}
})
.example('\t$0 --acs http://acme.okta.com/auth/saml20/exampleidp --aud https://www.okta.com/saml2/service-provider/spf5aFRRXFGIMAYXQPNV', '')
.check(function(argv, aliases) {
if (!fs.existsSync(argv.cert)) {
return 'IdP Signature PublicKey Certificate "' + argv.cert + '" is not a valid file path.\n' +
"Please generate a key-pair for the IdP using the following openssl command:\n" +
"\topenssl req -x509 -new -newkey rsa:2048 -nodes -subj '/C=US/ST=California/L=San Francisco/O=JankyCo/CN=Test Identity Provider' -keyout idp-private-key.pem -out idp-public-cert.pem -days 7300"
}
if (!fs.existsSync(argv.key)) {
return 'IdP Signature PrivateKey Certificate "' + argv.key + '" is not a valid file path.\n' +
"Please generate a key-pair for the IdP using the following openssl command:\n" +
"\topenssl req -x509 -new -newkey rsa:2048 -nodes -subj '/C=US/ST=California/L=San Francisco/O=JankyCo/CN=Test Identity Provider' -keyout idp-private-key.pem -out idp-public-cert.pem -days 7300"
}
argv.cert = fs.readFileSync(argv.cert);
argv.key = fs.readFileSync(argv.key);
})
.check(function(argv, aliases) {
if (argv.https) {
if (!fs.existsSync(argv.httpsPrivateKey)) {
return 'HTTPS Private Key "' + argv.httpsPrivateKey + '" is not a valid file path';
}
if (!fs.existsSync(argv.httpsCert)) {
return 'HTTPS Certificate "' + argv.httpsCert + '" is not a valid file path';
}
argv.httpsPrivateKey = fs.readFileSync(argv.httpsPrivateKey).toString();
argv.httpsCert = fs.readFileSync(argv.httpsCert).toString();
}
})
.check(function(argv, aliases) {
var hasFormat = function(file, header) {
var data = fs.readFileSync(file);
var re = new RegExp('-----BEGIN ' + header.toUpperCase() + '-----[^-]*-----END ' + header.toUpperCase() + '-----');
return re.test(data);
}
if (argv.encryptionCert) {
if (!fs.existsSync(argv.encryptionCert)) {
return 'Encryption cert "' + argv.encryptionCert + '" is not a valid file path';
}
if (!hasFormat(argv.encryptionCert, 'CERTIFICATE')) {
return 'Encryption cert "' + argv.encryptionCert + '" is not a valid PEM certificate';
}
if (argv.encryptionPublicKey === undefined) {
return 'encryptionPublicKey argument is also required for assertion encryption';
}
}
if (argv.encryptionPublicKey) {;
if (!fs.existsSync(argv.encryptionPublicKey)) {
return 'Encryption public key "' + argv.encryptionPublicKey + '" is not a valid file path';
}
if (!hasFormat(argv.encryptionPublicKey, 'PUBLIC KEY')) {
return 'Encryption cert "' + argv.encryptionPublicKey + '" is not a valid PEM certificate';
}
if (argv.encryptionCert === undefined) {
return 'encryptionCert argument is also required for assertion encryption';
}
// Set flag since both file args are present
argv.encryptAssertion = true;
}
return true;
})
.argv;
console.log();
console.log('Listener Port:\n\t' + argv.port);
console.log('HTTPS Listener:\n\t' + argv.https);
console.log('IdP Issuer URI:\n\t' + argv.issuer);
console.log('SP ACS URL:\n\t' + argv.acsUrl);
console.log('SP Audience URI:\n\t' + argv.audience);
console.log('Default RelayState:\n\t' + argv.relayState);
console.log('Allow SP to Specify ACS URLs:\n\t' + !argv.disableRequestAcsUrl);
console.log('Assertion Encryption:\n\t' + argv.encryptAssertion);
console.log();
/**
* IdP Configuration
*/
SimpleProfileMapper.prototype.metadata = config.metadata;
var idpOptions = {
issuer: argv.issuer,
cert: fs.readFileSync(path.join(__dirname, 'idp-public-cert.pem')),
key: fs.readFileSync(path.join(__dirname, 'idp-private-key.pem')),
audience: argv.audience,
recipient: argv.acsUrl,
destination: argv.acsUrl,
acsUrl: argv.acsUrl,
RelayState: argv.relayState,
allowRequestAcsUrl: !argv.disableRequestAcsUrl,
digestAlgorithm: 'sha1',
signatureAlgorithm: 'rsa-sha1',
signResponse: false,
encryptAssertion: argv.encryptAssertion,
encryptionAlgorithm: 'http://www.w3.org/2001/04/xmlenc#aes256-cbc',
keyEncryptionAlgorighm: 'http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p',
lifetimeInSeconds: 3600,
authnContextClassRef: 'urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport',
profileMapper: SimpleProfileMapper,
getUserFromRequest: function(req) { return req.user; },
getPostURL: function (audience, authnRequestDom, req, callback) {
return callback(null, (req.authnRequest && req.authnRequest.acsUrl) ?
req.authnRequest.acsUrl :
argv.acsUrl);
}
}
if (argv.encryptAssertion) {
idpOptions.encryptionCert = fs.readFileSync(argv.encryptionCert);
idpOptions.encryptionPublicKey = fs.readFileSync(argv.encryptionPublicKey);
}
/**
* App Environment
*/
app.set('port', process.env.PORT || argv.port);
app.set('views', path.join(__dirname, 'views'));
/**
* View Engine
*/
app.set('view engine', 'hbs');
app.set('view options', { layout: 'layout' })
app.engine('handlebars', hbs.__express);
// Register Helpers
hbs.registerHelper('extend', function(name, context) {
var block = blocks[name];
if (!block) {
block = blocks[name] = [];
}
block.push(context.fn(this));
});
hbs.registerHelper('block', function(name) {
var val = (blocks[name] || []).join('\n');
// clear the block
blocks[name] = [];
return val;
});
hbs.registerHelper('select', function(selected, options) {
return options.fn(this).replace(
new RegExp(' value=\"' + selected + '\"'),
'$& selected="selected"');
});
hbs.registerHelper('getProperty', function(attribute, context) {
return context[attribute];
});
hbs.registerHelper('serialize', function(context) {
return new Buffer(JSON.stringify(context)).toString('base64');
});
/**
* Middleware
*/
app.use(logger(':date> :method :url - {:referrer} => :status (:response-time ms)'));
app.use(bodyParser.urlencoded({extended: true}))
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
/**
* View Handlers
*/
var showUser = function (req, res, next) {
res.render('user', {
user: req.user,
metadata: req.metadata,
authnRequest: req.authnRequest,
idp: req.idp.options
});
}
/**
* Routes
*/
app.use(function(req, res, next){
req.user = config.user;
req.metadata = config.metadata;
req.idp = { options: idpOptions };
samlp.parseRequest(req, function(err, data) {
if (data) {
req.authnRequest = {
relayState: req.query.RelayState || req.body.RelayState,
id: data.id,
issuer: data.issuer,
destination: data.destination,
acsUrl: data.assertionConsumerServiceURL,
forceAuthn: data.forceAuthn,
sigAlg: req.query.SigAlg,
signature: req.query.Signature
};
console.log('Received AuthnRequest => \n', req.authnRequest);
}
next();
});
});
app.get(['/', '/idp'], showUser);
app.post(['/', '/idp'], function(req, res, next) {
var authOptions = extend({}, req.idp.options);
if (req.body.SAMLRequest) {
showUser(req, res, next);
} else {
// Form POST
Object.keys(req.body).forEach(function(key) {
var buffer;
if (key === '_authnRequest') {
buffer = new Buffer(req.body[key], 'base64');
req.authnRequest = JSON.parse(buffer.toString('utf8'));
// Apply AuthnRequest Params
authOptions.inResponseTo = req.authnRequest.id;
if (req.idp.options.allowRequestAcsUrl && req.authnRequest.acsUrl) {
authOptions.acsUrl = req.authnRequest.acsUrl;
authOptions.recipient = req.authnRequest.acsUrl;
authOptions.destination = req.authnRequest.acsUrl;
}
if (req.authnRequest.relayState) {
authOptions.RelayState = req.authnRequest.relayState;
}
} else {
req.user[key] = req.body[key];
}
});
if (!authOptions.encryptAssertion) {
delete authOptions.encryptionCert;
delete authOptions.encryptionPublicKey;
}
// Keep calm and Single Sign On
console.log('Sending Assertion with Options => \n', authOptions);
samlp.auth(authOptions)(req, res);
}
});
app.get('/metadata', function(req, res, next) {
samlp.metadata(req.idp.options)(req, res);
});
app.post('/metadata', function(req, res, next) {
if (req.body && req.body.attributeName && req.body.displayName) {
var attributeExists = false;
var attribute = {
id: req.body.attributeName,
optional: true,
displayName: req.body.displayName,
description: req.body.discription || '',
multiValue: req.body.valueType === 'multi'
};
req.metadata.forEach(function(entry) {
if (entry.id === req.body.attributeName) {
entry = attribute;
attributeExists = true;
}
});
if (!attributeExists) {
req.metadata.push(attribute);
}
console.log("Updated SAML Attribute Metadata => \n", req.metadata)
res.status(200).end();
}
});
app.get(['/settings'], function(req, res, next) {
res.render('settings', {
idp: req.idp.options
});
});
app.post(['/settings'], function(req, res, next) {
Object.keys(req.body).forEach(function(key) {
switch(req.body[key].toLowerCase()){
case "true": case "yes": case "1":
req.idp.options[key] = true;
break;
case "false": case "no": case "0":
req.idp.options[key] = false;
break;
default:
req.idp.options[key] = req.body[key];
break;
}
if (req.body[key].match(/^\d+$/)) {
req.idp.options[key] = parseInt(req.body[key], '10');
}
});
console.log('Updated IdP Configuration => \n', req.idp.options);
res.redirect('/');
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// development error handler
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
/**
* Start IdP Web Server
*/
console.log('starting server...');
httpServer = argv.https ?
https.createServer({ key: argv.httpsPrivateKey, cert: argv.httpsCert }, app) :
http.createServer(app);
httpServer.listen(app.get('port'), function() {
var scheme = argv.https ? 'https' : 'http',
address = httpServer.address(),
hostname = os.hostname();
baseUrl = address.address === '0.0.0.0' ?
scheme + '://' + hostname + ':' + address.port :
scheme + '://localhost:' + address.port;
console.log('listening on port: ' + app.get('port'));
console.log();
console.log('urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST');
console.log('\t=> ' + baseUrl + '/idp')
console.log('urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect');
console.log('\t=> ' + baseUrl + '/idp')
console.log();
});