25873c2bf4c8a6e7c45a6e11667ee687817d3be6
[ira/wip.git] / source4 / dns_server / dns_server.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    DNS server startup
5
6    Copyright (C) 2010 Kai Blin  <kai@samba.org>
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "includes.h"
23 #include "smbd/service_task.h"
24 #include "smbd/service.h"
25 #include "smbd/service_stream.h"
26 #include "smbd/process_model.h"
27 #include "lib/events/events.h"
28 #include "lib/socket/socket.h"
29 #include "lib/tsocket/tsocket.h"
30 #include "libcli/util/tstream.h"
31 #include "libcli/util/ntstatus.h"
32 #include "system/network.h"
33 #include "lib/stream/packet.h"
34 #include "lib/socket/netif.h"
35 #include "dns_server/dns_server.h"
36 #include "param/param.h"
37 #include "librpc/ndr/libndr.h"
38 #include "librpc/gen_ndr/ndr_dns.h"
39 #include "librpc/gen_ndr/ndr_dnsp.h"
40 #include <ldb.h>
41 #include "dsdb/samdb/samdb.h"
42 #include "dsdb/common/util.h"
43 #include "auth/session.h"
44 #include "lib/util/dlinklist.h"
45
46 NTSTATUS server_service_dns_init(void);
47
48 /* hold information about one dns socket */
49 struct dns_socket {
50         struct dns_server *dns;
51         struct tsocket_address *local_address;
52 };
53
54 struct dns_udp_socket {
55         struct dns_socket *dns_socket;
56         struct tdgram_context *dgram;
57         struct tevent_queue *send_queue;
58 };
59
60 /*
61   state of an open tcp connection
62 */
63 struct dns_tcp_connection {
64         /* stream connection we belong to */
65         struct stream_connection *conn;
66
67         /* the dns_server the connection belongs to */
68         struct dns_socket *dns_socket;
69
70         struct tstream_context *tstream;
71
72         struct tevent_queue *send_queue;
73 };
74
75 static void dns_tcp_terminate_connection(struct dns_tcp_connection *dnsconn, const char *reason)
76 {
77         stream_terminate_connection(dnsconn->conn, reason);
78 }
79
80 static void dns_tcp_recv(struct stream_connection *conn, uint16_t flags)
81 {
82         struct dns_tcp_connection *dnsconn = talloc_get_type(conn->private_data,
83                                                              struct dns_tcp_connection);
84         /* this should never be triggered! */
85         dns_tcp_terminate_connection(dnsconn, "dns_tcp_recv: called");
86 }
87
88 static void dns_tcp_send(struct stream_connection *conn, uint16_t flags)
89 {
90         struct dns_tcp_connection *dnsconn = talloc_get_type(conn->private_data,
91                                                              struct dns_tcp_connection);
92         /* this should never be triggered! */
93         dns_tcp_terminate_connection(dnsconn, "dns_tcp_send: called");
94 }
95
96 static NTSTATUS dns_process(struct dns_server *dns,
97                             TALLOC_CTX *mem_ctx,
98                             DATA_BLOB *in,
99                             DATA_BLOB *out)
100 {
101         enum ndr_err_code ndr_err;
102         WERROR ret;
103         struct dns_name_packet *in_packet;
104         struct dns_name_packet *out_packet;
105         struct dns_res_rec *answers = NULL, *nsrecs = NULL, *additional = NULL;
106         uint16_t num_answers = 0 , num_nsrecs = 0, num_additional = 0;
107
108         if (in->length < 12) {
109                 return NT_STATUS_INVALID_PARAMETER;
110         }
111
112         in_packet = talloc_zero(mem_ctx, struct dns_name_packet);
113         /* TODO: We don't really need an out_packet. */
114         out_packet = talloc_zero(mem_ctx, struct dns_name_packet);
115
116         if (in_packet == NULL) return NT_STATUS_NO_MEMORY;
117         if (out_packet == NULL) return NT_STATUS_NO_MEMORY;
118
119         dump_data(2, in->data, in->length);
120
121         ndr_err = ndr_pull_struct_blob(in, in_packet, in_packet,
122                         (ndr_pull_flags_fn_t)ndr_pull_dns_name_packet);
123         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
124                 TALLOC_FREE(in_packet);
125                 DEBUG(0, ("Failed to parse packet %d!\n", ndr_err));
126                 *out = *in;
127
128                 out->data[2] |= 0x80; /* Toggle DNS_FLAG_REPLY */
129                 out->data[3] |= DNS_RCODE_FORMERR;
130
131                 return NT_STATUS_OK;
132         }
133         if (DEBUGLVL(2)) {
134                 NDR_PRINT_DEBUG(dns_name_packet, in_packet);
135         }
136         *out_packet = *in_packet;
137         out_packet->operation |= DNS_FLAG_REPLY;
138
139         switch (in_packet->operation & DNS_OPCODE) {
140         case DNS_OPCODE_QUERY:
141
142                 ret = dns_server_process_query(dns, out_packet, in_packet,
143                                                &answers, &num_answers,
144                                                &nsrecs,  &num_nsrecs,
145                                                &additional, &num_additional);
146
147                 break;
148         case DNS_OPCODE_UPDATE:
149                 ret = dns_server_process_update(dns, out_packet, in_packet,
150                                                 &answers, &num_answers,
151                                                 &nsrecs,  &num_nsrecs,
152                                                 &additional, &num_additional);
153                 break;
154         default:
155                 ret = WERR_DNS_ERROR_RCODE_NOT_IMPLEMENTED;
156                 break;
157         }
158
159         if (W_ERROR_IS_OK(ret)) {
160                 out_packet->ancount = num_answers;
161                 out_packet->answers = answers;
162
163                 out_packet->nscount = num_nsrecs;
164                 out_packet->nsrecs  = nsrecs;
165
166                 out_packet->arcount = num_additional;
167                 out_packet->additional = additional;
168         } else {
169                 out_packet->operation |= werr_to_dns_err(ret);
170         }
171
172         if (DEBUGLVL(2)) {
173                 NDR_PRINT_DEBUG(dns_name_packet, out_packet);
174         }
175         ndr_err = ndr_push_struct_blob(out, out_packet, out_packet,
176                         (ndr_push_flags_fn_t)ndr_push_dns_name_packet);
177         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
178                 TALLOC_FREE(in_packet);
179                 TALLOC_FREE(out_packet);
180                 DEBUG(0, ("Failed to push packet %d!\n", ndr_err));
181                 *out = *in;
182
183                 out->data[2] |= 0x80; /* Toggle DNS_FLAG_REPLY */
184                 out->data[3] |= DNS_RCODE_SERVFAIL;
185
186                 return NT_STATUS_OK;
187         }
188
189         dump_data(2, out->data, out->length);
190         return NT_STATUS_OK;
191 }
192
193 struct dns_tcp_call {
194         struct dns_tcp_connection *dns_conn;
195         DATA_BLOB in;
196         DATA_BLOB out;
197         uint8_t out_hdr[4];
198         struct iovec out_iov[2];
199 };
200
201 static void dns_tcp_call_writev_done(struct tevent_req *subreq);
202
203 static void dns_tcp_call_loop(struct tevent_req *subreq)
204 {
205         struct dns_tcp_connection *dns_conn = tevent_req_callback_data(subreq,
206                                       struct dns_tcp_connection);
207         struct dns_tcp_call *call;
208         NTSTATUS status;
209
210         call = talloc(dns_conn, struct dns_tcp_call);
211         if (call == NULL) {
212                 dns_tcp_terminate_connection(dns_conn, "dns_tcp_call_loop: "
213                                 "no memory for dns_tcp_call");
214                 return;
215         }
216         call->dns_conn = dns_conn;
217
218         status = tstream_read_pdu_blob_recv(subreq,
219                                             call,
220                                             &call->in);
221         TALLOC_FREE(subreq);
222         if (!NT_STATUS_IS_OK(status)) {
223                 const char *reason;
224
225                 reason = talloc_asprintf(call, "dns_tcp_call_loop: "
226                                          "tstream_read_pdu_blob_recv() - %s",
227                                          nt_errstr(status));
228                 if (!reason) {
229                         reason = nt_errstr(status);
230                 }
231
232                 dns_tcp_terminate_connection(dns_conn, reason);
233                 return;
234         }
235
236         DEBUG(10,("Received krb5 TCP packet of length %lu from %s\n",
237                  (long) call->in.length,
238                  tsocket_address_string(dns_conn->conn->remote_address, call)));
239
240         /* skip length header */
241         call->in.data += 4;
242         call->in.length -= 4;
243
244         /* Call dns */
245         status = dns_process(dns_conn->dns_socket->dns, call, &call->in, &call->out);
246         if (!NT_STATUS_IS_OK(status)) {
247                 DEBUG(0, ("dns_process returned %s\n", nt_errstr(status)));
248                 dns_tcp_terminate_connection(dns_conn,
249                                 "dns_tcp_call_loop: process function failed");
250                 return;
251         }
252
253         /* First add the length of the out buffer */
254         RSIVAL(call->out_hdr, 0, call->out.length);
255         call->out_iov[0].iov_base = (char *) call->out_hdr;
256         call->out_iov[0].iov_len = 4;
257
258         call->out_iov[1].iov_base = (char *) call->out.data;
259         call->out_iov[1].iov_len = call->out.length;
260
261         subreq = tstream_writev_queue_send(call,
262                                            dns_conn->conn->event.ctx,
263                                            dns_conn->tstream,
264                                            dns_conn->send_queue,
265                                            call->out_iov, 2);
266         if (subreq == NULL) {
267                 dns_tcp_terminate_connection(dns_conn, "dns_tcp_call_loop: "
268                                 "no memory for tstream_writev_queue_send");
269                 return;
270         }
271         tevent_req_set_callback(subreq, dns_tcp_call_writev_done, call);
272
273         /*
274          * The krb5 tcp pdu's has the length as 4 byte (initial_read_size),
275          * packet_full_request_u32 provides the pdu length then.
276          */
277         subreq = tstream_read_pdu_blob_send(dns_conn,
278                                             dns_conn->conn->event.ctx,
279                                             dns_conn->tstream,
280                                             4, /* initial_read_size */
281                                             packet_full_request_u32,
282                                             dns_conn);
283         if (subreq == NULL) {
284                 dns_tcp_terminate_connection(dns_conn, "dns_tcp_call_loop: "
285                                 "no memory for tstream_read_pdu_blob_send");
286                 return;
287         }
288         tevent_req_set_callback(subreq, dns_tcp_call_loop, dns_conn);
289 }
290
291 static void dns_tcp_call_writev_done(struct tevent_req *subreq)
292 {
293         struct dns_tcp_call *call = tevent_req_callback_data(subreq,
294                         struct dns_tcp_call);
295         int sys_errno;
296         int rc;
297
298         rc = tstream_writev_queue_recv(subreq, &sys_errno);
299         TALLOC_FREE(subreq);
300         if (rc == -1) {
301                 const char *reason;
302
303                 reason = talloc_asprintf(call, "dns_tcp_call_writev_done: "
304                                          "tstream_writev_queue_recv() - %d:%s",
305                                          sys_errno, strerror(sys_errno));
306                 if (!reason) {
307                         reason = "dns_tcp_call_writev_done: tstream_writev_queue_recv() failed";
308                 }
309
310                 dns_tcp_terminate_connection(call->dns_conn, reason);
311                 return;
312         }
313
314         /* We don't care about errors */
315
316         talloc_free(call);
317 }
318
319 /*
320   called when we get a new connection
321 */
322 static void dns_tcp_accept(struct stream_connection *conn)
323 {
324         struct dns_socket *dns_socket;
325         struct dns_tcp_connection *dns_conn;
326         struct tevent_req *subreq;
327         int rc;
328
329         dns_conn = talloc_zero(conn, struct dns_tcp_connection);
330         if (dns_conn == NULL) {
331                 stream_terminate_connection(conn,
332                                 "dns_tcp_accept: out of memory");
333                 return;
334         }
335
336         dns_conn->send_queue = tevent_queue_create(conn, "dns_tcp_accept");
337         if (dns_conn->send_queue == NULL) {
338                 stream_terminate_connection(conn,
339                                 "dns_tcp_accept: out of memory");
340                 return;
341         }
342
343         dns_socket = talloc_get_type(conn->private_data, struct dns_socket);
344
345         TALLOC_FREE(conn->event.fde);
346
347         rc = tstream_bsd_existing_socket(dns_conn,
348                         socket_get_fd(conn->socket),
349                         &dns_conn->tstream);
350         if (rc < 0) {
351                 stream_terminate_connection(conn,
352                                 "dns_tcp_accept: out of memory");
353                 return;
354         }
355
356         dns_conn->conn = conn;
357         dns_conn->dns_socket = dns_socket;
358         conn->private_data = dns_conn;
359
360         /*
361          * The krb5 tcp pdu's has the length as 4 byte (initial_read_size),
362          * packet_full_request_u32 provides the pdu length then.
363          */
364         subreq = tstream_read_pdu_blob_send(dns_conn,
365                                             dns_conn->conn->event.ctx,
366                                             dns_conn->tstream,
367                                             4, /* initial_read_size */
368                                             packet_full_request_u32,
369                                             dns_conn);
370         if (subreq == NULL) {
371                 dns_tcp_terminate_connection(dns_conn, "dns_tcp_accept: "
372                                 "no memory for tstream_read_pdu_blob_send");
373                 return;
374         }
375         tevent_req_set_callback(subreq, dns_tcp_call_loop, dns_conn);
376 }
377
378 static const struct stream_server_ops dns_tcp_stream_ops = {
379         .name                   = "dns_tcp",
380         .accept_connection      = dns_tcp_accept,
381         .recv_handler           = dns_tcp_recv,
382         .send_handler           = dns_tcp_send
383 };
384
385 struct dns_udp_call {
386         struct tsocket_address *src;
387         DATA_BLOB in;
388         DATA_BLOB out;
389 };
390
391 static void dns_udp_call_sendto_done(struct tevent_req *subreq);
392
393 static void dns_udp_call_loop(struct tevent_req *subreq)
394 {
395         struct dns_udp_socket *sock = tevent_req_callback_data(subreq,
396                                       struct dns_udp_socket);
397         struct dns_udp_call *call;
398         uint8_t *buf;
399         ssize_t len;
400         int sys_errno;
401         NTSTATUS status;
402
403         call = talloc(sock, struct dns_udp_call);
404         if (call == NULL) {
405                 talloc_free(call);
406                 goto done;
407         }
408
409         len = tdgram_recvfrom_recv(subreq, &sys_errno,
410                                    call, &buf, &call->src);
411         TALLOC_FREE(subreq);
412         if (len == -1) {
413                 talloc_free(call);
414                 goto done;
415         }
416
417         call->in.data = buf;
418         call->in.length = len;
419
420         DEBUG(10,("Received DNS UDP packet of length %lu from %s\n",
421                  (long)call->in.length,
422                  tsocket_address_string(call->src, call)));
423
424         /* Call dns_process */
425         status = dns_process(sock->dns_socket->dns, call, &call->in, &call->out);
426         if (!NT_STATUS_IS_OK(status)) {
427                 talloc_free(call);
428                 DEBUG(0, ("dns_process returned %s\n", nt_errstr(status)));
429                 goto done;
430         }
431
432         subreq = tdgram_sendto_queue_send(call,
433                                           sock->dns_socket->dns->task->event_ctx,
434                                           sock->dgram,
435                                           sock->send_queue,
436                                           call->out.data,
437                                           call->out.length,
438                                           call->src);
439         if (subreq == NULL) {
440                 talloc_free(call);
441                 goto done;
442         }
443         tevent_req_set_callback(subreq, dns_udp_call_sendto_done, call);
444
445 done:
446         subreq = tdgram_recvfrom_send(sock,
447                                       sock->dns_socket->dns->task->event_ctx,
448                                       sock->dgram);
449         if (subreq == NULL) {
450                 task_server_terminate(sock->dns_socket->dns->task,
451                                       "no memory for tdgram_recvfrom_send",
452                                       true);
453                 return;
454         }
455         tevent_req_set_callback(subreq, dns_udp_call_loop, sock);
456 }
457
458 static void dns_udp_call_sendto_done(struct tevent_req *subreq)
459 {
460         struct dns_udp_call *call = tevent_req_callback_data(subreq,
461                                        struct dns_udp_call);
462         ssize_t ret;
463         int sys_errno;
464
465         ret = tdgram_sendto_queue_recv(subreq, &sys_errno);
466
467         /* We don't care about errors */
468
469         talloc_free(call);
470 }
471
472 /*
473   start listening on the given address
474 */
475 static NTSTATUS dns_add_socket(struct dns_server *dns,
476                                const struct model_ops *model_ops,
477                                const char *name,
478                                const char *address,
479                                uint16_t port)
480 {
481         struct dns_socket *dns_socket;
482         struct dns_udp_socket *dns_udp_socket;
483         struct tevent_req *udpsubreq;
484         NTSTATUS status;
485         int ret;
486
487         dns_socket = talloc(dns, struct dns_socket);
488         NT_STATUS_HAVE_NO_MEMORY(dns_socket);
489
490         dns_socket->dns = dns;
491
492         ret = tsocket_address_inet_from_strings(dns_socket, "ip",
493                                                 address, port,
494                                                 &dns_socket->local_address);
495         if (ret != 0) {
496                 status = map_nt_error_from_unix_common(errno);
497                 return status;
498         }
499
500         status = stream_setup_socket(dns->task,
501                                      dns->task->event_ctx,
502                                      dns->task->lp_ctx,
503                                      model_ops,
504                                      &dns_tcp_stream_ops,
505                                      "ip", address, &port,
506                                      lpcfg_socket_options(dns->task->lp_ctx),
507                                      dns_socket);
508         if (!NT_STATUS_IS_OK(status)) {
509                 DEBUG(0,("Failed to bind to %s:%u TCP - %s\n",
510                          address, port, nt_errstr(status)));
511                 talloc_free(dns_socket);
512                 return status;
513         }
514
515         dns_udp_socket = talloc(dns_socket, struct dns_udp_socket);
516         NT_STATUS_HAVE_NO_MEMORY(dns_udp_socket);
517
518         dns_udp_socket->dns_socket = dns_socket;
519
520         ret = tdgram_inet_udp_socket(dns_socket->local_address,
521                                      NULL,
522                                      dns_udp_socket,
523                                      &dns_udp_socket->dgram);
524         if (ret != 0) {
525                 status = map_nt_error_from_unix_common(errno);
526                 DEBUG(0,("Failed to bind to %s:%u UDP - %s\n",
527                          address, port, nt_errstr(status)));
528                 return status;
529         }
530
531         dns_udp_socket->send_queue = tevent_queue_create(dns_udp_socket,
532                                                          "dns_udp_send_queue");
533         NT_STATUS_HAVE_NO_MEMORY(dns_udp_socket->send_queue);
534
535         udpsubreq = tdgram_recvfrom_send(dns_udp_socket,
536                                          dns->task->event_ctx,
537                                          dns_udp_socket->dgram);
538         NT_STATUS_HAVE_NO_MEMORY(udpsubreq);
539         tevent_req_set_callback(udpsubreq, dns_udp_call_loop, dns_udp_socket);
540
541         return NT_STATUS_OK;
542 }
543
544 /*
545   setup our listening sockets on the configured network interfaces
546 */
547 static NTSTATUS dns_startup_interfaces(struct dns_server *dns, struct loadparm_context *lp_ctx,
548                                        struct interface *ifaces)
549 {
550         const struct model_ops *model_ops;
551         int num_interfaces;
552         TALLOC_CTX *tmp_ctx = talloc_new(dns);
553         NTSTATUS status;
554         int i;
555
556         /* within the dns task we want to be a single process, so
557            ask for the single process model ops and pass these to the
558            stream_setup_socket() call. */
559         model_ops = process_model_startup("single");
560         if (!model_ops) {
561                 DEBUG(0,("Can't find 'single' process model_ops\n"));
562                 return NT_STATUS_INTERNAL_ERROR;
563         }
564
565         num_interfaces = iface_list_count(ifaces);
566
567         for (i=0; i<num_interfaces; i++) {
568                 const char *address = talloc_strdup(tmp_ctx, iface_list_n_ip(ifaces, i));
569
570                 status = dns_add_socket(dns, model_ops, "dns", address, DNS_SERVICE_PORT);
571                 NT_STATUS_NOT_OK_RETURN(status);
572         }
573
574         talloc_free(tmp_ctx);
575
576         return NT_STATUS_OK;
577 }
578
579 static int dns_server_sort_zones(struct ldb_message **m1, struct ldb_message **m2)
580 {
581         const char *n1, *n2;
582         size_t l1, l2;
583
584         n1 = ldb_msg_find_attr_as_string(*m1, "name", NULL);
585         n2 = ldb_msg_find_attr_as_string(*m2, "name", NULL);
586
587         l1 = strlen(n1);
588         l2 = strlen(n2);
589
590         /* If the string lengths are not equal just sort by length */
591         if (l1 != l2) {
592                 /* If m1 is the larger zone name, return it first */
593                 return l2 - l1;
594         }
595
596         /*TODO: We need to compare DNs here, we want the DomainDNSZones first */
597         return 0;
598 }
599
600 static void dns_task_init(struct task_server *task)
601 {
602         struct dns_server *dns;
603         NTSTATUS status;
604         struct interface *ifaces;
605         int ret;
606         struct ldb_result *res;
607         static const char * const attrs[] = { "name", NULL};
608         unsigned int i;
609
610         switch (lpcfg_server_role(task->lp_ctx)) {
611         case ROLE_STANDALONE:
612                 task_server_terminate(task, "dns: no DNS required in standalone configuration", false);
613                 return;
614         case ROLE_DOMAIN_MEMBER:
615                 task_server_terminate(task, "dns: no DNS required in member server configuration", false);
616                 return;
617         case ROLE_DOMAIN_CONTROLLER:
618                 /* Yes, we want a DNS */
619                 break;
620         }
621
622         load_interface_list(task, task->lp_ctx, &ifaces);
623
624         if (iface_list_count(ifaces) == 0) {
625                 task_server_terminate(task, "dns: no network interfaces configured", false);
626                 return;
627         }
628
629         task_server_set_title(task, "task[dns]");
630
631         dns = talloc_zero(task, struct dns_server);
632         if (dns == NULL) {
633                 task_server_terminate(task, "dns: out of memory", true);
634                 return;
635         }
636
637         dns->task = task;
638
639         dns->samdb = samdb_connect(dns, dns->task->event_ctx, dns->task->lp_ctx,
640                               system_session(dns->task->lp_ctx), 0);
641         if (!dns->samdb) {
642                 task_server_terminate(task, "dns: samdb_connect failed", true);
643                 return;
644         }
645
646         // TODO: this search does not work against windows
647         ret = dsdb_search(dns->samdb, dns, &res, NULL, LDB_SCOPE_SUBTREE,
648                           attrs, DSDB_SEARCH_SEARCH_ALL_PARTITIONS, "(objectClass=dnsZone)");
649         if (ret != LDB_SUCCESS) {
650                 task_server_terminate(task,
651                                       "dns: failed to look up root DNS zones",
652                                       true);
653                 return;
654         }
655
656         TYPESAFE_QSORT(res->msgs, res->count, dns_server_sort_zones);
657
658         for (i=0; i < res->count; i++) {
659                 struct dns_server_zone *z;
660
661                 z = talloc_zero(dns, struct dns_server_zone);
662                 if (z == NULL) {
663                 }
664
665                 z->name = ldb_msg_find_attr_as_string(res->msgs[i], "name", NULL);
666                 z->dn = talloc_move(z, &res->msgs[i]->dn);
667
668                 DLIST_ADD_END(dns->zones, z, NULL);
669         }
670
671         status = dns_startup_interfaces(dns, task->lp_ctx, ifaces);
672         if (!NT_STATUS_IS_OK(status)) {
673                 task_server_terminate(task, "dns failed to setup interfaces", true);
674                 return;
675         }
676 }
677
678 NTSTATUS server_service_dns_init(void)
679 {
680         return register_server_service("dns", dns_task_init);
681 }