Skip to content

Consider allowing Exception instances to be serialized without requiring BinaryFormatter #43482

Open

Description

@GrabYourPitchforks

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 / StreamingContext infrastructure.
  • Cyclic or deeply-nested object graphs must not be constructed. This also disallows using the existing SerializationInfo / StreamingContext infrastructure.

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.

Activity

  1. svick commented on Sep 12, 2020

    @svick
    Member

    For those who don't know what some TLAs mean, like me, I think SDL refers to Microsoft Security Development Lifecycle.

  2. yaakov-h commented on Sep 12, 2020

    @yaakov-h
    Member

    The proper Exception-derived type will be instantiated after deserialization.

    What would happen in the case where the deserializing assembly/service/app/whatever does not know about or have access to the appropriate Exception subclass?

  3. GrabYourPitchforks commented on Sep 12, 2020

    @GrabYourPitchforks
    MemberAuthor

    What would happen in the case where the deserializing assembly/service/app/whatever does not know about or have access to the appropriate Exception subclass?

    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 Exception classes that might be instantiated. (This characteristic is true of any secure polymorphic deserialization technology; it's not unique to Exception and 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 requested Exception-derived type. There's no middle ground where the deserializer says "well, I found a Type that 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.

  4. AustinWise commented on Sep 13, 2020

    @AustinWise
    Contributor

    It would be nice if the new exposed something like .NET Framework's Exception.PreForRemoting method. That way exceptions could be rethrown while preserving the server-side stack trace.

  5. yaakov-h commented on Sep 14, 2020

    @yaakov-h
    Member

    That still relies on the Remoting infrastructure doing the serialization, and has been somewhat generalized with ExceptionDispatchInfo since .NET 4.5.

    Perhaps being able to serialize a ExceptionDispatchInfo would solve this problem?

  6. AustinWise commented on Sep 14, 2020

    @AustinWise
    Contributor

    @yaakov-h Thats a good point. EDI gets you most of the way there. All that PrepForRemoting adds is the extra markers in the stack trace that show a remoting boundary was crossed.

  7. eiriktsarpalis commented on Sep 14, 2020

    @eiriktsarpalis
    Member

    Speaking as a third party serializer author, my main issue with the existing design is that the Exception(Serialization, StreamingContext) constructor provides the only viable mechanism for unmarshalling an exception with all of its runtime metadata intact (Stacktrace, Data, etc.). Consequently, any serializer that needs to implement faithful exception deserialization needs to also support ISerializable. I would personally appreciate a serializer-independent mechanism that would let users augment a newly created exception instance with all necessary metadata, something like an ExceptionDispatchInfoBuilder.

    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 / StreamingContext infrastructure.

    Assuming the highly experimental abstract static interface methods ever gets adopted, one could conceive of a type safe and linker-friendly successor to SerializationInfo/StreamingContext constructors. This is largely how languages with type classes implement type-safe serialization.

  8. GrabYourPitchforks commented on Sep 14, 2020

    @GrabYourPitchforks
    MemberAuthor

    A 100% faithful reconstruction of the original Exception instance 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.

  9. olivier-spinelli commented on Sep 15, 2020

    @olivier-spinelli

    Fully aggree with the fact that an actual exception is not required. For years we used a simple stupid projection into a "Data" object (factory method is here; https://github.com/Invenietis/CK-Core/blob/master/CK.Core/CKExceptionData.cs#L143). This data is "as serializable as possible" and its only data.
    And the information captured appeared to be "good enough" for (as I said) numerous years.

  10. eiriktsarpalis commented on Sep 15, 2020

    @eiriktsarpalis
    Member

    A 100% faithful reconstruction of the original Exception instance 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.)

    Agreed, although that should be a design decision preferably made by the serializer implementation, rather than something forced by the underlying exception reconstruction mechanism.

  11. AArnott commented on Sep 19, 2020

    @AArnott
    Contributor

    I am surprised that the requirements in the description do not include a provision for dropping sensitive information from the exception so it's safe for remote parties with an Information Disclosure risk.

  12. GrabYourPitchforks commented on Sep 21, 2020

    @GrabYourPitchforks
    MemberAuthor

    @AArnott I don't think that's a viable requirement. In general it's a bad idea to send any object that contains privileged information through a serializer, as there's too high a risk that the sensitive information might be transmitted. This also runs the risk that for any given Exception object, sensitive information may or may not be disclosed depending on the exact Exception type, which isn't always under the dev's control. This makes the system very difficult to reason about from a security perspective.

    Any threat model of this serializer would absolutely include information disclosure as a threat. But I suspect the answer to that will be "this serializer is not intended for use in environments where the recipient is not trustworthy."

  13. transferred this issue fromdotnet/designson Oct 16, 2020
  14. Dotnet-GitSync-Bot commented on Oct 16, 2020

    @Dotnet-GitSync-Bot
    Collaborator

    I couldn't figure out the best area label to add to this issue. If you have write-permissions please help me learn by adding exactly one area label.

  15. added
    untriaged
    on Oct 16, 2020
  16. 46 remaining items

  17. KalleOlaviNiemitalo commented on Aug 15, 2024

    @KalleOlaviNiemitalo

    Because the deserialization constructor expects the entry for "Data" to be of a specific type, it will fail unless the SerializationInfo provider has already determined that "Data" should have been deserialized as that 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?

  18. eiriktsarpalis commented on Aug 15, 2024

    @eiriktsarpalis
    Member

    I think that might be possible, yes. Although I think it would still be challenging to support in AOT.

  19. AArnott commented on Aug 15, 2024

    @AArnott
    Contributor

    Because the deserialization constructor expects the entry for "Data" to be of a specific type, it will fail unless the SerializationInfo provider has already determined that "Data" should have been deserialized as that type. Since it is not possible to know ahead of time what types a particular deserialization constructor might require, this information needs to be incorporated in the payload itself

    I don't understand why this must be the case.
    Consider this part of your code:

    info.GetValue("Data", typeof(SomeOpaqueType));

    That right there provides the type that is expected to be deserialized. That isn't data-driven -- that's right there in compiled code. StreamJsonRpc can use that to deserialize "Data", allowing the cast to succeed.

    Can the provider implement a System.Runtime.Serialization.IFormatterConverter whose object Convert(object value, Type type) method converts from some other representation to SomeOpaqueType?

    Yes. That is exactly what StreamJsonRpc does. Essentially we defer deserialization of certain fragments until we know what type was expected -- not by the data but by the trusted code itself.

    As for AOT, yes this requires reflection (or at least some hints as to which types should be prepared for deserialization). AOT represents a very small portion of all .NET code, so while it's great that it's support is growing, I'm not sure we should throw out a system that gives us support to serialize nearly all exceptions for something that will only support a small subset of exceptions after changes are made to them in order to support AOT which is also a tiny subset.

    If we can agree that this ISerializable approach is adequate for exception serialization, we can move on to figuring out the best way to make this shine in AOT environments too.

  20. jkotas commented on Aug 15, 2024

    @jkotas
    Member

    If we can agree that this ISerializable approach is adequate for exception serialization,

    I do not think that ISerializable approach can be the base for safe exception serialization. You cannot make an assumption that BF deserialization constructor of every exception type out there is hardened for untrusted input. The problem exists even when the payload is limited to primitive types. You can have:

    int data = (int)info.GetValue("Data", typeof(int))!;
    if (data == 42)
    {
         hang or crash
    }
    

    Of course, the code is not going to be written like this, the actual logic would be more complicated, but the net effect can be the same.

  21. eiriktsarpalis commented on Aug 15, 2024

    @eiriktsarpalis
    Member

    I'm not sure we should throw out a system that gives us support to serialize nearly all exceptions for something that will only support a small subset of exceptions after changes are made to them in order to support AOT which is also a tiny subset.

    I don't think anybody proposed we remove ISerializable, it wouldn't be feasible given all the code that depends on it. The issue fundamentally is that ISerializable is insecure by design. Yes, the common risks can be mitigated by jumping through a lot of hoops but it's not something that you get in the path of least resistance, which is why I think we are correct to warn when those APIs are being used.

    If we can agree that this ISerializable approach is adequate for exception serialization, we can move on to figuring out the best way to make this shine in AOT environments too.

    Would it be possible to build some of the StreamJsonRpc mitigations into SerializationInfo directly? (either via a new constructor or some derived type?).

    The problem exists even when the payload is limited to primitive types. You can have:

    @jkotas sure, but doesn't this type of risk also exist in modern serializers? I can easily see the same type of problem occurring in a user-defined JsonConverter.

  22. AArnott commented on Aug 15, 2024

    @AArnott
    Contributor

    Of course, the code is not going to be written like this, the actual logic would be more complicated, but the net effect can be the same.

    Fair enough. But that isn't a BF-specific vulnerability at that point. It sounds like you're making the case that "all existing deserializers may have some bug somewhere that could be exploited, so we should rewrite all of them" but I see no reason to believe that any rewrite would be anything other than as-likely to have security bugs like what you suggest here.

    I don't think anybody proposed we remove ISerializable

    What I'm concerned about is not that the interface may be removed, but rather that exception types defined in .NET will stop implementing it, or start throwing from their implementations. And that future exception types defined will not support it. And that the guidance is for 3rd parties to stop implementing such interfaces and deserializing constructors. That will undermine the goodness that we have with StreamJsonRpc.

    The issue fundamentally is that ISerializable is insecure by design. Yes, the common risks can be mitigated by jumping through a lot of hoops but it's not something that you get in the path of least resistance,

    I still am not seeing this. I don't see that StreamJsonRpc jumped through a lot of hoops. We just implemented it cautiously. And it was a relatively small amount of code.
    If .NET's guidance was simply: implement your deserializing constructors carefully, considering the Context where necessary to assess trust level, I think we'd tap into a lot of value that is that nearly every Exception already does it, and does it right.

  23. jkotas commented on Aug 15, 2024

    @jkotas
    Member

    @jkotas sure, but doesn't this type of risk also exist in modern serializers?

    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.

    If .NET's guidance was simply: implement your deserializing constructors carefully, considering the Context where necessary to assess trust level, I think we'd tap into a lot of value that is that nearly every Exception already does it, and does it right.

    This guidance has been non-existent for ISerializable-based contracts. I do not think that it is acceptable to apply it retroactively.

    goodness that we have with StreamJsonRpc.

    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.

  24. eiriktsarpalis commented on Aug 16, 2024

    @eiriktsarpalis
    Member

    The issue fundamentally is that ISerializable is insecure by design. Yes, the common risks can be mitigated by jumping through a lot of hoops but it's not something that you get in the path of least resistance,

    I still am not seeing this. I don't see that StreamJsonRpc jumped through a lot of hoops. We just implemented it cautiously.

    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 FormatterConverter that 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.

    The scheme is probably acceptable for closed system like VS cross-process communication where actively malicious input is less of a concern.

    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.

  25. jkotas commented on Aug 16, 2024

    @jkotas
    Member
  26. eiriktsarpalis commented on Aug 17, 2024

    @eiriktsarpalis
    Member

    Sure, I'm just pointing out that these systems are designed to accept requests that execute remote code and that should factor into their threat modelling.

  27. jeffhandley commented on Oct 8, 2024

    @jeffhandley
    Member

    The documentation we create for this needs to also incorporate the questions and scenarios from #101159, which I just closed as a duplicate of this one.

  28. modified the milestones: 9.0.0, 10.0.0 on May 16, 2025
  29. modified the milestones: 10.0.0, Future on Jul 14, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area-System.Runtimebinaryformatter-migrationdocumentation

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions