Skip to content

Commit

Permalink
Remove HasPadding check (#190)
Browse files Browse the repository at this point in the history
Rely on paylod size in encrypted payload
  • Loading branch information
ShortDevelopment authored Jan 26, 2025
1 parent 7e81980 commit 5f08569
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 21 deletions.
22 changes: 2 additions & 20 deletions lib/ShortDev.Microsoft.ConnectedDevices/Encryption/CdpCryptor.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using ShortDev.Microsoft.ConnectedDevices.Exceptions;
using ShortDev.Microsoft.ConnectedDevices.Messages;
using ShortDev.Microsoft.ConnectedDevices.Transports;
using System.Buffers;
using System.Buffers.Binary;
using System.Diagnostics;
using System.Security.Cryptography;
Expand Down Expand Up @@ -59,10 +58,8 @@ public ReadOnlyMemory<byte> DecryptMessage(CommonHeader header, ReadOnlySpan<byt

byte[] decryptedPayload = _aes.DecryptCbc(payload, iv, PaddingMode.None);

if (HasPadding(decryptedPayload, out var paddingSize))
return decryptedPayload.AsMemory()[0..^paddingSize];

return decryptedPayload;
var payloadSize = BinaryPrimitives.ReadUInt32BigEndian(decryptedPayload.AsSpan()[..sizeof(uint)]);
return decryptedPayload.AsMemory(sizeof(uint), (int)payloadSize);
}

void VerifyHMac(CommonHeader header, ReadOnlySpan<byte> payload, ReadOnlySpan<byte> hmac)
Expand Down Expand Up @@ -157,10 +154,6 @@ public void Read(ref EndianReader reader, CommonHeader header)

var decryptedPayload = DecryptMessage(header, encryptedPayload, hmac);
reader = new(Endianness.BigEndian, decryptedPayload.Span);

var payloadLength = reader.ReadUInt32();
if (payloadLength != decryptedPayload.Length - sizeof(Int32))
throw new CdpSecurityException($"Expected payload to be {payloadLength} bytes long");
}

public void Dispose()
Expand All @@ -169,15 +162,4 @@ public void Dispose()
_aes.Dispose();
_hmac.Dispose();
}

static bool HasPadding(ReadOnlySpan<byte> buffer, out byte paddingSize)
{
paddingSize = buffer[^1];
for (int i = buffer.Length - paddingSize; i < buffer.Length; i++)
{
if (paddingSize != buffer[i])
return false;
}
return true;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public void Decrypt_ShouldYieldSameAsEncrypt()

var decrypted = cryptor.DecryptMessage(header, encryptedPayload, hmac).Span;

Assert.True(payload.SequenceEqual(decrypted[sizeof(uint)..]));
Assert.True(payload.SequenceEqual(decrypted));
}

sealed class FragmentSenderSpy : IFragmentSender
Expand Down

0 comments on commit 5f08569

Please sign in to comment.