LookupServer: Move case randomization into DNSName

* DNSName knows how to randomize itself
* DNSPacket no longer constructs DNSQuestion instances, it receives an already
  built DNSQuestion and just adds it to the list
* LookupServer::lookup() explicitly calls randomize_case() if it needs to
  randomize the case.
This commit is contained in:
Sergey Bugaev 2021-02-14 16:25:48 +03:00 committed by Andreas Kling
parent 89f718c4c5
commit bacbde31f3
Notes: sideshowbarker 2024-07-18 22:16:58 +09:00
5 changed files with 27 additions and 23 deletions

View File

@ -27,6 +27,7 @@
#include "DNSName.h"
#include <AK/Vector.h>
#include <ctype.h>
namespace LookupServer {
@ -77,6 +78,22 @@ size_t DNSName::serialized_size() const
return m_name.length() + 2;
}
void DNSName::randomize_case()
{
StringBuilder builder;
for (char c : m_name) {
// Randomize the 0x20 bit in every ASCII character.
if (isalpha(c)) {
if (arc4random_uniform(2))
c |= 0x20;
else
c &= ~0x20;
}
builder.append(c);
}
m_name = builder.to_string();
}
OutputStream& operator<<(OutputStream& stream, const DNSName& name)
{
auto parts = name.as_string().split_view('.');

View File

@ -41,6 +41,8 @@ public:
size_t serialized_size() const;
const String& as_string() const { return m_name; }
void randomize_case();
private:
String m_name;
};

View File

@ -37,29 +37,11 @@
namespace LookupServer {
void DNSPacket::add_question(const String& name, u16 record_type, ShouldRandomizeCase should_randomize_case)
void DNSPacket::add_question(const DNSQuestion& question)
{
m_questions.empend(question);
ASSERT(m_questions.size() <= UINT16_MAX);
if (name.is_empty())
return;
StringBuilder builder;
for (size_t i = 0; i < name.length(); ++i) {
u8 ch = name[i];
if (should_randomize_case == ShouldRandomizeCase::Yes) {
// Randomize the 0x20 bit in every ASCII character.
if (isalpha(ch)) {
if (arc4random_uniform(2))
ch |= 0x20;
else
ch &= ~0x20;
}
}
builder.append(ch);
}
m_questions.empend(builder.to_string(), record_type, (u16)C_IN);
}
ByteBuffer DNSPacket::to_byte_buffer() const

View File

@ -79,7 +79,7 @@ public:
return m_answers.size();
}
void add_question(const String& name, u16 record_type, ShouldRandomizeCase);
void add_question(const DNSQuestion&);
enum class Code : u8 {
NOERROR = 0,

View File

@ -172,7 +172,10 @@ Vector<String> LookupServer::lookup(const DNSName& name, const String& nameserve
DNSPacket request;
request.set_is_query();
request.set_id(arc4random_uniform(UINT16_MAX));
request.add_question(name.as_string(), record_type, should_randomize_case);
DNSName name_in_question = name;
if (should_randomize_case == ShouldRandomizeCase::Yes)
name_in_question.randomize_case();
request.add_question({ name_in_question, record_type, C_IN });
auto buffer = request.to_byte_buffer();