QueryLanguage.Remoting.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. // See comment in Observable.Remoting.cs for why we build this code into System.Reactive, which is mostly
  5. // just a type forwarding legacy facade.
  6. #if HAS_REMOTING
  7. extern alias SystemReactiveNet;
  8. using SystemReactiveNet::System.Reactive.Disposables;
  9. using SystemReactiveNet::System.Reactive;
  10. using System.Runtime.Remoting;
  11. using System.Runtime.Remoting.Lifetime;
  12. using System.Security;
  13. using System.Threading;
  14. //
  15. // DESIGN: The MarshalByRefObject (MBRO) implementations for RemotableObserver and RemotableSubscription act as
  16. // self-sponsoring objects controlling their lease times in order to tie those to the lifetime of the
  17. // underlying observable sequence (ended by OnError or OnCompleted) or the user-controlled subscription
  18. // lifetime. If we were to implement InitializeLifetimeService to return null, we'd end up with leases
  19. // that are infinite, so we need a more fine-grained lease scheme. The default configuration would time
  20. // out after 5 minutes, causing clients to fail while they're still observing the sequence. To solve
  21. // this, those MBROs also implement ISponsor with a Renewal method that continues to renew the lease
  22. // upon every call. When the sequence comes to an end or the subscription is disposed, the sponsor gets
  23. // unregistered, allowing the objects to be reclaimed eventually by the Remoting infrastructure.
  24. //
  25. // SECURITY: Registration and unregistration of sponsors is protected by SecurityCritical annotations. The
  26. // implementation of ISponsor is known (i.e. no foreign implementation can be passed in) at the call
  27. // sites of the Register and Unregister methods. The call to Register happens in the SecurityCritical
  28. // InitializeLifetimeService method and is called by trusted Remoting infrastructure. The Renewal
  29. // method is also marked as SecurityCritical and called by Remoting. The Unregister method is wrapped
  30. // in a ***SecurityTreatAsSafe*** private method which only gets called by the observer's OnError and
  31. // OnCompleted notifications, or the subscription's Dispose method. In the former case, the sequence
  32. // indicates it has reached the end, and hence resources can be reclaimed. Clients will no longer be
  33. // connected to the source due to auto-detach behavior enforced in the SerializableObservable client-
  34. // side implementation. In the latter case of disposing the subscription, the client is in control
  35. // and will cause the underlying remote subscription to be disposed as well, allowing resources to be
  36. // reclaimed. Rogue messages on either the data or the subscription channel can cause a DoS of the
  37. // client-server communication but this is subject to the security of the Remoting channels used. In
  38. // no case an untrusted party can cause _extension_ of the lease time.
  39. //
  40. //
  41. // Notice this assembly is marked as APTCA in official builds, causing methods to be treated as transparent,
  42. // thus requiring the ***SecurityTreatAsSafe*** annotation on the security boundaries described above. When not
  43. // applied, the following exception would occur at runtime:
  44. //
  45. // System.MethodAccessException:
  46. //
  47. // Attempt by security transparent method 'System.Reactive.Linq.QueryLanguage+RemotableObservable`1+
  48. // RemotableSubscription<T>.Unregister()' to access security critical method 'System.Runtime.Remoting.Lifetime.
  49. // ILease.Unregister(System.Runtime.Remoting.Lifetime.ISponsor)' failed.
  50. //
  51. // Assembly 'System.Reactive.Linq, Version=2.0.ymmdd.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'
  52. // is marked with the AllowPartiallyTrustedCallersAttribute, and uses the level 2 security transparency model.
  53. // Level 2 transparency causes all methods in AllowPartiallyTrustedCallers assemblies to become security
  54. // transparent by default, which may be the cause of this exception.
  55. //
  56. //
  57. // The two CodeAnalysis suppressions below are explained by the Justification property (scroll to the right):
  58. //
  59. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2136:TransparencyAnnotationsShouldNotConflictFxCopRule", Scope = "member", Target = "~M:System.Reactive.Linq.RemotingObservable.RemotableObserver`1.Unregister", Justification = "This error only occurs while running FxCop on local builds that don't have NO_CODECOVERAGE set, causing the assembly not to be marked with APTCA (see AssemblyInfo.cs). When APTCA is enabled in official builds, this SecurityTreatAsSafe annotation is required.")]
  60. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2136:TransparencyAnnotationsShouldNotConflictFxCopRule", Scope = "member", Target = "~M:System.Reactive.Linq.RemotingObservable.RemotableObservable`1.RemotableSubscription.Unregister", Justification = "This error only occurs while running FxCop on local builds that don't have NO_CODECOVERAGE set, causing the assembly not to be marked with APTCA (see AssemblyInfo.cs). When APTCA is enabled in official builds, this SecurityTreatAsSafe annotation is required.")]
  61. namespace System.Reactive.Linq
  62. {
  63. public static partial class RemotingObservable
  64. {
  65. #region Remotable
  66. private static IObservable<TSource> Remotable_<TSource>(IObservable<TSource> source)
  67. {
  68. return new SerializableObservable<TSource>(new RemotableObservable<TSource>(source, null));
  69. }
  70. private static IObservable<TSource> Remotable_<TSource>(IObservable<TSource> source, ILease? lease)
  71. {
  72. return new SerializableObservable<TSource>(new RemotableObservable<TSource>(source, lease));
  73. }
  74. [Serializable]
  75. private sealed class SerializableObservable<T> : IObservable<T>
  76. {
  77. private readonly RemotableObservable<T> _remotableObservable;
  78. public SerializableObservable(RemotableObservable<T> remotableObservable)
  79. {
  80. _remotableObservable = remotableObservable;
  81. }
  82. public IDisposable Subscribe(IObserver<T> observer)
  83. {
  84. var consumer = SafeObserver<T>.Wrap(observer);
  85. //
  86. // [OK] Use of unsafe Subscribe: non-pretentious transparent wrapping through remoting; exception coming from the remote object is not re-routed.
  87. //
  88. var d = _remotableObservable.Subscribe/*Unsafe*/(new RemotableObserver<T>(consumer));
  89. consumer.SetResource(d);
  90. return d;
  91. }
  92. }
  93. private sealed class RemotableObserver<T> : MarshalByRefObject, IObserver<T>, ISponsor
  94. {
  95. private readonly IObserver<T> _underlyingObserver;
  96. public RemotableObserver(IObserver<T> underlyingObserver)
  97. {
  98. _underlyingObserver = underlyingObserver;
  99. }
  100. public void OnNext(T value)
  101. {
  102. _underlyingObserver.OnNext(value);
  103. }
  104. public void OnError(Exception exception)
  105. {
  106. try
  107. {
  108. _underlyingObserver.OnError(exception);
  109. }
  110. finally
  111. {
  112. Unregister();
  113. }
  114. }
  115. public void OnCompleted()
  116. {
  117. try
  118. {
  119. _underlyingObserver.OnCompleted();
  120. }
  121. finally
  122. {
  123. Unregister();
  124. }
  125. }
  126. [SecuritySafeCritical] // See remarks at the top of the file.
  127. private void Unregister()
  128. {
  129. var lease = (ILease)RemotingServices.GetLifetimeService(this);
  130. lease?.Unregister(this);
  131. }
  132. [SecurityCritical]
  133. public override object InitializeLifetimeService()
  134. {
  135. var lease = (ILease)base.InitializeLifetimeService();
  136. lease.Register(this);
  137. return lease;
  138. }
  139. [SecurityCritical]
  140. TimeSpan ISponsor.Renewal(ILease lease)
  141. {
  142. return lease.InitialLeaseTime;
  143. }
  144. }
  145. [Serializable]
  146. private sealed class RemotableObservable<T> : MarshalByRefObject, IObservable<T>
  147. {
  148. private readonly IObservable<T> _underlyingObservable;
  149. private readonly ILease? _lease;
  150. public RemotableObservable(IObservable<T> underlyingObservable, ILease? lease)
  151. {
  152. _underlyingObservable = underlyingObservable;
  153. _lease = lease;
  154. }
  155. public IDisposable Subscribe(IObserver<T> observer)
  156. {
  157. //
  158. // [OK] Use of unsafe Subscribe: non-pretentious transparent wrapping through remoting; throwing across remoting boundaries is fine.
  159. //
  160. return new RemotableSubscription(_underlyingObservable.Subscribe/*Unsafe*/(observer));
  161. }
  162. [SecurityCritical]
  163. public override object? InitializeLifetimeService()
  164. {
  165. return _lease;
  166. }
  167. private sealed class RemotableSubscription : MarshalByRefObject, IDisposable, ISponsor
  168. {
  169. private IDisposable _underlyingSubscription;
  170. public RemotableSubscription(IDisposable underlyingSubscription)
  171. {
  172. _underlyingSubscription = underlyingSubscription;
  173. }
  174. public void Dispose()
  175. {
  176. //
  177. // Avoiding double-dispose and dropping the reference upon disposal.
  178. //
  179. using (Interlocked.Exchange(ref _underlyingSubscription, Disposable.Empty))
  180. {
  181. Unregister();
  182. }
  183. }
  184. [SecuritySafeCritical] // See remarks at the top of the file.
  185. private void Unregister()
  186. {
  187. var lease = (ILease)RemotingServices.GetLifetimeService(this);
  188. lease?.Unregister(this);
  189. }
  190. [SecurityCritical]
  191. public override object InitializeLifetimeService()
  192. {
  193. var lease = (ILease)base.InitializeLifetimeService();
  194. lease.Register(this);
  195. return lease;
  196. }
  197. [SecurityCritical]
  198. TimeSpan ISponsor.Renewal(ILease lease)
  199. {
  200. return lease.InitialLeaseTime;
  201. }
  202. }
  203. }
  204. #endregion
  205. }
  206. }
  207. #endif