kk Blog —— 通用基础

date [-d @int|str] [+%s|"+%F %T"]

DNS示例

https://gist.github.com/fffaraz/9d9170b57791c28ccda9255b48315168

DNS 示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
// gcc dns.c -lpthread

#include <stdio.h>  //printf
#include <string.h> //strlen
#include <stdlib.h> //malloc
#include <sys/socket.h> //you know what this is for
#include <arpa/inet.h>  //inet_addr, inet_ntoa, ntohs etc
#include <netinet/in.h>
#include <unistd.h> //getpid
#include <pthread.h>
#include <time.h>

#define T_A   1   //IPv4 address
#define T_NS  2   //Nameserver
#define T_CNAME   5   // canonical name
#define T_SOA 6   /* start of authority zone */
#define T_PTR 12  /* domain name pointer */
#define T_MX  15  //Mail server
#define T_AAAA    28  // IPv6

#define NIPQUAD(addr) ((unsigned char *)addr)[0], ((unsigned char *)addr)[1], ((unsigned char *)addr)[2], ((unsigned char *)addr)[3]

//DNS header structure
struct DNS_HEADER
{
	unsigned short id;    // identification number

	unsigned char rd :1;  // recursion desired
	unsigned char tc :1;  // truncated message
	unsigned char aa :1;  // authoritive answer
	unsigned char opcode :4;  // purpose of message
	unsigned char qr :1;  // query/response flag

	unsigned char rcode :4;   // response code
	unsigned char cd :1;  // checking disabled
	unsigned char ad :1;  // authenticated data
	unsigned char z :1;   // its z! reserved
	unsigned char ra :1;  // recursion available

	unsigned short q_count;   // number of question entries
	unsigned short ans_count; // number of answer entries
	unsigned short auth_count;    // number of authority entries
	unsigned short add_count; // number of resource entries
};

//Constant sized fields of query structure
struct QUESTION
{
	unsigned short qtype;
	unsigned short qclass;
};

//Constant sized fields of the resource record structure
#pragma pack(push, 1)
struct R_DATA
{
	unsigned short type;
	unsigned short _class;
	unsigned int ttl;
	unsigned short data_len;
};
#pragma pack(pop)

//Pointers to resource record contents
struct RES_RECORD
{
	unsigned char *name;
	struct R_DATA *resource;
	unsigned char *rdata;
};

//Structure of a Query
typedef struct
{
	unsigned char *name;
	struct QUESTION *ques;
} QUERY;

// convert www.google.com to 3www6google3com
void ChangetoDnsNameFormat(unsigned char* dns, unsigned char* host)
{
	int lock = 0, i;
	for (i = 0; i <= strlen(host); i ++) {
		if (host[i] == '.' || host[i] == '\0') {
			*dns++ = i - lock;
			for( ; lock < i; lock ++)
				*dns++ = host[lock];
			lock ++;
		}
	}
	*dns++ = '\0';
}

// convert 3www6google3com0 to www.google.com
void changeToHost(unsigned char *dns)
{
	int i = 0, j = 0, p;

	while (i < 100 && dns[i] && dns[i] < 100) {
		p = dns[i];
		i = i + p + 1;
		while (p --) {
			dns[j] = dns[j+1];
			j ++;
		}
		dns[j++] = '.';
	}
	dns[j-1] = '\0'; //remove the last dot
}

int readName(unsigned char *reader, unsigned char *buffer, unsigned char *to, unsigned char *end)
{
	unsigned char *start = reader;
	unsigned int p = 0, step = 1, offset, count = 0;
	int i, j;

	//read the names in 3www6google3com format

	while (*reader != 0) {
		if (*reader >= 0xc0) {
			offset = (*reader)*256 + *(reader+1) - 0xc000; //49152 = 11000000 00000000
			reader = buffer + offset;
			step = 0;
		} else {
			to[p++] = *reader ++;
			count += step;
		}
		if (reader > end)
			goto err;
	}
	to[p] = '\0';
	count += (step == 0) ? 2 : 1;

	if (start + count > end)
		goto err;

	changeToHost(to);

	return count;
err:
	return 1000000;
}

