Skip to content

Commit

Permalink
Using a crypto random number generator in Request (#88)
Browse files Browse the repository at this point in the history
* 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 <[email protected]>
  • Loading branch information
danieljoos and kapetan authored Nov 24, 2021
1 parent 6cb35e4 commit cf7105a
Showing 1 changed file with 9 additions and 2 deletions.
11 changes: 9 additions & 2 deletions DNS/Protocol/Request.cs
Original file line number Diff line number Diff line change
@@ -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<Question> questions;
private Header header;
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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);
}
}
}

0 comments on commit cf7105a

Please sign in to comment.