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