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 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
|
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Security
{
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IdentityModel.Policy;
using System.IdentityModel.Tokens;
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Security.Tokens;
using System.Xml;
abstract class NegotiationTokenAuthenticator<T> : CommunicationObjectSecurityTokenAuthenticator, IIssuanceSecurityTokenAuthenticator, ISecurityContextSecurityTokenCacheProvider
where T : NegotiationTokenAuthenticatorState
{
internal const string defaultServerMaxNegotiationLifetimeString = "00:01:00";
internal const string defaultServerIssuedTokenLifetimeString = "10:00:00";
internal const string defaultServerIssuedTransitionTokenLifetimeString = "00:15:00";
internal const int defaultServerMaxActiveNegotiations = 128;
internal static readonly TimeSpan defaultServerMaxNegotiationLifetime = TimeSpan.Parse(defaultServerMaxNegotiationLifetimeString, CultureInfo.InvariantCulture);
internal static readonly TimeSpan defaultServerIssuedTokenLifetime = TimeSpan.Parse(defaultServerIssuedTokenLifetimeString, CultureInfo.InvariantCulture);
internal static readonly TimeSpan defaultServerIssuedTransitionTokenLifetime = TimeSpan.Parse(defaultServerIssuedTransitionTokenLifetimeString, CultureInfo.InvariantCulture);
internal const int defaultServerMaxCachedTokens = 1000;
internal const bool defaultServerMaintainState = true;
internal static readonly SecurityStandardsManager defaultStandardsManager = SecurityStandardsManager.DefaultInstance;
internal static readonly SecurityStateEncoder defaultSecurityStateEncoder = new DataProtectionSecurityStateEncoder();
NegotiationTokenAuthenticatorStateCache<T> stateCache;
RenewedSecurityTokenHandler renewedSecurityTokenHandler;
NegotiationHost negotiationHost;
bool encryptStateInServiceToken;
TimeSpan serviceTokenLifetime;
int maximumCachedNegotiationState;
TimeSpan negotiationTimeout;
bool isClientAnonymous;
SecurityStandardsManager standardsManager;
SecurityAlgorithmSuite securityAlgorithmSuite;
SecurityTokenParameters issuedSecurityTokenParameters;
ISecurityContextSecurityTokenCache issuedTokenCache;
BindingContext issuerBindingContext;
Uri listenUri;
string sctUri;
AuditLogLocation auditLogLocation;
bool suppressAuditFailure;
AuditLevel messageAuthenticationAuditLevel;
SecurityStateEncoder securityStateEncoder;
SecurityContextCookieSerializer cookieSerializer;
IMessageFilterTable<EndpointAddress> endpointFilterTable;
IssuedSecurityTokenHandler issuedSecurityTokenHandler;
int maxMessageSize;
IList<Type> knownTypes;
int maximumConcurrentNegotiations;
List<IChannel> activeNegotiationChannels1;
List<IChannel> activeNegotiationChannels2;
IOThreadTimer idlingNegotiationSessionTimer;
bool isTimerCancelled;
protected NegotiationTokenAuthenticator() : base()
{
InitializeDefaults();
}
public IssuedSecurityTokenHandler IssuedSecurityTokenHandler
{
get
{
return this.issuedSecurityTokenHandler;
}
set
{
this.issuedSecurityTokenHandler = value;
}
}
public RenewedSecurityTokenHandler RenewedSecurityTokenHandler
{
get
{
return this.renewedSecurityTokenHandler;
}
set
{
this.renewedSecurityTokenHandler = value;
}
}
// settings
public bool EncryptStateInServiceToken
{
get
{
return this.encryptStateInServiceToken;
}
set
{
this.CommunicationObject.ThrowIfDisposedOrImmutable();
this.encryptStateInServiceToken = value;
}
}
public TimeSpan ServiceTokenLifetime
{
get
{
return this.serviceTokenLifetime;
}
set
{
this.CommunicationObject.ThrowIfDisposedOrImmutable();
if (value <= TimeSpan.Zero)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", SR.GetString(SR.TimeSpanMustbeGreaterThanTimeSpanZero)));
}
if (TimeoutHelper.IsTooLarge(value))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.SFxTimeoutOutOfRangeTooBig)));
}
this.serviceTokenLifetime = value;
}
}
public int MaximumCachedNegotiationState
{
get
{
return this.maximumCachedNegotiationState;
}
set
{
this.CommunicationObject.ThrowIfDisposedOrImmutable();
if (value < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", SR.GetString(SR.ValueMustBeNonNegative)));
}
this.maximumCachedNegotiationState = value;
}
}
public int MaximumConcurrentNegotiations
{
get
{
return this.maximumConcurrentNegotiations;
}
set
{
this.CommunicationObject.ThrowIfDisposedOrImmutable();
if (value < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", SR.GetString(SR.ValueMustBeNonNegative)));
}
this.maximumConcurrentNegotiations = value;
}
}
public TimeSpan NegotiationTimeout
{
get
{
return this.negotiationTimeout;
}
set
{
this.CommunicationObject.ThrowIfDisposedOrImmutable();
if (value <= TimeSpan.Zero)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", SR.GetString(SR.TimeSpanMustbeGreaterThanTimeSpanZero)));
}
if (TimeoutHelper.IsTooLarge(value))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.SFxTimeoutOutOfRangeTooBig)));
}
this.negotiationTimeout = value;
}
}
public bool IsClientAnonymous
{
get
{
return this.isClientAnonymous;
}
set
{
this.CommunicationObject.ThrowIfDisposedOrImmutable();
this.isClientAnonymous = value;
}
}
public SecurityAlgorithmSuite SecurityAlgorithmSuite
{
get
{
return this.securityAlgorithmSuite;
}
set
{
this.CommunicationObject.ThrowIfDisposedOrImmutable();
this.securityAlgorithmSuite = value;
}
}
public IMessageFilterTable<EndpointAddress> EndpointFilterTable
{
get
{
return this.endpointFilterTable;
}
set
{
this.CommunicationObject.ThrowIfDisposedOrImmutable();
this.endpointFilterTable = value;
}
}
ISecurityContextSecurityTokenCache ISecurityContextSecurityTokenCacheProvider.TokenCache
{
get
{
return this.IssuedTokenCache;
}
}
public virtual XmlDictionaryString RequestSecurityTokenAction
{
get
{
return this.StandardsManager.TrustDriver.RequestSecurityTokenAction;
}
}
public virtual XmlDictionaryString RequestSecurityTokenResponseAction
{
get
{
return this.StandardsManager.TrustDriver.RequestSecurityTokenResponseAction;
}
}
public virtual XmlDictionaryString RequestSecurityTokenResponseFinalAction
{
get
{
return this.StandardsManager.TrustDriver.RequestSecurityTokenResponseFinalAction;
}
}
public SecurityStandardsManager StandardsManager
{
get
{
return this.standardsManager;
}
set
{
this.CommunicationObject.ThrowIfDisposedOrImmutable();
this.standardsManager = (value != null ? value : SecurityStandardsManager.DefaultInstance);
}
}
public SecurityTokenParameters IssuedSecurityTokenParameters
{
get
{
return this.issuedSecurityTokenParameters;
}
set
{
this.CommunicationObject.ThrowIfDisposedOrImmutable();
this.issuedSecurityTokenParameters = value;
}
}
public ISecurityContextSecurityTokenCache IssuedTokenCache
{
get { return this.issuedTokenCache; }
set
{
this.CommunicationObject.ThrowIfDisposedOrImmutable();
this.issuedTokenCache = value;
}
}
public AuditLogLocation AuditLogLocation
{
get
{
return this.auditLogLocation;
}
set
{
this.CommunicationObject.ThrowIfDisposedOrImmutable();
this.auditLogLocation = value;
}
}
public bool SuppressAuditFailure
{
get
{
return this.suppressAuditFailure;
}
set
{
this.CommunicationObject.ThrowIfDisposedOrImmutable();
this.suppressAuditFailure = value;
}
}
public AuditLevel MessageAuthenticationAuditLevel
{
get
{
return this.messageAuthenticationAuditLevel;
}
set
{
this.CommunicationObject.ThrowIfDisposedOrImmutable();
this.messageAuthenticationAuditLevel = value;
}
}
public BindingContext IssuerBindingContext
{
get { return this.issuerBindingContext; }
set
{
this.CommunicationObject.ThrowIfDisposedOrImmutable();
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
}
this.issuerBindingContext = value.Clone();
}
}
public Uri ListenUri
{
get { return this.listenUri; }
set
{
this.CommunicationObject.ThrowIfDisposedOrImmutable();
this.listenUri = value;
}
}
public SecurityStateEncoder SecurityStateEncoder
{
get { return this.securityStateEncoder; }
set
{
this.CommunicationObject.ThrowIfDisposedOrImmutable();
this.securityStateEncoder = value;
}
}
public IList<Type> KnownTypes
{
get { return this.knownTypes; }
set
{
this.CommunicationObject.ThrowIfDisposedOrImmutable();
if (value != null)
{
this.knownTypes = new Collection<Type>(value);
}
else
{
this.knownTypes = null;
}
}
}
public int MaxMessageSize
{
get { return this.maxMessageSize; }
set
{
this.CommunicationObject.ThrowIfDisposedOrImmutable();
this.maxMessageSize = value;
}
}
protected string SecurityContextTokenUri
{
get
{
this.CommunicationObject.ThrowIfNotOpened();
return this.sctUri;
}
}
Object ThisLock
{
get
{
return this.CommunicationObject;
}
}
// helpers
protected SecurityContextSecurityToken IssueSecurityContextToken(UniqueId contextId, string id, byte[] key,
DateTime tokenEffectiveTime, DateTime tokenExpirationTime,
ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies, bool isCookieMode)
{
return IssueSecurityContextToken(contextId, id, key, tokenEffectiveTime, tokenExpirationTime, null,
tokenEffectiveTime, tokenExpirationTime, authorizationPolicies, isCookieMode);
}
protected SecurityContextSecurityToken IssueSecurityContextToken(UniqueId contextId, string id, byte[] key,
DateTime tokenEffectiveTime, DateTime tokenExpirationTime, UniqueId keyGeneration, DateTime keyEffectiveTime,
DateTime keyExpirationTime, ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies, bool isCookieMode)
{
this.CommunicationObject.ThrowIfClosedOrNotOpen();
if (this.securityStateEncoder == null && isCookieMode)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SctCookieNotSupported)));
}
byte[] cookieBlob = (isCookieMode) ? this.cookieSerializer.CreateCookieFromSecurityContext(contextId, id, key, tokenEffectiveTime, tokenExpirationTime, keyGeneration,
keyEffectiveTime, keyExpirationTime, authorizationPolicies) : null;
SecurityContextSecurityToken issuedToken = new SecurityContextSecurityToken(contextId, id, key, tokenEffectiveTime, tokenExpirationTime,
authorizationPolicies, isCookieMode, cookieBlob, keyGeneration, keyEffectiveTime, keyExpirationTime);
return issuedToken;
}
void InitializeDefaults()
{
this.encryptStateInServiceToken = !defaultServerMaintainState;
this.serviceTokenLifetime = defaultServerIssuedTokenLifetime;
this.maximumCachedNegotiationState = defaultServerMaxActiveNegotiations;
this.negotiationTimeout = defaultServerMaxNegotiationLifetime;
this.isClientAnonymous = false;
this.standardsManager = defaultStandardsManager;
this.securityStateEncoder = defaultSecurityStateEncoder;
this.maximumConcurrentNegotiations = defaultServerMaxActiveNegotiations;
// we rely on the transport encoders to enforce the message size except in the
// mixed mode nego case, where the client is unauthenticated and the maxMessageSize is too
// large to be a mitigation
this.maxMessageSize = Int32.MaxValue;
}
public override void OnClose(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
if (this.negotiationHost != null)
{
this.negotiationHost.Close(timeoutHelper.RemainingTime());
this.negotiationHost = null;
}
lock (ThisLock)
{
if (this.idlingNegotiationSessionTimer != null && !this.isTimerCancelled)
{
this.isTimerCancelled = true;
this.idlingNegotiationSessionTimer.Cancel();
}
}
base.OnClose(timeoutHelper.RemainingTime());
}
public override void OnAbort()
{
if (this.negotiationHost != null)
{
this.negotiationHost.Abort();
this.negotiationHost = null;
}
lock (ThisLock)
{
if (this.idlingNegotiationSessionTimer != null && !this.isTimerCancelled)
{
this.isTimerCancelled = true;
this.idlingNegotiationSessionTimer.Cancel();
}
}
base.OnAbort();
}
public override void OnOpen(TimeSpan timeout)
{
if (this.IssuerBindingContext == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.IssuerBuildContextNotSet, this.GetType())));
}
if (this.IssuedSecurityTokenParameters == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.IssuedSecurityTokenParametersNotSet, this.GetType())));
}
if (this.SecurityAlgorithmSuite == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SecurityAlgorithmSuiteNotSet, this.GetType())));
}
if (this.IssuedTokenCache == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.IssuedTokenCacheNotSet, this.GetType())));
}
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
this.SetupServiceHost();
negotiationHost.Open(timeoutHelper.RemainingTime());
this.stateCache = new NegotiationTokenAuthenticatorStateCache<T>(this.NegotiationTimeout, this.MaximumCachedNegotiationState);
this.sctUri = this.StandardsManager.SecureConversationDriver.TokenTypeUri;
if (this.SecurityStateEncoder != null)
{
this.cookieSerializer = new SecurityContextCookieSerializer(this.SecurityStateEncoder, this.KnownTypes);
}
if (this.negotiationTimeout < TimeSpan.MaxValue)
{
lock (ThisLock)
{
this.activeNegotiationChannels1 = new List<IChannel>();
this.activeNegotiationChannels2 = new List<IChannel>();
this.idlingNegotiationSessionTimer = new IOThreadTimer(new Action<object>(this.OnIdlingNegotiationSessionTimer), this, false);
this.isTimerCancelled = false;
this.idlingNegotiationSessionTimer.Set(this.negotiationTimeout);
}
}
base.OnOpen(timeoutHelper.RemainingTime());
}
protected override bool CanValidateTokenCore(SecurityToken token)
{
return (token is SecurityContextSecurityToken);
}
protected override ReadOnlyCollection<IAuthorizationPolicy> ValidateTokenCore(SecurityToken token)
{
SecurityContextSecurityToken sct = (SecurityContextSecurityToken)token;
return sct.AuthorizationPolicies;
}
protected abstract Binding GetNegotiationBinding(Binding binding);
protected abstract bool IsMultiLegNegotiation { get; }
protected abstract MessageFilter GetListenerFilter();
void SetupServiceHost()
{
ChannelBuilder channelBuilder = new ChannelBuilder(this.IssuerBindingContext.Clone(), true);
channelBuilder.Binding.Elements.Insert(0, new ReplyAdapterBindingElement());
channelBuilder.Binding = new CustomBinding(this.GetNegotiationBinding(channelBuilder.Binding));
negotiationHost = new NegotiationHost(this, this.ListenUri, channelBuilder, this.GetListenerFilter());
}
// message processing abstract method
protected abstract BodyWriter ProcessRequestSecurityToken(Message request, RequestSecurityToken requestSecurityToken, out T negotiationState);
protected abstract BodyWriter ProcessRequestSecurityTokenResponse(T negotiationState, Message request, RequestSecurityTokenResponse requestSecurityTokenResponse);
// message handlers
protected virtual void ParseMessageBody(Message message, out string context, out RequestSecurityToken requestSecurityToken, out RequestSecurityTokenResponse requestSecurityTokenResponse)
{
requestSecurityToken = null;
requestSecurityTokenResponse = null;
if (message.Headers.Action == this.RequestSecurityTokenAction.Value)
{
XmlDictionaryReader reader = message.GetReaderAtBodyContents();
using (reader)
{
requestSecurityToken = RequestSecurityToken.CreateFrom(this.StandardsManager, reader);
message.ReadFromBodyContentsToEnd(reader);
}
context = requestSecurityToken.Context;
}
else if (message.Headers.Action == this.RequestSecurityTokenResponseAction.Value)
{
XmlDictionaryReader reader = message.GetReaderAtBodyContents();
using (reader)
{
requestSecurityTokenResponse = RequestSecurityTokenResponse.CreateFrom(this.StandardsManager, reader);
message.ReadFromBodyContentsToEnd(reader);
}
context = requestSecurityTokenResponse.Context;
}
else
{
throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(SR.GetString(SR.InvalidActionForNegotiationMessage, message.Headers.Action)), message);
}
}
static Message CreateReply(Message request, XmlDictionaryString action, BodyWriter body)
{
if (request.Headers.MessageId != null)
{
Message reply = Message.CreateMessage(request.Version, ActionHeader.Create(action, request.Version.Addressing), body);
reply.InitializeReply(request);
return reply;
}
else
{
// the message id may not be present if MapToHttp is true
return Message.CreateMessage(request.Version, ActionHeader.Create(action, request.Version.Addressing), body);
}
}
void OnTokenIssued(SecurityToken token)
{
if (this.issuedSecurityTokenHandler != null)
{
this.issuedSecurityTokenHandler(token, null);
}
}
void AddNegotiationChannelForIdleTracking()
{
if (OperationContext.Current.SessionId == null)
{
return;
}
lock (ThisLock)
{
if (this.idlingNegotiationSessionTimer == null)
{
return;
}
IChannel channel = OperationContext.Current.Channel;
if (!this.activeNegotiationChannels1.Contains(channel) && !this.activeNegotiationChannels2.Contains(channel))
{
this.activeNegotiationChannels1.Add(channel);
}
if (this.isTimerCancelled)
{
this.isTimerCancelled = false;
this.idlingNegotiationSessionTimer.Set(this.negotiationTimeout);
}
}
}
void RemoveNegotiationChannelFromIdleTracking()
{
if (OperationContext.Current.SessionId == null)
{
return;
}
lock (ThisLock)
{
if (this.idlingNegotiationSessionTimer == null)
{
return;
}
IChannel channel = OperationContext.Current.Channel;
this.activeNegotiationChannels1.Remove(channel);
this.activeNegotiationChannels2.Remove(channel);
if (this.activeNegotiationChannels1.Count == 0 && this.activeNegotiationChannels2.Count == 0)
{
this.isTimerCancelled = true;
this.idlingNegotiationSessionTimer.Cancel();
}
}
}
void OnIdlingNegotiationSessionTimer(object state)
{
lock (ThisLock)
{
if (this.isTimerCancelled || (this.CommunicationObject.State != CommunicationState.Opened && this.CommunicationObject.State != CommunicationState.Opening))
{
return;
}
try
{
for (int i = 0; i < this.activeNegotiationChannels2.Count; ++i)
{
this.activeNegotiationChannels2[i].Abort();
}
List<IChannel> temp = this.activeNegotiationChannels2;
temp.Clear();
this.activeNegotiationChannels2 = this.activeNegotiationChannels1;
this.activeNegotiationChannels1 = temp;
}
#pragma warning suppress 56500
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
}
finally
{
if (this.CommunicationObject.State == CommunicationState.Opened || this.CommunicationObject.State == CommunicationState.Opening)
{
if (this.activeNegotiationChannels1.Count == 0 && this.activeNegotiationChannels2.Count == 0)
{
this.isTimerCancelled = true;
this.idlingNegotiationSessionTimer.Cancel();
}
else
{
this.idlingNegotiationSessionTimer.Set(this.negotiationTimeout);
}
}
}
}
}
Message ProcessRequestCore(Message request)
{
if (request == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("request");
}
Uri to = null;
RequestSecurityToken rst = null;
RequestSecurityTokenResponse rstr = null;
string context = null;
bool disposeRequest = false;
bool isNegotiationFailure = true;
T negotiationState = null;
try
{
// validate the message size if needed
if (this.maxMessageSize < int.MaxValue)
{
string action = request.Headers.Action;
try
{
using (MessageBuffer buffer = request.CreateBufferedCopy(this.maxMessageSize))
{
request = buffer.CreateMessage();
disposeRequest = true;
}
}
catch (QuotaExceededException e)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(SR.GetString(SR.SecurityNegotiationMessageTooLarge, action, this.maxMessageSize), e));
}
}
try
{
to = request.Headers.To;
ParseMessageBody(request, out context, out rst, out rstr);
// check if there is existing state
if (context != null)
{
negotiationState = this.stateCache.GetState(context);
}
else
{
negotiationState = null;
}
bool disposeState = false;
BodyWriter replyBody;
try
{
if (rst != null)
{
if (negotiationState != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new SecurityNegotiationException(SR.GetString(SR.NegotiationStateAlreadyPresent, context)));
}
replyBody = this.ProcessRequestSecurityToken(request, rst, out negotiationState);
lock (negotiationState.ThisLock)
{
if (negotiationState.IsNegotiationCompleted)
{
// if session-sct add it to cache and add a redirect header
if (!negotiationState.ServiceToken.IsCookieMode)
{
this.IssuedTokenCache.AddContext(negotiationState.ServiceToken);
}
this.OnTokenIssued(negotiationState.ServiceToken);
SecurityTraceRecordHelper.TraceServiceSecurityNegotiationCompleted(request, this, negotiationState.ServiceToken);
disposeState = true;
}
else
{
this.stateCache.AddState(context, negotiationState);
disposeState = false;
}
AddNegotiationChannelForIdleTracking();
}
}
else
{
if (negotiationState == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new SecurityNegotiationException(SR.GetString(SR.CannotFindNegotiationState, context)));
}
lock (negotiationState.ThisLock)
{
replyBody = this.ProcessRequestSecurityTokenResponse(negotiationState, request, rstr);
if (negotiationState.IsNegotiationCompleted)
{
// if session-sct add it to cache and add a redirect header
if (!negotiationState.ServiceToken.IsCookieMode)
{
this.IssuedTokenCache.AddContext(negotiationState.ServiceToken);
}
this.OnTokenIssued(negotiationState.ServiceToken);
SecurityTraceRecordHelper.TraceServiceSecurityNegotiationCompleted(request, this, negotiationState.ServiceToken);
disposeState = true;
}
else
{
disposeState = false;
}
}
}
if (negotiationState.IsNegotiationCompleted && null != this.ListenUri)
{
if (AuditLevel.Success == (this.messageAuthenticationAuditLevel & AuditLevel.Success))
{
string primaryIdentity = negotiationState.GetRemoteIdentityName();
SecurityAuditHelper.WriteSecurityNegotiationSuccessEvent(this.auditLogLocation,
this.suppressAuditFailure, request, request.Headers.To, request.Headers.Action,
primaryIdentity, this.GetType().Name);
}
}
isNegotiationFailure = false;
}
catch (Exception exception)
{
if (Fx.IsFatal(exception))
throw;
if (PerformanceCounters.PerformanceCountersEnabled && null != this.ListenUri)
{
PerformanceCounters.AuthenticationFailed(request, this.ListenUri);
}
if (AuditLevel.Failure == (this.messageAuthenticationAuditLevel & AuditLevel.Failure))
{
try
{
string primaryIdentity = (negotiationState != null) ? negotiationState.GetRemoteIdentityName() : String.Empty;
SecurityAuditHelper.WriteSecurityNegotiationFailureEvent(this.auditLogLocation,
this.suppressAuditFailure, request, request.Headers.To, request.Headers.Action,
primaryIdentity, this.GetType().Name, exception);
}
#pragma warning suppress 56500
catch (Exception auditException)
{
if (Fx.IsFatal(auditException))
throw;
DiagnosticUtility.TraceHandledException(auditException, TraceEventType.Error);
}
}
disposeState = true;
throw;
}
finally
{
if (disposeState)
{
if (negotiationState != null)
{
if (context != null)
{
stateCache.RemoveState(context);
}
negotiationState.Dispose();
}
}
}
return CreateReply(request, (replyBody is RequestSecurityTokenResponseCollection) ? RequestSecurityTokenResponseFinalAction : RequestSecurityTokenResponseAction, replyBody);
}
finally
{
if (disposeRequest)
{
request.Close();
}
}
}
finally
{
if (isNegotiationFailure)
{
AddNegotiationChannelForIdleTracking();
}
else if (negotiationState != null && negotiationState.IsNegotiationCompleted)
{
RemoveNegotiationChannelFromIdleTracking();
}
}
}
// negotiation failure methods
Message HandleNegotiationException(Message request, Exception e)
{
SecurityTraceRecordHelper.TraceServiceSecurityNegotiationFailure<T>(
EventTraceActivityHelper.TryExtractActivity(request),
this,
e);
return CreateFault(request, e);
}
Message CreateFault(Message request, Exception e)
{
MessageVersion version = request.Version;
FaultCode subCode;
FaultReason reason;
bool isSenderFault;
if (e is SecurityTokenValidationException || e is System.ComponentModel.Win32Exception)
{
subCode = new FaultCode(TrustApr2004Strings.FailedAuthenticationFaultCode, TrustFeb2005Strings.Namespace);
reason = new FaultReason(SR.GetString(SR.FailedAuthenticationTrustFaultCode), CultureInfo.CurrentCulture);
isSenderFault = true;
}
else if (e is QuotaExceededException)
{
// send a receiver fault so that the sender can retry
subCode = new FaultCode(DotNetSecurityStrings.SecurityServerTooBusyFault, DotNetSecurityStrings.Namespace);
reason = new FaultReason(SR.GetString(SR.NegotiationQuotasExceededFaultReason), CultureInfo.CurrentCulture);
isSenderFault = false;
}
else
{
subCode = new FaultCode(TrustApr2004Strings.InvalidRequestFaultCode, TrustFeb2005Strings.Namespace);
reason = new FaultReason(SR.GetString(SR.InvalidRequestTrustFaultCode), CultureInfo.CurrentCulture);
isSenderFault = true;
}
FaultCode faultCode;
if (isSenderFault)
{
faultCode = FaultCode.CreateSenderFaultCode(subCode);
}
else
{
faultCode = FaultCode.CreateReceiverFaultCode(subCode);
}
MessageFault fault = MessageFault.CreateFault(faultCode, reason);
Message faultReply = Message.CreateMessage(version, fault, version.Addressing.DefaultFaultAction);
faultReply.Headers.RelatesTo = request.Headers.MessageId;
return faultReply;
}
class NegotiationHost : ServiceHostBase
{
NegotiationTokenAuthenticator<T> authenticator;
Uri listenUri;
ChannelBuilder channelBuilder;
MessageFilter listenerFilter;
public NegotiationHost(NegotiationTokenAuthenticator<T> authenticator, Uri listenUri, ChannelBuilder channelBuilder, MessageFilter listenerFilter)
{
this.authenticator = authenticator;
this.listenUri = listenUri;
this.channelBuilder = channelBuilder;
this.listenerFilter = listenerFilter;
}
protected override ServiceDescription CreateDescription(out IDictionary<string, ContractDescription> implementedContracts)
{
implementedContracts = null;
return null;
}
protected override void InitializeRuntime()
{
MessageFilter contractFilter = this.listenerFilter;
int filterPriority = 10;
Type[] endpointChannelTypes = new Type[] { typeof(IReplyChannel),
typeof(IDuplexChannel),
typeof(IReplySessionChannel),
typeof(IDuplexSessionChannel) };
IChannelListener listener = null;
BindingParameterCollection parameters = new BindingParameterCollection(this.channelBuilder.BindingParameters);
Binding binding = this.channelBuilder.Binding;
binding.ReceiveTimeout = this.authenticator.NegotiationTimeout;
parameters.Add(new ChannelDemuxerFilter(contractFilter, filterPriority));
DispatcherBuilder.MaybeCreateListener(true, endpointChannelTypes, binding, parameters,
this.listenUri, "", ListenUriMode.Explicit, this.ServiceThrottle, out listener);
if (listener == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.CannotCreateTwoWayListenerForNegotiation)));
}
ChannelDispatcher channelDispatcher = new ChannelDispatcher(listener, null, binding);
channelDispatcher.MessageVersion = binding.MessageVersion;
channelDispatcher.ManualAddressing = true;
channelDispatcher.ServiceThrottle = new ServiceThrottle(this);
channelDispatcher.ServiceThrottle.MaxConcurrentCalls = this.authenticator.MaximumConcurrentNegotiations;
channelDispatcher.ServiceThrottle.MaxConcurrentSessions = this.authenticator.MaximumConcurrentNegotiations;
EndpointDispatcher endpointDispatcher = new EndpointDispatcher(new EndpointAddress(this.listenUri), "SecurityNegotiationContract", NamingHelper.DefaultNamespace, true);
endpointDispatcher.DispatchRuntime.SingletonInstanceContext = new InstanceContext(null, this.authenticator, false);
endpointDispatcher.DispatchRuntime.ConcurrencyMode = ConcurrencyMode.Multiple;
endpointDispatcher.AddressFilter = new MatchAllMessageFilter();
endpointDispatcher.ContractFilter = contractFilter;
endpointDispatcher.FilterPriority = filterPriority;
endpointDispatcher.DispatchRuntime.PrincipalPermissionMode = PrincipalPermissionMode.None;
endpointDispatcher.DispatchRuntime.InstanceContextProvider = new SingletonInstanceContextProvider(endpointDispatcher.DispatchRuntime);
endpointDispatcher.DispatchRuntime.SynchronizationContext = null;
DispatchOperation operation = new DispatchOperation(endpointDispatcher.DispatchRuntime, "*", MessageHeaders.WildcardAction, MessageHeaders.WildcardAction);
operation.Formatter = new MessageOperationFormatter();
operation.Invoker = new NegotiationSyncInvoker(this.authenticator);
endpointDispatcher.DispatchRuntime.UnhandledDispatchOperation = operation;
channelDispatcher.Endpoints.Add(endpointDispatcher);
this.ChannelDispatchers.Add(channelDispatcher);
}
class NegotiationSyncInvoker : IOperationInvoker
{
NegotiationTokenAuthenticator<T> parent;
internal NegotiationSyncInvoker(NegotiationTokenAuthenticator<T> parent)
{
this.parent = parent;
}
public bool IsSynchronous { get { return true; } }
public object[] AllocateInputs()
{
return EmptyArray<object>.Allocate(1);
}
public object Invoke(object instance, object[] inputs, out object[] outputs)
{
Message request = (Message)inputs[0];
outputs = EmptyArray<object>.Allocate(0);
try
{
return parent.ProcessRequestCore(request);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
return parent.HandleNegotiationException(request, e);
}
}
public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
}
}
}
}
|