forked from tngan/samlify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinding-post.ts
337 lines (324 loc) Β· 13.7 KB
/
binding-post.ts
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
/**
* @file binding-post.ts
* @author tngan
* @desc Binding-level API, declare the functions using POST binding
*/
import { wording, namespace, StatusCode } from './urn';
import { BindingContext } from './entity';
import libsaml from './libsaml';
import utility, { get } from './utility';
import { LogoutResponseTemplate } from './libsaml';
const binding = wording.binding;
/**
* @desc Generate a base64 encoded login request
* @param {string} referenceTagXPath reference uri
* @param {object} entity object includes both idp and sp
* @param {function} customTagReplacement used when developers have their own login response template
*/
function base64LoginRequest(referenceTagXPath: string, entity: any, customTagReplacement?: (template: string) => BindingContext): BindingContext {
const metadata = { idp: entity.idp.entityMeta, sp: entity.sp.entityMeta };
const spSetting = entity.sp.entitySetting;
let id: string = '';
if (metadata && metadata.idp && metadata.sp) {
const base = metadata.idp.getSingleSignOnService(binding.post);
let rawSamlRequest: string;
if (spSetting.loginRequestTemplate && customTagReplacement) {
const info = customTagReplacement(spSetting.loginRequestTemplate.context);
id = get(info, 'id', null);
rawSamlRequest = get(info, 'context', null);
} else {
const nameIDFormat = spSetting.nameIDFormat;
const selectedNameIDFormat = Array.isArray(nameIDFormat) ? nameIDFormat[0] : nameIDFormat;
id = spSetting.generateID();
rawSamlRequest = libsaml.replaceTagsByValue(libsaml.defaultLoginRequestTemplate.context, {
ID: id,
Destination: base,
Issuer: metadata.sp.getEntityID(),
IssueInstant: new Date().toISOString(),
AssertionConsumerServiceURL: metadata.sp.getAssertionConsumerService(binding.post),
EntityID: metadata.sp.getEntityID(),
AllowCreate: spSetting.allowCreate,
NameIDFormat: selectedNameIDFormat
} as any);
}
if (metadata.idp.isWantAuthnRequestsSigned()) {
const { privateKey, privateKeyPass, requestSignatureAlgorithm: signatureAlgorithm, transformationAlgorithms } = spSetting;
return {
id,
context: libsaml.constructSAMLSignature({
referenceTagXPath,
privateKey,
privateKeyPass,
signatureAlgorithm,
transformationAlgorithms,
rawSamlMessage: rawSamlRequest,
signingCert: metadata.sp.getX509Certificate('signing'),
signatureConfig: spSetting.signatureConfig || {
prefix: 'ds',
location: { reference: "/*[local-name(.)='AuthnRequest']/*[local-name(.)='Issuer']", action: 'after' },
}
}),
};
}
// No need to embeded XML signature
return {
id,
context: utility.base64Encode(rawSamlRequest),
};
}
throw new Error('ERR_GENERATE_POST_LOGIN_REQUEST_MISSING_METADATA');
}
/**
* @desc Generate a base64 encoded login response
* @param {object} requestInfo corresponding request, used to obtain the id
* @param {object} entity object includes both idp and sp
* @param {object} user current logged user (e.g. req.user)
* @param {function} customTagReplacement used when developers have their own login response template
* @param {boolean} encryptThenSign whether or not to encrypt then sign first (if signing). Defaults to sign-then-encrypt
*/
async function base64LoginResponse(requestInfo: any = {}, entity: any, user: any = {}, customTagReplacement?: (template: string) => BindingContext, encryptThenSign: boolean = false): Promise<BindingContext> {
const idpSetting = entity.idp.entitySetting;
const spSetting = entity.sp.entitySetting;
const id = idpSetting.generateID();
const metadata = {
idp: entity.idp.entityMeta,
sp: entity.sp.entityMeta,
};
const nameIDFormat = idpSetting.nameIDFormat;
const selectedNameIDFormat = Array.isArray(nameIDFormat) ? nameIDFormat[0] : nameIDFormat;
if (metadata && metadata.idp && metadata.sp) {
const base = metadata.sp.getAssertionConsumerService(binding.post);
let rawSamlResponse: string;
const nowTime = new Date();
const spEntityID = metadata.sp.getEntityID();
const fiveMinutesLaterTime = new Date(nowTime.getTime());
fiveMinutesLaterTime.setMinutes(fiveMinutesLaterTime.getMinutes() + 5);
const fiveMinutesLater = fiveMinutesLaterTime.toISOString();
const now = nowTime.toISOString();
const acl = metadata.sp.getAssertionConsumerService(binding.post);
const tvalue: any = {
ID: id,
AssertionID: idpSetting.generateID(),
Destination: base,
Audience: spEntityID,
EntityID: spEntityID,
SubjectRecipient: acl,
Issuer: metadata.idp.getEntityID(),
IssueInstant: now,
AssertionConsumerServiceURL: acl,
StatusCode: StatusCode.Success,
// can be customized
ConditionsNotBefore: now,
ConditionsNotOnOrAfter: fiveMinutesLater,
SubjectConfirmationDataNotOnOrAfter: fiveMinutesLater,
NameIDFormat: selectedNameIDFormat,
NameID: user.email || '',
InResponseTo: get(requestInfo, 'extract.request.id', ''),
AuthnStatement: '',
AttributeStatement: '',
};
if (idpSetting.loginResponseTemplate && customTagReplacement) {
const template = customTagReplacement(idpSetting.loginResponseTemplate.context);
rawSamlResponse = get(template, 'context', null);
} else {
if (requestInfo !== null) {
tvalue.InResponseTo = requestInfo.extract.request.id;
}
rawSamlResponse = libsaml.replaceTagsByValue(libsaml.defaultLoginResponseTemplate.context, tvalue);
}
const { privateKey, privateKeyPass, requestSignatureAlgorithm: signatureAlgorithm } = idpSetting;
const config = {
privateKey,
privateKeyPass,
signatureAlgorithm,
signingCert: metadata.idp.getX509Certificate('signing'),
isBase64Output: false,
};
// step: sign assertion ? -> encrypted ? -> sign message ?
if (metadata.sp.isWantAssertionsSigned()) {
// console.debug('sp wants assertion signed');
rawSamlResponse = libsaml.constructSAMLSignature({
...config,
rawSamlMessage: rawSamlResponse,
transformationAlgorithms: spSetting.transformationAlgorithms,
referenceTagXPath: "/*[local-name(.)='Response']/*[local-name(.)='Assertion']",
signatureConfig: {
prefix: 'ds',
location: { reference: "/*[local-name(.)='Response']/*[local-name(.)='Assertion']/*[local-name(.)='Issuer']", action: 'after' },
},
});
}
// console.debug('after assertion signed', rawSamlResponse);
// SAML response must be signed sign message first, then encrypt
if (!encryptThenSign && (spSetting.wantMessageSigned || !metadata.sp.isWantAssertionsSigned())) {
// console.debug('sign then encrypt and sign entire message');
rawSamlResponse = libsaml.constructSAMLSignature({
...config,
rawSamlMessage: rawSamlResponse,
isMessageSigned: true,
transformationAlgorithms: spSetting.transformationAlgorithms,
signatureConfig: spSetting.signatureConfig || {
prefix: 'ds',
location: { reference: "/*[local-name(.)='Response']/*[local-name(.)='Issuer']", action: 'after' },
},
});
}
// console.debug('after message signed', rawSamlResponse);
if (idpSetting.isAssertionEncrypted) {
// console.debug('idp is configured to do encryption');
const context = await libsaml.encryptAssertion(entity.idp, entity.sp, rawSamlResponse);
if (encryptThenSign) {
//need to decode it
rawSamlResponse = utility.base64Decode(context) as string;
} else {
return Promise.resolve({ id, context });
}
}
//sign after encrypting
if (encryptThenSign && (spSetting.wantMessageSigned || !metadata.sp.isWantAssertionsSigned())) {
rawSamlResponse = libsaml.constructSAMLSignature({
...config,
rawSamlMessage: rawSamlResponse,
isMessageSigned: true,
transformationAlgorithms: spSetting.transformationAlgorithms,
signatureConfig: spSetting.signatureConfig || {
prefix: 'ds',
location: { reference: "/*[local-name(.)='Response']/*[local-name(.)='Issuer']", action: 'after' },
},
});
}
return Promise.resolve({
id,
context: utility.base64Encode(rawSamlResponse),
});
}
throw new Error('ERR_GENERATE_POST_LOGIN_RESPONSE_MISSING_METADATA');
}
/**
* @desc Generate a base64 encoded logout request
* @param {object} user current logged user (e.g. req.user)
* @param {string} referenceTagXPath reference uri
* @param {object} entity object includes both idp and sp
* @param {function} customTagReplacement used when developers have their own login response template
* @return {string} base64 encoded request
*/
function base64LogoutRequest(user, referenceTagXPath, entity, customTagReplacement?: (template: string) => BindingContext): BindingContext {
const metadata = { init: entity.init.entityMeta, target: entity.target.entityMeta };
const initSetting = entity.init.entitySetting;
const nameIDFormat = initSetting.nameIDFormat;
const selectedNameIDFormat = Array.isArray(nameIDFormat) ? nameIDFormat[0] : nameIDFormat; let id: string = '';
if (metadata && metadata.init && metadata.target) {
let rawSamlRequest: string;
if (initSetting.logoutRequestTemplate && customTagReplacement) {
const template = customTagReplacement(initSetting.logoutRequestTemplate.context);
id = get(template, 'id', null);
rawSamlRequest = get(template, 'context', null);
} else {
id = initSetting.generateID();
const tvalue: any = {
ID: id,
Destination: metadata.target.getSingleLogoutService(binding.redirect),
Issuer: metadata.init.getEntityID(),
IssueInstant: new Date().toISOString(),
EntityID: metadata.init.getEntityID(),
NameIDFormat: selectedNameIDFormat,
NameID: user.logoutNameID,
};
rawSamlRequest = libsaml.replaceTagsByValue(libsaml.defaultLogoutRequestTemplate.context, tvalue);
}
if (entity.target.entitySetting.wantLogoutRequestSigned) {
// Need to embeded XML signature
const { privateKey, privateKeyPass, requestSignatureAlgorithm: signatureAlgorithm, transformationAlgorithms } = initSetting;
return {
id,
context: libsaml.constructSAMLSignature({
referenceTagXPath,
privateKey,
privateKeyPass,
signatureAlgorithm,
transformationAlgorithms,
rawSamlMessage: rawSamlRequest,
signingCert: metadata.init.getX509Certificate('signing'),
signatureConfig: initSetting.signatureConfig || {
prefix: 'ds',
location: { reference: "/*[local-name(.)='LogoutRequest']/*[local-name(.)='Issuer']", action: 'after' },
}
}),
};
}
return {
id,
context: utility.base64Encode(rawSamlRequest),
};
}
throw new Error('ERR_GENERATE_POST_LOGOUT_REQUEST_MISSING_METADATA');
}
/**
* @desc Generate a base64 encoded logout response
* @param {object} requestInfo corresponding request, used to obtain the id
* @param {string} referenceTagXPath reference uri
* @param {object} entity object includes both idp and sp
* @param {function} customTagReplacement used when developers have their own login response template
*/
function base64LogoutResponse(requestInfo: any, entity: any, customTagReplacement: (template: string) => BindingContext): BindingContext {
const metadata = {
init: entity.init.entityMeta,
target: entity.target.entityMeta,
};
let id: string = '';
const initSetting = entity.init.entitySetting;
if (metadata && metadata.init && metadata.target) {
let rawSamlResponse;
if (initSetting.logoutResponseTemplate) {
const template = customTagReplacement(initSetting.logoutResponseTemplate.context);
id = template.id;
rawSamlResponse = template.context;
} else {
id = initSetting.generateID();
const tvalue: any = {
ID: id,
Destination: metadata.target.getSingleLogoutService(binding.post),
EntityID: metadata.init.getEntityID(),
Issuer: metadata.init.getEntityID(),
IssueInstant: new Date().toISOString(),
StatusCode: StatusCode.Success,
InResponseTo: get(requestInfo, 'extract.request.id', null)
};
rawSamlResponse = libsaml.replaceTagsByValue(libsaml.defaultLogoutResponseTemplate.context, tvalue);
}
if (entity.target.entitySetting.wantLogoutResponseSigned) {
const { privateKey, privateKeyPass, requestSignatureAlgorithm: signatureAlgorithm, transformationAlgorithms } = initSetting;
return {
id,
context: libsaml.constructSAMLSignature({
isMessageSigned: true,
transformationAlgorithms: transformationAlgorithms,
privateKey,
privateKeyPass,
signatureAlgorithm,
rawSamlMessage: rawSamlResponse,
signingCert: metadata.init.getX509Certificate('signing'),
signatureConfig: {
prefix: 'ds',
location: {
reference: "/*[local-name(.)='LogoutResponse']/*[local-name(.)='Issuer']",
action: 'after'
}
}
}),
};
}
return {
id,
context: utility.base64Encode(rawSamlResponse),
};
}
throw new Error('ERR_GENERATE_POST_LOGOUT_RESPONSE_MISSING_METADATA');
}
const postBinding = {
base64LoginRequest,
base64LoginResponse,
base64LogoutRequest,
base64LogoutResponse,
};
export default postBinding;