/*
 * sending a packet
 */
void sendPacket(int fd, struct sockaddr_in *dest, unsigned char *host, int query_type)
{
	unsigned char buf[65536], *qname, *reader;
	int i, j;

	struct DNS_HEADER *dns = NULL;
	struct QUESTION *qinfo = NULL;

	//Set the DNS structure to standard queries
	dns = (struct DNS_HEADER *)&buf;

	dns->id = htons(getpid());
	dns->qr = 0; //This is a query
	dns->opcode = 0; //This is a standard query
	dns->aa = 0; //Not Authoritative
	dns->tc = 0; //This message is not truncated
	dns->rd = 1; //Recursion Desired
	dns->ra = 0; //Recursion not available! hey we dont have it (lol)
	dns->z = 0;
	dns->ad = 0;
	dns->cd = 0;
	dns->rcode = 0;
	dns->q_count = htons(1); //we have only 1 question
	dns->ans_count = 0;
	dns->auth_count = 0;
	dns->add_count = 0;

	//point to the query portion
	qname = &buf[sizeof(struct DNS_HEADER)];

	ChangetoDnsNameFormat(qname, host);
	qinfo = (struct QUESTION*)&buf[sizeof(struct DNS_HEADER) + (strlen(qname) + 1)]; //fill it

	qinfo->qtype = htons(query_type); //type of the query, A, MX, CNAME, NS etc
	qinfo->qclass = htons(1); //its internet (lol)

	if (sendto(fd, buf, sizeof(struct DNS_HEADER) + (strlen(qname) + 1) + sizeof(struct QUESTION), 0, (struct sockaddr*)dest, sizeof(*dest)) < 0) {
		perror("sendto failed");
	}
	printf("send Done\n");
	return;
}

int expBuf(char buf[], int len)
{
	unsigned char *end = buf + len;

	struct DNS_HEADER *dns = NULL;
	struct QUESTION *qinfo = NULL;
	struct R_DATA *resource;

	unsigned char *qname, *reader;

	char name[256];
	char rdata[256];
	int i, j;

	if (len < sizeof(struct DNS_HEADER))
		goto err;

	dns = (struct DNS_HEADER*) buf;

	printf("The response contains:\n");
	printf("%d Questions.\n", ntohs(dns->q_count));
	printf("%d Answers.\n", ntohs(dns->ans_count));
	printf("%d Authoritative Servers.\n", ntohs(dns->auth_count));
	printf("%d Additional records.\n\n", ntohs(dns->add_count));
	
	//move ahead of the dns header and the query field
	//reader = &buf[sizeof(struct DNS_HEADER) + (strlen((const char*)qname) + 1) + sizeof(struct QUESTION)];
	reader = &buf[sizeof(struct DNS_HEADER)];

	//Start reading answers
	printf("Questions Records: %d\n", ntohs(dns->q_count));
	for (i = 0; i < ntohs(dns->q_count); i ++) {
		reader += readName(reader, buf, name, end);
		qinfo = (struct QUESTION *)reader;
		reader = reader + sizeof(struct QUESTION);
		if (reader > end)
			goto err;

		printf("Name: %s Type: %d\n", name, ntohs(qinfo->qtype));
	}
	printf("\n");

	printf("Answer Records: %d\n", ntohs(dns->ans_count));
	for (i = 0; i < ntohs(dns->ans_count); i++) {
		reader += readName(reader, buf, name, end);
		resource = (struct R_DATA*)(reader);
		reader = reader + sizeof(struct R_DATA);
		if (reader > end)
			goto err;

		printf("Name: %s Type: %d ", name, ntohs(resource->type));

		if (ntohs(resource->type) == T_A || ntohs(resource->type) == T_AAAA) { //if its an ipv4 address
			if (reader + ntohs(resource->data_len) > end)
				goto err;
			printf("IPv4: %d.%d.%d.%d", NIPQUAD(reader));
			reader = reader + ntohs(resource->data_len);
		} else {
			reader += readName(reader, buf, rdata, end);
			if (reader > end)
				goto err;
			if (ntohs(resource->type) == T_CNAME)
				printf("CNAME: %s", rdata);
		}
		printf("\n");
	}
	printf("\n");

	//read authorities
	printf("Authoritive Records: %d\n", ntohs(dns->auth_count));
	for(i = 0; i < ntohs(dns->auth_count); i++) {
		reader += readName(reader, buf, name, end);
		resource = (struct R_DATA*)(reader);
		reader += sizeof(struct R_DATA);
		if (reader > end)
			goto err;

		reader += readName(reader, buf, rdata, end);
		if (reader > end)
			goto err;

		printf("Name: %s Type: %d ", name, ntohs(resource->type));

		if (ntohs(resource->type) == T_NS) {
			printf("nameserver: %s", rdata);
		}
		printf("\n");
	}
	printf("\n");

	//read additional
	printf("Additional Records: %d\n", ntohs(dns->add_count));
	for(i = 0; i < ntohs(dns->add_count); i++) {
		reader += readName(reader, buf, name, end);
		resource = (struct R_DATA*)(reader);
		reader += sizeof(struct R_DATA);
		if (reader > end)
			goto err;

		printf("Name: %s Type: %d ", name, ntohs(resource->type));

		if (ntohs(resource->type) == T_A || ntohs(resource->type) == T_AAAA) {
			if (reader + ntohs(resource->data_len) > end)
				goto err;
			printf("IPv4: %d.%d.%d.%d", NIPQUAD(reader));
			reader = reader + ntohs(resource->data_len);
		} else {
			reader += readName(reader, buf, rdata, end);
			if (reader > end)
				goto err;
		}
		printf("\n");
	}
	printf("\n\n");
	return 0;
err:
	printf("\n\n");
	return -1;
}

