This repository has been archived by the owner on Dec 4, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
index.js
287 lines (243 loc) · 7.74 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
const passport = require("passport-strategy");
const util = require("util");
var xmlCrypto = require("xml-crypto");
var xmlbuilder = require("xmlbuilder");
const saml = require("passport-saml").SAML;
function SpidStrategy(options, verify) {
if (typeof options === "function") {
verify = options;
options = {};
}
if (!verify) {
throw new Error("SAML authentication strategy requires a verify function");
}
this.name = "spid";
passport.Strategy.call(this);
this.spidOptions = options;
this._verify = verify;
this._passReqToCallback = !!options.passReqToCallback;
this._authnRequestBinding = options.authnRequestBinding || "HTTP-Redirect";
}
util.inherits(SpidStrategy, passport.Strategy);
SpidStrategy.prototype.authenticate = function(req, options) {
const self = this;
const spidOptions = this.spidOptions.sp;
const entityID = req.query.entityID;
if (entityID !== undefined) {
const idp = this.spidOptions.idp[entityID];
spidOptions.entryPoint = idp.entryPoint;
spidOptions.cert = idp.cert;
} else {
// Do a check against all IDP certs if we don't have an entityID
const idps = this.spidOptions.idp;
spidOptions.cert = Object.keys(idps).map(k => idps[k].cert);
}
const samlClient = new saml(spidOptions);
options.samlFallback = options.samlFallback || "login-request";
function validateCallback(err, profile, loggedOut) {
if (err) {
return self.error(err);
}
if (loggedOut) {
req.logout();
if (profile) {
req.samlLogoutRequest = profile;
return samlClient.getLogoutResponseUrl(req, redirectIfSuccess);
}
return self.pass();
}
const verified = function(err, user, info) {
if (err) {
return self.error(err);
}
if (!user) {
return self.fail(info);
}
self.success(user, info);
};
if (self._passReqToCallback) {
self._verify(req, profile, verified);
} else {
self._verify(profile, verified);
}
}
function redirectIfSuccess(err, url) {
if (err) {
self.error(err);
} else {
self.redirect(url);
}
}
if (req.body && req.body.SAMLResponse) {
samlClient.validatePostResponse(req.body, validateCallback);
} else if (req.body && req.body.SAMLRequest) {
samlClient.validatePostRequest(req.body, validateCallback);
} else {
const requestHandler = {
"login-request": function() {
if (self._authnRequestBinding === "HTTP-POST") {
samlClient.getAuthorizeForm(req, function(err, data) {
if (err) {
self.error(err);
} else {
const res = req.res;
res.send(data);
}
});
} else {
// Defaults to HTTP-Redirect
samlClient.getAuthorizeUrl(req, redirectIfSuccess);
}
}.bind(self),
"logout-request": function() {
samlClient.getLogoutUrl(req, redirectIfSuccess);
}.bind(self)
}[options.samlFallback];
if (typeof requestHandler !== "function") {
return self.fail();
}
requestHandler();
}
};
SpidStrategy.prototype.logout = function(req, callback) {
const spidOptions = this.spidOptions.sp;
const entityID = req.query.entityID;
if (entityID !== undefined) {
const idp = this.spidOptions.idp[entityID];
spidOptions.entryPoint = idp.entryPoint;
spidOptions.cert = idp.cert;
}
const samlClient = new saml(spidOptions);
samlClient.getLogoutUrl(req, callback);
};
SpidStrategy.prototype.generateServiceProviderMetadata = function(
decryptionCert
) {
const spidOptions = this.spidOptions.sp;
const samlClient = new saml(spidOptions);
const metadata = {
EntityDescriptor: {
"@xmlns": "urn:oasis:names:tc:SAML:2.0:metadata",
"@xmlns:ds": "http://www.w3.org/2000/09/xmldsig#",
"@entityID": spidOptions.issuer,
"@ID": spidOptions.issuer.replace(/\W/g, "_"),
SPSSODescriptor: {
"@protocolSupportEnumeration": "urn:oasis:names:tc:SAML:2.0:protocol",
"@AuthnRequestsSigned": true,
"@WantAssertionsSigned": true
}
}
};
if (spidOptions.decryptionPvk) {
if (!decryptionCert) {
throw new Error(
"Missing decryptionCert while generating metadata for decrypting service provider"
);
}
decryptionCert = decryptionCert.replace(/-+BEGIN CERTIFICATE-+\r?\n?/, "");
decryptionCert = decryptionCert.replace(/-+END CERTIFICATE-+\r?\n?/, "");
decryptionCert = decryptionCert.replace(/\r\n/g, "\n");
metadata.EntityDescriptor.SPSSODescriptor.KeyDescriptor = {
"ds:KeyInfo": {
"ds:X509Data": {
"ds:X509Certificate": {
"#text": decryptionCert
}
}
},
EncryptionMethod: [
// this should be the set that the xmlenc library supports
{ "@Algorithm": "http://www.w3.org/2001/04/xmlenc#aes256-cbc" },
{ "@Algorithm": "http://www.w3.org/2001/04/xmlenc#aes128-cbc" },
{ "@Algorithm": "http://www.w3.org/2001/04/xmlenc#tripledes-cbc" }
]
};
}
if (spidOptions.logoutCallbackUrl) {
metadata.EntityDescriptor.SPSSODescriptor.SingleLogoutService = {
"@Binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST",
"@Location": spidOptions.logoutCallbackUrl
};
}
metadata.EntityDescriptor.SPSSODescriptor.NameIDFormat =
spidOptions.identifierFormat;
metadata.EntityDescriptor.SPSSODescriptor.AssertionConsumerService = {
"@index": spidOptions.attributeConsumingServiceIndex,
"@isDefault": "true",
"@Binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST",
"@Location": samlClient.getCallbackUrl({})
};
if (spidOptions.attributes) {
function getFriendlyName(name) {
const friendlyNames = {
name: "Nome",
familyName: "Cognome",
fiscalNumber: "Codice fiscale",
email: "Email"
};
return friendlyNames[name];
}
const attributes = spidOptions.attributes.attributes.map(function(item) {
return {
"@Name": item,
"@NameFormat":
"urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified",
"@FriendlyName": getFriendlyName(item)
};
});
metadata.EntityDescriptor.SPSSODescriptor.AttributeConsumingService = {
"@index": spidOptions.attributeConsumingServiceIndex,
ServiceName: {
"@xml:lang": "it",
"#text": spidOptions.attributes.name
},
RequestedAttribute: attributes
};
}
if (spidOptions.organization) {
metadata.EntityDescriptor.Organization = {
OrganizationName: spidOptions.organization.name,
OrganizationDisplayName: spidOptions.organization.displayName,
OrganizationURL: spidOptions.organization.URL
};
}
const xml = xmlbuilder.create(metadata).end({
pretty: true,
indent: " ",
newline: "\n"
});
function MyKeyInfo(file) {
this.file = file;
this.getKeyInfo = function(key, prefix) {
prefix = prefix || "";
prefix = prefix ? prefix + ":" : prefix;
return (
"<" +
prefix +
"X509Data><X509Certificate>" +
decryptionCert +
"</X509Certificate></" +
prefix +
"X509Data>"
);
};
this.getKey = function(keyInfo) {
return this.file;
};
}
var sig = new xmlCrypto.SignedXml();
sig.signingKey = spidOptions.privateCert;
sig.keyInfoProvider = new MyKeyInfo(decryptionCert);
sig.addReference(
"//*[local-name(.)='EntityDescriptor']",
[
"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.signatureAlgorithm = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
sig.computeSignature(xml);
return sig.getSignedXml();
};
module.exports = SpidStrategy;