forked from i8beef/SAML2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSaml20LogoutHandler.cs
More file actions
513 lines (426 loc) · 21.2 KB
/
Saml20LogoutHandler.cs
File metadata and controls
513 lines (426 loc) · 21.2 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
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
using System;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Xml;
using SAML2.Bindings;
using SAML2.Config;
using SAML2.Exceptions;
using SAML2.Schema.Metadata;
using SAML2.Schema.Protocol;
using SAML2.Utils;
namespace SAML2.Protocol
{
/// <summary>
/// Handles logout for all SAML bindings.
/// </summary>
public class Saml20LogoutHandler : Saml20AbstractEndpointHandler
{
/// <summary>
/// Initializes a new instance of the <see cref="Saml20LogoutHandler"/> class.
/// </summary>
public Saml20LogoutHandler()
{
// Read the proper redirect url from config
try
{
RedirectUrl = Saml2Config.Current.ServiceProvider.LogoutEndpoint.RedirectUrl;
}
catch (Exception e)
{
Logger.Error(e.Message, e);
}
}
#region IHttpHandler related
/// <summary>
/// Handles a request.
/// </summary>
/// <param name="context">The context.</param>
protected override void Handle(HttpContext context)
{
Logger.Debug(TraceMessages.LogoutHandlerCalled);
// Some IDP's are known to fail to set an actual value in the SOAPAction header
// so we just check for the existence of the header field.
if (Array.Exists(context.Request.Headers.AllKeys, s => s == SoapConstants.SoapAction))
{
HandleSoap(context, context.Request.InputStream);
return;
}
if (!string.IsNullOrEmpty(context.Request.Params["SAMLart"]))
{
HandleArtifact(context);
return;
}
if (!string.IsNullOrEmpty(context.Request.Params["SAMLResponse"]))
{
HandleResponse(context);
}
else if (!string.IsNullOrEmpty(context.Request.Params["SAMLRequest"]))
{
HandleRequest(context);
}
else
{
IdentityProvider idpEndpoint = null;
var idpId = StateService.Get<string>(IdpSessionIdKey);
if (!string.IsNullOrEmpty(idpId))
{
idpEndpoint = RetrieveIDPConfiguration(StateService.Get<string>(IdpLoginSessionKey));
}
if (idpEndpoint == null)
{
// TODO: Reconsider how to accomplish this.
context.User = null;
FormsAuthentication.SignOut();
Logger.ErrorFormat(ErrorMessages.UnknownIdentityProvider, string.Empty);
throw new Saml20Exception(string.Format(ErrorMessages.UnknownIdentityProvider, string.Empty));
}
TransferClient(idpEndpoint, context);
}
}
#endregion
#region Private methods - Handlers
/// <summary>
/// Handles executing the logout.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="idpInitiated">if set to <c>true</c> identity provider is initiated.</param>
private void DoLogout(HttpContext context, bool idpInitiated = false)
{
Logger.Debug(TraceMessages.LogoutActionsExecuting);
foreach (var action in Actions.Actions.GetActions())
{
Logger.DebugFormat("{0}.{1} called", action.GetType(), "LogoutAction()");
action.LogoutAction(this, context, idpInitiated);
Logger.DebugFormat("{0}.{1} finished", action.GetType(), "LogoutAction()");
}
}
/// <summary>
/// Handles the artifact.
/// </summary>
/// <param name="context">The context.</param>
private void HandleArtifact(HttpContext context)
{
var builder = new HttpArtifactBindingBuilder(context);
var inputStream = builder.ResolveArtifact();
HandleSoap(context, inputStream);
}
/// <summary>
/// Handles the SOAP message.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="inputStream">The input stream.</param>
private void HandleSoap(HttpContext context, Stream inputStream)
{
var parser = new HttpArtifactBindingParser(inputStream);
Logger.DebugFormat(TraceMessages.SOAPMessageParse, parser.SamlMessage.OuterXml);
var builder = new HttpArtifactBindingBuilder(context);
var config = Saml2Config.Current;
var idp = RetrieveIDPConfiguration(parser.Issuer);
if (parser.IsArtifactResolve)
{
Logger.DebugFormat(TraceMessages.ArtifactResolveReceived, parser.SamlMessage);
if (!parser.CheckSamlMessageSignature(idp.Metadata.Keys))
{
Logger.ErrorFormat(ErrorMessages.ArtifactResolveSignatureInvalid);
throw new Saml20Exception(ErrorMessages.ArtifactResolveSignatureInvalid);
}
builder.RespondToArtifactResolve(parser.ArtifactResolve);
}
else if (parser.IsArtifactResponse)
{
Logger.DebugFormat(TraceMessages.ArtifactResponseReceived, parser.SamlMessage);
if (!parser.CheckSamlMessageSignature(idp.Metadata.Keys))
{
Logger.Error(ErrorMessages.ArtifactResponseSignatureInvalid);
throw new Saml20Exception(ErrorMessages.ArtifactResponseSignatureInvalid);
}
var status = parser.ArtifactResponse.Status;
if (status.StatusCode.Value != Saml20Constants.StatusCodes.Success)
{
Logger.ErrorFormat(ErrorMessages.ArtifactResponseStatusCodeInvalid, status.StatusCode.Value);
throw new Saml20Exception(string.Format(ErrorMessages.ArtifactResponseStatusCodeInvalid, status.StatusCode.Value));
}
if (parser.ArtifactResponse.Any.LocalName == LogoutRequest.ElementName)
{
Logger.DebugFormat(TraceMessages.LogoutRequestReceived, parser.ArtifactResponse.Any.OuterXml);
var req = Serialization.DeserializeFromXmlString<LogoutRequest>(parser.ArtifactResponse.Any.OuterXml);
// Send logoutresponse via artifact
var response = new Saml20LogoutResponse
{
Issuer = config.ServiceProvider.Id,
StatusCode = Saml20Constants.StatusCodes.Success,
InResponseTo = req.Id
};
var endpoint = RetrieveIDPConfiguration(StateService.Get<string>(IdpLoginSessionKey));
var destination = DetermineEndpointConfiguration(BindingType.Redirect, endpoint.LogoutEndpoint, endpoint.Metadata.IDPSLOEndpoints);
builder.RedirectFromLogout(destination, response);
}
else if (parser.ArtifactResponse.Any.LocalName == LogoutResponse.ElementName)
{
DoLogout(context);
}
else
{
Logger.ErrorFormat(ErrorMessages.ArtifactResponseMissingResponse);
throw new Saml20Exception(ErrorMessages.ArtifactResponseMissingResponse);
}
}
else if (parser.IsLogoutReqest)
{
Logger.DebugFormat(TraceMessages.LogoutRequestReceived, parser.SamlMessage.OuterXml);
var req = parser.LogoutRequest;
// Build the response object
var response = new Saml20LogoutResponse
{
Issuer = config.ServiceProvider.Id,
StatusCode = Saml20Constants.StatusCodes.Success,
InResponseTo = req.Id
};
// response.Destination = destination.Url;
var doc = response.GetXml();
XmlSignatureUtils.SignDocument(doc, response.Id);
if (doc.FirstChild is XmlDeclaration)
{
doc.RemoveChild(doc.FirstChild);
}
builder.SendResponseMessage(doc.OuterXml);
}
else
{
Logger.ErrorFormat(ErrorMessages.SOAPMessageUnsupportedSamlMessage);
throw new Saml20Exception(ErrorMessages.SOAPMessageUnsupportedSamlMessage);
}
}
/// <summary>
/// Handles the request.
/// </summary>
/// <param name="context">The context.</param>
private void HandleRequest(HttpContext context)
{
Logger.DebugFormat(TraceMessages.LogoutRequestReceived);
// Fetch the endpoint configuration
var idp = RetrieveIDPConfiguration(StateService.Get<string>(IdpLoginSessionKey));
var destination = DetermineEndpointConfiguration(BindingType.Redirect, idp.LogoutEndpoint, idp.Metadata.IDPSLOEndpoints);
// Fetch config object
var config = Saml2Config.Current;
// Build the response object
var response = new Saml20LogoutResponse
{
Issuer = config.ServiceProvider.Id,
Destination = destination.Url,
StatusCode = Saml20Constants.StatusCodes.Success
};
string message;
if (context.Request.RequestType == "GET")
{
// HTTP Redirect binding
var parser = new HttpRedirectBindingParser(context.Request.Url);
Logger.DebugFormat(TraceMessages.LogoutRequestRedirectBindingParse, parser.Message, parser.SignatureAlgorithm, parser.Signature);
var endpoint = config.IdentityProviders.FirstOrDefault(x => x.Id == idp.Id);
if (endpoint == null || endpoint.Metadata == null)
{
Logger.ErrorFormat(ErrorMessages.UnknownIdentityProvider, idp.Id);
throw new Saml20Exception(string.Format(ErrorMessages.UnknownIdentityProvider, idp.Id));
}
var metadata = endpoint.Metadata;
if (!parser.VerifySignature(metadata.GetKeys(KeyTypes.Signing)))
{
Logger.Error(ErrorMessages.RequestSignatureInvalid);
throw new Saml20Exception(ErrorMessages.RequestSignatureInvalid);
}
message = parser.Message;
}
else if (context.Request.RequestType == "POST")
{
// HTTP Post binding
var parser = new HttpPostBindingParser(context);
Logger.DebugFormat(TraceMessages.LogoutRequestPostBindingParse, parser.Message);
if (!parser.IsSigned)
{
Logger.Error(ErrorMessages.RequestSignatureMissing);
throw new Saml20Exception(ErrorMessages.RequestSignatureMissing);
}
var endpoint = config.IdentityProviders.FirstOrDefault(x => x.Id == idp.Id);
if (endpoint == null || endpoint.Metadata == null)
{
Logger.ErrorFormat(ErrorMessages.UnknownIdentityProvider, idp.Id);
throw new Saml20Exception(string.Format(ErrorMessages.UnknownIdentityProvider, idp.Id));
}
var metadata = endpoint.Metadata;
// Check signature
if (!parser.CheckSignature(metadata.GetKeys(KeyTypes.Signing)))
{
Logger.Error(ErrorMessages.RequestSignatureInvalid);
throw new Saml20Exception(ErrorMessages.RequestSignatureInvalid);
}
message = parser.Message;
}
else
{
// Error: We don't support HEAD, PUT, CONNECT, TRACE, DELETE and OPTIONS
Logger.ErrorFormat(ErrorMessages.UnsupportedRequestType, context.Request.RequestType);
throw new Saml20Exception(string.Format(ErrorMessages.UnsupportedRequestType, context.Request.RequestType));
}
Logger.DebugFormat(TraceMessages.LogoutRequestParsed, message);
// Log the user out locally
DoLogout(context, true);
var req = Serialization.DeserializeFromXmlString<LogoutRequest>(message);
response.InResponseTo = req.Id;
// Respond using redirect binding
if (destination.Binding == BindingType.Redirect)
{
var builder = new HttpRedirectBindingBuilder
{
RelayState = context.Request.Params["RelayState"],
Response = response.GetXml().OuterXml,
SigningKey = Saml2Config.Current.ServiceProvider.SigningCertificate.GetCertificate().PrivateKey
};
Logger.DebugFormat(TraceMessages.LogoutResponseSent, builder.Response);
context.Response.Redirect(destination.Url + "?" + builder.ToQuery(), true);
return;
}
// Respond using post binding
if (destination.Binding == BindingType.Post)
{
var builder = new HttpPostBindingBuilder(destination)
{
Action = SamlActionType.SAMLResponse
};
var responseDocument = response.GetXml();
Logger.DebugFormat(TraceMessages.LogoutResponseSent, responseDocument.OuterXml);
XmlSignatureUtils.SignDocument(responseDocument, response.Id);
builder.Response = responseDocument.OuterXml;
builder.RelayState = context.Request.Params["RelayState"];
builder.GetPage().ProcessRequest(context);
}
}
/// <summary>
/// Handles the response.
/// </summary>
/// <param name="context">The context.</param>
private void HandleResponse(HttpContext context)
{
Logger.DebugFormat(TraceMessages.LogoutResponseReceived);
var message = string.Empty;
LogoutResponse response = null;
if (context.Request.RequestType == "GET")
{
var parser = new HttpRedirectBindingParser(context.Request.Url);
response = Serialization.DeserializeFromXmlString<LogoutResponse>(parser.Message);
Logger.DebugFormat(TraceMessages.LogoutResponseRedirectBindingParse, parser.Message, parser.SignatureAlgorithm, parser.Signature);
var idp = RetrieveIDPConfiguration(response.Issuer.Value);
if (idp.Metadata == null)
{
Logger.ErrorFormat(ErrorMessages.UnknownIdentityProvider, idp.Id);
throw new Saml20Exception(string.Format(ErrorMessages.UnknownIdentityProvider, idp.Id));
}
if (!parser.VerifySignature(idp.Metadata.Keys))
{
Logger.Error(ErrorMessages.ResponseSignatureInvalid);
throw new Saml20Exception(ErrorMessages.ResponseSignatureInvalid);
}
message = parser.Message;
}
else if (context.Request.RequestType == "POST")
{
var parser = new HttpPostBindingParser(context);
Logger.DebugFormat(TraceMessages.LogoutResponsePostBindingParse, parser.Message);
response = Serialization.DeserializeFromXmlString<LogoutResponse>(parser.Message);
var idp = RetrieveIDPConfiguration(response.Issuer.Value);
if (idp.Metadata == null)
{
Logger.ErrorFormat(ErrorMessages.UnknownIdentityProvider, idp.Id);
throw new Saml20Exception(string.Format(ErrorMessages.UnknownIdentityProvider, idp.Id));
}
if (!parser.IsSigned)
{
Logger.Error(ErrorMessages.ResponseSignatureMissing);
throw new Saml20Exception(ErrorMessages.ResponseSignatureMissing);
}
// signature on final message in logout
if (!parser.CheckSignature(idp.Metadata.Keys))
{
Logger.Error(ErrorMessages.ResponseSignatureInvalid);
throw new Saml20Exception(ErrorMessages.ResponseSignatureInvalid);
}
message = parser.Message;
}
if (response == null)
{
Logger.ErrorFormat(ErrorMessages.UnsupportedRequestType, context.Request.RequestType);
throw new Saml20Exception(string.Format(ErrorMessages.UnsupportedRequestType, context.Request.RequestType));
}
Logger.DebugFormat(TraceMessages.LogoutResponseParsed, message);
if (response.Status.StatusCode.Value != Saml20Constants.StatusCodes.Success)
{
Logger.ErrorFormat(ErrorMessages.ResponseStatusNotSuccessful, response.Status.StatusCode.Value);
throw new Saml20Exception(string.Format(ErrorMessages.ResponseStatusNotSuccessful, response.Status.StatusCode.Value));
}
// Log the user out locally
DoLogout(context);
}
/// <summary>
/// Transfers the client.
/// </summary>
/// <param name="idp">The identity provider.</param>
/// <param name="context">The context.</param>
private void TransferClient(IdentityProvider idp, HttpContext context)
{
var request = Saml20LogoutRequest.GetDefault();
// Determine which endpoint to use from the configuration file or the endpoint metadata.
var destination = DetermineEndpointConfiguration(BindingType.Redirect, idp.LogoutEndpoint, idp.Metadata.IDPSLOEndpoints);
request.Destination = destination.Url;
var nameIdFormat = StateService.Get<string>(IdpNameIdFormat);
request.SubjectToLogOut.Format = nameIdFormat;
// Handle POST binding
if (destination.Binding == BindingType.Post)
{
var builder = new HttpPostBindingBuilder(destination);
request.Destination = destination.Url;
request.Reason = Saml20Constants.Reasons.User;
request.SubjectToLogOut.Value = StateService.Get<string>(IdpNameId);
request.SessionIndex = StateService.Get<string>(IdpSessionIdKey);
var requestDocument = request.GetXml();
XmlSignatureUtils.SignDocument(requestDocument, request.Id);
builder.Request = requestDocument.OuterXml;
Logger.DebugFormat(TraceMessages.LogoutRequestSent, idp.Id, "POST", builder.Request);
builder.GetPage().ProcessRequest(context);
context.Response.End();
return;
}
// Handle Redirect binding
if (destination.Binding == BindingType.Redirect)
{
request.Destination = destination.Url;
request.Reason = Saml20Constants.Reasons.User;
request.SubjectToLogOut.Value = StateService.Get<string>(IdpNameId);
request.SessionIndex = StateService.Get<string>(IdpSessionIdKey);
var builder = new HttpRedirectBindingBuilder
{
Request = request.GetXml().OuterXml,
SigningKey = Saml2Config.Current.ServiceProvider.SigningCertificate.GetCertificate().PrivateKey
};
var redirectUrl = destination.Url + "?" + builder.ToQuery();
Logger.DebugFormat(TraceMessages.LogoutRequestSent, idp.Id, "REDIRECT", redirectUrl);
context.Response.Redirect(redirectUrl, true);
return;
}
// Handle Artifact binding
if (destination.Binding == BindingType.Artifact)
{
request.Destination = destination.Url;
request.Reason = Saml20Constants.Reasons.User;
request.SubjectToLogOut.Value = StateService.Get<string>(IdpNameId);
request.SessionIndex = StateService.Get<string>(IdpSessionIdKey);
Logger.DebugFormat(TraceMessages.LogoutRequestSent, idp.Id, "ARTIFACT", request.GetXml().OuterXml);
var builder = new HttpArtifactBindingBuilder(context);
builder.RedirectFromLogout(destination, request, Guid.NewGuid().ToString("N"));
}
Logger.Error(ErrorMessages.EndpointBindingInvalid);
throw new Saml20Exception(ErrorMessages.EndpointBindingInvalid);
}
#endregion
}
}