runtime: Consider allowing Exception instances to be serialized without requiring BinaryFormatter
Some remoting technologies use BinaryFormatter to serialize Exception instances across security boundaries, which puts them out of SDL compliance and potentially exposes consumers to security vulnerabilities. The current recommended way to serialize exception information safely is to call ToString on the exception instance, then transmit the resulting string across the wire. However, this does not create useful object models for consuming applications, as they can’t interact with a simple string like they can a rich exception instance (accessing properties, using try / catch, etc.).
In an ideal world, an exception serialization tech would have the following characteristics:
- The proper
Exception-derived type will be instantiated after deserialization. - The human-readable message and stack trace are preserved.
- The inner exceptions are preserved.
- Vital information about the exception is preserved. This is normally information passed to the Exception ctor and exposed via properties, such as the argument name provided to an
ArgumentOutOfRangeException.
To maintain SDL compliance and work with our linker technology, we’d need to enforce a few extra behaviors:
- The payload cannot be the sole arbiter of type information. The deserializer needs to provide an allow list of legal
Exception-derived types, and the payload cannot attempt to instantiate types outside that allowed list - The deserializer tech must go through normal instance validation and type safety checks, normally performed by the exception’s ctor. This disallows using the existing
SerializationInfo/StreamingContextinfrastructure. - Cyclic or deeply-nested object graphs must not be constructed. This also disallows using the existing
SerializationInfo/StreamingContextinfrastructure.
It’s possible that the deserialization tech would need to include special-case handling of each allowed Exception-derived type in order to fulfill these requirements. Perhaps this could be simplified by understanding canonical patterns like .ctor(string message, Exception innerException). But we’ll cross that bridge when we come to it.
About this issue
- Original URL
- State: open
- Created 6 years ago
- Reactions: 11
- Comments: 58 (53 by maintainers)
For those who don’t know what some TLAs mean, like me, I think SDL refers to Microsoft Security Development Lifecycle.
RuntimeHelpers.GetUninitializedObjectcreates uninitialized object. It does not run any constructors and it can create invalid instances. Any forward-looking scheme needs to run a proper (public) constructor of the given exception type.Can the provider implement a System.Runtime.Serialization.IFormatterConverter whose
object Convert(object value, Type type)method converts from some other representation to SomeOpaqueType?The point I’m trying to make is that unless you are a serialization expert that is keenly aware of the security ramifications, you will most likely end up implementing things using the readily available, insecure way (a.k.a. passing in
FormatterConverterthat does not support non-trivial delayed type conversions). A search using grep.app shows many occurrences of this, including major frameworks like orleans or akka.net. It is also what is recommended by many SO answers and ChatGPT.I think it stands to reason that we only recommend exception deserialization for applications not expected to handle untrusted input. This is true for the aforementioned orleans and akka.net that essentially implement remoting across distributed compute clusters.
Custom converters for modern deserializers are expected to be written against modern security requirements. It includes things like explicit allow-lists of types that have been hardened for untrusted input. If you see a type that implements ISerialiable, it is impossible to tell whether the ISerializable implementation has been hardened against untrusted input.
This guidance has been non-existent for ISerializable-based contracts. I do not think that it is acceptable to apply it retroactively.
I am not convinced that the StreamJsonRpc scheme is secure. The scheme is probably acceptable for closed system like VS cross-process communication where actively malicious input is less of a concern. I do not think it would be acceptable for general use for arbitrary end points that have to be hardened against actively malicious input.
No it isn’t.
System.Runtime.Serialization.Formatters.Binary.BinaryFormatterandSystem.Runtime.Serialization.SerializationInfoare not in the same namespace.IMO that’s a flaw in how we obsoleted APIs. Folks were over-eager to obsolete all APIs used with BinaryFormatter instead of obsoleting only APIs directly and solely used with BinaryFormatter. We should fix this by removing the excess obsolete attributes on APIs that are not themselves fundamentally insecure.
That’s true. Although in all our use with StreamJsonRpc (which is substantial, but tiny on a .NET scale), we’ve never encountered such a failure. And actually I should refine my words: if the Exception type itself has a property typed as SomeType, then we’ll go ahead and deserialize that. We only reduce complex objects to dictionaries of primitives for objects for the likes of the Data dictionary where the declared type is
object. So in practice this problem would only manifest if an Exception-derived type declared an FooBase property and gave it a FooDerived value, and upon deserialization expected FooDerived and downcast it in its deserializing constructor. That seems pretty weird to do though, IMO.True. Although this could be resolved using something like
[KnownTypeAttribute]or a list of expected exception types in the app so that the serializer can pregenerate code to deserialize such types.Can you elaborate on this? Why is it insecure by design? In fact ISerializable is the only pattern I’ve ever seen for serializers where the intended use is explicitly given to the serializing/deserializing code so it can consider security matters. If StreamJsonRpc can implement a serializer/deserializer that leverages these APIs securely (as I’ve described), and we’re not really using any of the APIs in a hacky way, it doesn’t seem like an insecure API design IMO.
Agreed. That’s why StreamJsonRpc doesn’t deserialize such objects except as harmless dictionaries of primitives. The only way I can think of for an injection attack to succeed is by way of primitive values that the executing code then read and interpret in a dangerous way. For example, if the Data dictionary contained a “Commands” key with a
format c:string value, and the Exception class blindly executed it, then yes, we’d have a problem.I disagree with this. I have code that serializes and deserializes arbitrary Exception types using the ISerializable interface they implement. I would even argue I do it securely. I don’t use BinaryFormatter at all.
This is almost what I do (in StreamJsonRpc). Except I didn’t have to replace ISerializable. I used it as-is. It works great. I’m happy to provide details.
What we do in StreamJsonRpc is just that, IIRC. Any complex object from the Data dictionary is simply serialized as a dictionary of primitives, and therefore they get deserialized as a dictionary of primitives. Perfectly safe that way, while retaining the data.
The only arbitrary object we even instantiate in this system are Exception-derived types. We made the decision to assume that Exception types are generally safe to instantiate (e.g. assume that none of them have harmful finalizers or other behavior). If that turns out to be false, we have a disallow-list that can block it. We also allow for exceptions that don’t conform to the ISerializable patterns. In either case (blocked or non-conformant) or if we simply cannot find the exception type in the deserializer, we simply deserialize as System.Exception instead of its derived type.
I think what is missing is a centralized pattern that exception authors can use to enable serialization for their types. Being able to copy the stack trace is one part of the puzzle, however being able to fully rehydrate an exception (including matching the original exception type) is not easy without resorting to
ISerializable. I should note that polymorphic exception serialization is a crucial ingredient in distributed actor systems, since they’re being used to drive supervision hierachies.They seem to be calling into the
ISerializableAPIs directly, a.k.a. replicating how BF does it. To my knowledge that’s the only available mechanism for marshalling exceptions.I think the point of this issue is to provide an alternative mechanism for framework/library authors that isn’t prone to the usual security problems. We don’t need to (and probably shouldn’t) bake this into our built-in serializers though.
A 100% faithful reconstruction of the original
Exceptioninstance is not necessarily required. For example, perhaps it’s good enough for our serializer to say that it doesn’t deal with serializing the Data dictionary. (If we were to try to handle that, we’d become a serializer for arbitrary data, and the .NET ecosystem does not need yet another arbitrary data serializer.) This also means that we’d lose Watson bucket info. But we’d definitely want to keep useful information like the human-readable stack trace around. Restoring that data might involve the creation of new API surface within the runtime.That still relies on the Remoting infrastructure doing the serialization, and has been somewhat generalized with
ExceptionDispatchInfosince .NET 4.5.Perhaps being able to serialize a ExceptionDispatchInfo would solve this problem?
The case of “not having access” shouldn’t be possible with this design. The deserializer needs to have ahead-of-time knowledge about all possible
Exceptionclasses that might be instantiated. (This characteristic is true of any secure polymorphic deserialization technology; it’s not unique toExceptionand derived types.)This means that deserialization scenarios fall into only two buckets: (1) the deserializer is aware of the requested
Exception-derived type and knows how to instantiate it; or (2) the deserializer is not aware of the requestedException-derived type. There’s no middle ground where the deserializer says “well, I found aTypethat corresponds to what the payload is requesting, but I don’t know how to instantate it.”In the case of the second bucket above, I imagine the deserializer would instantiate a placeholder
Exception-derived type and include the original error message and the original stack trace.