From cf7105aa2aae90d6656088fe5a8ee1d5730773b6 Mon Sep 17 00:00:00 2001 From: Daniel Joos Date: Wed, 24 Nov 2021 13:29:48 +0100 Subject: [PATCH] Using a crypto random number generator in `Request` (#88) * Using a crypto random number generator in `Request` This changes `Request` to use cryptographically secure random numbers. It prevents possible spoofing of DNS responses. * Fix style Co-authored-by: Mirza Kapetanovic --- DNS/Protocol/Request.cs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/DNS/Protocol/Request.cs b/DNS/Protocol/Request.cs index 86661b8..9bdf8b7 100644 --- a/DNS/Protocol/Request.cs +++ b/DNS/Protocol/Request.cs @@ -1,12 +1,13 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Security.Cryptography; using DNS.Protocol.Utils; using DNS.Protocol.ResourceRecords; namespace DNS.Protocol { public class Request : IRequest { - private static readonly Random RANDOM = new Random(); + private static readonly RandomNumberGenerator RANDOM = new RNGCryptoServiceProvider(); private IList questions; private Header header; @@ -41,7 +42,7 @@ public Request() { this.header.OperationCode = OperationCode.Query; this.header.Response = false; - this.header.Id = RANDOM.Next(UInt16.MaxValue); + this.header.Id = NextRandomId(); } public Request(IRequest request) { @@ -112,5 +113,11 @@ private void UpdateHeader() { header.QuestionCount = questions.Count; header.AdditionalRecordCount = additional.Count; } + + private ushort NextRandomId() { + byte[] buffer = new byte[sizeof(ushort)]; + RANDOM.GetBytes(buffer); + return BitConverter.ToUInt16(buffer, 0); + } } }