Usman Altaf
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- title: 'DNS QUERY CLIENT' disqus: hackmd --- Writing your own DNS Query Client === ## Table of Contents [TOC] Over the summer, I had the opportunity to intern at Carbonteq. The assignment was to understand the DNS protocol and the implementation of its client side. I didn't know anything at first, but with research and guidance, I began to understand the logic and operation of the DNS client. Along with this, I began learning about various techniques, principles, and practices that assisted us in writing code that was easier to read, test, debug, and extend. The experience was enjoyable because I learned a lot. You may be wondering what a DNS client is, I got you covered. ## What is a DNS Query Client When a browser/machine/actor needs to resolve a host name into its IP address, it sends a request packet to the DNS server, which returns the IP address of the remote host as a response packet. ![](https://i.imgur.com/Aywzwsy.jpg) ## DNS Packet Structure DNS is quite convenient in the sense that requests and responses use almost the same format. Each message consists of a header section and four other sections: question, answer, authority, and an additional section. | Section | Size | |:---------- | -------- | | Header | 12 Bytes | | Question | Variable | | Answer | Variable | | Authority | Variable | | Additional | Variable | ### DNS Header --- ![](https://i.imgur.com/oC03GNy.png) **ID** : A 16 bit identifier that generates randomly. ID remains the same when the response packet arrives. **QR** : A 1 bit flag i.e. 0 for queries, 1 for responses. **OPCODE** : A 1 bit flag that is typically set to 0 for which represents a *standard query*. **AA** : A 1 bit flag only meaningful in responses, and specifies whether the responding name server owns the queried domain or not. **TC** : A 1 bit flag specifying if the message has been truncated. Our message was short i.e. limited to 512 bytes , and won’t need to be truncated, so we can set this to 0. **RD** : A 1 bit flag specifying if recursion is desired. If the DNS server doesn’t know the answer to our query, it can recursively ask other DNS servers. In our project we set the recursion to 1.Recursive query support is optional. **RA** : A 1 bit flag specifying whether the recursive query support is available in the [Name Server](https://en.wikipedia.org/wiki/Name_server) or not. 1 for available 0 for not available. **Z** : A 3 bit flag reserved for the later use. **RCODE** : A 4 bit flag is set as part of responses.The values and there interpretation is given below. | Value | Interpretation | | ----- | ------------------ | | 0 | No error condition | | 1 | Format error | | 2 | Server failure | | 3 | Name Error | | 4 | Not Implemented | | 5 | Refused | **QDCOUNT** : A 16 bit integer simply specifying the number of entries in the question section. **ANCOUNT** : A 16 bit integer specifying the number of answers in the answer section. Initially this field is set to 0 in the request packet. In the response packet this may change depending upon the number of responses. **NSCOUNT** : A 16 bit integer specifying the number of entries in the Authority Section **ARCOUNT** : 16 bit integer specifying the number of entries in the Additional Section ### DNS Questions --- ![](https://i.imgur.com/mbLwv2u.png) **QNAME** : This contains the hostname who’s IP address we wish to find. It is encoded as a series of ‘labels’ i.e. a Label Sequence terminated by a null byte. Each label corresponds to a section of the hostname preceded by it's length as 1-byte integer.E.g "www.google.com" contains 3 sections.The first one will be www => ==03 77 77 77== , with the first byte 03 specifying the length of this section, an the rest being the encoded ascii representation of each character in www. Similarly, google would be encoded as ==06 67 6f 6f 67 6c 65== and com as ==03 63 6f 6d==. The whole encoded hostname would therefore be ==03 77 77 77 06 67 6f 6f 67 6c 65 03 63 6f 6d 00==. The last byte here is the null byte representing the end of this Label Sequence. **QTYPE** : A 2 byte code which specifies the type of the query. **QCLASS** : A 2 byte code that specifies the class of the query. For example, the QCLASS field is almost always set to 1 i.e. IN for the Internet. ### DNS Answers --- ![](https://i.imgur.com/F257GLK.png) **NAME** : The domain name that was queried. **TYPE** : A 2 byte field containing one of the Query Type codes. **CLASS** : A 2 byte field which specifies the class of the data in the RDATA field. **TTL** : A 4 byte filed that represent the number of seconds the results can be cached. **RDLENGTH** :A 2 byte field representing the length of the record type specific data. **RDATA** : The data of the response. The format is dependent on the TYPE field: if the TYPE is for A records, then this is the IP address (4 bytes). ## Implementation After plenty of research and understanding we finally dove right into the implementation.The primary task was to pack and parse the DNS packets. ### Goals The primary goal of the implementation was to pack DNS query packet in a proper manner as investigated in the DNS protocol.Send it over to the socket. And finally parse the response after receiving it from the socket. Create proper abstractions in order to make the code simple and easy to understand. We may not use any external library. In order to achieve the above goals we created a package. It enables us to construct the DNS packet using a single call (==DNSQuery.ipv4('google.com')==) and then parse the response packet using multiple calls one for each section i.e. header, question and answer. You may iterate over the question and answer call depending upon the number of questions and the number of answers. The modules we used were [Node:Buffer](https://nodejs.org/api/buffer.html) for packing and parsing, and [Node:Dgram](https://nodejs.org/api/dgram.html) for creating socket. ### DNS Parsing and Packing --- #### Creating a Buffer We created our own wrapper class around the Node:Buffer which provides us with some extra functionality required for our project along with adding another level of abstraction. ~~~typescript import { Buffer } from 'node:buffer'; export class DNSBuffer { private _offset: number; private _data: Buffer; constructor(capacity = 512) { this._offset = 0; this._data = Buffer.alloc(capacity); } ~~~ #### Parsing a DNS Query: Since the response from the socket is also a DNSBuffer which also contains bytes data so we now have to convert it back into desired data type. ~~~typescript readByte(): number { const val = this._data.readUint8(this._offset); this._offset++; return val; } readShort(): number { const val = this._data.readUint16BE(this._offset); this._offset += 2; return val; } readInt4(): number { const val = this._data.readUint32BE(this._offset); this._offset += 4; return val; } readString(string_length: number): string { const str = this._data .subarray(this.offset, this.offset + string_length) .toString(); this._offset += string_length; return str; } ~~~ #### Packing a DNS Query: We packed the data into the DNSBuffer which was then sent over to the DNS server through a socket. ##### Writing to a Buffer ~~~typescript writeStr(str: string) { this._data.write(str, this._offset); this._offset += str.length; } writeByte(val: number) { // todo: check if val is byte this._data.writeUInt8(val, this._offset); this._offset++; } writeShort(val: number) { //write this._data.writeUInt16BE(val, this._offset); this._offset += 2; } writeInt4(val: number) { //write this._data.writeUint32BE(val); this._offset += 4; } ~~~ ## Scope Our Client works for A type and CNAME type queries. ## Our Learning Outcomes ### Technical: 1. Understanding of the DNS protocol. 2. What actually is a DNS client and what does it do. 3. The detailed working of a DNS client. 4. The structure of the requests and responses. 5. Types of requests i.e. A,AAAA,CNAME etc. 6. Bit Masking. 7. The packing of the requests and the parsing of their responses which we did using node "Buffer". One important thing to keep in consideration here is that the packing and parsing must be done in "network byte order" i.e. Network Endian because the TCP/IP Internet protocol also uses big endian/network endian regardless of the hardware at either end. 8. Debugging and running unit tests. 9. Best Practices and principles which make your code simple, readable and easier to understand, test, debug and extend. 10. Version control using git. ### Non-Technical: 1. Team work 2. Work ethics 3. Meeting deadlines 4. Doing efficient research 5. Resource utilization # Conclusion It was quiet a wonderful experience. Working through the DNS client and getting to know how it works was very interesting. Without a doubt implementing it was even more interesting. Assuredly we can say that our days were productive. You can find our project at GitHub. https://github.com/usman7384/typescript-dns-client

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully