SecurityChannelFactory.cs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917
  1. //----------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //------------------------------------------------------------
  4. namespace System.ServiceModel.Channels
  5. {
  6. using System.Collections.Generic;
  7. using System.Diagnostics;
  8. using System.Runtime;
  9. using System.Runtime.InteropServices;
  10. //using System.Runtime.Remoting.Messaging;
  11. using System.Security.Authentication.ExtendedProtection;
  12. using System.ServiceModel;
  13. using System.ServiceModel.Diagnostics.Application;
  14. using System.ServiceModel.Dispatcher;
  15. using System.ServiceModel.Security;
  16. using ServiceModelActivity = System.ServiceModel.Diagnostics.ServiceModelActivity;
  17. using TraceUtility = System.ServiceModel.Diagnostics.TraceUtility;
  18. sealed class SecurityChannelFactory<TChannel>
  19. : LayeredChannelFactory<TChannel>
  20. {
  21. ChannelBuilder channelBuilder;
  22. SecurityProtocolFactory securityProtocolFactory;
  23. SecuritySessionClientSettings<TChannel> sessionClientSettings;
  24. bool sessionMode;
  25. MessageVersion messageVersion;
  26. ISecurityCapabilities securityCapabilities;
  27. public SecurityChannelFactory(ISecurityCapabilities securityCapabilities, BindingContext context,
  28. SecuritySessionClientSettings<TChannel> sessionClientSettings)
  29. : this(securityCapabilities, context, sessionClientSettings.ChannelBuilder, sessionClientSettings.CreateInnerChannelFactory())
  30. {
  31. this.sessionMode = true;
  32. this.sessionClientSettings = sessionClientSettings;
  33. }
  34. public SecurityChannelFactory(ISecurityCapabilities securityCapabilities, BindingContext context, ChannelBuilder channelBuilder, SecurityProtocolFactory protocolFactory)
  35. : this(securityCapabilities, context, channelBuilder, protocolFactory, channelBuilder.BuildChannelFactory<TChannel>())
  36. {
  37. }
  38. public SecurityChannelFactory(ISecurityCapabilities securityCapabilities, BindingContext context, ChannelBuilder channelBuilder, SecurityProtocolFactory protocolFactory, IChannelFactory innerChannelFactory)
  39. : this(securityCapabilities, context, channelBuilder, innerChannelFactory)
  40. {
  41. this.securityProtocolFactory = protocolFactory;
  42. }
  43. SecurityChannelFactory(ISecurityCapabilities securityCapabilities, BindingContext context, ChannelBuilder channelBuilder, IChannelFactory innerChannelFactory)
  44. : base(context.Binding, innerChannelFactory)
  45. {
  46. this.channelBuilder = channelBuilder;
  47. this.messageVersion = context.Binding.MessageVersion;
  48. this.securityCapabilities = securityCapabilities;
  49. }
  50. // used by internal test code
  51. internal SecurityChannelFactory(Binding binding, SecurityProtocolFactory protocolFactory, IChannelFactory innerChannelFactory)
  52. : base(binding, innerChannelFactory)
  53. {
  54. this.securityProtocolFactory = protocolFactory;
  55. }
  56. public ChannelBuilder ChannelBuilder
  57. {
  58. get
  59. {
  60. return this.channelBuilder;
  61. }
  62. }
  63. public SecurityProtocolFactory SecurityProtocolFactory
  64. {
  65. get
  66. {
  67. return this.securityProtocolFactory;
  68. }
  69. }
  70. public SecuritySessionClientSettings<TChannel> SessionClientSettings
  71. {
  72. get
  73. {
  74. Fx.Assert(SessionMode == true, "SessionClientSettings can only be used if SessionMode == true");
  75. return this.sessionClientSettings;
  76. }
  77. }
  78. public bool SessionMode
  79. {
  80. get
  81. {
  82. return this.sessionMode;
  83. }
  84. }
  85. bool SupportsDuplex
  86. {
  87. get
  88. {
  89. ThrowIfProtocolFactoryNotSet();
  90. return this.securityProtocolFactory.SupportsDuplex;
  91. }
  92. }
  93. bool SupportsRequestReply
  94. {
  95. get
  96. {
  97. ThrowIfProtocolFactoryNotSet();
  98. return this.securityProtocolFactory.SupportsRequestReply;
  99. }
  100. }
  101. public MessageVersion MessageVersion
  102. {
  103. get
  104. {
  105. return this.messageVersion;
  106. }
  107. }
  108. void CloseProtocolFactory(bool aborted, TimeSpan timeout)
  109. {
  110. if (this.securityProtocolFactory != null && !this.SessionMode)
  111. {
  112. this.securityProtocolFactory.Close(aborted, timeout);
  113. this.securityProtocolFactory = null;
  114. }
  115. }
  116. public override T GetProperty<T>()
  117. {
  118. if (this.SessionMode && (typeof(T) == typeof(IChannelSecureConversationSessionSettings)))
  119. {
  120. return (T)(object)this.SessionClientSettings;
  121. }
  122. else if (typeof(T) == typeof(ISecurityCapabilities))
  123. {
  124. return (T)(object)this.securityCapabilities;
  125. }
  126. return base.GetProperty<T>();
  127. }
  128. protected override void OnAbort()
  129. {
  130. base.OnAbort();
  131. CloseProtocolFactory(true, TimeSpan.Zero);
  132. if (this.sessionClientSettings != null)
  133. {
  134. this.sessionClientSettings.Abort();
  135. }
  136. }
  137. protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
  138. {
  139. List<OperationWithTimeoutBeginCallback> begins = new List<OperationWithTimeoutBeginCallback>();
  140. List<OperationEndCallback> ends = new List<OperationEndCallback>();
  141. begins.Add(new OperationWithTimeoutBeginCallback(base.OnBeginClose));
  142. ends.Add(new OperationEndCallback(base.OnEndClose));
  143. if (this.securityProtocolFactory != null && !this.SessionMode)
  144. {
  145. begins.Add(new OperationWithTimeoutBeginCallback(this.securityProtocolFactory.BeginClose));
  146. ends.Add(new OperationEndCallback(this.securityProtocolFactory.EndClose));
  147. }
  148. if (this.sessionClientSettings != null)
  149. {
  150. begins.Add(new OperationWithTimeoutBeginCallback(this.sessionClientSettings.BeginClose));
  151. ends.Add(new OperationEndCallback(this.sessionClientSettings.EndClose));
  152. }
  153. return OperationWithTimeoutComposer.BeginComposeAsyncOperations(timeout, begins.ToArray(), ends.ToArray(), callback, state);
  154. }
  155. protected override void OnEndClose(IAsyncResult result)
  156. {
  157. OperationWithTimeoutComposer.EndComposeAsyncOperations(result);
  158. }
  159. protected override void OnClose(TimeSpan timeout)
  160. {
  161. TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
  162. base.OnClose(timeout);
  163. CloseProtocolFactory(false, timeoutHelper.RemainingTime());
  164. if (this.sessionClientSettings != null)
  165. {
  166. this.sessionClientSettings.Close(timeoutHelper.RemainingTime());
  167. }
  168. }
  169. protected override TChannel OnCreateChannel(EndpointAddress address, Uri via)
  170. {
  171. ThrowIfDisposed();
  172. if (this.SessionMode)
  173. {
  174. return this.sessionClientSettings.OnCreateChannel(address, via);
  175. }
  176. if (typeof(TChannel) == typeof(IOutputChannel))
  177. {
  178. return (TChannel)(object)new SecurityOutputChannel(this, this.securityProtocolFactory, ((IChannelFactory<IOutputChannel>)this.InnerChannelFactory).CreateChannel(address, via), address, via);
  179. }
  180. else if (typeof(TChannel) == typeof(IOutputSessionChannel))
  181. {
  182. return (TChannel)(object)new SecurityOutputSessionChannel(this, this.securityProtocolFactory, ((IChannelFactory<IOutputSessionChannel>)this.InnerChannelFactory).CreateChannel(address, via), address, via);
  183. }
  184. else if (typeof(TChannel) == typeof(IDuplexChannel))
  185. {
  186. return (TChannel)(object)new SecurityDuplexChannel(this, this.securityProtocolFactory, ((IChannelFactory<IDuplexChannel>)this.InnerChannelFactory).CreateChannel(address, via), address, via);
  187. }
  188. else if (typeof(TChannel) == typeof(IDuplexSessionChannel))
  189. {
  190. return (TChannel)(object)new SecurityDuplexSessionChannel(this, this.securityProtocolFactory, ((IChannelFactory<IDuplexSessionChannel>)this.InnerChannelFactory).CreateChannel(address, via), address, via);
  191. }
  192. else if (typeof(TChannel) == typeof(IRequestChannel))
  193. {
  194. return (TChannel)(object)new SecurityRequestChannel(this, this.securityProtocolFactory, ((IChannelFactory<IRequestChannel>)this.InnerChannelFactory).CreateChannel(address, via), address, via);
  195. }
  196. //typeof(TChannel) == typeof(IRequestSessionChannel)
  197. return (TChannel)(object)new SecurityRequestSessionChannel(this, this.securityProtocolFactory, ((IChannelFactory<IRequestSessionChannel>)this.InnerChannelFactory).CreateChannel(address, via), address, via);
  198. }
  199. protected override void OnOpen(TimeSpan timeout)
  200. {
  201. TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
  202. OnOpenCore(timeoutHelper.RemainingTime());
  203. base.OnOpen(timeoutHelper.RemainingTime());
  204. this.SetBufferManager();
  205. }
  206. void SetBufferManager()
  207. {
  208. ITransportFactorySettings transportSettings = this.GetProperty<ITransportFactorySettings>();
  209. if (transportSettings == null)
  210. return;
  211. BufferManager bufferManager = transportSettings.BufferManager;
  212. if (bufferManager == null)
  213. return;
  214. if (this.SessionMode && this.SessionClientSettings != null && this.SessionClientSettings.SessionProtocolFactory != null)
  215. {
  216. this.SessionClientSettings.SessionProtocolFactory.StreamBufferManager = bufferManager;
  217. }
  218. else
  219. {
  220. ThrowIfProtocolFactoryNotSet();
  221. this.securityProtocolFactory.StreamBufferManager = bufferManager;
  222. }
  223. }
  224. protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
  225. {
  226. return new OperationWithTimeoutAsyncResult(new OperationWithTimeoutCallback(this.OnOpen), timeout, callback, state);
  227. }
  228. protected override void OnEndOpen(IAsyncResult result)
  229. {
  230. OperationWithTimeoutAsyncResult.End(result);
  231. }
  232. void OnOpenCore(TimeSpan timeout)
  233. {
  234. TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
  235. if (this.SessionMode)
  236. {
  237. this.SessionClientSettings.Open(this, this.InnerChannelFactory, this.ChannelBuilder, timeoutHelper.RemainingTime());
  238. }
  239. else
  240. {
  241. ThrowIfProtocolFactoryNotSet();
  242. this.securityProtocolFactory.Open(true, timeoutHelper.RemainingTime());
  243. }
  244. }
  245. void ThrowIfDuplexNotSupported()
  246. {
  247. if (!this.SupportsDuplex)
  248. {
  249. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
  250. SR.GetString(SR.SecurityProtocolFactoryDoesNotSupportDuplex, this.securityProtocolFactory)));
  251. }
  252. }
  253. void ThrowIfProtocolFactoryNotSet()
  254. {
  255. if (this.securityProtocolFactory == null)
  256. {
  257. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
  258. SR.GetString(SR.SecurityProtocolFactoryShouldBeSetBeforeThisOperation)));
  259. }
  260. }
  261. void ThrowIfRequestReplyNotSupported()
  262. {
  263. if (!this.SupportsRequestReply)
  264. {
  265. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
  266. SR.GetString(SR.SecurityProtocolFactoryDoesNotSupportRequestReply, this.securityProtocolFactory)));
  267. }
  268. }
  269. abstract class ClientSecurityChannel<UChannel> : SecurityChannel<UChannel>
  270. where UChannel : class, IChannel
  271. {
  272. EndpointAddress to;
  273. Uri via;
  274. SecurityProtocolFactory securityProtocolFactory;
  275. ChannelParameterCollection channelParameters;
  276. protected ClientSecurityChannel(ChannelManagerBase factory, SecurityProtocolFactory securityProtocolFactory,
  277. UChannel innerChannel, EndpointAddress to, Uri via)
  278. : base(factory, innerChannel)
  279. {
  280. this.to = to;
  281. this.via = via;
  282. this.securityProtocolFactory = securityProtocolFactory;
  283. this.channelParameters = new ChannelParameterCollection(this);
  284. }
  285. protected SecurityProtocolFactory SecurityProtocolFactory
  286. {
  287. get { return this.securityProtocolFactory; }
  288. }
  289. public EndpointAddress RemoteAddress
  290. {
  291. get { return this.to; }
  292. }
  293. public Uri Via
  294. {
  295. get { return this.via; }
  296. }
  297. protected bool TryGetSecurityFaultException(Message faultMessage, out Exception faultException)
  298. {
  299. faultException = null;
  300. if (!faultMessage.IsFault)
  301. {
  302. return false;
  303. }
  304. MessageFault fault = MessageFault.CreateFault(faultMessage, TransportDefaults.MaxSecurityFaultSize);
  305. faultException = SecurityUtils.CreateSecurityFaultException(fault);
  306. return true;
  307. }
  308. protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
  309. {
  310. EnableChannelBindingSupport();
  311. return new OpenAsyncResult(this, timeout, callback, state);
  312. }
  313. protected override void OnEndOpen(IAsyncResult result)
  314. {
  315. OpenAsyncResult.End(result);
  316. }
  317. protected override void OnOpen(TimeSpan timeout)
  318. {
  319. TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
  320. EnableChannelBindingSupport();
  321. SecurityProtocol securityProtocol = this.SecurityProtocolFactory.CreateSecurityProtocol(
  322. this.to,
  323. this.Via,
  324. null,
  325. typeof(TChannel) == typeof(IRequestChannel),
  326. timeoutHelper.RemainingTime());
  327. OnProtocolCreationComplete(securityProtocol);
  328. this.SecurityProtocol.Open(timeoutHelper.RemainingTime());
  329. base.OnOpen(timeoutHelper.RemainingTime());
  330. }
  331. void EnableChannelBindingSupport()
  332. {
  333. if (this.securityProtocolFactory != null && this.securityProtocolFactory.ExtendedProtectionPolicy != null && this.securityProtocolFactory.ExtendedProtectionPolicy.CustomChannelBinding != null)
  334. {
  335. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.ExtendedProtectionPolicyCustomChannelBindingNotSupported)));
  336. }
  337. // Do not enable channel binding if there is no reason as it sets up chunking mode.
  338. if ((SecurityUtils.IsChannelBindingDisabled) || (!SecurityUtils.IsSecurityBindingSuitableForChannelBinding(this.SecurityProtocolFactory.SecurityBindingElement as TransportSecurityBindingElement)))
  339. return;
  340. if (InnerChannel != null)
  341. {
  342. IChannelBindingProvider cbp = InnerChannel.GetProperty<IChannelBindingProvider>();
  343. if (cbp != null)
  344. {
  345. cbp.EnableChannelBindingSupport();
  346. }
  347. }
  348. }
  349. void OnProtocolCreationComplete(SecurityProtocol securityProtocol)
  350. {
  351. this.SecurityProtocol = securityProtocol;
  352. this.SecurityProtocol.ChannelParameters = this.channelParameters;
  353. }
  354. public override T GetProperty<T>()
  355. {
  356. if (typeof(T) == typeof(ChannelParameterCollection))
  357. {
  358. return (T)(object)this.channelParameters;
  359. }
  360. return base.GetProperty<T>();
  361. }
  362. sealed class OpenAsyncResult : AsyncResult
  363. {
  364. readonly ClientSecurityChannel<UChannel> clientChannel;
  365. TimeoutHelper timeoutHelper;
  366. static readonly AsyncCallback openInnerChannelCallback = Fx.ThunkCallback(new AsyncCallback(OpenInnerChannelCallback));
  367. static readonly AsyncCallback openSecurityProtocolCallback = Fx.ThunkCallback(new AsyncCallback(OpenSecurityProtocolCallback));
  368. public OpenAsyncResult(ClientSecurityChannel<UChannel> clientChannel, TimeSpan timeout,
  369. AsyncCallback callback, object state)
  370. : base(callback, state)
  371. {
  372. this.timeoutHelper = new TimeoutHelper(timeout);
  373. this.clientChannel = clientChannel;
  374. SecurityProtocol securityProtocol = this.clientChannel.SecurityProtocolFactory.CreateSecurityProtocol(this.clientChannel.to,
  375. this.clientChannel.Via,
  376. null, typeof(TChannel) == typeof(IRequestChannel), timeoutHelper.RemainingTime());
  377. bool completeSelf = this.OnCreateSecurityProtocolComplete(securityProtocol);
  378. if (completeSelf)
  379. {
  380. Complete(true);
  381. }
  382. }
  383. internal static void End(IAsyncResult result)
  384. {
  385. AsyncResult.End<OpenAsyncResult>(result);
  386. }
  387. bool OnCreateSecurityProtocolComplete(SecurityProtocol securityProtocol)
  388. {
  389. this.clientChannel.OnProtocolCreationComplete(securityProtocol);
  390. IAsyncResult result = securityProtocol.BeginOpen(timeoutHelper.RemainingTime(), openSecurityProtocolCallback, this);
  391. if (!result.CompletedSynchronously)
  392. {
  393. return false;
  394. }
  395. securityProtocol.EndOpen(result);
  396. return this.OnSecurityProtocolOpenComplete();
  397. }
  398. static void OpenSecurityProtocolCallback(IAsyncResult result)
  399. {
  400. if (result.CompletedSynchronously)
  401. {
  402. return;
  403. }
  404. OpenAsyncResult self = result.AsyncState as OpenAsyncResult;
  405. if (self == null)
  406. {
  407. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.InvalidAsyncResult), "result"));
  408. }
  409. Exception completionException = null;
  410. bool completeSelf = false;
  411. try
  412. {
  413. self.clientChannel.SecurityProtocol.EndOpen(result);
  414. completeSelf = self.OnSecurityProtocolOpenComplete();
  415. }
  416. #pragma warning suppress 56500 // covered by FxCOP
  417. catch (Exception e)
  418. {
  419. if (Fx.IsFatal(e))
  420. {
  421. throw;
  422. }
  423. completionException = e;
  424. completeSelf = true;
  425. }
  426. if (completeSelf)
  427. {
  428. self.Complete(false, completionException);
  429. }
  430. }
  431. bool OnSecurityProtocolOpenComplete()
  432. {
  433. IAsyncResult result = this.clientChannel.InnerChannel.BeginOpen(this.timeoutHelper.RemainingTime(), openInnerChannelCallback, this);
  434. if (!result.CompletedSynchronously)
  435. {
  436. return false;
  437. }
  438. this.clientChannel.InnerChannel.EndOpen(result);
  439. return true;
  440. }
  441. static void OpenInnerChannelCallback(IAsyncResult result)
  442. {
  443. if (result == null)
  444. {
  445. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("result"));
  446. }
  447. if (result.CompletedSynchronously)
  448. {
  449. return;
  450. }
  451. OpenAsyncResult self = result.AsyncState as OpenAsyncResult;
  452. if (self == null)
  453. {
  454. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.InvalidAsyncResult), "result"));
  455. }
  456. Exception completionException = null;
  457. try
  458. {
  459. self.clientChannel.InnerChannel.EndOpen(result);
  460. }
  461. #pragma warning suppress 56500 // covered by FxCOP
  462. catch (Exception e)
  463. {
  464. if (Fx.IsFatal(e))
  465. {
  466. throw;
  467. }
  468. completionException = e;
  469. }
  470. self.Complete(false, completionException);
  471. }
  472. }
  473. }
  474. class SecurityOutputChannel : ClientSecurityChannel<IOutputChannel>, IOutputChannel
  475. {
  476. public SecurityOutputChannel(ChannelManagerBase factory, SecurityProtocolFactory securityProtocolFactory, IOutputChannel innerChannel, EndpointAddress to, Uri via)
  477. : base(factory, securityProtocolFactory, innerChannel, to, via)
  478. {
  479. }
  480. public IAsyncResult BeginSend(Message message, AsyncCallback callback, object state)
  481. {
  482. return this.BeginSend(message, this.DefaultSendTimeout, callback, state);
  483. }
  484. public IAsyncResult BeginSend(Message message, TimeSpan timeout, AsyncCallback callback, object state)
  485. {
  486. ThrowIfFaulted();
  487. ThrowIfDisposedOrNotOpen(message);
  488. return new OutputChannelSendAsyncResult(message, this.SecurityProtocol, this.InnerChannel, timeout, callback, state);
  489. }
  490. public void EndSend(IAsyncResult result)
  491. {
  492. OutputChannelSendAsyncResult.End(result);
  493. }
  494. public void Send(Message message)
  495. {
  496. this.Send(message, this.DefaultSendTimeout);
  497. }
  498. public void Send(Message message, TimeSpan timeout)
  499. {
  500. ThrowIfFaulted();
  501. ThrowIfDisposedOrNotOpen(message);
  502. TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
  503. this.SecurityProtocol.SecureOutgoingMessage(ref message, timeoutHelper.RemainingTime());
  504. this.InnerChannel.Send(message, timeoutHelper.RemainingTime());
  505. }
  506. }
  507. sealed class SecurityOutputSessionChannel : SecurityOutputChannel, IOutputSessionChannel
  508. {
  509. public SecurityOutputSessionChannel(ChannelManagerBase factory, SecurityProtocolFactory securityProtocolFactory, IOutputSessionChannel innerChannel, EndpointAddress to, Uri via)
  510. : base(factory, securityProtocolFactory, innerChannel, to, via)
  511. {
  512. }
  513. public IOutputSession Session
  514. {
  515. get
  516. {
  517. return ((IOutputSessionChannel)this.InnerChannel).Session;
  518. }
  519. }
  520. }
  521. class SecurityRequestChannel : ClientSecurityChannel<IRequestChannel>, IRequestChannel
  522. {
  523. public SecurityRequestChannel(ChannelManagerBase factory, SecurityProtocolFactory securityProtocolFactory, IRequestChannel innerChannel, EndpointAddress to, Uri via)
  524. : base(factory, securityProtocolFactory, innerChannel, to, via)
  525. {
  526. }
  527. public IAsyncResult BeginRequest(Message message, AsyncCallback callback, object state)
  528. {
  529. return this.BeginRequest(message, this.DefaultSendTimeout, callback, state);
  530. }
  531. public IAsyncResult BeginRequest(Message message, TimeSpan timeout, AsyncCallback callback, object state)
  532. {
  533. ThrowIfFaulted();
  534. ThrowIfDisposedOrNotOpen(message);
  535. return new RequestChannelSendAsyncResult(message, this.SecurityProtocol, this.InnerChannel, this, timeout, callback, state);
  536. }
  537. public Message EndRequest(IAsyncResult result)
  538. {
  539. return RequestChannelSendAsyncResult.End(result);
  540. }
  541. public Message Request(Message message)
  542. {
  543. return this.Request(message, this.DefaultSendTimeout);
  544. }
  545. internal Message ProcessReply(Message reply, SecurityProtocolCorrelationState correlationState, TimeSpan timeout)
  546. {
  547. if (reply != null)
  548. {
  549. if (DiagnosticUtility.ShouldUseActivity)
  550. {
  551. ServiceModelActivity replyActivity = TraceUtility.ExtractActivity(reply);
  552. if (replyActivity != null &&
  553. correlationState != null &&
  554. correlationState.Activity != null &&
  555. replyActivity.Id != correlationState.Activity.Id)
  556. {
  557. using (ServiceModelActivity.BoundOperation(replyActivity))
  558. {
  559. if (null != FxTrace.Trace)
  560. {
  561. FxTrace.Trace.TraceTransfer(correlationState.Activity.Id);
  562. }
  563. replyActivity.Stop();
  564. }
  565. }
  566. }
  567. ServiceModelActivity activity = correlationState == null ? null : correlationState.Activity;
  568. using (ServiceModelActivity.BoundOperation(activity))
  569. {
  570. if (DiagnosticUtility.ShouldUseActivity)
  571. {
  572. TraceUtility.SetActivity(reply, activity);
  573. }
  574. Message unverifiedMessage = reply;
  575. Exception faultException = null;
  576. try
  577. {
  578. this.SecurityProtocol.VerifyIncomingMessage(ref reply, timeout, correlationState);
  579. }
  580. catch (MessageSecurityException)
  581. {
  582. TryGetSecurityFaultException(unverifiedMessage, out faultException);
  583. if (faultException == null)
  584. {
  585. throw;
  586. }
  587. }
  588. if (faultException != null)
  589. {
  590. this.Fault(faultException);
  591. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(faultException);
  592. }
  593. }
  594. }
  595. return reply;
  596. }
  597. public Message Request(Message message, TimeSpan timeout)
  598. {
  599. ThrowIfFaulted();
  600. ThrowIfDisposedOrNotOpen(message);
  601. TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
  602. SecurityProtocolCorrelationState correlationState = this.SecurityProtocol.SecureOutgoingMessage(ref message, timeoutHelper.RemainingTime(), null);
  603. Message reply = this.InnerChannel.Request(message, timeoutHelper.RemainingTime());
  604. return ProcessReply(reply, correlationState, timeoutHelper.RemainingTime());
  605. }
  606. }
  607. sealed class SecurityRequestSessionChannel : SecurityRequestChannel, IRequestSessionChannel
  608. {
  609. public SecurityRequestSessionChannel(ChannelManagerBase factory, SecurityProtocolFactory securityProtocolFactory, IRequestSessionChannel innerChannel, EndpointAddress to, Uri via)
  610. : base(factory, securityProtocolFactory, innerChannel, to, via)
  611. {
  612. }
  613. public IOutputSession Session
  614. {
  615. get
  616. {
  617. return ((IRequestSessionChannel)this.InnerChannel).Session;
  618. }
  619. }
  620. }
  621. class SecurityDuplexChannel : SecurityOutputChannel, IDuplexChannel
  622. {
  623. public SecurityDuplexChannel(ChannelManagerBase factory, SecurityProtocolFactory securityProtocolFactory, IDuplexChannel innerChannel, EndpointAddress to, Uri via)
  624. : base(factory, securityProtocolFactory, innerChannel, to, via)
  625. {
  626. }
  627. internal IDuplexChannel InnerDuplexChannel
  628. {
  629. get { return (IDuplexChannel)this.InnerChannel; }
  630. }
  631. public EndpointAddress LocalAddress
  632. {
  633. get
  634. {
  635. return this.InnerDuplexChannel.LocalAddress;
  636. }
  637. }
  638. internal virtual bool AcceptUnsecuredFaults
  639. {
  640. get { return false; }
  641. }
  642. public Message Receive()
  643. {
  644. return this.Receive(this.DefaultReceiveTimeout);
  645. }
  646. public Message Receive(TimeSpan timeout)
  647. {
  648. return InputChannel.HelpReceive(this, timeout);
  649. }
  650. public IAsyncResult BeginReceive(AsyncCallback callback, object state)
  651. {
  652. return this.BeginReceive(this.DefaultReceiveTimeout, callback, state);
  653. }
  654. public IAsyncResult BeginReceive(TimeSpan timeout, AsyncCallback callback, object state)
  655. {
  656. return InputChannel.HelpBeginReceive(this, timeout, callback, state);
  657. }
  658. public Message EndReceive(IAsyncResult result)
  659. {
  660. return InputChannel.HelpEndReceive(result);
  661. }
  662. public virtual IAsyncResult BeginTryReceive(TimeSpan timeout, AsyncCallback callback, object state)
  663. {
  664. if (DoneReceivingInCurrentState())
  665. {
  666. return new DoneReceivingAsyncResult(callback, state);
  667. }
  668. ClientDuplexReceiveMessageAndVerifySecurityAsyncResult result =
  669. new ClientDuplexReceiveMessageAndVerifySecurityAsyncResult(this, this.InnerDuplexChannel, timeout, callback, state);
  670. result.Start();
  671. return result;
  672. }
  673. public virtual bool EndTryReceive(IAsyncResult result, out Message message)
  674. {
  675. DoneReceivingAsyncResult doneRecevingResult = result as DoneReceivingAsyncResult;
  676. if (doneRecevingResult != null)
  677. {
  678. return DoneReceivingAsyncResult.End(doneRecevingResult, out message);
  679. }
  680. return ClientDuplexReceiveMessageAndVerifySecurityAsyncResult.End(result, out message);
  681. }
  682. internal Message ProcessMessage(Message message, TimeSpan timeout)
  683. {
  684. if (message == null)
  685. {
  686. return null;
  687. }
  688. Message unverifiedMessage = message;
  689. Exception faultException = null;
  690. try
  691. {
  692. this.SecurityProtocol.VerifyIncomingMessage(ref message, timeout);
  693. }
  694. catch (MessageSecurityException)
  695. {
  696. TryGetSecurityFaultException(unverifiedMessage, out faultException);
  697. if (faultException == null)
  698. {
  699. throw;
  700. }
  701. }
  702. if (faultException != null)
  703. {
  704. if (AcceptUnsecuredFaults)
  705. {
  706. Fault(faultException);
  707. }
  708. throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(faultException);
  709. }
  710. return message;
  711. }
  712. public bool TryReceive(TimeSpan timeout, out Message message)
  713. {
  714. if (DoneReceivingInCurrentState())
  715. {
  716. message = null;
  717. return true;
  718. }
  719. TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
  720. if (!this.InnerDuplexChannel.TryReceive(timeoutHelper.RemainingTime(), out message))
  721. {
  722. return false;
  723. }
  724. message = ProcessMessage(message, timeoutHelper.RemainingTime());
  725. return true;
  726. }
  727. public bool WaitForMessage(TimeSpan timeout)
  728. {
  729. return this.InnerDuplexChannel.WaitForMessage(timeout);
  730. }
  731. public IAsyncResult BeginWaitForMessage(TimeSpan timeout, AsyncCallback callback, object state)
  732. {
  733. return this.InnerDuplexChannel.BeginWaitForMessage(timeout, callback, state);
  734. }
  735. public bool EndWaitForMessage(IAsyncResult result)
  736. {
  737. return this.InnerDuplexChannel.EndWaitForMessage(result);
  738. }
  739. }
  740. sealed class SecurityDuplexSessionChannel : SecurityDuplexChannel, IDuplexSessionChannel
  741. {
  742. public SecurityDuplexSessionChannel(ChannelManagerBase factory, SecurityProtocolFactory securityProtocolFactory, IDuplexSessionChannel innerChannel, EndpointAddress to, Uri via)
  743. : base(factory, securityProtocolFactory, innerChannel, to, via)
  744. {
  745. }
  746. public IDuplexSession Session
  747. {
  748. get
  749. {
  750. return ((IDuplexSessionChannel)this.InnerChannel).Session;
  751. }
  752. }
  753. internal override bool AcceptUnsecuredFaults
  754. {
  755. get { return true; }
  756. }
  757. }
  758. sealed class RequestChannelSendAsyncResult : ApplySecurityAndSendAsyncResult<IRequestChannel>
  759. {
  760. Message reply;
  761. SecurityRequestChannel securityChannel;
  762. public RequestChannelSendAsyncResult(Message message, SecurityProtocol protocol, IRequestChannel channel, SecurityRequestChannel securityChannel, TimeSpan timeout,
  763. AsyncCallback callback, object state)
  764. : base(protocol, channel, timeout, callback, state)
  765. {
  766. this.securityChannel = securityChannel;
  767. this.Begin(message, null);
  768. }
  769. protected override IAsyncResult BeginSendCore(IRequestChannel channel, Message message, TimeSpan timeout, AsyncCallback callback, object state)
  770. {
  771. return channel.BeginRequest(message, timeout, callback, state);
  772. }
  773. internal static Message End(IAsyncResult result)
  774. {
  775. RequestChannelSendAsyncResult self = result as RequestChannelSendAsyncResult;
  776. OnEnd(self);
  777. return self.reply;
  778. }
  779. protected override void EndSendCore(IRequestChannel channel, IAsyncResult result)
  780. {
  781. this.reply = channel.EndRequest(result);
  782. }
  783. protected override void OnSendCompleteCore(TimeSpan timeout)
  784. {
  785. this.reply = securityChannel.ProcessReply(reply, this.CorrelationState, timeout);
  786. }
  787. }
  788. class ClientDuplexReceiveMessageAndVerifySecurityAsyncResult : ReceiveMessageAndVerifySecurityAsyncResultBase
  789. {
  790. SecurityDuplexChannel channel;
  791. public ClientDuplexReceiveMessageAndVerifySecurityAsyncResult(SecurityDuplexChannel channel, IDuplexChannel innerChannel, TimeSpan timeout, AsyncCallback callback, object state)
  792. : base(innerChannel, timeout, callback, state)
  793. {
  794. this.channel = channel;
  795. }
  796. protected override bool OnInnerReceiveDone(ref Message message, TimeSpan timeout)
  797. {
  798. message = this.channel.ProcessMessage(message, timeout);
  799. return true;
  800. }
  801. }
  802. }
  803. }