void *recvPacket(void *arg)
{
	int fd = *((int *)arg);
	struct sockaddr_in dest;
	unsigned char buf[65536];
	int s, len;

	while (1) {
		//Receive the answer
		s = sizeof(dest);
		if ((len = recvfrom(fd, buf, 65536, 0, (struct sockaddr*)&dest, (socklen_t*)&s)) < 0) {
			perror("recvfrom failed");
		}
		printf("recv Done. len=%d\n", len);
		if (expBuf(buf, len)) {
			printf("exp err\n");
		}
	}
}

/*
 * Get the DNS servers from /etc/resolv.conf file on Linux
 */
void get_dns_servers(char dns_servers[])
{
	FILE *fp;
	char line[200], *p;
	if ((fp = fopen("/etc/resolv.conf", "r")) == NULL) {
		printf("Failed opening /etc/resolv.conf file \n");
	}

	while (fgets(line, 200, fp)) {
		if (line[0] == '#') {
			continue;
		}
		if (strncmp(line, "nameserver", 10) == 0) {
			p = strtok(line, " ");
			p = strtok(NULL, " ");

			//p now is the dns ip :)
			//????
		}
	}

	strcpy(dns_servers, "127.0.1.1");
}

int main(int argc, char *argv[])
{
	int fd;
	struct sockaddr_in dest;
	unsigned char hostname[100];
	pthread_t tid;

	char dns_servers[100];

	//Get the DNS servers from the resolv.conf file
	get_dns_servers(dns_servers);

	dest.sin_family = AF_INET;
	dest.sin_port = htons(53);
	dest.sin_addr.s_addr = inet_addr(dns_servers);

	fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

	if (pthread_create(&tid, NULL, recvPacket, (void *)&fd)) {
		printf("pthread err\n");
		exit(-1);
	}

	while (1) {
		printf("Enter Hostname to Lookup: ");
		scanf("%s", hostname);
		sendPacket(fd, &dest, hostname, T_A);
		usleep(500000);
	}

	pthread_join(tid, NULL);
	return 0;
}