bug #10609: CVE-2014-0239 Don't reply to replies
[metze/samba-autobuild/.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 #include "lib/util/tevent_werror.h"
46 #include "auth/auth.h"
47 #include "auth/credentials/credentials.h"
48
49 #undef DBGC_CLASS
50 #define DBGC_CLASS DBGC_DNS
51
52 NTSTATUS server_service_dns_init(void);
53
54 /* hold information about one dns socket */
55 struct dns_socket {
56         struct dns_server *dns;
57         struct tsocket_address *local_address;
58 };
59
60 struct dns_udp_socket {
61         struct dns_socket *dns_socket;
62         struct tdgram_context *dgram;
63         struct tevent_queue *send_queue;
64 };
65
66 /*
67   state of an open tcp connection
68 */
69 struct dns_tcp_connection {
70         /* stream connection we belong to */
71         struct stream_connection *conn;
72
73         /* the dns_server the connection belongs to */
74         struct dns_socket *dns_socket;
75
76         struct tstream_context *tstream;
77
78         struct tevent_queue *send_queue;
79 };
80
81 static void dns_tcp_terminate_connection(struct dns_tcp_connection *dnsconn, const char *reason)
82 {
83         stream_terminate_connection(dnsconn->conn, reason);
84 }
85
86 static void dns_tcp_recv(struct stream_connection *conn, uint16_t flags)
87 {
88         struct dns_tcp_connection *dnsconn = talloc_get_type(conn->private_data,
89                                                              struct dns_tcp_connection);
90         /* this should never be triggered! */
91         dns_tcp_terminate_connection(dnsconn, "dns_tcp_recv: called");
92 }
93
94 static void dns_tcp_send(struct stream_connection *conn, uint16_t flags)
95 {
96         struct dns_tcp_connection *dnsconn = talloc_get_type(conn->private_data,
97                                                              struct dns_tcp_connection);
98         /* this should never be triggered! */
99         dns_tcp_terminate_connection(dnsconn, "dns_tcp_send: called");
100 }
101
102 struct dns_process_state {
103         DATA_BLOB *in;
104         struct dns_server *dns;
105         struct dns_name_packet in_packet;
106         struct dns_request_state state;
107         uint16_t dns_err;
108         struct dns_name_packet out_packet;
109         DATA_BLOB out;
110 };
111
112 static void dns_process_done(struct tevent_req *subreq);
113
114 static struct tevent_req *dns_process_send(TALLOC_CTX *mem_ctx,
115                                            struct tevent_context *ev,
116                                            struct dns_server *dns,
117                                            DATA_BLOB *in)
118 {
119         struct tevent_req *req, *subreq;
120         struct dns_process_state *state;
121         enum ndr_err_code ndr_err;
122         WERROR ret;
123         const char *forwarder = lpcfg_dns_forwarder(dns->task->lp_ctx);
124         req = tevent_req_create(mem_ctx, &state, struct dns_process_state);
125         if (req == NULL) {
126                 return NULL;
127         }
128         state->in = in;
129
130         state->dns = dns;
131
132         if (in->length < 12) {
133                 tevent_req_werror(req, WERR_INVALID_PARAM);
134                 return tevent_req_post(req, ev);
135         }
136         dump_data_dbgc(DBGC_DNS, 8, in->data, in->length);
137
138         ndr_err = ndr_pull_struct_blob(
139                 in, state, &state->in_packet,
140                 (ndr_pull_flags_fn_t)ndr_pull_dns_name_packet);
141
142         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
143                 state->dns_err = DNS_RCODE_FORMERR;
144                 tevent_req_done(req);
145                 return tevent_req_post(req, ev);
146         }
147         if (DEBUGLVLC(DBGC_DNS, 8)) {
148                 NDR_PRINT_DEBUGC(DBGC_DNS, dns_name_packet, &state->in_packet);
149         }
150
151         ret = dns_verify_tsig(dns, state, &state->state, &state->in_packet, in);
152         if (!W_ERROR_IS_OK(ret)) {
153                 DEBUG(1, ("Failed to verify TSIG!\n"));
154                 state->dns_err = werr_to_dns_err(ret);
155                 tevent_req_done(req);
156                 return tevent_req_post(req, ev);
157         }
158
159         if (state->in_packet.operation & DNS_FLAG_REPLY) {
160                 DEBUG(1, ("Won't reply to replies.\n"));
161                 tevent_req_werror(req, WERR_INVALID_PARAM);
162                 return tevent_req_post(req, ev);
163         }
164
165         state->state.flags = state->in_packet.operation;
166         state->state.flags |= DNS_FLAG_REPLY;
167
168         
169         if (forwarder && *forwarder) {
170                 state->state.flags |= DNS_FLAG_RECURSION_AVAIL;
171         }
172
173         state->out_packet = state->in_packet;
174
175         switch (state->in_packet.operation & DNS_OPCODE) {
176         case DNS_OPCODE_QUERY:
177                 subreq = dns_server_process_query_send(
178                         state, ev, dns, &state->state, &state->in_packet);
179                 if (tevent_req_nomem(subreq, req)) {
180                         return tevent_req_post(req, ev);
181                 }
182                 tevent_req_set_callback(subreq, dns_process_done, req);
183                 return req;
184         case DNS_OPCODE_UPDATE:
185                 ret = dns_server_process_update(
186                         dns, &state->state, state, &state->in_packet,
187                         &state->out_packet.answers, &state->out_packet.ancount,
188                         &state->out_packet.nsrecs,  &state->out_packet.nscount,
189                         &state->out_packet.additional,
190                         &state->out_packet.arcount);
191                 break;
192         default:
193                 ret = WERR_DNS_ERROR_RCODE_NOT_IMPLEMENTED;
194         }
195         if (!W_ERROR_IS_OK(ret)) {
196                 state->dns_err = werr_to_dns_err(ret);
197         }
198         tevent_req_done(req);
199         return tevent_req_post(req, ev);
200 }
201
202 static void dns_process_done(struct tevent_req *subreq)
203 {
204         struct tevent_req *req = tevent_req_callback_data(
205                 subreq, struct tevent_req);
206         struct dns_process_state *state = tevent_req_data(
207                 req, struct dns_process_state);
208         WERROR ret;
209
210         ret = dns_server_process_query_recv(
211                 subreq, state,
212                 &state->out_packet.answers, &state->out_packet.ancount,
213                 &state->out_packet.nsrecs,  &state->out_packet.nscount,
214                 &state->out_packet.additional, &state->out_packet.arcount);
215         TALLOC_FREE(subreq);
216
217         if (!W_ERROR_IS_OK(ret)) {
218                 state->dns_err = werr_to_dns_err(ret);
219         }
220         tevent_req_done(req);
221 }
222
223 static WERROR dns_process_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
224                                DATA_BLOB *out)
225 {
226         struct dns_process_state *state = tevent_req_data(
227                 req, struct dns_process_state);
228         enum ndr_err_code ndr_err;
229         WERROR ret;
230
231         if (tevent_req_is_werror(req, &ret)) {
232                 return ret;
233         }
234         if (state->dns_err != DNS_RCODE_OK) {
235                 goto drop;
236         }
237         state->out_packet.operation |= state->state.flags;
238
239         if (state->state.sign) {
240                 ret = dns_sign_tsig(state->dns, mem_ctx, &state->state,
241                                     &state->out_packet, 0);
242                 if (!W_ERROR_IS_OK(ret)) {
243                         state->dns_err = DNS_RCODE_SERVFAIL;
244                         goto drop;
245                 }
246         }
247
248         if (DEBUGLVLC(DBGC_DNS, 8)) {
249                 NDR_PRINT_DEBUGC(DBGC_DNS, dns_name_packet, &state->out_packet);
250         }
251
252         ndr_err = ndr_push_struct_blob(
253                 out, mem_ctx, &state->out_packet,
254                 (ndr_push_flags_fn_t)ndr_push_dns_name_packet);
255         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
256                 DEBUG(1, ("Failed to push packet: %s!\n",
257                           ndr_errstr(ndr_err)));
258                 state->dns_err = DNS_RCODE_SERVFAIL;
259                 goto drop;
260         }
261         return WERR_OK;
262
263 drop:
264         *out = data_blob_talloc(mem_ctx, state->in->data, state->in->length);
265         if (out->data == NULL) {
266                 return WERR_NOMEM;
267         }
268         out->data[2] |= 0x80; /* Toggle DNS_FLAG_REPLY */
269         out->data[3] |= state->dns_err;
270         return WERR_OK;
271 }
272
273 struct dns_tcp_call {
274         struct dns_tcp_connection *dns_conn;
275         DATA_BLOB in;
276         DATA_BLOB out;
277         uint8_t out_hdr[4];
278         struct iovec out_iov[2];
279 };
280
281 static void dns_tcp_call_process_done(struct tevent_req *subreq);
282 static void dns_tcp_call_writev_done(struct tevent_req *subreq);
283
284 static void dns_tcp_call_loop(struct tevent_req *subreq)
285 {
286         struct dns_tcp_connection *dns_conn = tevent_req_callback_data(subreq,
287                                       struct dns_tcp_connection);
288         struct dns_server *dns = dns_conn->dns_socket->dns;
289         struct dns_tcp_call *call;
290         NTSTATUS status;
291
292         call = talloc(dns_conn, struct dns_tcp_call);
293         if (call == NULL) {
294                 dns_tcp_terminate_connection(dns_conn, "dns_tcp_call_loop: "
295                                 "no memory for dns_tcp_call");
296                 return;
297         }
298         call->dns_conn = dns_conn;
299
300         status = tstream_read_pdu_blob_recv(subreq,
301                                             call,
302                                             &call->in);
303         TALLOC_FREE(subreq);
304         if (!NT_STATUS_IS_OK(status)) {
305                 const char *reason;
306
307                 reason = talloc_asprintf(call, "dns_tcp_call_loop: "
308                                          "tstream_read_pdu_blob_recv() - %s",
309                                          nt_errstr(status));
310                 if (!reason) {
311                         reason = nt_errstr(status);
312                 }
313
314                 dns_tcp_terminate_connection(dns_conn, reason);
315                 return;
316         }
317
318         DEBUG(10,("Received DNS TCP packet of length %lu from %s\n",
319                  (long) call->in.length,
320                  tsocket_address_string(dns_conn->conn->remote_address, call)));
321
322         /* skip length header */
323         call->in.data += 2;
324         call->in.length -= 2;
325
326         subreq = dns_process_send(call, dns->task->event_ctx, dns,
327                                   &call->in);
328         if (subreq == NULL) {
329                 dns_tcp_terminate_connection(
330                         dns_conn, "dns_tcp_call_loop: dns_process_send "
331                         "failed\n");
332                 return;
333         }
334         tevent_req_set_callback(subreq, dns_tcp_call_process_done, call);
335
336         /*
337          * The dns tcp pdu's has the length as 2 byte (initial_read_size),
338          * packet_full_request_u16 provides the pdu length then.
339          */
340         subreq = tstream_read_pdu_blob_send(dns_conn,
341                                             dns_conn->conn->event.ctx,
342                                             dns_conn->tstream,
343                                             2, /* initial_read_size */
344                                             packet_full_request_u16,
345                                             dns_conn);
346         if (subreq == NULL) {
347                 dns_tcp_terminate_connection(dns_conn, "dns_tcp_call_loop: "
348                                 "no memory for tstream_read_pdu_blob_send");
349                 return;
350         }
351         tevent_req_set_callback(subreq, dns_tcp_call_loop, dns_conn);
352 }
353
354 static void dns_tcp_call_process_done(struct tevent_req *subreq)
355 {
356         struct dns_tcp_call *call = tevent_req_callback_data(subreq,
357                         struct dns_tcp_call);
358         struct dns_tcp_connection *dns_conn = call->dns_conn;
359         WERROR err;
360
361         err = dns_process_recv(subreq, call, &call->out);
362         TALLOC_FREE(subreq);
363         if (!W_ERROR_IS_OK(err)) {
364                 DEBUG(1, ("dns_process returned %s\n", win_errstr(err)));
365                 dns_tcp_terminate_connection(dns_conn,
366                                 "dns_tcp_call_loop: process function failed");
367                 return;
368         }
369
370         /* First add the length of the out buffer */
371         RSSVAL(call->out_hdr, 0, call->out.length);
372         call->out_iov[0].iov_base = (char *) call->out_hdr;
373         call->out_iov[0].iov_len = 2;
374
375         call->out_iov[1].iov_base = (char *) call->out.data;
376         call->out_iov[1].iov_len = call->out.length;
377
378         subreq = tstream_writev_queue_send(call,
379                                            dns_conn->conn->event.ctx,
380                                            dns_conn->tstream,
381                                            dns_conn->send_queue,
382                                            call->out_iov, 2);
383         if (subreq == NULL) {
384                 dns_tcp_terminate_connection(dns_conn, "dns_tcp_call_loop: "
385                                 "no memory for tstream_writev_queue_send");
386                 return;
387         }
388         tevent_req_set_callback(subreq, dns_tcp_call_writev_done, call);
389 }
390
391 static void dns_tcp_call_writev_done(struct tevent_req *subreq)
392 {
393         struct dns_tcp_call *call = tevent_req_callback_data(subreq,
394                         struct dns_tcp_call);
395         int sys_errno;
396         int rc;
397
398         rc = tstream_writev_queue_recv(subreq, &sys_errno);
399         TALLOC_FREE(subreq);
400         if (rc == -1) {
401                 const char *reason;
402
403                 reason = talloc_asprintf(call, "dns_tcp_call_writev_done: "
404                                          "tstream_writev_queue_recv() - %d:%s",
405                                          sys_errno, strerror(sys_errno));
406                 if (!reason) {
407                         reason = "dns_tcp_call_writev_done: tstream_writev_queue_recv() failed";
408                 }
409
410                 dns_tcp_terminate_connection(call->dns_conn, reason);
411                 return;
412         }
413
414         /* We don't care about errors */
415
416         talloc_free(call);
417 }
418
419 /*
420   called when we get a new connection
421 */
422 static void dns_tcp_accept(struct stream_connection *conn)
423 {
424         struct dns_socket *dns_socket;
425         struct dns_tcp_connection *dns_conn;
426         struct tevent_req *subreq;
427         int rc;
428
429         dns_conn = talloc_zero(conn, struct dns_tcp_connection);
430         if (dns_conn == NULL) {
431                 stream_terminate_connection(conn,
432                                 "dns_tcp_accept: out of memory");
433                 return;
434         }
435
436         dns_conn->send_queue = tevent_queue_create(conn, "dns_tcp_accept");
437         if (dns_conn->send_queue == NULL) {
438                 stream_terminate_connection(conn,
439                                 "dns_tcp_accept: out of memory");
440                 return;
441         }
442
443         dns_socket = talloc_get_type(conn->private_data, struct dns_socket);
444
445         TALLOC_FREE(conn->event.fde);
446
447         rc = tstream_bsd_existing_socket(dns_conn,
448                         socket_get_fd(conn->socket),
449                         &dns_conn->tstream);
450         if (rc < 0) {
451                 stream_terminate_connection(conn,
452                                 "dns_tcp_accept: out of memory");
453                 return;
454         }
455
456         dns_conn->conn = conn;
457         dns_conn->dns_socket = dns_socket;
458         conn->private_data = dns_conn;
459
460         /*
461          * The dns tcp pdu's has the length as 2 byte (initial_read_size),
462          * packet_full_request_u16 provides the pdu length then.
463          */
464         subreq = tstream_read_pdu_blob_send(dns_conn,
465                                             dns_conn->conn->event.ctx,
466                                             dns_conn->tstream,
467                                             2, /* initial_read_size */
468                                             packet_full_request_u16,
469                                             dns_conn);
470         if (subreq == NULL) {
471                 dns_tcp_terminate_connection(dns_conn, "dns_tcp_accept: "
472                                 "no memory for tstream_read_pdu_blob_send");
473                 return;
474         }
475         tevent_req_set_callback(subreq, dns_tcp_call_loop, dns_conn);
476 }
477
478 static const struct stream_server_ops dns_tcp_stream_ops = {
479         .name                   = "dns_tcp",
480         .accept_connection      = dns_tcp_accept,
481         .recv_handler           = dns_tcp_recv,
482         .send_handler           = dns_tcp_send
483 };
484
485 struct dns_udp_call {
486         struct dns_udp_socket *sock;
487         struct tsocket_address *src;
488         DATA_BLOB in;
489         DATA_BLOB out;
490 };
491
492 static void dns_udp_call_process_done(struct tevent_req *subreq);
493 static void dns_udp_call_sendto_done(struct tevent_req *subreq);
494
495 static void dns_udp_call_loop(struct tevent_req *subreq)
496 {
497         struct dns_udp_socket *sock = tevent_req_callback_data(subreq,
498                                       struct dns_udp_socket);
499         struct dns_server *dns = sock->dns_socket->dns;
500         struct dns_udp_call *call;
501         uint8_t *buf;
502         ssize_t len;
503         int sys_errno;
504
505         call = talloc(sock, struct dns_udp_call);
506         if (call == NULL) {
507                 talloc_free(call);
508                 goto done;
509         }
510         call->sock = sock;
511
512         len = tdgram_recvfrom_recv(subreq, &sys_errno,
513                                    call, &buf, &call->src);
514         TALLOC_FREE(subreq);
515         if (len == -1) {
516                 talloc_free(call);
517                 goto done;
518         }
519
520         call->in.data = buf;
521         call->in.length = len;
522
523         DEBUG(10,("Received DNS UDP packet of length %lu from %s\n",
524                  (long)call->in.length,
525                  tsocket_address_string(call->src, call)));
526
527         subreq = dns_process_send(call, dns->task->event_ctx, dns,
528                                   &call->in);
529         if (subreq == NULL) {
530                 TALLOC_FREE(call);
531                 goto done;
532         }
533         tevent_req_set_callback(subreq, dns_udp_call_process_done, call);
534
535 done:
536         subreq = tdgram_recvfrom_send(sock,
537                                       sock->dns_socket->dns->task->event_ctx,
538                                       sock->dgram);
539         if (subreq == NULL) {
540                 task_server_terminate(sock->dns_socket->dns->task,
541                                       "no memory for tdgram_recvfrom_send",
542                                       true);
543                 return;
544         }
545         tevent_req_set_callback(subreq, dns_udp_call_loop, sock);
546 }
547
548 static void dns_udp_call_process_done(struct tevent_req *subreq)
549 {
550         struct dns_udp_call *call = tevent_req_callback_data(
551                 subreq, struct dns_udp_call);
552         struct dns_udp_socket *sock = call->sock;
553         struct dns_server *dns = sock->dns_socket->dns;
554         WERROR err;
555
556         err = dns_process_recv(subreq, call, &call->out);
557         TALLOC_FREE(subreq);
558         if (!W_ERROR_IS_OK(err)) {
559                 DEBUG(1, ("dns_process returned %s\n", win_errstr(err)));
560                 TALLOC_FREE(call);
561                 return;
562         }
563
564         subreq = tdgram_sendto_queue_send(call,
565                                           dns->task->event_ctx,
566                                           sock->dgram,
567                                           sock->send_queue,
568                                           call->out.data,
569                                           call->out.length,
570                                           call->src);
571         if (subreq == NULL) {
572                 talloc_free(call);
573                 return;
574         }
575         tevent_req_set_callback(subreq, dns_udp_call_sendto_done, call);
576
577 }
578 static void dns_udp_call_sendto_done(struct tevent_req *subreq)
579 {
580         struct dns_udp_call *call = tevent_req_callback_data(subreq,
581                                        struct dns_udp_call);
582         int sys_errno;
583
584         tdgram_sendto_queue_recv(subreq, &sys_errno);
585
586         /* We don't care about errors */
587
588         talloc_free(call);
589 }
590
591 /*
592   start listening on the given address
593 */
594 static NTSTATUS dns_add_socket(struct dns_server *dns,
595                                const struct model_ops *model_ops,
596                                const char *name,
597                                const char *address,
598                                uint16_t port)
599 {
600         struct dns_socket *dns_socket;
601         struct dns_udp_socket *dns_udp_socket;
602         struct tevent_req *udpsubreq;
603         NTSTATUS status;
604         int ret;
605
606         dns_socket = talloc(dns, struct dns_socket);
607         NT_STATUS_HAVE_NO_MEMORY(dns_socket);
608
609         dns_socket->dns = dns;
610
611         ret = tsocket_address_inet_from_strings(dns_socket, "ip",
612                                                 address, port,
613                                                 &dns_socket->local_address);
614         if (ret != 0) {
615                 status = map_nt_error_from_unix_common(errno);
616                 return status;
617         }
618
619         status = stream_setup_socket(dns->task,
620                                      dns->task->event_ctx,
621                                      dns->task->lp_ctx,
622                                      model_ops,
623                                      &dns_tcp_stream_ops,
624                                      "ip", address, &port,
625                                      lpcfg_socket_options(dns->task->lp_ctx),
626                                      dns_socket);
627         if (!NT_STATUS_IS_OK(status)) {
628                 DEBUG(0,("Failed to bind to %s:%u TCP - %s\n",
629                          address, port, nt_errstr(status)));
630                 talloc_free(dns_socket);
631                 return status;
632         }
633
634         dns_udp_socket = talloc(dns_socket, struct dns_udp_socket);
635         NT_STATUS_HAVE_NO_MEMORY(dns_udp_socket);
636
637         dns_udp_socket->dns_socket = dns_socket;
638
639         ret = tdgram_inet_udp_socket(dns_socket->local_address,
640                                      NULL,
641                                      dns_udp_socket,
642                                      &dns_udp_socket->dgram);
643         if (ret != 0) {
644                 status = map_nt_error_from_unix_common(errno);
645                 DEBUG(0,("Failed to bind to %s:%u UDP - %s\n",
646                          address, port, nt_errstr(status)));
647                 return status;
648         }
649
650         dns_udp_socket->send_queue = tevent_queue_create(dns_udp_socket,
651                                                          "dns_udp_send_queue");
652         NT_STATUS_HAVE_NO_MEMORY(dns_udp_socket->send_queue);
653
654         udpsubreq = tdgram_recvfrom_send(dns_udp_socket,
655                                          dns->task->event_ctx,
656                                          dns_udp_socket->dgram);
657         NT_STATUS_HAVE_NO_MEMORY(udpsubreq);
658         tevent_req_set_callback(udpsubreq, dns_udp_call_loop, dns_udp_socket);
659
660         return NT_STATUS_OK;
661 }
662
663 /*
664   setup our listening sockets on the configured network interfaces
665 */
666 static NTSTATUS dns_startup_interfaces(struct dns_server *dns,
667                                        struct interface *ifaces)
668 {
669         const struct model_ops *model_ops;
670         int num_interfaces;
671         TALLOC_CTX *tmp_ctx = talloc_new(dns);
672         NTSTATUS status;
673         int i;
674
675         /* within the dns task we want to be a single process, so
676            ask for the single process model ops and pass these to the
677            stream_setup_socket() call. */
678         model_ops = process_model_startup("single");
679         if (!model_ops) {
680                 DEBUG(0,("Can't find 'single' process model_ops\n"));
681                 return NT_STATUS_INTERNAL_ERROR;
682         }
683
684         if (ifaces != NULL) {
685                 num_interfaces = iface_list_count(ifaces);
686
687                 for (i=0; i<num_interfaces; i++) {
688                         const char *address = talloc_strdup(tmp_ctx,
689                                                             iface_list_n_ip(ifaces, i));
690
691                         status = dns_add_socket(dns, model_ops, "dns", address,
692                                                 DNS_SERVICE_PORT);
693                         NT_STATUS_NOT_OK_RETURN(status);
694                 }
695         } else {
696                 char **wcard;
697                 wcard = iface_list_wildcard(tmp_ctx);
698                 if (wcard == NULL) {
699                         DEBUG(0, ("No wildcard address available\n"));
700                         return NT_STATUS_INTERNAL_ERROR;
701                 }
702                 for (i = 0; wcard[i] != NULL; i++) {
703                         status = dns_add_socket(dns, model_ops, "dns", wcard[i],
704                                                 DNS_SERVICE_PORT);
705                         NT_STATUS_NOT_OK_RETURN(status);
706                 }
707         }
708
709         talloc_free(tmp_ctx);
710
711         return NT_STATUS_OK;
712 }
713
714 static int dns_server_sort_zones(struct ldb_message **m1, struct ldb_message **m2)
715 {
716         const char *n1, *n2;
717         size_t l1, l2;
718
719         n1 = ldb_msg_find_attr_as_string(*m1, "name", NULL);
720         n2 = ldb_msg_find_attr_as_string(*m2, "name", NULL);
721
722         l1 = strlen(n1);
723         l2 = strlen(n2);
724
725         /* If the string lengths are not equal just sort by length */
726         if (l1 != l2) {
727                 /* If m1 is the larger zone name, return it first */
728                 return l2 - l1;
729         }
730
731         /*TODO: We need to compare DNs here, we want the DomainDNSZones first */
732         return 0;
733 }
734
735 static struct dns_server_tkey_store *tkey_store_init(TALLOC_CTX *mem_ctx,
736                                                      uint16_t size)
737 {
738         struct dns_server_tkey_store *buffer = talloc_zero(mem_ctx,
739                                                 struct dns_server_tkey_store);
740
741         if (buffer == NULL) {
742                 return NULL;
743         }
744
745         buffer->size = size;
746         buffer->next_idx = 0;
747
748         buffer->tkeys = talloc_zero_array(buffer, struct dns_server_tkey *, size);
749         if (buffer->tkeys == NULL) {
750                 TALLOC_FREE(buffer);
751         }
752
753         return buffer;
754 }
755
756 static void dns_task_init(struct task_server *task)
757 {
758         struct dns_server *dns;
759         NTSTATUS status;
760         struct interface *ifaces = NULL;
761         int ret;
762         struct ldb_result *res;
763         static const char * const attrs[] = { "name", NULL};
764         static const char * const attrs_none[] = { NULL};
765         unsigned int i;
766         struct ldb_message *dns_acc;
767         char *hostname_lower;
768         char *dns_spn;
769
770         switch (lpcfg_server_role(task->lp_ctx)) {
771         case ROLE_STANDALONE:
772                 task_server_terminate(task, "dns: no DNS required in standalone configuration", false);
773                 return;
774         case ROLE_DOMAIN_MEMBER:
775                 task_server_terminate(task, "dns: no DNS required in member server configuration", false);
776                 return;
777         case ROLE_ACTIVE_DIRECTORY_DC:
778                 /* Yes, we want a DNS */
779                 break;
780         }
781
782         if (lpcfg_interfaces(task->lp_ctx) && lpcfg_bind_interfaces_only(task->lp_ctx)) {
783                 load_interface_list(task, task->lp_ctx, &ifaces);
784
785                 if (iface_list_count(ifaces) == 0) {
786                         task_server_terminate(task, "dns: no network interfaces configured", false);
787                         return;
788                 }
789         }
790
791         task_server_set_title(task, "task[dns]");
792
793         dns = talloc_zero(task, struct dns_server);
794         if (dns == NULL) {
795                 task_server_terminate(task, "dns: out of memory", true);
796                 return;
797         }
798
799         dns->task = task;
800         /*FIXME: Make this a configurable option */
801         dns->max_payload = 4096;
802
803         dns->server_credentials = cli_credentials_init(dns);
804         if (!dns->server_credentials) {
805                 task_server_terminate(task, "Failed to init server credentials\n", true);
806                 return;
807         }
808
809         dns->samdb = samdb_connect(dns, dns->task->event_ctx, dns->task->lp_ctx,
810                               system_session(dns->task->lp_ctx), 0);
811         if (!dns->samdb) {
812                 task_server_terminate(task, "dns: samdb_connect failed", true);
813                 return;
814         }
815
816         cli_credentials_set_conf(dns->server_credentials, task->lp_ctx);
817
818         hostname_lower = strlower_talloc(dns, lpcfg_netbios_name(task->lp_ctx));
819         dns_spn = talloc_asprintf(dns, "DNS/%s.%s",
820                                   hostname_lower,
821                                   lpcfg_dnsdomain(task->lp_ctx));
822         TALLOC_FREE(hostname_lower);
823
824         ret = dsdb_search_one(dns->samdb, dns, &dns_acc,
825                               ldb_get_default_basedn(dns->samdb), LDB_SCOPE_SUBTREE,
826                               attrs_none, 0, "(servicePrincipalName=%s)",
827                               dns_spn);
828         if (ret == LDB_SUCCESS) {
829                 TALLOC_FREE(dns_acc);
830                 if (!dns_spn) {
831                         task_server_terminate(task, "dns: talloc_asprintf failed", true);
832                         return;
833                 }
834                 status = cli_credentials_set_stored_principal(dns->server_credentials, task->lp_ctx, dns_spn);
835                 if (!NT_STATUS_IS_OK(status)) {
836                         task_server_terminate(task,
837                                               talloc_asprintf(task, "Failed to obtain server credentials for DNS, "
838                                                               "despite finding it in the samdb! %s\n",
839                                                               nt_errstr(status)),
840                                               true);
841                         return;
842                 }
843         } else {
844                 TALLOC_FREE(dns_spn);
845                 status = cli_credentials_set_machine_account(dns->server_credentials, task->lp_ctx);
846                 if (!NT_STATUS_IS_OK(status)) {
847                         task_server_terminate(task,
848                                               talloc_asprintf(task, "Failed to obtain server credentials, perhaps a standalone server?: %s\n",
849                                                               nt_errstr(status)),
850                                               true);
851                         return;
852                 }
853         }
854
855         dns->tkeys = tkey_store_init(dns, TKEY_BUFFER_SIZE);
856         if (!dns->tkeys) {
857                 task_server_terminate(task, "Failed to allocate tkey storage\n", true);
858                 return;
859         }
860
861         // TODO: this search does not work against windows
862         ret = dsdb_search(dns->samdb, dns, &res, NULL, LDB_SCOPE_SUBTREE,
863                           attrs, DSDB_SEARCH_SEARCH_ALL_PARTITIONS, "(objectClass=dnsZone)");
864         if (ret != LDB_SUCCESS) {
865                 task_server_terminate(task,
866                                       "dns: failed to look up root DNS zones",
867                                       true);
868                 return;
869         }
870
871         TYPESAFE_QSORT(res->msgs, res->count, dns_server_sort_zones);
872
873         for (i=0; i < res->count; i++) {
874                 struct dns_server_zone *z;
875
876                 z = talloc_zero(dns, struct dns_server_zone);
877                 if (z == NULL) {
878                         task_server_terminate(task, "dns failed to allocate memory", true);
879                 }
880
881                 z->name = ldb_msg_find_attr_as_string(res->msgs[i], "name", NULL);
882                 z->dn = talloc_move(z, &res->msgs[i]->dn);
883                 /*
884                  * Ignore the RootDNSServers zone and zones that we don't support yet
885                  * RootDNSServers should never be returned (Windows DNS server don't)
886                  * ..TrustAnchors should never be returned as is, (Windows returns
887                  * TrustAnchors) and for the moment we don't support DNSSEC so we'd better
888                  * not return this zone.
889                  */
890                 if ((strcmp(z->name, "RootDNSServers") == 0) ||
891                     (strcmp(z->name, "..TrustAnchors") == 0))
892                 {
893                         DEBUG(10, ("Ignoring zone %s\n", z->name));
894                         talloc_free(z);
895                         continue;
896                 }
897                 DLIST_ADD_END(dns->zones, z, NULL);
898         }
899
900         status = dns_startup_interfaces(dns, ifaces);
901         if (!NT_STATUS_IS_OK(status)) {
902                 task_server_terminate(task, "dns failed to setup interfaces", true);
903                 return;
904         }
905 }
906
907 NTSTATUS server_service_dns_init(void)
908 {
909         return register_server_service("dns", dns_task_init);
910 }