首页 > 解决方案 > 从 DNS 接收答案是否需要 root/更高权限

问题描述

再会,

我不确定我应该把这个问题放在哪里,我正在学习 DNS 以及它是如何工作的,据我所知,我在 UDP 端口 53 上向服务器发送了一个请求,主机应该在该端口上响应我正确吗?

这是我正在使用的一个脚本,它可以工作并且准确地描述了 DNS 消息查询和使用,甚至可以为我返回一个 DNS 答案。

如果在系统上没有 root 就无法侦听端口 53,这怎么可能?

DNS 数据包详细信息

;DNS HEADER;
   ; AA AA - ID
   ; 01 00 - Query parameters
   ; 00 01 - Number of questions
   ; 00 00 - Number of answers
   ; 00 00 - Number of authority records
   ; 00 00 - Number of additional records
   ; DNS QUESTION --
   ; 07 - 'example' has length 7, ;so change this to be the length of domain ; keep in ming there are not '.' in the question.
   ; 65 - e
   ; 78 - x
   ; 61 - a
   ; 6D - m
   ; 70 - p
   ; 6C - l
   ; 65 - e

   ; 03 - subdomain '.com'  length 03  ; change this to be the length of type.

   ; 63 - c
   ; 6F - o
   ; 6D - m

代码 :

import binascii
import socket


def send_udp_message(message, address, port):
    """send_udp_message sends a message to UDP server

    message should be a hexadecimal encoded string
    """
    message = message.replace(" ", "").replace("\n", "")
    server_address = (address, port)

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        sock.sendto(binascii.unhexlify(message), server_address)
        data, _ = sock.recvfrom(4096)
    finally:
        sock.close()
    return binascii.hexlify(data).decode("utf-8")


def format_hex(hex):
    """format_hex returns a pretty version of a hex string"""
    octets = [hex[i:i+2] for i in range(0, len(hex), 2)]
    pairs = [" ".join(octets[i:i+2]) for i in range(0, len(octets), 2)]
    return "\n".join(pairs)


message = "AA AA 01 00 00 01 00 00 00 00 00 00 " \
"07 65 78 61 6d 70 6c 65 03 63 6f 6d 00 00 01 00 01"

response = send_udp_message(message, "8.8.8.8", 53)
print(format_hex(response))

回复:

aa aa
81 80
00 01
00 01
00 00
00 00
07 65
78 61
6d 70
6c 65
03 63
6f 6d
00 00
01 00
01 c0
0c 00
01 00
01 00
00 32
98 00
04 5d
b8 d8
22

如果您查看最后四个字节,您会发现这是 example.com 的 IP,十六进制5db8d822

你可以去这里看看。 十六进制到 IP 转换器在线

标签: pythonlinuxsocketsdns

解决方案


不,您的源端口不是端口 53。用户进程被分配了 1023 以上的出站端口号,这些端口号是非特权的。

一个简单的同步 Python DNS 客户端基本上会阻塞并保持相同的端口打开,直到服务器响应。您发送的 IP 数据包包含服务器需要的信息,以便知道在哪里回复(这是在 IP 数据包本身的标头中,在 DNS 查询有效负载之前)。


推荐阅读