-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
342 lines (296 loc) · 15.5 KB
/
index.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
const express = require('express');
const session = require('express-session')
const bodyParser = require('body-parser');
const fs = require('fs');
const ejs = require('ejs');
const path = require('path');
const http = require('http');
const https = require('https');
const xpath = require('xpath');
const xmldom = require('xmldom');
const SignedXml = require('xml-crypto').SignedXml;
const saml20 = require('saml').Saml20;
const uuid = require('uuid');
const helmet = require('helmet');
// Get our config!
const version = process.env.npm_package_version ? process.env.npm_package_version : JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'))).version;
const config = JSON.parse(fs.readFileSync(path.join(__dirname, './data', 'config.json')));
// Setup servers
var privateKey = fs.readFileSync(path.join(__dirname, config.service.key_file));
var certificate = fs.readFileSync(path.join(__dirname, config.service.cert_file));
var credentials = {key: privateKey, cert: certificate};
var app = express();
var httpsServer = https.createServer(credentials, app);
var io = require("socket.io")(httpsServer);
// Sessions
var io_session = require("express-socket.io-session");
var e_session = require("express-session");
var ee_session = e_session({
secret: config.service.cookie_secret,
resave: true,
saveUninitialized: true,
cookie: { secure: true },
name: 'sessionid'
});
var sharedsession = require("express-socket.io-session");
const { Console } = require('console');
io.use(io_session(ee_session, { autoSave:true }));
// Default claims provided by our solitons
var outboundClaims=[];
outboundClaims.push({id: 'http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationinstant', name: 'Authentication Instant'});
outboundClaims.push({id: 'http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod', name: 'Authentication Method'});
outboundClaims.push({id: 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/authenticated', name: 'User Authentication State'});
outboundClaims.push({id: 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress', name: 'E-mail Address'});
outboundClaims.push({id: 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier', name: 'Name ID'});
outboundClaims.push({id: 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name', name: 'Name'});
outboundClaims.push({id: 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname', name: 'Given Name'});
outboundClaims.push({id: 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname', name: 'Surname'});
// Fetch all templates from the disk and enter them into the array
var templates = {};
fs.readdirSync(path.join(__dirname, './templates')).forEach(function (tmplFile) {
var content = fs.readFileSync(path.join(__dirname, './templates', tmplFile));
var template = ejs.compile(content.toString());
templates[tmplFile.slice(0, -4)] = template;
});
// Supporting function to compare bolleanish strings
function strbool(value) {
return value=="true" ? true : false;
}
function stripCert(certificateData) {
var pem = /-----BEGIN (\w*)-----([^-]*)-----END (\w*)-----/g.exec(certificateData.toString());
if (pem && pem.length > 0) {
return pem[2].replace(/[\n|\r\n]/g, '');
}
return null;
}
// Resolve the hostname for this host
function getHost(req, endpointPath) {
var protocol = req.headers['x-forwarded-proto'] || req.protocol;
var host = req.headers['x-forwarded-host'] || req.headers['host'];
return protocol + '://' + host + endpointPath;
}
// Create a time to use in SAML responses
function getInstant(date) {
return date.getUTCFullYear() + '-' +
('0' + (date.getUTCMonth() + 1)).slice(-2) + '-' +
('0' + date.getUTCDate()).slice(-2) + 'T' +
('0' + date.getUTCHours()).slice(-2) + ":" +
('0' + date.getUTCMinutes()).slice(-2) + ":" +
('0' + date.getUTCSeconds()).slice(-2) + "." +
('00' + date.getUTCMilliseconds()).slice(-3) + "Z";
};
// Create a saml and sign it
function buildSamlResponse(options) {
var SAMLResponse = templates.samlresponse({
id: '_' + uuid.v4(),
instant: getInstant(new Date()),
destination: options.destination || options.audience,
inResponseTo: options.inResponseTo,
issuer: options.issuer,
samlStatusCode: options.samlStatusCode,
samlStatusMessage: options.samlStatusMessage,
assertion: options.signedAssertion || ''
});
var cannonicalized = SAMLResponse.replace(/\r\n/g, '').replace(/\n/g,'').replace(/>(\s*)</g, '><').trim();
var sig = new SignedXml(null, { signatureAlgorithm: 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256' });
sig.addReference("//*[local-name(.)='Response' and namespace-uri(.)='urn:oasis:names:tc:SAML:2.0:protocol']", ["http://www.w3.org/2000/09/xmldsig#enveloped-signature", "http://www.w3.org/2001/10/xml-exc-c14n#"],"http://www.w3.org/2001/04/xmlenc#sha256");
sig.signingKey = options.key;
sig.keyInfoProvider = {
getKeyInfo: function (key, prefix) {
prefix = prefix ? prefix + ':' : prefix;
return "<" + prefix + "X509Data><" + prefix + "X509Certificate>" + stripCert(options.cert) + "</" + prefix + "X509Certificate></" + prefix + "X509Data>";
}
};
sig.computeSignature(cannonicalized, { prefix: options.signatureNamespacePrefix, location: { action: 'after', reference: "//*[local-name(.)='Issuer']" }});
return sig.getSignedXml();
}
// ***************************************************************************************
// MAIN APPLICATION CODE
// ***************************************************************************************
if (process.argv && process.argv[2] && process.argv[2]==='-generate') {
console.log("Generating files..")
for(var idp in config) {
if (idp!="service") {
var signingCert = stripCert(fs.readFileSync(path.join(__dirname, config[idp].issuer.cert_file)));
var idpXml = templates.metadata({
signingPem: signingCert,
redirectEndpoint: "https://"+config.service.hostname+":"+config.service.port+"/"+idp+"/login",
postEndpoint: "https://"+config.service.hostname+":"+config.service.port+"/"+idp+"/login",
claimTypes: outboundClaims,
issuer: "https://"+config.service.hostname+":"+config.service.port+"/"+idp,
issuerContact: config[idp].issuer.contact,
issuerEmail: config[idp].issuer.email,
issuerDisplayName: config[idp].issuer.display_name,
issuerUrl: config[idp].issuer.url,
})
fs.writeFileSync(path.join(__dirname,`./data/metadata/${config[idp].domain.replace(".","_")}.xml`), idpXml, (err)=>{
});
console.log("Created static Metadata for "+config[idp].domain.replace(".","_")+" in /data/metadata")
var idpPS = templates.powershell({
domainName: config[idp].domain,
serviceHost: config.service.hostname,
servicePort: config.service.port,
idp: idp,
idpName: "https://"+config.service.hostname+":"+config.service.port+"/"+idp,
signingCert: signingCert
});
fs.writeFileSync(path.join(__dirname,`./data/powershell/${config[idp].domain.replace(".","_")}.ps1`), idpPS, (err)=>{
});
console.log("Created PowerShell configuration for "+config[idp].domain.replace(".","_")+" in /data/powershell")
}
}
process.exit();
}
// Start the basic server to handle incomming requests
app.set('trust proxy', 1) // trust first proxy
app.use(ee_session);
app.use(helmet());
app.use(bodyParser.urlencoded({extended: true}));
app.use("/resources/", express.static(path.join(__dirname, './resources')));
// Expose the metadata endpoint
app.get('/:site/FederationMetadata/2007-06/FederationMetadata.xml', (req, res) => {
var site = req.params.site;
if (!config[site]) {
return res.status(404).send(templates.error_404({
moduleversion: version,
nodeversion: process.version
}));
}
res.set('Content-Type', 'application/xml');
res.send(templates.metadata({
signingPem: stripCert(fs.readFileSync(path.join(__dirname, config[idp].issuer.cert_file))),
redirectEndpoint: "https://"+config.service.hostname+":"+config.service.port+"/"+idp+"/login",
postEndpoint: "https://"+config.service.hostname+":"+config.service.port+"/"+idp+"/login",
claimTypes: outboundClaims,
issuer: "https://"+config.service.hostname+":"+config.service.port+"/"+idp,
issuerContact: config[site].issuer.contact,
issuerEmail: config[site].issuer.email,
issuerDisplayName: config[site].issuer.display_name,
issuerUrl: config[site].issuer.url,
}).replace(/\n(?:\s*\n)+/g, '\n'));
});
// Show the login form
app.post("/:site/login", (req, res) => {
var site = req.params.site;
if (!config[site]) {
return res.status(404).send(templates.error_404({
moduleversion: version,
nodeversion: process.version
}));
}
var samlRequestDom = new xmldom.DOMParser().parseFromString(Buffer.from(req.body.SAMLRequest, 'base64').toString('utf-8'));
var relayState = req.body.RelayState;
var request_user = req.body.username;
var request_issuer = xpath.select("//*[local-name(.)='Issuer' and namespace-uri(.)='urn:oasis:names:tc:SAML:2.0:assertion']/text()",samlRequestDom);
resuest_issuer = (request_issuer && request_issuer.length > 0) ? request_issuer[0].textContent: "";
var request_id = samlRequestDom.documentElement.getAttribute('ID');
req.session.relayState = relayState;
req.session.requestUser = request_user;
req.session.requestId = request_id;
req.session.service = site;
req.session.save();
res.send(templates[`loginform_${config[site].template}`]({
userId: request_user,
logoUrl: config[site].logo_url,
logoText: config[site].display_name,
helpText: config[site].help_text,
termsUrl: config[site].terms_url,
privacyUrl: config[site].privacy_url,
pageTitle: config[site].title
}));
});
// Handle 404
app.use(function (req, res, next) {
res.status(404).send(templates.error_404({
moduleversion: version,
nodeversion: process.version
}));
})
// Handle 500
app.use(function (err, req, res, next) {
res.status(500).send(templates.error_500({
moduleversion: version,
nodeversion: process.version
}));
})
// Socket listener
io.on("connection", function(socket) {
socket.on("authRequest", function() {
socket.emit("authResponse", { status: 'preparing' });
if (socket.handshake.session.service) {
const site = socket.handshake.session.service;
const eidprovider = require('eid');
var eidconfig = eid.configFactory({clientType: 'frejaeid', enviroment: config[site].profile});
for(var override in config[site].settings) {
if (override==='ca_cert'||override==='jwt_cert'||override==='client_cert'){
eidconfig[override] = fs.readFileSync(path.join(__dirname, config[site].settings[override]));
} else {
eidconfig[override] = config[site].settings[override];
}
}
var eidclient = eid.clientFactory(eidconfig);
if (config[site].accounting==='true') {
fs.appendFile(path.join(__dirname,`./data/accunting/${config[site].domain.replace(".","_")}.log`), `${getInstant(new Date())},${socket.handshake.session.requestUser}\r\n`, (err)=>{} );
}
eidclient.authRequest(socket.handshake.session.requestUser, (data)=>{
socket.emit("authResponse", { status: data.status, code: data.code });
}, (data)=>{
socket.emit("authResponse", { status: data.status, code: data.code });
}).then((data)=>{
if (data.status='completed') {
var options = {
signatureAlgorithm: 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256',
digestAlgorithm: 'http://www.w3.org/2001/04/xmlenc#sha256',
cert: fs.readFileSync(path.join(__dirname, config[site].issuer.cert_file)),
key: fs.readFileSync(path.join(__dirname, config[site].issuer.key_file)),
issuer: "https://"+config.service.hostname+':'+config.service.port+'/'+site,
audiences: 'urn:federation:MicrosoftOnline',
inResponseTo: socket.handshake.session.requestId,
signatureNamespacePrefix: 'ds'
};
if (!data.user) {
options.samlStatusCode = 'urn:oasis:names:tc:SAML:2.0:status:Responder';
options.samlStatusMessage = data.code;
var SAMLResponse = buildSamlResponse(options);
return socket.emit("authResponse", { status: "error", code: "internal_error", action: 'https://login.microsoftonline.com/login.srf', ticket: Buffer.from(SAMLResponse, 'utf-8').toString('base64'), state: socket.handshake.session.relayState })
}
options.lifetimeInSeconds = 3600;
options.nameIdentifier = Buffer.from(data.user.id, 'utf-8').toString('base64');
options.nameIdentifierFormat = 'urn:oasis:names:tc:SAML:2.0:nameid-format:persistent';
options.authnContextClassRef = 'urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport';
options.attributes = {
'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/authenticated': 'true',
'http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod': eidconfig.minimumLevel,
'http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationinstant': getInstant(new Date()),
'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier': Buffer.from(data.user.id, 'utf-8').toString('base64'),
'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress': socket.handshake.session.requestUser,
'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name': data.user.fullname,
'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname': data.user.firstname,
'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname': data.user.lastname
};
saml20.create(options, function (err, signedAssertion) {
if (err) {
options.samlStatusCode = 'urn:oasis:names:tc:SAML:2.0:status:Responder';
options.samlStatusMessage = err.toString();
var SAMLResponse = buildSamlResponse(options);
socket.emit("authResponse", { status: "error", code: "internal_error", action: 'https://login.microsoftonline.com/login.srf', ticket: Buffer.from(SAMLResponse, 'utf-8').toString('base64'), state: socket.handshake.session.relayState })
}
options.signedAssertion = signedAssertion;
options.samlStatusCode = "urn:oasis:names:tc:SAML:2.0:status:Success";
var SAMLResponse = buildSamlResponse(options);
socket.emit("authResponse", { status: data.status, code: data.code, action: 'https://login.microsoftonline.com/login.srf', ticket: Buffer.from(SAMLResponse, 'utf-8').toString('base64'), state: socket.handshake.session.relayState })
});
} else {
options.samlStatusCode = 'urn:oasis:names:tc:SAML:2.0:status:Responder';
options.samlStatusMessage = data.code;
var SAMLResponse = buildSamlResponse(options);
socket.emit("authResponse", { status: "error", code: "internal_error", action: 'https://login.microsoftonline.com/login.srf', ticket: Buffer.from(SAMLResponse, 'utf-8').toString('base64'), state: socket.handshake.session.relayState })
}
});
}
});
});
// Start the https server
httpsServer.listen(config.service.port, () => {
console.log('Server running on port '+config.service.port);
});