4b5bb0772a42b4b560baf794fdab8713264a4a42
[bbaumbach/samba-autobuild/.git] / source4 / dns_server / dns_query.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    DNS server handler for queries
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 "libcli/util/werror.h"
25 #include "librpc/ndr/libndr.h"
26 #include "librpc/gen_ndr/ndr_dns.h"
27 #include "librpc/gen_ndr/ndr_dnsp.h"
28 #include <ldb.h>
29 #include "param/param.h"
30 #include "dsdb/samdb/samdb.h"
31 #include "dsdb/common/util.h"
32 #include "dns_server/dns_server.h"
33 #include "libcli/dns/libdns.h"
34 #include "lib/util/dlinklist.h"
35 #include "lib/util/util_net.h"
36 #include "lib/util/tevent_werror.h"
37 #include "auth/auth.h"
38 #include "auth/credentials/credentials.h"
39 #include "auth/gensec/gensec.h"
40
41 #undef DBGC_CLASS
42 #define DBGC_CLASS DBGC_DNS
43
44 struct forwarder_string {
45         const char *forwarder;
46         struct forwarder_string *prev, *next;
47 };
48
49 static WERROR add_response_rr(const char *name,
50                               const struct dnsp_DnssrvRpcRecord *rec,
51                               struct dns_res_rec **answers)
52 {
53         struct dns_res_rec *ans = *answers;
54         uint16_t ai = talloc_array_length(ans);
55         enum ndr_err_code ndr_err;
56
57         if (ai == UINT16_MAX) {
58                 return WERR_BUFFER_OVERFLOW;
59         }
60
61         /*
62          * "ans" is always non-NULL and thus its own talloc context
63          */
64         ans = talloc_realloc(ans, ans, struct dns_res_rec, ai+1);
65         if (ans == NULL) {
66                 return WERR_NOT_ENOUGH_MEMORY;
67         }
68
69         ZERO_STRUCT(ans[ai]);
70
71         switch (rec->wType) {
72         case DNS_QTYPE_CNAME:
73                 ans[ai].rdata.cname_record = talloc_strdup(ans, rec->data.cname);
74                 W_ERROR_HAVE_NO_MEMORY(ans[ai].rdata.cname_record);
75                 break;
76         case DNS_QTYPE_A:
77                 ans[ai].rdata.ipv4_record = talloc_strdup(ans, rec->data.ipv4);
78                 W_ERROR_HAVE_NO_MEMORY(ans[ai].rdata.ipv4_record);
79                 break;
80         case DNS_QTYPE_AAAA:
81                 ans[ai].rdata.ipv6_record = talloc_strdup(ans, rec->data.ipv6);
82                 W_ERROR_HAVE_NO_MEMORY(ans[ai].rdata.ipv6_record);
83                 break;
84         case DNS_TYPE_NS:
85                 ans[ai].rdata.ns_record = talloc_strdup(ans, rec->data.ns);
86                 W_ERROR_HAVE_NO_MEMORY(ans[ai].rdata.ns_record);
87                 break;
88         case DNS_QTYPE_SRV:
89                 ans[ai].rdata.srv_record.priority = rec->data.srv.wPriority;
90                 ans[ai].rdata.srv_record.weight   = rec->data.srv.wWeight;
91                 ans[ai].rdata.srv_record.port     = rec->data.srv.wPort;
92                 ans[ai].rdata.srv_record.target   = talloc_strdup(
93                         ans, rec->data.srv.nameTarget);
94                 W_ERROR_HAVE_NO_MEMORY(ans[ai].rdata.srv_record.target);
95                 break;
96         case DNS_QTYPE_SOA:
97                 ans[ai].rdata.soa_record.mname   = talloc_strdup(
98                         ans, rec->data.soa.mname);
99                 W_ERROR_HAVE_NO_MEMORY(ans[ai].rdata.soa_record.mname);
100                 ans[ai].rdata.soa_record.rname   = talloc_strdup(
101                         ans, rec->data.soa.rname);
102                 W_ERROR_HAVE_NO_MEMORY(ans[ai].rdata.soa_record.rname);
103                 ans[ai].rdata.soa_record.serial  = rec->data.soa.serial;
104                 ans[ai].rdata.soa_record.refresh = rec->data.soa.refresh;
105                 ans[ai].rdata.soa_record.retry   = rec->data.soa.retry;
106                 ans[ai].rdata.soa_record.expire  = rec->data.soa.expire;
107                 ans[ai].rdata.soa_record.minimum = rec->data.soa.minimum;
108                 break;
109         case DNS_QTYPE_PTR:
110                 ans[ai].rdata.ptr_record = talloc_strdup(ans, rec->data.ptr);
111                 W_ERROR_HAVE_NO_MEMORY(ans[ai].rdata.ptr_record);
112                 break;
113         case DNS_QTYPE_MX:
114                 ans[ai].rdata.mx_record.preference = rec->data.mx.wPriority;
115                 ans[ai].rdata.mx_record.exchange = talloc_strdup(
116                         ans, rec->data.mx.nameTarget);
117                 if (ans[ai].rdata.mx_record.exchange == NULL) {
118                         return WERR_NOT_ENOUGH_MEMORY;
119                 }
120                 break;
121         case DNS_QTYPE_TXT:
122                 ndr_err = ndr_dnsp_string_list_copy(ans,
123                                                     &rec->data.txt,
124                                                     &ans[ai].rdata.txt_record.txt);
125                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
126                         return WERR_NOT_ENOUGH_MEMORY;
127                 }
128                 break;
129         default:
130                 DEBUG(0, ("Got unhandled type %u query.\n", rec->wType));
131                 return DNS_ERR(NOT_IMPLEMENTED);
132         }
133
134         ans[ai].name = talloc_strdup(ans, name);
135         W_ERROR_HAVE_NO_MEMORY(ans[ai].name);
136         ans[ai].rr_type = rec->wType;
137         ans[ai].rr_class = DNS_QCLASS_IN;
138         ans[ai].ttl = rec->dwTtlSeconds;
139         ans[ai].length = UINT16_MAX;
140
141         *answers = ans;
142
143         return WERR_OK;
144 }
145
146 static WERROR add_dns_res_rec(struct dns_res_rec **pdst,
147                               const struct dns_res_rec *src)
148 {
149         struct dns_res_rec *dst = *pdst;
150         uint16_t di = talloc_array_length(dst);
151         enum ndr_err_code ndr_err;
152
153         if (di == UINT16_MAX) {
154                 return WERR_BUFFER_OVERFLOW;
155         }
156
157         dst = talloc_realloc(dst, dst, struct dns_res_rec, di+1);
158         if (dst == NULL) {
159                 return WERR_NOT_ENOUGH_MEMORY;
160         }
161
162         ZERO_STRUCT(dst[di]);
163
164         dst[di] = (struct dns_res_rec) {
165                 .name = talloc_strdup(dst, src->name),
166                 .rr_type = src->rr_type,
167                 .rr_class = src->rr_class,
168                 .ttl = src->ttl,
169                 .length = src->length
170         };
171
172         if (dst[di].name == NULL) {
173                 return WERR_NOT_ENOUGH_MEMORY;
174         }
175
176         switch (src->rr_type) {
177         case DNS_QTYPE_CNAME:
178                 dst[di].rdata.cname_record = talloc_strdup(
179                         dst, src->rdata.cname_record);
180                 if (dst[di].rdata.cname_record == NULL) {
181                         return WERR_NOT_ENOUGH_MEMORY;
182                 }
183                 break;
184         case DNS_QTYPE_A:
185                 dst[di].rdata.ipv4_record = talloc_strdup(
186                         dst, src->rdata.ipv4_record);
187                 if (dst[di].rdata.ipv4_record == NULL) {
188                         return WERR_NOT_ENOUGH_MEMORY;
189                 }
190                 break;
191         case DNS_QTYPE_AAAA:
192                 dst[di].rdata.ipv6_record = talloc_strdup(
193                         dst, src->rdata.ipv6_record);
194                 if (dst[di].rdata.ipv6_record == NULL) {
195                         return WERR_NOT_ENOUGH_MEMORY;
196                 }
197                 break;
198         case DNS_TYPE_NS:
199                 dst[di].rdata.ns_record = talloc_strdup(
200                         dst, src->rdata.ns_record);
201                 if (dst[di].rdata.ns_record == NULL) {
202                         return WERR_NOT_ENOUGH_MEMORY;
203                 }
204                 break;
205         case DNS_QTYPE_SRV:
206                 dst[di].rdata.srv_record = (struct dns_srv_record) {
207                         .priority = src->rdata.srv_record.priority,
208                         .weight   = src->rdata.srv_record.weight,
209                         .port     = src->rdata.srv_record.port,
210                         .target   = talloc_strdup(
211                                 dst, src->rdata.srv_record.target)
212                 };
213                 if (dst[di].rdata.srv_record.target == NULL) {
214                         return WERR_NOT_ENOUGH_MEMORY;
215                 }
216                 break;
217         case DNS_QTYPE_SOA:
218                 dst[di].rdata.soa_record = (struct dns_soa_record) {
219                         .mname   = talloc_strdup(
220                                 dst, src->rdata.soa_record.mname),
221                         .rname   = talloc_strdup(
222                                 dst, src->rdata.soa_record.rname),
223                         .serial  = src->rdata.soa_record.serial,
224                         .refresh = src->rdata.soa_record.refresh,
225                         .retry   = src->rdata.soa_record.retry,
226                         .expire  = src->rdata.soa_record.expire,
227                         .minimum = src->rdata.soa_record.minimum
228                 };
229
230                 if ((dst[di].rdata.soa_record.mname == NULL) ||
231                     (dst[di].rdata.soa_record.rname == NULL)) {
232                         return WERR_NOT_ENOUGH_MEMORY;
233                 }
234
235                 break;
236         case DNS_QTYPE_PTR:
237                 dst[di].rdata.ptr_record = talloc_strdup(
238                         dst, src->rdata.ptr_record);
239                 if (dst[di].rdata.ptr_record == NULL) {
240                         return WERR_NOT_ENOUGH_MEMORY;
241                 }
242                 break;
243         case DNS_QTYPE_MX:
244                 dst[di].rdata.mx_record = (struct dns_mx_record) {
245                         .preference = src->rdata.mx_record.preference,
246                         .exchange   = talloc_strdup(
247                                 src, src->rdata.mx_record.exchange)
248                 };
249
250                 if (dst[di].rdata.mx_record.exchange == NULL) {
251                         return WERR_NOT_ENOUGH_MEMORY;
252                 }
253                 break;
254         case DNS_QTYPE_TXT:
255                 ndr_err = ndr_dnsp_string_list_copy(dst,
256                                                     &src->rdata.txt_record.txt,
257                                                     &dst[di].rdata.txt_record.txt);
258                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
259                         return WERR_NOT_ENOUGH_MEMORY;
260                 }
261                 break;
262         default:
263                 DBG_WARNING("Got unhandled type %u query.\n", src->rr_type);
264                 return DNS_ERR(NOT_IMPLEMENTED);
265         }
266
267         *pdst = dst;
268
269         return WERR_OK;
270 }
271
272 struct ask_forwarder_state {
273         struct tevent_context *ev;
274         uint16_t id;
275         struct dns_name_packet in_packet;
276 };
277
278 static void ask_forwarder_done(struct tevent_req *subreq);
279
280 static struct tevent_req *ask_forwarder_send(
281         TALLOC_CTX *mem_ctx, struct tevent_context *ev,
282         struct dns_server *dns,
283         const char *forwarder, struct dns_name_question *question)
284 {
285         struct tevent_req *req, *subreq;
286         struct ask_forwarder_state *state;
287         struct dns_res_rec *options;
288         struct dns_name_packet out_packet = { 0, };
289         DATA_BLOB out_blob;
290         enum ndr_err_code ndr_err;
291         WERROR werr;
292
293         req = tevent_req_create(mem_ctx, &state, struct ask_forwarder_state);
294         if (req == NULL) {
295                 return NULL;
296         }
297         state->ev = ev;
298         generate_random_buffer((uint8_t *)&state->id, sizeof(state->id));
299
300         if (!is_ipaddress(forwarder)) {
301                 DEBUG(0, ("Invalid 'dns forwarder' setting '%s', needs to be "
302                           "an IP address\n", forwarder));
303                 tevent_req_werror(req, DNS_ERR(NAME_ERROR));
304                 return tevent_req_post(req, ev);
305         }
306
307         out_packet.id = state->id;
308         out_packet.operation |= DNS_OPCODE_QUERY | DNS_FLAG_RECURSION_DESIRED;
309         out_packet.qdcount = 1;
310         out_packet.questions = question;
311
312         werr = dns_generate_options(dns, state, &options);
313         if (!W_ERROR_IS_OK(werr)) {
314                 tevent_req_werror(req, werr);
315                 return tevent_req_post(req, ev);
316         }
317
318         out_packet.arcount = 1;
319         out_packet.additional = options;
320
321         ndr_err = ndr_push_struct_blob(
322                 &out_blob, state, &out_packet,
323                 (ndr_push_flags_fn_t)ndr_push_dns_name_packet);
324         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
325                 tevent_req_werror(req, DNS_ERR(SERVER_FAILURE));
326                 return tevent_req_post(req, ev);
327         }
328         subreq = dns_udp_request_send(state, ev, forwarder, out_blob.data,
329                                       out_blob.length);
330         if (tevent_req_nomem(subreq, req)) {
331                 return tevent_req_post(req, ev);
332         }
333         tevent_req_set_callback(subreq, ask_forwarder_done, req);
334         return req;
335 }
336
337 static void ask_forwarder_done(struct tevent_req *subreq)
338 {
339         struct tevent_req *req = tevent_req_callback_data(
340                 subreq, struct tevent_req);
341         struct ask_forwarder_state *state = tevent_req_data(
342                 req, struct ask_forwarder_state);
343         DATA_BLOB in_blob;
344         enum ndr_err_code ndr_err;
345         int ret;
346
347         ret = dns_udp_request_recv(subreq, state,
348                                    &in_blob.data, &in_blob.length);
349         TALLOC_FREE(subreq);
350
351         if (ret != 0) {
352                 tevent_req_werror(req, unix_to_werror(ret));
353                 return;
354         }
355
356         ndr_err = ndr_pull_struct_blob(
357                 &in_blob, state, &state->in_packet,
358                 (ndr_pull_flags_fn_t)ndr_pull_dns_name_packet);
359         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
360                 tevent_req_werror(req, DNS_ERR(SERVER_FAILURE));
361                 return;
362         }
363         if (state->in_packet.id != state->id) {
364                 tevent_req_werror(req, DNS_ERR(NAME_ERROR));
365                 return;
366         }
367         tevent_req_done(req);
368 }
369
370 static WERROR ask_forwarder_recv(
371         struct tevent_req *req, TALLOC_CTX *mem_ctx,
372         struct dns_res_rec **answers, uint16_t *ancount,
373         struct dns_res_rec **nsrecs, uint16_t *nscount,
374         struct dns_res_rec **additional, uint16_t *arcount)
375 {
376         struct ask_forwarder_state *state = tevent_req_data(
377                 req, struct ask_forwarder_state);
378         struct dns_name_packet *in_packet = &state->in_packet;
379         WERROR err;
380
381         if (tevent_req_is_werror(req, &err)) {
382                 return err;
383         }
384
385         *ancount = in_packet->ancount;
386         *answers = talloc_move(mem_ctx, &in_packet->answers);
387
388         *nscount = in_packet->nscount;
389         *nsrecs = talloc_move(mem_ctx, &in_packet->nsrecs);
390
391         *arcount = in_packet->arcount;
392         *additional = talloc_move(mem_ctx, &in_packet->additional);
393
394         return WERR_OK;
395 }
396
397 static WERROR add_zone_authority_record(struct dns_server *dns,
398                                         TALLOC_CTX *mem_ctx,
399                                         const struct dns_name_question *question,
400                                         struct dns_res_rec **nsrecs)
401 {
402         const char *zone = NULL;
403         struct dnsp_DnssrvRpcRecord *recs;
404         struct dns_res_rec *ns = *nsrecs;
405         uint16_t rec_count;
406         struct ldb_dn *dn = NULL;
407         unsigned int ri;
408         WERROR werror;
409
410         zone = dns_get_authoritative_zone(dns, question->name);
411         DEBUG(10, ("Creating zone authority record for '%s'\n", zone));
412
413         werror = dns_name2dn(dns, mem_ctx, zone, &dn);
414         if (!W_ERROR_IS_OK(werror)) {
415                 return werror;
416         }
417
418         werror = dns_lookup_records(dns, mem_ctx, dn, &recs, &rec_count);
419         if (!W_ERROR_IS_OK(werror)) {
420                 return werror;
421         }
422
423         for (ri = 0; ri < rec_count; ri++) {
424                 if (recs[ri].wType == DNS_TYPE_SOA) {
425                         werror = add_response_rr(zone, &recs[ri], &ns);
426                         if (!W_ERROR_IS_OK(werror)) {
427                                 return werror;
428                         }
429                 }
430         }
431
432         *nsrecs = ns;
433
434         return WERR_OK;
435 }
436
437 static struct tevent_req *handle_authoritative_send(
438         TALLOC_CTX *mem_ctx, struct tevent_context *ev,
439         struct dns_server *dns, const char *forwarder,
440         struct dns_name_question *question,
441         struct dns_res_rec **answers, struct dns_res_rec **nsrecs);
442 static WERROR handle_authoritative_recv(struct tevent_req *req);
443
444 struct handle_dnsrpcrec_state {
445         struct dns_res_rec **answers;
446         struct dns_res_rec **nsrecs;
447 };
448
449 static void handle_dnsrpcrec_gotauth(struct tevent_req *subreq);
450 static void handle_dnsrpcrec_gotforwarded(struct tevent_req *subreq);
451
452 static struct tevent_req *handle_dnsrpcrec_send(
453         TALLOC_CTX *mem_ctx, struct tevent_context *ev,
454         struct dns_server *dns, const char *forwarder,
455         const struct dns_name_question *question,
456         struct dnsp_DnssrvRpcRecord *rec,
457         struct dns_res_rec **answers, struct dns_res_rec **nsrecs)
458 {
459         struct tevent_req *req, *subreq;
460         struct handle_dnsrpcrec_state *state;
461         struct dns_name_question *new_q;
462         bool resolve_cname;
463         WERROR werr;
464
465         req = tevent_req_create(mem_ctx, &state,
466                                 struct handle_dnsrpcrec_state);
467         if (req == NULL) {
468                 return NULL;
469         }
470         state->answers = answers;
471         state->nsrecs = nsrecs;
472
473         resolve_cname = ((rec->wType == DNS_TYPE_CNAME) &&
474                          ((question->question_type == DNS_QTYPE_A) ||
475                           (question->question_type == DNS_QTYPE_AAAA)));
476
477         if (!resolve_cname) {
478                 if ((question->question_type != DNS_QTYPE_ALL) &&
479                     (rec->wType !=
480                      (enum dns_record_type) question->question_type)) {
481                         tevent_req_done(req);
482                         return tevent_req_post(req, ev);
483                 }
484
485                 werr = add_response_rr(question->name, rec, state->answers);
486                 if (tevent_req_werror(req, werr)) {
487                         return tevent_req_post(req, ev);
488                 }
489
490                 tevent_req_done(req);
491                 return tevent_req_post(req, ev);
492         }
493
494         werr = add_response_rr(question->name, rec, state->answers);
495         if (tevent_req_werror(req, werr)) {
496                 return tevent_req_post(req, ev);
497         }
498
499         new_q = talloc(state, struct dns_name_question);
500         if (tevent_req_nomem(new_q, req)) {
501                 return tevent_req_post(req, ev);
502         }
503
504         *new_q = (struct dns_name_question) {
505                 .question_type = question->question_type,
506                 .question_class = question->question_class,
507                 .name = rec->data.cname
508         };
509
510         if (dns_authoritative_for_zone(dns, new_q->name)) {
511                 subreq = handle_authoritative_send(
512                         state, ev, dns, forwarder, new_q,
513                         state->answers, state->nsrecs);
514                 if (tevent_req_nomem(subreq, req)) {
515                         return tevent_req_post(req, ev);
516                 }
517                 tevent_req_set_callback(subreq, handle_dnsrpcrec_gotauth, req);
518                 return req;
519         }
520
521         subreq = ask_forwarder_send(state, ev, dns, forwarder, new_q);
522         if (tevent_req_nomem(subreq, req)) {
523                 return tevent_req_post(req, ev);
524         }
525         tevent_req_set_callback(subreq, handle_dnsrpcrec_gotforwarded, req);
526
527         return req;
528 }
529
530 static void handle_dnsrpcrec_gotauth(struct tevent_req *subreq)
531 {
532         struct tevent_req *req = tevent_req_callback_data(
533                 subreq, struct tevent_req);
534         WERROR werr;
535
536         werr = handle_authoritative_recv(subreq);
537         TALLOC_FREE(subreq);
538         if (tevent_req_werror(req, werr)) {
539                 return;
540         }
541         tevent_req_done(req);
542 }
543
544 static void handle_dnsrpcrec_gotforwarded(struct tevent_req *subreq)
545 {
546         struct tevent_req *req = tevent_req_callback_data(
547                 subreq, struct tevent_req);
548         struct handle_dnsrpcrec_state *state = tevent_req_data(
549                 req, struct handle_dnsrpcrec_state);
550         struct dns_res_rec *answers, *nsrecs, *additional;
551         uint16_t ancount = 0;
552         uint16_t nscount = 0;
553         uint16_t arcount = 0;
554         uint16_t i;
555         WERROR werr;
556
557         werr = ask_forwarder_recv(subreq, state, &answers, &ancount,
558                                   &nsrecs, &nscount, &additional, &arcount);
559         if (tevent_req_werror(req, werr)) {
560                 return;
561         }
562
563         for (i=0; i<ancount; i++) {
564                 werr = add_dns_res_rec(state->answers, &answers[i]);
565                 if (tevent_req_werror(req, werr)) {
566                         return;
567                 }
568         }
569
570         for (i=0; i<nscount; i++) {
571                 werr = add_dns_res_rec(state->nsrecs, &nsrecs[i]);
572                 if (tevent_req_werror(req, werr)) {
573                         return;
574                 }
575         }
576
577         tevent_req_done(req);
578 }
579
580 static WERROR handle_dnsrpcrec_recv(struct tevent_req *req)
581 {
582         return tevent_req_simple_recv_werror(req);
583 }
584
585 struct handle_authoritative_state {
586         struct tevent_context *ev;
587         struct dns_server *dns;
588         struct dns_name_question *question;
589         const char *forwarder;
590
591         struct dnsp_DnssrvRpcRecord *recs;
592         uint16_t rec_count;
593         uint16_t recs_done;
594
595         struct dns_res_rec **answers;
596         struct dns_res_rec **nsrecs;
597 };
598
599 static void handle_authoritative_done(struct tevent_req *subreq);
600
601 static struct tevent_req *handle_authoritative_send(
602         TALLOC_CTX *mem_ctx, struct tevent_context *ev,
603         struct dns_server *dns, const char *forwarder,
604         struct dns_name_question *question,
605         struct dns_res_rec **answers, struct dns_res_rec **nsrecs)
606 {
607         struct tevent_req *req, *subreq;
608         struct handle_authoritative_state *state;
609         struct ldb_dn *dn = NULL;
610         WERROR werr;
611
612         req = tevent_req_create(mem_ctx, &state,
613                                 struct handle_authoritative_state);
614         if (req == NULL) {
615                 return NULL;
616         }
617         state->ev = ev;
618         state->dns = dns;
619         state->question = question;
620         state->forwarder = forwarder;
621         state->answers = answers;
622         state->nsrecs = nsrecs;
623
624         werr = dns_name2dn(dns, state, question->name, &dn);
625         if (tevent_req_werror(req, werr)) {
626                 return tevent_req_post(req, ev);
627         }
628
629         werr = dns_lookup_records(dns, state, dn, &state->recs,
630                                   &state->rec_count);
631         TALLOC_FREE(dn);
632         if (tevent_req_werror(req, werr)) {
633                 return tevent_req_post(req, ev);
634         }
635
636         if (state->rec_count == 0) {
637                 tevent_req_werror(req, DNS_ERR(NAME_ERROR));
638                 return tevent_req_post(req, ev);
639         }
640
641         subreq = handle_dnsrpcrec_send(
642                 state, state->ev, state->dns, state->forwarder,
643                 state->question, &state->recs[state->recs_done],
644                 state->answers, state->nsrecs);
645         if (tevent_req_nomem(subreq, req)) {
646                 return tevent_req_post(req, ev);
647         }
648         tevent_req_set_callback(subreq, handle_authoritative_done, req);
649         return req;
650 }
651
652 static void handle_authoritative_done(struct tevent_req *subreq)
653 {
654         struct tevent_req *req = tevent_req_callback_data(
655                 subreq, struct tevent_req);
656         struct handle_authoritative_state *state = tevent_req_data(
657                 req, struct handle_authoritative_state);
658         WERROR werr;
659
660         werr = handle_dnsrpcrec_recv(subreq);
661         TALLOC_FREE(subreq);
662         if (tevent_req_werror(req, werr)) {
663                 return;
664         }
665
666         state->recs_done += 1;
667
668         if (state->recs_done == state->rec_count) {
669                 tevent_req_done(req);
670                 return;
671         }
672
673         subreq = handle_dnsrpcrec_send(
674                 state, state->ev, state->dns, state->forwarder,
675                 state->question, &state->recs[state->recs_done],
676                 state->answers, state->nsrecs);
677         if (tevent_req_nomem(subreq, req)) {
678                 return;
679         }
680         tevent_req_set_callback(subreq, handle_authoritative_done, req);
681 }
682
683 static WERROR handle_authoritative_recv(struct tevent_req *req)
684 {
685         struct handle_authoritative_state *state = tevent_req_data(
686                 req, struct handle_authoritative_state);
687         WERROR werr;
688
689         if (tevent_req_is_werror(req, &werr)) {
690                 return werr;
691         }
692
693         werr = add_zone_authority_record(state->dns, state, state->question,
694                                          state->nsrecs);
695         if (!W_ERROR_IS_OK(werr)) {
696                 return werr;
697         }
698
699         return WERR_OK;
700 }
701
702 static NTSTATUS create_tkey(struct dns_server *dns,
703                             const char* name,
704                             const char* algorithm,
705                             const struct tsocket_address *remote_address,
706                             const struct tsocket_address *local_address,
707                             struct dns_server_tkey **tkey)
708 {
709         NTSTATUS status;
710         struct dns_server_tkey_store *store = dns->tkeys;
711         struct dns_server_tkey *k = talloc_zero(store, struct dns_server_tkey);
712
713         if (k == NULL) {
714                 return NT_STATUS_NO_MEMORY;
715         }
716
717         k->name = talloc_strdup(k, name);
718
719         if (k->name  == NULL) {
720                 return NT_STATUS_NO_MEMORY;
721         }
722
723         k->algorithm = talloc_strdup(k, algorithm);
724         if (k->algorithm == NULL) {
725                 return NT_STATUS_NO_MEMORY;
726         }
727
728         /*
729          * We only allow SPNEGO/KRB5 currently
730          * and rely on the backend to be RPC/IPC free.
731          *
732          * It allows gensec_update() not to block.
733          */
734         status = samba_server_gensec_krb5_start(k,
735                                                 dns->task->event_ctx,
736                                                 dns->task->msg_ctx,
737                                                 dns->task->lp_ctx,
738                                                 dns->server_credentials,
739                                                 "dns",
740                                                 &k->gensec);
741         if (!NT_STATUS_IS_OK(status)) {
742                 DEBUG(1, ("Failed to start GENSEC server code: %s\n", nt_errstr(status)));
743                 *tkey = NULL;
744                 return status;
745         }
746
747         gensec_want_feature(k->gensec, GENSEC_FEATURE_SIGN);
748
749         status = gensec_set_remote_address(k->gensec,
750                                            remote_address);
751         if (!NT_STATUS_IS_OK(status)) {
752                 DEBUG(1, ("Failed to set remote address into GENSEC: %s\n",
753                           nt_errstr(status)));
754                 *tkey = NULL;
755                 return status;
756         }
757
758         status = gensec_set_local_address(k->gensec,
759                                           local_address);
760         if (!NT_STATUS_IS_OK(status)) {
761                 DEBUG(1, ("Failed to set local address into GENSEC: %s\n",
762                           nt_errstr(status)));
763                 *tkey = NULL;
764                 return status;
765         }
766
767         status = gensec_start_mech_by_oid(k->gensec, GENSEC_OID_SPNEGO);
768
769         if (!NT_STATUS_IS_OK(status)) {
770                 DEBUG(1, ("Failed to start GENSEC server code: %s\n",
771                           nt_errstr(status)));
772                 *tkey = NULL;
773                 return status;
774         }
775
776         if (store->tkeys[store->next_idx] != NULL) {
777                 TALLOC_FREE(store->tkeys[store->next_idx]);
778         }
779
780         store->tkeys[store->next_idx] = k;
781         (store->next_idx)++;
782         store->next_idx %= store->size;
783
784         *tkey = k;
785         return NT_STATUS_OK;
786 }
787
788 static NTSTATUS accept_gss_ticket(TALLOC_CTX *mem_ctx,
789                                   struct dns_server *dns,
790                                   struct dns_server_tkey *tkey,
791                                   const DATA_BLOB *key,
792                                   DATA_BLOB *reply,
793                                   uint16_t *dns_auth_error)
794 {
795         NTSTATUS status;
796
797         /*
798          * We use samba_server_gensec_krb5_start(),
799          * which only allows SPNEGO/KRB5 currently
800          * and makes sure the backend to be RPC/IPC free.
801          *
802          * See gensec_gssapi_update_internal() as
803          * GENSEC_SERVER.
804          *
805          * It allows gensec_update() not to block.
806          *
807          * If that changes in future we need to use
808          * gensec_update_send/recv here!
809          */
810         status = gensec_update(tkey->gensec, mem_ctx,
811                                *key, reply);
812
813         if (NT_STATUS_EQUAL(NT_STATUS_MORE_PROCESSING_REQUIRED, status)) {
814                 *dns_auth_error = DNS_RCODE_OK;
815                 return status;
816         }
817
818         if (NT_STATUS_IS_OK(status)) {
819
820                 status = gensec_session_info(tkey->gensec, tkey, &tkey->session_info);
821                 if (!NT_STATUS_IS_OK(status)) {
822                         *dns_auth_error = DNS_RCODE_BADKEY;
823                         return status;
824                 }
825                 *dns_auth_error = DNS_RCODE_OK;
826         }
827
828         return status;
829 }
830
831 static WERROR handle_tkey(struct dns_server *dns,
832                           TALLOC_CTX *mem_ctx,
833                           const struct dns_name_packet *in,
834                           struct dns_request_state *state,
835                           struct dns_res_rec **answers,
836                           uint16_t *ancount)
837 {
838         struct dns_res_rec *in_tkey = NULL;
839         struct dns_res_rec *ret_tkey;
840         uint16_t i;
841
842         for (i = 0; i < in->arcount; i++) {
843                 if (in->additional[i].rr_type == DNS_QTYPE_TKEY) {
844                         in_tkey = &in->additional[i];
845                         break;
846                 }
847         }
848
849         /* If this is a TKEY query, it should have a TKEY RR.
850          * Behaviour is not really specified in RFC 2930 or RFC 3645, but
851          * FORMAT_ERROR seems to be what BIND uses .*/
852         if (in_tkey == NULL) {
853                 return DNS_ERR(FORMAT_ERROR);
854         }
855
856         ret_tkey = talloc_zero(mem_ctx, struct dns_res_rec);
857         if (ret_tkey == NULL) {
858                 return WERR_NOT_ENOUGH_MEMORY;
859         }
860
861         ret_tkey->name = talloc_strdup(ret_tkey, in_tkey->name);
862         if (ret_tkey->name == NULL) {
863                 return WERR_NOT_ENOUGH_MEMORY;
864         }
865
866         ret_tkey->rr_type = DNS_QTYPE_TKEY;
867         ret_tkey->rr_class = DNS_QCLASS_ANY;
868         ret_tkey->length = UINT16_MAX;
869
870         ret_tkey->rdata.tkey_record.algorithm = talloc_strdup(ret_tkey,
871                         in_tkey->rdata.tkey_record.algorithm);
872         if (ret_tkey->rdata.tkey_record.algorithm  == NULL) {
873                 return WERR_NOT_ENOUGH_MEMORY;
874         }
875
876         ret_tkey->rdata.tkey_record.inception = in_tkey->rdata.tkey_record.inception;
877         ret_tkey->rdata.tkey_record.expiration = in_tkey->rdata.tkey_record.expiration;
878         ret_tkey->rdata.tkey_record.mode = in_tkey->rdata.tkey_record.mode;
879
880         switch (in_tkey->rdata.tkey_record.mode) {
881         case DNS_TKEY_MODE_DH:
882                 /* FIXME: According to RFC 2930, we MUST support this, but we don't.
883                  * Still, claim it's a bad key instead of a bad mode */
884                 ret_tkey->rdata.tkey_record.error = DNS_RCODE_BADKEY;
885                 break;
886         case DNS_TKEY_MODE_GSSAPI: {
887                 NTSTATUS status;
888                 struct dns_server_tkey *tkey;
889                 DATA_BLOB key;
890                 DATA_BLOB reply;
891
892                 tkey = dns_find_tkey(dns->tkeys, in->questions[0].name);
893                 if (tkey != NULL && tkey->complete) {
894                         /* TODO: check if the key is still valid */
895                         DEBUG(1, ("Rejecting tkey negotiation for already established key\n"));
896                         ret_tkey->rdata.tkey_record.error = DNS_RCODE_BADNAME;
897                         break;
898                 }
899
900                 if (tkey == NULL) {
901                         status  = create_tkey(dns, in->questions[0].name,
902                                               in_tkey->rdata.tkey_record.algorithm,
903                                               state->remote_address,
904                                               state->local_address,
905                                               &tkey);
906                         if (!NT_STATUS_IS_OK(status)) {
907                                 ret_tkey->rdata.tkey_record.error = DNS_RCODE_BADKEY;
908                                 return ntstatus_to_werror(status);
909                         }
910                 }
911
912                 key.data = in_tkey->rdata.tkey_record.key_data;
913                 key.length = in_tkey->rdata.tkey_record.key_size;
914
915                 status = accept_gss_ticket(ret_tkey, dns, tkey, &key, &reply,
916                                            &ret_tkey->rdata.tkey_record.error);
917                 if (NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
918                         DEBUG(1, ("More processing required\n"));
919                         ret_tkey->rdata.tkey_record.error = DNS_RCODE_BADKEY;
920                 } else if (NT_STATUS_IS_OK(status)) {
921                         DEBUG(1, ("Tkey handshake completed\n"));
922                         ret_tkey->rdata.tkey_record.key_size = reply.length;
923                         ret_tkey->rdata.tkey_record.key_data = talloc_memdup(ret_tkey,
924                                                                 reply.data,
925                                                                 reply.length);
926                         state->sign = true;
927                         state->key_name = talloc_strdup(state->mem_ctx, tkey->name);
928                         if (state->key_name == NULL) {
929                                 return WERR_NOT_ENOUGH_MEMORY;
930                         }
931                 } else {
932                         DEBUG(1, ("GSS key negotiation returned %s\n", nt_errstr(status)));
933                         ret_tkey->rdata.tkey_record.error = DNS_RCODE_BADKEY;
934                 }
935
936                 break;
937                 }
938         case DNS_TKEY_MODE_DELETE:
939                 /* TODO: implement me */
940                 DEBUG(1, ("Should delete tkey here\n"));
941                 ret_tkey->rdata.tkey_record.error = DNS_RCODE_OK;
942                 break;
943         case DNS_TKEY_MODE_NULL:
944         case DNS_TKEY_MODE_SERVER:
945         case DNS_TKEY_MODE_CLIENT:
946         case DNS_TKEY_MODE_LAST:
947                 /* We don't have to implement these, return a mode error */
948                 ret_tkey->rdata.tkey_record.error = DNS_RCODE_BADMODE;
949                 break;
950         default:
951                 DEBUG(1, ("Unsupported TKEY mode %d\n",
952                       in_tkey->rdata.tkey_record.mode));
953         }
954
955         *answers = ret_tkey;
956         *ancount = 1;
957
958         return WERR_OK;
959 }
960
961 struct dns_server_process_query_state {
962         struct tevent_context *ev;
963         struct dns_server *dns;
964         struct dns_name_question *question;
965
966         struct dns_res_rec *answers;
967         uint16_t ancount;
968         struct dns_res_rec *nsrecs;
969         uint16_t nscount;
970         struct dns_res_rec *additional;
971         uint16_t arcount;
972         struct forwarder_string *forwarders;
973 };
974
975 static void dns_server_process_query_got_auth(struct tevent_req *subreq);
976 static void dns_server_process_query_got_response(struct tevent_req *subreq);
977
978 struct tevent_req *dns_server_process_query_send(
979         TALLOC_CTX *mem_ctx, struct tevent_context *ev,
980         struct dns_server *dns, struct dns_request_state *req_state,
981         const struct dns_name_packet *in)
982 {
983         struct tevent_req *req, *subreq;
984         struct dns_server_process_query_state *state;
985         const char **forwarders = NULL;
986         unsigned int i;
987
988         req = tevent_req_create(mem_ctx, &state,
989                                 struct dns_server_process_query_state);
990         if (req == NULL) {
991                 return NULL;
992         }
993         if (in->qdcount != 1) {
994                 tevent_req_werror(req, DNS_ERR(FORMAT_ERROR));
995                 return tevent_req_post(req, ev);
996         }
997
998         /* Windows returns NOT_IMPLEMENTED on this as well */
999         if (in->questions[0].question_class == DNS_QCLASS_NONE) {
1000                 tevent_req_werror(req, DNS_ERR(NOT_IMPLEMENTED));
1001                 return tevent_req_post(req, ev);
1002         }
1003
1004         if (in->questions[0].question_type == DNS_QTYPE_TKEY) {
1005                 WERROR err;
1006
1007                 err = handle_tkey(dns, state, in, req_state,
1008                                   &state->answers, &state->ancount);
1009                 if (tevent_req_werror(req, err)) {
1010                         return tevent_req_post(req, ev);
1011                 }
1012                 tevent_req_done(req);
1013                 return tevent_req_post(req, ev);
1014         }
1015
1016         state->dns = dns;
1017         state->ev = ev;
1018         state->question = &in->questions[0];
1019
1020         forwarders = lpcfg_dns_forwarder(dns->task->lp_ctx);
1021         for (i = 0; forwarders != NULL && forwarders[i] != NULL; i++) {
1022                 struct forwarder_string *f = talloc_zero(state,
1023                                                          struct forwarder_string);
1024                 f->forwarder = forwarders[i];
1025                 DLIST_ADD_END(state->forwarders, f);
1026         }
1027
1028         if (dns_authoritative_for_zone(dns, in->questions[0].name)) {
1029
1030                 req_state->flags |= DNS_FLAG_AUTHORITATIVE;
1031
1032                 /*
1033                  * Initialize the response arrays, so that we can use
1034                  * them as their own talloc contexts when doing the
1035                  * realloc
1036                  */
1037                 state->answers = talloc_array(state, struct dns_res_rec, 0);
1038                 if (tevent_req_nomem(state->answers, req)) {
1039                         return tevent_req_post(req, ev);
1040                 }
1041                 state->nsrecs = talloc_array(state, struct dns_res_rec, 0);
1042                 if (tevent_req_nomem(state->nsrecs, req)) {
1043                         return tevent_req_post(req, ev);
1044                 }
1045
1046                 subreq = handle_authoritative_send(
1047                         state, ev, dns, (forwarders == NULL ? NULL : forwarders[0]),
1048                         &in->questions[0], &state->answers, &state->nsrecs);
1049                 if (tevent_req_nomem(subreq, req)) {
1050                         return tevent_req_post(req, ev);
1051                 }
1052                 tevent_req_set_callback(
1053                         subreq, dns_server_process_query_got_auth, req);
1054                 return req;
1055         }
1056
1057         if ((req_state->flags & DNS_FLAG_RECURSION_DESIRED) &&
1058             (req_state->flags & DNS_FLAG_RECURSION_AVAIL)) {
1059                 DEBUG(5, ("Not authoritative for '%s', forwarding\n",
1060                           in->questions[0].name));
1061
1062                 subreq = ask_forwarder_send(state, ev, dns,
1063                                             (forwarders == NULL ? NULL : forwarders[0]),
1064                                             &in->questions[0]);
1065                 if (tevent_req_nomem(subreq, req)) {
1066                         return tevent_req_post(req, ev);
1067                 }
1068                 tevent_req_set_callback(
1069                         subreq, dns_server_process_query_got_response, req);
1070                 return req;
1071         }
1072
1073         tevent_req_werror(req, DNS_ERR(NAME_ERROR));
1074         return tevent_req_post(req, ev);
1075 }
1076
1077 static void dns_server_process_query_got_response(struct tevent_req *subreq)
1078 {
1079         struct tevent_req *req = tevent_req_callback_data(
1080                 subreq, struct tevent_req);
1081         struct dns_server_process_query_state *state = tevent_req_data(
1082                 req, struct dns_server_process_query_state);
1083         WERROR werr;
1084
1085         werr = ask_forwarder_recv(subreq, state,
1086                                   &state->answers, &state->ancount,
1087                                   &state->nsrecs, &state->nscount,
1088                                   &state->additional, &state->arcount);
1089         TALLOC_FREE(subreq);
1090
1091         /* If you get an error, attempt a different forwarder */
1092         if (!W_ERROR_IS_OK(werr)) {
1093                 if (state->forwarders != NULL) {
1094                         DLIST_REMOVE(state->forwarders, state->forwarders);
1095                 }
1096
1097                 /* If you have run out of forwarders, simply finish */
1098                 if (state->forwarders == NULL) {
1099                         tevent_req_werror(req, werr);
1100                         return;
1101                 }
1102
1103                 DEBUG(5, ("DNS query returned %s, trying another forwarder.\n",
1104                           win_errstr(werr)));
1105                 subreq = ask_forwarder_send(state, state->ev, state->dns,
1106                                             state->forwarders->forwarder,
1107                                             state->question);
1108
1109                 if (tevent_req_nomem(subreq, req)) {
1110                         return;
1111                 }
1112
1113                 tevent_req_set_callback(subreq,
1114                                         dns_server_process_query_got_response,
1115                                         req);
1116                 return;
1117         }
1118
1119         tevent_req_done(req);
1120 }
1121
1122 static void dns_server_process_query_got_auth(struct tevent_req *subreq)
1123 {
1124         struct tevent_req *req = tevent_req_callback_data(
1125                 subreq, struct tevent_req);
1126         struct dns_server_process_query_state *state = tevent_req_data(
1127                 req, struct dns_server_process_query_state);
1128         WERROR werr;
1129
1130         werr = handle_authoritative_recv(subreq);
1131         TALLOC_FREE(subreq);
1132
1133         /* If you get an error, attempt a different forwarder */
1134         if (!W_ERROR_IS_OK(werr)) {
1135                 if (state->forwarders != NULL) {
1136                         DLIST_REMOVE(state->forwarders, state->forwarders);
1137                 }
1138
1139                 /* If you have run out of forwarders, simply finish */
1140                 if (state->forwarders == NULL) {
1141                         tevent_req_werror(req, werr);
1142                         return;
1143                 }
1144
1145                 DEBUG(5, ("Error: %s, trying a different forwarder.\n",
1146                           win_errstr(werr)));
1147                 subreq = handle_authoritative_send(state, state->ev, state->dns,
1148                                                    state->forwarders->forwarder,
1149                                                    state->question, &state->answers,
1150                                                    &state->nsrecs);
1151
1152                 if (tevent_req_nomem(subreq, req)) {
1153                         return;
1154                 }
1155
1156                 tevent_req_set_callback(subreq,
1157                                         dns_server_process_query_got_auth,
1158                                         req);
1159                 return;
1160         }
1161
1162         state->ancount = talloc_array_length(state->answers);
1163         state->nscount = talloc_array_length(state->nsrecs);
1164         state->arcount = talloc_array_length(state->additional);
1165
1166         tevent_req_done(req);
1167 }
1168
1169 WERROR dns_server_process_query_recv(
1170         struct tevent_req *req, TALLOC_CTX *mem_ctx,
1171         struct dns_res_rec **answers,    uint16_t *ancount,
1172         struct dns_res_rec **nsrecs,     uint16_t *nscount,
1173         struct dns_res_rec **additional, uint16_t *arcount)
1174 {
1175         struct dns_server_process_query_state *state = tevent_req_data(
1176                 req, struct dns_server_process_query_state);
1177         WERROR err = WERR_OK;
1178
1179         if (tevent_req_is_werror(req, &err)) {
1180
1181                 if ((!W_ERROR_EQUAL(err, DNS_ERR(NAME_ERROR))) &&
1182                     (!W_ERROR_EQUAL(err, WERR_DNS_ERROR_NAME_DOES_NOT_EXIST))) {
1183                         return err;
1184                 }
1185         }
1186         *answers = talloc_move(mem_ctx, &state->answers);
1187         *ancount = state->ancount;
1188         *nsrecs = talloc_move(mem_ctx, &state->nsrecs);
1189         *nscount = state->nscount;
1190         *additional = talloc_move(mem_ctx, &state->additional);
1191         *arcount = state->arcount;
1192         return err;
1193 }