Security and stability issues around BitConverter.Int64BitsToDouble in C #

I am writing a custom deserialization system for packetizing data over a network, and serialization doubles as follows:

private static string EncodeDouble(double raw) { long value = BitConverter.DoubleToInt64Bits(raw); return EncodeInteger(value); } 

The EncodeInteger function simply turns an integer into a marked string, so the deserialization code knows that it received the correct data type.

On the other hand, I am deserializing the following:

 private static double DecodeDouble(string raw) { long value = DecodeInteger<long>(raw); return BitConverter.Int64BitsToDouble(value); } 

Again, DecodeInteger simply removes the tag and checks that the value is within the range for a long time, and then moves on to the length. This is safe, because if something goes wrong, it will just throw an exception.

The reason for my concern is that after going to the original source, I see this direct dangerous action:

 public static unsafe double Int64BitsToDouble(long value) { return *((double *)&value); } 

The problem that I foresee is that the long value can be arbitrarily changed as it moves across the network. I was not worried that the value was changed arbitrarily, but rather the chance that the CLR would run into problems if an invalid double base view was sent.

I'm not sure if there are potential long values ​​that do not map to a valid double , but if so, what will I probably see? Failure in the CLR, resulting in a denial of service? Or is there an exception that can be caught?

+4
source share
1 answer

AFAIK there are no "invalid" values; just meanings that you did not initially think. So you, you have nothing to worry about in terms of denial of service. Please note that, on the contrary, decimal may have invalid binary representations - they just throw an exception, and one call will fail - it still doesn’t be a denial of service (just: they will see a failure).

Personally, however, I would advise that encoding double as long and then string probably makes it a difficult / inefficient way. If you desperately need it as a string , consider base-64 instead.

+2
source

Source: https://habr.com/ru/post/1501067/


All Articles