923f7233eb995baaa524621567a75e981a0f32c5
[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 = (enum dns_qtype)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 dns_name_packet *reply;
274 };
275
276 static void ask_forwarder_done(struct tevent_req *subreq);
277
278 static struct tevent_req *ask_forwarder_send(
279         TALLOC_CTX *mem_ctx, struct tevent_context *ev,
280         const char *forwarder, struct dns_name_question *question)
281 {
282         struct tevent_req *req, *subreq;
283         struct ask_forwarder_state *state;
284
285         req = tevent_req_create(mem_ctx, &state, struct ask_forwarder_state);
286         if (req == NULL) {
287                 return NULL;
288         }
289
290         subreq = dns_cli_request_send(state, ev, forwarder,
291                                       question->name, question->question_class,
292                                       question->question_type);
293         if (tevent_req_nomem(subreq, req)) {
294                 return tevent_req_post(req, ev);
295         }
296         tevent_req_set_callback(subreq, ask_forwarder_done, req);
297         return req;
298 }
299
300 static void ask_forwarder_done(struct tevent_req *subreq)
301 {
302         struct tevent_req *req = tevent_req_callback_data(
303                 subreq, struct tevent_req);
304         struct ask_forwarder_state *state = tevent_req_data(
305                 req, struct ask_forwarder_state);
306         int ret;
307
308         ret = dns_cli_request_recv(subreq, state, &state->reply);
309         TALLOC_FREE(subreq);
310
311         if (ret != 0) {
312                 tevent_req_werror(req, unix_to_werror(ret));
313                 return;
314         }
315
316         tevent_req_done(req);
317 }
318
319 static WERROR ask_forwarder_recv(
320         struct tevent_req *req, TALLOC_CTX *mem_ctx,
321         struct dns_res_rec **answers, uint16_t *ancount,
322         struct dns_res_rec **nsrecs, uint16_t *nscount,
323         struct dns_res_rec **additional, uint16_t *arcount)
324 {
325         struct ask_forwarder_state *state = tevent_req_data(
326                 req, struct ask_forwarder_state);
327         struct dns_name_packet *in_packet = state->reply;
328         WERROR err;
329
330         if (tevent_req_is_werror(req, &err)) {
331                 return err;
332         }
333
334         *ancount = in_packet->ancount;
335         *answers = talloc_move(mem_ctx, &in_packet->answers);
336
337         *nscount = in_packet->nscount;
338         *nsrecs = talloc_move(mem_ctx, &in_packet->nsrecs);
339
340         *arcount = in_packet->arcount;
341         *additional = talloc_move(mem_ctx, &in_packet->additional);
342
343         return WERR_OK;
344 }
345
346 static WERROR add_zone_authority_record(struct dns_server *dns,
347                                         TALLOC_CTX *mem_ctx,
348                                         const struct dns_name_question *question,
349                                         struct dns_res_rec **nsrecs)
350 {
351         const char *zone = NULL;
352         struct dnsp_DnssrvRpcRecord *recs;
353         struct dns_res_rec *ns = *nsrecs;
354         uint16_t rec_count;
355         struct ldb_dn *dn = NULL;
356         unsigned int ri;
357         WERROR werror;
358
359         zone = dns_get_authoritative_zone(dns, question->name);
360         DEBUG(10, ("Creating zone authority record for '%s'\n", zone));
361
362         werror = dns_name2dn(dns, mem_ctx, zone, &dn);
363         if (!W_ERROR_IS_OK(werror)) {
364                 return werror;
365         }
366
367         werror = dns_lookup_records(dns, mem_ctx, dn, &recs, &rec_count);
368         if (!W_ERROR_IS_OK(werror)) {
369                 return werror;
370         }
371
372         for (ri = 0; ri < rec_count; ri++) {
373                 if (recs[ri].wType == DNS_TYPE_SOA) {
374                         werror = add_response_rr(zone, &recs[ri], &ns);
375                         if (!W_ERROR_IS_OK(werror)) {
376                                 return werror;
377                         }
378                 }
379         }
380
381         *nsrecs = ns;
382
383         return WERR_OK;
384 }
385
386 static struct tevent_req *handle_authoritative_send(
387         TALLOC_CTX *mem_ctx, struct tevent_context *ev,
388         struct dns_server *dns, const char *forwarder,
389         struct dns_name_question *question,
390         struct dns_res_rec **answers, struct dns_res_rec **nsrecs);
391 static WERROR handle_authoritative_recv(struct tevent_req *req);
392
393 struct handle_dnsrpcrec_state {
394         struct dns_res_rec **answers;
395         struct dns_res_rec **nsrecs;
396 };
397
398 static void handle_dnsrpcrec_gotauth(struct tevent_req *subreq);
399 static void handle_dnsrpcrec_gotforwarded(struct tevent_req *subreq);
400
401 static struct tevent_req *handle_dnsrpcrec_send(
402         TALLOC_CTX *mem_ctx, struct tevent_context *ev,
403         struct dns_server *dns, const char *forwarder,
404         const struct dns_name_question *question,
405         struct dnsp_DnssrvRpcRecord *rec,
406         struct dns_res_rec **answers, struct dns_res_rec **nsrecs)
407 {
408         struct tevent_req *req, *subreq;
409         struct handle_dnsrpcrec_state *state;
410         struct dns_name_question *new_q;
411         bool resolve_cname;
412         WERROR werr;
413
414         req = tevent_req_create(mem_ctx, &state,
415                                 struct handle_dnsrpcrec_state);
416         if (req == NULL) {
417                 return NULL;
418         }
419         state->answers = answers;
420         state->nsrecs = nsrecs;
421
422         resolve_cname = ((rec->wType == DNS_TYPE_CNAME) &&
423                          ((question->question_type == DNS_QTYPE_A) ||
424                           (question->question_type == DNS_QTYPE_AAAA)));
425
426         if (!resolve_cname) {
427                 if ((question->question_type != DNS_QTYPE_ALL) &&
428                     (rec->wType !=
429                      (enum dns_record_type) question->question_type)) {
430                         tevent_req_done(req);
431                         return tevent_req_post(req, ev);
432                 }
433
434                 werr = add_response_rr(question->name, rec, state->answers);
435                 if (tevent_req_werror(req, werr)) {
436                         return tevent_req_post(req, ev);
437                 }
438
439                 tevent_req_done(req);
440                 return tevent_req_post(req, ev);
441         }
442
443         werr = add_response_rr(question->name, rec, state->answers);
444         if (tevent_req_werror(req, werr)) {
445                 return tevent_req_post(req, ev);
446         }
447
448         new_q = talloc(state, struct dns_name_question);
449         if (tevent_req_nomem(new_q, req)) {
450                 return tevent_req_post(req, ev);
451         }
452
453         *new_q = (struct dns_name_question) {
454                 .question_type = question->question_type,
455                 .question_class = question->question_class,
456                 .name = rec->data.cname
457         };
458
459         if (dns_authoritative_for_zone(dns, new_q->name)) {
460                 subreq = handle_authoritative_send(
461                         state, ev, dns, forwarder, new_q,
462                         state->answers, state->nsrecs);
463                 if (tevent_req_nomem(subreq, req)) {
464                         return tevent_req_post(req, ev);
465                 }
466                 tevent_req_set_callback(subreq, handle_dnsrpcrec_gotauth, req);
467                 return req;
468         }
469
470         subreq = ask_forwarder_send(state, ev, forwarder, new_q);
471         if (tevent_req_nomem(subreq, req)) {
472                 return tevent_req_post(req, ev);
473         }
474         tevent_req_set_callback(subreq, handle_dnsrpcrec_gotforwarded, req);
475
476         return req;
477 }
478
479 static void handle_dnsrpcrec_gotauth(struct tevent_req *subreq)
480 {
481         struct tevent_req *req = tevent_req_callback_data(
482                 subreq, struct tevent_req);
483         WERROR werr;
484
485         werr = handle_authoritative_recv(subreq);
486         TALLOC_FREE(subreq);
487         if (tevent_req_werror(req, werr)) {
488                 return;
489         }
490         tevent_req_done(req);
491 }
492
493 static void handle_dnsrpcrec_gotforwarded(struct tevent_req *subreq)
494 {
495         struct tevent_req *req = tevent_req_callback_data(
496                 subreq, struct tevent_req);
497         struct handle_dnsrpcrec_state *state = tevent_req_data(
498                 req, struct handle_dnsrpcrec_state);
499         struct dns_res_rec *answers, *nsrecs, *additional;
500         uint16_t ancount = 0;
501         uint16_t nscount = 0;
502         uint16_t arcount = 0;
503         uint16_t i;
504         WERROR werr;
505
506         werr = ask_forwarder_recv(subreq, state, &answers, &ancount,
507                                   &nsrecs, &nscount, &additional, &arcount);
508         if (tevent_req_werror(req, werr)) {
509                 return;
510         }
511
512         for (i=0; i<ancount; i++) {
513                 werr = add_dns_res_rec(state->answers, &answers[i]);
514                 if (tevent_req_werror(req, werr)) {
515                         return;
516                 }
517         }
518
519         for (i=0; i<nscount; i++) {
520                 werr = add_dns_res_rec(state->nsrecs, &nsrecs[i]);
521                 if (tevent_req_werror(req, werr)) {
522                         return;
523                 }
524         }
525
526         tevent_req_done(req);
527 }
528
529 static WERROR handle_dnsrpcrec_recv(struct tevent_req *req)
530 {
531         return tevent_req_simple_recv_werror(req);
532 }
533
534 struct handle_authoritative_state {
535         struct tevent_context *ev;
536         struct dns_server *dns;
537         struct dns_name_question *question;
538         const char *forwarder;
539
540         struct dnsp_DnssrvRpcRecord *recs;
541         uint16_t rec_count;
542         uint16_t recs_done;
543
544         struct dns_res_rec **answers;
545         struct dns_res_rec **nsrecs;
546 };
547
548 static void handle_authoritative_done(struct tevent_req *subreq);
549
550 static struct tevent_req *handle_authoritative_send(
551         TALLOC_CTX *mem_ctx, struct tevent_context *ev,
552         struct dns_server *dns, const char *forwarder,
553         struct dns_name_question *question,
554         struct dns_res_rec **answers, struct dns_res_rec **nsrecs)
555 {
556         struct tevent_req *req, *subreq;
557         struct handle_authoritative_state *state;
558         struct ldb_dn *dn = NULL;
559         WERROR werr;
560
561         req = tevent_req_create(mem_ctx, &state,
562                                 struct handle_authoritative_state);
563         if (req == NULL) {
564                 return NULL;
565         }
566         state->ev = ev;
567         state->dns = dns;
568         state->question = question;
569         state->forwarder = forwarder;
570         state->answers = answers;
571         state->nsrecs = nsrecs;
572
573         werr = dns_name2dn(dns, state, question->name, &dn);
574         if (tevent_req_werror(req, werr)) {
575                 return tevent_req_post(req, ev);
576         }
577         werr = dns_lookup_records_wildcard(dns, state, dn, &state->recs,
578                                            &state->rec_count);
579         TALLOC_FREE(dn);
580         if (tevent_req_werror(req, werr)) {
581                 return tevent_req_post(req, ev);
582         }
583
584         if (state->rec_count == 0) {
585                 tevent_req_werror(req, DNS_ERR(NAME_ERROR));
586                 return tevent_req_post(req, ev);
587         }
588
589         subreq = handle_dnsrpcrec_send(
590                 state, state->ev, state->dns, state->forwarder,
591                 state->question, &state->recs[state->recs_done],
592                 state->answers, state->nsrecs);
593         if (tevent_req_nomem(subreq, req)) {
594                 return tevent_req_post(req, ev);
595         }
596         tevent_req_set_callback(subreq, handle_authoritative_done, req);
597         return req;
598 }
599
600 static void handle_authoritative_done(struct tevent_req *subreq)
601 {
602         struct tevent_req *req = tevent_req_callback_data(
603                 subreq, struct tevent_req);
604         struct handle_authoritative_state *state = tevent_req_data(
605                 req, struct handle_authoritative_state);
606         WERROR werr;
607
608         werr = handle_dnsrpcrec_recv(subreq);
609         TALLOC_FREE(subreq);
610         if (tevent_req_werror(req, werr)) {
611                 return;
612         }
613
614         state->recs_done += 1;
615
616         if (state->recs_done == state->rec_count) {
617                 tevent_req_done(req);
618                 return;
619         }
620
621         subreq = handle_dnsrpcrec_send(
622                 state, state->ev, state->dns, state->forwarder,
623                 state->question, &state->recs[state->recs_done],
624                 state->answers, state->nsrecs);
625         if (tevent_req_nomem(subreq, req)) {
626                 return;
627         }
628         tevent_req_set_callback(subreq, handle_authoritative_done, req);
629 }
630
631 static WERROR handle_authoritative_recv(struct tevent_req *req)
632 {
633         struct handle_authoritative_state *state = tevent_req_data(
634                 req, struct handle_authoritative_state);
635         WERROR werr;
636
637         if (tevent_req_is_werror(req, &werr)) {
638                 return werr;
639         }
640
641         werr = add_zone_authority_record(state->dns, state, state->question,
642                                          state->nsrecs);
643         if (!W_ERROR_IS_OK(werr)) {
644                 return werr;
645         }
646
647         return WERR_OK;
648 }
649
650 static NTSTATUS create_tkey(struct dns_server *dns,
651                             const char* name,
652                             const char* algorithm,
653                             const struct tsocket_address *remote_address,
654                             const struct tsocket_address *local_address,
655                             struct dns_server_tkey **tkey)
656 {
657         NTSTATUS status;
658         struct dns_server_tkey_store *store = dns->tkeys;
659         struct dns_server_tkey *k = talloc_zero(store, struct dns_server_tkey);
660
661         if (k == NULL) {
662                 return NT_STATUS_NO_MEMORY;
663         }
664
665         k->name = talloc_strdup(k, name);
666
667         if (k->name  == NULL) {
668                 return NT_STATUS_NO_MEMORY;
669         }
670
671         k->algorithm = talloc_strdup(k, algorithm);
672         if (k->algorithm == NULL) {
673                 return NT_STATUS_NO_MEMORY;
674         }
675
676         /*
677          * We only allow SPNEGO/KRB5 currently
678          * and rely on the backend to be RPC/IPC free.
679          *
680          * It allows gensec_update() not to block.
681          */
682         status = samba_server_gensec_krb5_start(k,
683                                                 dns->task->event_ctx,
684                                                 dns->task->msg_ctx,
685                                                 dns->task->lp_ctx,
686                                                 dns->server_credentials,
687                                                 "dns",
688                                                 &k->gensec);
689         if (!NT_STATUS_IS_OK(status)) {
690                 DEBUG(1, ("Failed to start GENSEC server code: %s\n", nt_errstr(status)));
691                 *tkey = NULL;
692                 return status;
693         }
694
695         gensec_want_feature(k->gensec, GENSEC_FEATURE_SIGN);
696
697         status = gensec_set_remote_address(k->gensec,
698                                            remote_address);
699         if (!NT_STATUS_IS_OK(status)) {
700                 DEBUG(1, ("Failed to set remote address into GENSEC: %s\n",
701                           nt_errstr(status)));
702                 *tkey = NULL;
703                 return status;
704         }
705
706         status = gensec_set_local_address(k->gensec,
707                                           local_address);
708         if (!NT_STATUS_IS_OK(status)) {
709                 DEBUG(1, ("Failed to set local address into GENSEC: %s\n",
710                           nt_errstr(status)));
711                 *tkey = NULL;
712                 return status;
713         }
714
715         status = gensec_start_mech_by_oid(k->gensec, GENSEC_OID_SPNEGO);
716
717         if (!NT_STATUS_IS_OK(status)) {
718                 DEBUG(1, ("Failed to start GENSEC server code: %s\n",
719                           nt_errstr(status)));
720                 *tkey = NULL;
721                 return status;
722         }
723
724         TALLOC_FREE(store->tkeys[store->next_idx]);
725
726         store->tkeys[store->next_idx] = k;
727         (store->next_idx)++;
728         store->next_idx %= store->size;
729
730         *tkey = k;
731         return NT_STATUS_OK;
732 }
733
734 static NTSTATUS accept_gss_ticket(TALLOC_CTX *mem_ctx,
735                                   struct dns_server *dns,
736                                   struct dns_server_tkey *tkey,
737                                   const DATA_BLOB *key,
738                                   DATA_BLOB *reply,
739                                   uint16_t *dns_auth_error)
740 {
741         NTSTATUS status;
742
743         /*
744          * We use samba_server_gensec_krb5_start(),
745          * which only allows SPNEGO/KRB5 currently
746          * and makes sure the backend to be RPC/IPC free.
747          *
748          * See gensec_gssapi_update_internal() as
749          * GENSEC_SERVER.
750          *
751          * It allows gensec_update() not to block.
752          *
753          * If that changes in future we need to use
754          * gensec_update_send/recv here!
755          */
756         status = gensec_update(tkey->gensec, mem_ctx,
757                                *key, reply);
758
759         if (NT_STATUS_EQUAL(NT_STATUS_MORE_PROCESSING_REQUIRED, status)) {
760                 *dns_auth_error = DNS_RCODE_OK;
761                 return status;
762         }
763
764         if (NT_STATUS_IS_OK(status)) {
765
766                 status = gensec_session_info(tkey->gensec, tkey, &tkey->session_info);
767                 if (!NT_STATUS_IS_OK(status)) {
768                         *dns_auth_error = DNS_RCODE_BADKEY;
769                         return status;
770                 }
771                 *dns_auth_error = DNS_RCODE_OK;
772         }
773
774         return status;
775 }
776
777 static WERROR handle_tkey(struct dns_server *dns,
778                           TALLOC_CTX *mem_ctx,
779                           const struct dns_name_packet *in,
780                           struct dns_request_state *state,
781                           struct dns_res_rec **answers,
782                           uint16_t *ancount)
783 {
784         struct dns_res_rec *in_tkey = NULL;
785         struct dns_res_rec *ret_tkey;
786         uint16_t i;
787
788         for (i = 0; i < in->arcount; i++) {
789                 if (in->additional[i].rr_type == DNS_QTYPE_TKEY) {
790                         in_tkey = &in->additional[i];
791                         break;
792                 }
793         }
794
795         /* If this is a TKEY query, it should have a TKEY RR.
796          * Behaviour is not really specified in RFC 2930 or RFC 3645, but
797          * FORMAT_ERROR seems to be what BIND uses .*/
798         if (in_tkey == NULL) {
799                 return DNS_ERR(FORMAT_ERROR);
800         }
801
802         ret_tkey = talloc_zero(mem_ctx, struct dns_res_rec);
803         if (ret_tkey == NULL) {
804                 return WERR_NOT_ENOUGH_MEMORY;
805         }
806
807         ret_tkey->name = talloc_strdup(ret_tkey, in_tkey->name);
808         if (ret_tkey->name == NULL) {
809                 return WERR_NOT_ENOUGH_MEMORY;
810         }
811
812         ret_tkey->rr_type = DNS_QTYPE_TKEY;
813         ret_tkey->rr_class = DNS_QCLASS_ANY;
814         ret_tkey->length = UINT16_MAX;
815
816         ret_tkey->rdata.tkey_record.algorithm = talloc_strdup(ret_tkey,
817                         in_tkey->rdata.tkey_record.algorithm);
818         if (ret_tkey->rdata.tkey_record.algorithm  == NULL) {
819                 return WERR_NOT_ENOUGH_MEMORY;
820         }
821
822         ret_tkey->rdata.tkey_record.inception = in_tkey->rdata.tkey_record.inception;
823         ret_tkey->rdata.tkey_record.expiration = in_tkey->rdata.tkey_record.expiration;
824         ret_tkey->rdata.tkey_record.mode = in_tkey->rdata.tkey_record.mode;
825
826         switch (in_tkey->rdata.tkey_record.mode) {
827         case DNS_TKEY_MODE_DH:
828                 /* FIXME: According to RFC 2930, we MUST support this, but we don't.
829                  * Still, claim it's a bad key instead of a bad mode */
830                 ret_tkey->rdata.tkey_record.error = DNS_RCODE_BADKEY;
831                 break;
832         case DNS_TKEY_MODE_GSSAPI: {
833                 NTSTATUS status;
834                 struct dns_server_tkey *tkey;
835                 DATA_BLOB key;
836                 DATA_BLOB reply;
837
838                 tkey = dns_find_tkey(dns->tkeys, in->questions[0].name);
839                 if (tkey != NULL && tkey->complete) {
840                         /* TODO: check if the key is still valid */
841                         DEBUG(1, ("Rejecting tkey negotiation for already established key\n"));
842                         ret_tkey->rdata.tkey_record.error = DNS_RCODE_BADNAME;
843                         break;
844                 }
845
846                 if (tkey == NULL) {
847                         status  = create_tkey(dns, in->questions[0].name,
848                                               in_tkey->rdata.tkey_record.algorithm,
849                                               state->remote_address,
850                                               state->local_address,
851                                               &tkey);
852                         if (!NT_STATUS_IS_OK(status)) {
853                                 ret_tkey->rdata.tkey_record.error = DNS_RCODE_BADKEY;
854                                 return ntstatus_to_werror(status);
855                         }
856                 }
857
858                 key.data = in_tkey->rdata.tkey_record.key_data;
859                 key.length = in_tkey->rdata.tkey_record.key_size;
860
861                 status = accept_gss_ticket(ret_tkey, dns, tkey, &key, &reply,
862                                            &ret_tkey->rdata.tkey_record.error);
863                 if (NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
864                         DEBUG(1, ("More processing required\n"));
865                         ret_tkey->rdata.tkey_record.error = DNS_RCODE_BADKEY;
866                 } else if (NT_STATUS_IS_OK(status)) {
867                         DBG_DEBUG("Tkey handshake completed\n");
868                         ret_tkey->rdata.tkey_record.key_size = reply.length;
869                         ret_tkey->rdata.tkey_record.key_data = talloc_memdup(ret_tkey,
870                                                                 reply.data,
871                                                                 reply.length);
872                         if (ret_tkey->rdata.tkey_record.key_data == NULL) {
873                                 return WERR_NOT_ENOUGH_MEMORY;
874                         }
875                         state->sign = true;
876                         state->key_name = talloc_strdup(state->mem_ctx, tkey->name);
877                         if (state->key_name == NULL) {
878                                 return WERR_NOT_ENOUGH_MEMORY;
879                         }
880                 } else {
881                         DEBUG(1, ("GSS key negotiation returned %s\n", nt_errstr(status)));
882                         ret_tkey->rdata.tkey_record.error = DNS_RCODE_BADKEY;
883                 }
884
885                 break;
886                 }
887         case DNS_TKEY_MODE_DELETE:
888                 /* TODO: implement me */
889                 DEBUG(1, ("Should delete tkey here\n"));
890                 ret_tkey->rdata.tkey_record.error = DNS_RCODE_OK;
891                 break;
892         case DNS_TKEY_MODE_NULL:
893         case DNS_TKEY_MODE_SERVER:
894         case DNS_TKEY_MODE_CLIENT:
895         case DNS_TKEY_MODE_LAST:
896                 /* We don't have to implement these, return a mode error */
897                 ret_tkey->rdata.tkey_record.error = DNS_RCODE_BADMODE;
898                 break;
899         default:
900                 DEBUG(1, ("Unsupported TKEY mode %d\n",
901                       in_tkey->rdata.tkey_record.mode));
902         }
903
904         *answers = ret_tkey;
905         *ancount = 1;
906
907         return WERR_OK;
908 }
909
910 struct dns_server_process_query_state {
911         struct tevent_context *ev;
912         struct dns_server *dns;
913         struct dns_name_question *question;
914
915         struct dns_res_rec *answers;
916         uint16_t ancount;
917         struct dns_res_rec *nsrecs;
918         uint16_t nscount;
919         struct dns_res_rec *additional;
920         uint16_t arcount;
921         struct forwarder_string *forwarders;
922 };
923
924 static void dns_server_process_query_got_auth(struct tevent_req *subreq);
925 static void dns_server_process_query_got_response(struct tevent_req *subreq);
926
927 struct tevent_req *dns_server_process_query_send(
928         TALLOC_CTX *mem_ctx, struct tevent_context *ev,
929         struct dns_server *dns, struct dns_request_state *req_state,
930         const struct dns_name_packet *in)
931 {
932         struct tevent_req *req, *subreq;
933         struct dns_server_process_query_state *state;
934         const char **forwarders = NULL;
935         unsigned int i;
936
937         req = tevent_req_create(mem_ctx, &state,
938                                 struct dns_server_process_query_state);
939         if (req == NULL) {
940                 return NULL;
941         }
942         if (in->qdcount != 1) {
943                 tevent_req_werror(req, DNS_ERR(FORMAT_ERROR));
944                 return tevent_req_post(req, ev);
945         }
946
947         /* Windows returns NOT_IMPLEMENTED on this as well */
948         if (in->questions[0].question_class == DNS_QCLASS_NONE) {
949                 tevent_req_werror(req, DNS_ERR(NOT_IMPLEMENTED));
950                 return tevent_req_post(req, ev);
951         }
952
953         if (in->questions[0].question_type == DNS_QTYPE_TKEY) {
954                 WERROR err;
955
956                 err = handle_tkey(dns, state, in, req_state,
957                                   &state->answers, &state->ancount);
958                 if (tevent_req_werror(req, err)) {
959                         return tevent_req_post(req, ev);
960                 }
961                 tevent_req_done(req);
962                 return tevent_req_post(req, ev);
963         }
964
965         state->dns = dns;
966         state->ev = ev;
967         state->question = &in->questions[0];
968
969         forwarders = lpcfg_dns_forwarder(dns->task->lp_ctx);
970         for (i = 0; forwarders != NULL && forwarders[i] != NULL; i++) {
971                 struct forwarder_string *f = talloc_zero(state,
972                                                          struct forwarder_string);
973                 f->forwarder = forwarders[i];
974                 DLIST_ADD_END(state->forwarders, f);
975         }
976
977         if (dns_authoritative_for_zone(dns, in->questions[0].name)) {
978
979                 req_state->flags |= DNS_FLAG_AUTHORITATIVE;
980
981                 /*
982                  * Initialize the response arrays, so that we can use
983                  * them as their own talloc contexts when doing the
984                  * realloc
985                  */
986                 state->answers = talloc_array(state, struct dns_res_rec, 0);
987                 if (tevent_req_nomem(state->answers, req)) {
988                         return tevent_req_post(req, ev);
989                 }
990                 state->nsrecs = talloc_array(state, struct dns_res_rec, 0);
991                 if (tevent_req_nomem(state->nsrecs, req)) {
992                         return tevent_req_post(req, ev);
993                 }
994
995                 subreq = handle_authoritative_send(
996                         state, ev, dns, (forwarders == NULL ? NULL : forwarders[0]),
997                         &in->questions[0], &state->answers, &state->nsrecs);
998                 if (tevent_req_nomem(subreq, req)) {
999                         return tevent_req_post(req, ev);
1000                 }
1001                 tevent_req_set_callback(
1002                         subreq, dns_server_process_query_got_auth, req);
1003                 return req;
1004         }
1005
1006         if ((req_state->flags & DNS_FLAG_RECURSION_DESIRED) &&
1007             (req_state->flags & DNS_FLAG_RECURSION_AVAIL)) {
1008                 DEBUG(5, ("Not authoritative for '%s', forwarding\n",
1009                           in->questions[0].name));
1010
1011                 subreq = ask_forwarder_send(state, ev,
1012                                             (forwarders == NULL ? NULL : forwarders[0]),
1013                                             &in->questions[0]);
1014                 if (tevent_req_nomem(subreq, req)) {
1015                         return tevent_req_post(req, ev);
1016                 }
1017                 tevent_req_set_callback(
1018                         subreq, dns_server_process_query_got_response, req);
1019                 return req;
1020         }
1021
1022         tevent_req_werror(req, DNS_ERR(NAME_ERROR));
1023         return tevent_req_post(req, ev);
1024 }
1025
1026 static void dns_server_process_query_got_response(struct tevent_req *subreq)
1027 {
1028         struct tevent_req *req = tevent_req_callback_data(
1029                 subreq, struct tevent_req);
1030         struct dns_server_process_query_state *state = tevent_req_data(
1031                 req, struct dns_server_process_query_state);
1032         WERROR werr;
1033
1034         werr = ask_forwarder_recv(subreq, state,
1035                                   &state->answers, &state->ancount,
1036                                   &state->nsrecs, &state->nscount,
1037                                   &state->additional, &state->arcount);
1038         TALLOC_FREE(subreq);
1039
1040         /* If you get an error, attempt a different forwarder */
1041         if (!W_ERROR_IS_OK(werr)) {
1042                 if (state->forwarders != NULL) {
1043                         DLIST_REMOVE(state->forwarders, state->forwarders);
1044                 }
1045
1046                 /* If you have run out of forwarders, simply finish */
1047                 if (state->forwarders == NULL) {
1048                         tevent_req_werror(req, werr);
1049                         return;
1050                 }
1051
1052                 DEBUG(5, ("DNS query returned %s, trying another forwarder.\n",
1053                           win_errstr(werr)));
1054                 subreq = ask_forwarder_send(state, state->ev,
1055                                             state->forwarders->forwarder,
1056                                             state->question);
1057
1058                 if (tevent_req_nomem(subreq, req)) {
1059                         return;
1060                 }
1061
1062                 tevent_req_set_callback(subreq,
1063                                         dns_server_process_query_got_response,
1064                                         req);
1065                 return;
1066         }
1067
1068         tevent_req_done(req);
1069 }
1070
1071 static void dns_server_process_query_got_auth(struct tevent_req *subreq)
1072 {
1073         struct tevent_req *req = tevent_req_callback_data(
1074                 subreq, struct tevent_req);
1075         struct dns_server_process_query_state *state = tevent_req_data(
1076                 req, struct dns_server_process_query_state);
1077         WERROR werr;
1078
1079         werr = handle_authoritative_recv(subreq);
1080         TALLOC_FREE(subreq);
1081
1082         /* If you get an error, attempt a different forwarder */
1083         if (!W_ERROR_IS_OK(werr)) {
1084                 if (state->forwarders != NULL) {
1085                         DLIST_REMOVE(state->forwarders, state->forwarders);
1086                 }
1087
1088                 /* If you have run out of forwarders, simply finish */
1089                 if (state->forwarders == NULL) {
1090                         tevent_req_werror(req, werr);
1091                         return;
1092                 }
1093
1094                 DEBUG(5, ("Error: %s, trying a different forwarder.\n",
1095                           win_errstr(werr)));
1096                 subreq = handle_authoritative_send(state, state->ev, state->dns,
1097                                                    state->forwarders->forwarder,
1098                                                    state->question, &state->answers,
1099                                                    &state->nsrecs);
1100
1101                 if (tevent_req_nomem(subreq, req)) {
1102                         return;
1103                 }
1104
1105                 tevent_req_set_callback(subreq,
1106                                         dns_server_process_query_got_auth,
1107                                         req);
1108                 return;
1109         }
1110
1111         state->ancount = talloc_array_length(state->answers);
1112         state->nscount = talloc_array_length(state->nsrecs);
1113         state->arcount = talloc_array_length(state->additional);
1114
1115         tevent_req_done(req);
1116 }
1117
1118 WERROR dns_server_process_query_recv(
1119         struct tevent_req *req, TALLOC_CTX *mem_ctx,
1120         struct dns_res_rec **answers,    uint16_t *ancount,
1121         struct dns_res_rec **nsrecs,     uint16_t *nscount,
1122         struct dns_res_rec **additional, uint16_t *arcount)
1123 {
1124         struct dns_server_process_query_state *state = tevent_req_data(
1125                 req, struct dns_server_process_query_state);
1126         WERROR err = WERR_OK;
1127
1128         if (tevent_req_is_werror(req, &err)) {
1129
1130                 if ((!W_ERROR_EQUAL(err, DNS_ERR(NAME_ERROR))) &&
1131                     (!W_ERROR_EQUAL(err, WERR_DNS_ERROR_NAME_DOES_NOT_EXIST))) {
1132                         return err;
1133                 }
1134         }
1135         *answers = talloc_move(mem_ctx, &state->answers);
1136         *ancount = state->ancount;
1137         *nsrecs = talloc_move(mem_ctx, &state->nsrecs);
1138         *nscount = state->nscount;
1139         *additional = talloc_move(mem_ctx, &state->additional);
1140         *arcount = state->arcount;
1141         return err;
1142 }