dns wildcards: fix BUG 13536
[samba.git] / source4 / dns_server / dnsserver_common.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    DNS server utils
5
6    Copyright (C) 2010 Kai Blin
7    Copyright (C) 2014 Stefan Metzmacher
8    Copyright (C) 2015 Andrew Bartlett
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 */
23
24 #include "includes.h"
25 #include "libcli/util/ntstatus.h"
26 #include "libcli/util/werror.h"
27 #include "librpc/ndr/libndr.h"
28 #include "librpc/gen_ndr/ndr_dns.h"
29 #include "librpc/gen_ndr/ndr_dnsp.h"
30 #include <ldb.h>
31 #include "dsdb/samdb/samdb.h"
32 #include "dsdb/common/util.h"
33 #include "dns_server/dnsserver_common.h"
34 #include "rpc_server/dnsserver/dnsserver.h"
35 #include "lib/util/dlinklist.h"
36
37 #undef DBGC_CLASS
38 #define DBGC_CLASS DBGC_DNS
39
40 uint8_t werr_to_dns_err(WERROR werr)
41 {
42         if (W_ERROR_EQUAL(WERR_OK, werr)) {
43                 return DNS_RCODE_OK;
44         } else if (W_ERROR_EQUAL(DNS_ERR(FORMAT_ERROR), werr)) {
45                 return DNS_RCODE_FORMERR;
46         } else if (W_ERROR_EQUAL(DNS_ERR(SERVER_FAILURE), werr)) {
47                 return DNS_RCODE_SERVFAIL;
48         } else if (W_ERROR_EQUAL(DNS_ERR(NAME_ERROR), werr)) {
49                 return DNS_RCODE_NXDOMAIN;
50         } else if (W_ERROR_EQUAL(WERR_DNS_ERROR_NAME_DOES_NOT_EXIST, werr)) {
51                 return DNS_RCODE_NXDOMAIN;
52         } else if (W_ERROR_EQUAL(DNS_ERR(NOT_IMPLEMENTED), werr)) {
53                 return DNS_RCODE_NOTIMP;
54         } else if (W_ERROR_EQUAL(DNS_ERR(REFUSED), werr)) {
55                 return DNS_RCODE_REFUSED;
56         } else if (W_ERROR_EQUAL(DNS_ERR(YXDOMAIN), werr)) {
57                 return DNS_RCODE_YXDOMAIN;
58         } else if (W_ERROR_EQUAL(DNS_ERR(YXRRSET), werr)) {
59                 return DNS_RCODE_YXRRSET;
60         } else if (W_ERROR_EQUAL(DNS_ERR(NXRRSET), werr)) {
61                 return DNS_RCODE_NXRRSET;
62         } else if (W_ERROR_EQUAL(DNS_ERR(NOTAUTH), werr)) {
63                 return DNS_RCODE_NOTAUTH;
64         } else if (W_ERROR_EQUAL(DNS_ERR(NOTZONE), werr)) {
65                 return DNS_RCODE_NOTZONE;
66         } else if (W_ERROR_EQUAL(DNS_ERR(BADKEY), werr)) {
67                 return DNS_RCODE_BADKEY;
68         }
69         DEBUG(5, ("No mapping exists for %s\n", win_errstr(werr)));
70         return DNS_RCODE_SERVFAIL;
71 }
72
73 WERROR dns_common_extract(struct ldb_context *samdb,
74                           const struct ldb_message_element *el,
75                           TALLOC_CTX *mem_ctx,
76                           struct dnsp_DnssrvRpcRecord **records,
77                           uint16_t *num_records)
78 {
79         uint16_t ri;
80         struct dnsp_DnssrvRpcRecord *recs;
81
82         *records = NULL;
83         *num_records = 0;
84
85         recs = talloc_zero_array(mem_ctx, struct dnsp_DnssrvRpcRecord,
86                                  el->num_values);
87         if (recs == NULL) {
88                 return WERR_NOT_ENOUGH_MEMORY;
89         }
90         for (ri = 0; ri < el->num_values; ri++) {
91                 bool am_rodc;
92                 int ret;
93                 const char *dnsHostName = NULL;
94                 struct ldb_val *v = &el->values[ri];
95                 enum ndr_err_code ndr_err;
96                 ndr_err = ndr_pull_struct_blob(v, recs, &recs[ri],
97                                 (ndr_pull_flags_fn_t)ndr_pull_dnsp_DnssrvRpcRecord);
98                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
99                         TALLOC_FREE(recs);
100                         DEBUG(0, ("Failed to grab dnsp_DnssrvRpcRecord\n"));
101                         return DNS_ERR(SERVER_FAILURE);
102                 }
103
104                 /*
105                  * In AD, except on an RODC (where we should list a random RWDC,
106                  * we should over-stamp the MNAME with our own hostname
107                  */
108                 if (recs[ri].wType != DNS_TYPE_SOA) {
109                         continue;
110                 }
111
112                 ret = samdb_rodc(samdb, &am_rodc);
113                 if (ret != LDB_SUCCESS) {
114                         DEBUG(0, ("Failed to confirm we are not an RODC: %s\n",
115                                   ldb_errstring(samdb)));
116                         return DNS_ERR(SERVER_FAILURE);
117                 }
118
119                 if (am_rodc) {
120                         continue;
121                 }
122
123                 ret = samdb_dns_host_name(samdb, &dnsHostName);
124                 if (ret != LDB_SUCCESS || dnsHostName == NULL) {
125                         DEBUG(0, ("Failed to get dnsHostName from rootDSE"));
126                         return DNS_ERR(SERVER_FAILURE);
127                 }
128
129                 recs[ri].data.soa.mname = talloc_strdup(recs, dnsHostName);
130         }
131
132         *records = recs;
133         *num_records = el->num_values;
134         return WERR_OK;
135 }
136
137 /*
138  * Lookup a DNS record, performing an exact match.
139  * i.e. DNS wild card records are not considered.
140  */
141 WERROR dns_common_lookup(struct ldb_context *samdb,
142                          TALLOC_CTX *mem_ctx,
143                          struct ldb_dn *dn,
144                          struct dnsp_DnssrvRpcRecord **records,
145                          uint16_t *num_records,
146                          bool *tombstoned)
147 {
148         static const char * const attrs[] = {
149                 "dnsRecord",
150                 "dNSTombstoned",
151                 NULL
152         };
153         int ret;
154         WERROR werr;
155         struct ldb_message *msg = NULL;
156         struct ldb_message_element *el;
157
158         *records = NULL;
159         *num_records = 0;
160
161         if (tombstoned != NULL) {
162                 *tombstoned = false;
163                 ret = dsdb_search_one(samdb, mem_ctx, &msg, dn,
164                         LDB_SCOPE_BASE, attrs, 0,
165                         "(objectClass=dnsNode)");
166         } else {
167                 ret = dsdb_search_one(samdb, mem_ctx, &msg, dn,
168                         LDB_SCOPE_BASE, attrs, 0,
169                         "(&(objectClass=dnsNode)(!(dNSTombstoned=TRUE)))");
170         }
171         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
172                 return WERR_DNS_ERROR_NAME_DOES_NOT_EXIST;
173         }
174         if (ret != LDB_SUCCESS) {
175                 /* TODO: we need to check if there's a glue record we need to
176                  * create a referral to */
177                 return DNS_ERR(NAME_ERROR);
178         }
179
180         if (tombstoned != NULL) {
181                 *tombstoned = ldb_msg_find_attr_as_bool(msg,
182                                         "dNSTombstoned", false);
183         }
184
185         el = ldb_msg_find_element(msg, "dnsRecord");
186         if (el == NULL) {
187                 TALLOC_FREE(msg);
188                 /*
189                  * records produced by older Samba releases
190                  * keep dnsNode objects without dnsRecord and
191                  * without setting dNSTombstoned=TRUE.
192                  *
193                  * We just pretend they're tombstones.
194                  */
195                 if (tombstoned != NULL) {
196                         struct dnsp_DnssrvRpcRecord *recs;
197                         recs = talloc_array(mem_ctx,
198                                             struct dnsp_DnssrvRpcRecord,
199                                             1);
200                         if (recs == NULL) {
201                                 return WERR_NOT_ENOUGH_MEMORY;
202                         }
203                         recs[0] = (struct dnsp_DnssrvRpcRecord) {
204                                 .wType = DNS_TYPE_TOMBSTONE,
205                                 /*
206                                  * A value of timestamp != 0
207                                  * indicated that the object was already
208                                  * a tombstone, this will be used
209                                  * in dns_common_replace()
210                                  */
211                                 .data.timestamp = 1,
212                         };
213
214                         *tombstoned = true;
215                         *records = recs;
216                         *num_records = 1;
217                         return WERR_OK;
218                 } else {
219                         /*
220                          * Because we are not looking for a tombstone
221                          * in this codepath, we just pretend it does
222                          * not exist at all.
223                          */
224                         return WERR_DNS_ERROR_NAME_DOES_NOT_EXIST;
225                 }
226         }
227
228         werr = dns_common_extract(samdb, el, mem_ctx, records, num_records);
229         TALLOC_FREE(msg);
230         if (!W_ERROR_IS_OK(werr)) {
231                 return werr;
232         }
233
234         return WERR_OK;
235 }
236
237 /*
238  * Build an ldb_parse_tree node for an equality check
239  *
240  * Note: name is assumed to have been validated by dns_name_check
241  *       so will be zero terminated and of a reasonable size.
242  */
243 static struct ldb_parse_tree *build_equality_operation(
244         TALLOC_CTX *mem_ctx,
245         bool add_asterix,     /* prepend an '*' to the name          */
246         const uint8_t *name,  /* the value being matched             */
247         const char *attr,     /* the attribute to check name against */
248         size_t size)          /* length of name                      */
249 {
250
251         struct ldb_parse_tree *el = NULL;  /* Equality node being built */
252         struct ldb_val *value = NULL;      /* Value the attr will be compared
253                                               with */
254         size_t length = 0;                 /* calculated length of the value
255                                               including option '*' prefix and
256                                               '\0' string terminator */
257
258         el = talloc(mem_ctx, struct ldb_parse_tree);
259         if (el == NULL) {
260                 DBG_ERR("Unable to allocate ldb_parse_tree\n");
261                 return NULL;
262         }
263
264         el->operation = LDB_OP_EQUALITY;
265         el->u.equality.attr = talloc_strdup(mem_ctx, attr);
266         value = &el->u.equality.value;
267         length = (add_asterix) ? size + 2 : size + 1;
268         value->data = talloc_zero_array(el, uint8_t, length);
269         if (el == NULL) {
270                 DBG_ERR("Unable to allocate value->data\n");
271                 TALLOC_FREE(el);
272                 return NULL;
273         }
274
275         value->length = length;
276         if (add_asterix) {
277                 value->data[0] = '*';
278                 memcpy(&value->data[1], name, size);
279         } else {
280                 memcpy(value->data, name, size);
281         }
282         return el;
283 }
284
285 /*
286  * Determine the number of levels in name
287  * essentially the number of '.'s in the name + 1
288  *
289  * name is assumed to have been validated by dns_name_check
290  */
291 static unsigned int number_of_labels(const struct ldb_val *name) {
292         int x  = 0;
293         unsigned int labels = 1;
294         for (x = 0; x < name->length; x++) {
295                 if (name->data[x] == '.') {
296                         labels++;
297                 }
298         }
299         return labels;
300 }
301 /*
302  * Build a query that matches the target name, and any possible
303  * DNS wild card entries
304  *
305  * Builds a parse tree equivalent to the example query.
306  *
307  * x.y.z -> (|(name=x.y.z)(name=\2a.y.z)(name=\2a.z)(name=\2a))
308  *
309  * The attribute 'name' is used as this is what the LDB index is on
310  * (the RDN, being 'dc' in this use case, does not have an index in
311  * the AD schema).
312  *
313  * Returns NULL if unable to build the query.
314  *
315  * The first component of the DN is assumed to be the name being looked up
316  * and also that it has been validated by dns_name_check
317  *
318  */
319 #define BASE "(&(objectClass=dnsNode)(!(dNSTombstoned=TRUE))(|(a=b)(c=d)))"
320 static struct ldb_parse_tree *build_wildcard_query(
321         TALLOC_CTX *mem_ctx,
322         struct ldb_dn *dn)
323 {
324         const struct ldb_val *name = NULL;            /* The DNS name being
325                                                          queried */
326         const char *attr = "name";                    /* The attribute name */
327         struct ldb_parse_tree *query = NULL;          /* The constructed query
328                                                          parse tree*/
329         struct ldb_parse_tree *wildcard_query = NULL; /* The parse tree for the
330                                                          name and wild card
331                                                          entries */
332         int labels = 0;         /* The number of labels in the name */
333
334         name = ldb_dn_get_rdn_val(dn);
335         if (name == NULL) {
336                 DBG_ERR("Unable to get domain name value\n");
337                 return NULL;
338         }
339         labels = number_of_labels(name);
340
341         query = ldb_parse_tree(mem_ctx, BASE);
342         if (query == NULL) {
343                 DBG_ERR("Unable to parse query %s\n", BASE);
344                 return NULL;
345         }
346
347         /*
348          * The 3rd element of BASE is a place holder which is replaced with
349          * the actual wild card query
350          */
351         wildcard_query = query->u.list.elements[2];
352         TALLOC_FREE(wildcard_query->u.list.elements);
353
354         wildcard_query->u.list.num_elements = labels + 1;
355         wildcard_query->u.list.elements = talloc_array(
356                 wildcard_query,
357                 struct ldb_parse_tree *,
358                 labels + 1);
359         /*
360          * Build the wild card query
361          */
362         {
363                 int x = 0;   /* current character in the name               */
364                 int l = 0;   /* current equality operator index in elements */
365                 struct ldb_parse_tree *el = NULL; /* Equality operator being
366                                                      built */
367                 bool add_asterix = true;  /* prepend an '*' to the value    */
368                 for (l = 0, x = 0; l < labels && x < name->length; l++) {
369                         unsigned int size = name->length - x;
370                         add_asterix = (name->data[x] == '.');
371                         el = build_equality_operation(
372                                 mem_ctx,
373                                 add_asterix,
374                                 &name->data[x],
375                                 attr,
376                                 size);
377                         if (el == NULL) {
378                                 return NULL;  /* Reason will have been logged */
379                         }
380                         wildcard_query->u.list.elements[l] = el;
381
382                         /* skip to the start of the next label */
383                         x++;
384                         for (;x < name->length && name->data[x] != '.'; x++);
385                 }
386
387                 /* Add the base level "*" only query */
388                 el = build_equality_operation(mem_ctx, true, NULL, attr, 0);
389                 if (el == NULL) {
390                         TALLOC_FREE(query);
391                         return NULL;  /* Reason will have been logged */
392                 }
393                 wildcard_query->u.list.elements[l] = el;
394         }
395         return query;
396 }
397
398 /*
399  * Scan the list of records matching a dns wildcard query and return the
400  * best match.
401  *
402  * The best match is either an exact name match, or the longest wild card
403  * entry returned
404  *
405  * i.e. name = a.b.c candidates *.b.c, *.c,        - *.b.c would be selected
406  *      name = a.b.c candidates a.b.c, *.b.c, *.c  - a.b.c would be selected
407  */
408 static struct ldb_message *get_best_match(struct ldb_dn *dn,
409                                           struct ldb_result *result)
410 {
411         int matched = 0;    /* Index of the current best match in result */
412         size_t length = 0;  /* The length of the current candidate       */
413         const struct ldb_val *target = NULL;    /* value we're looking for */
414         const struct ldb_val *candidate = NULL; /* current candidate value */
415         int x = 0;
416
417         target = ldb_dn_get_rdn_val(dn);
418         for(x = 0; x < result->count; x++) {
419                 candidate = ldb_dn_get_rdn_val(result->msgs[x]->dn);
420                 if (strncasecmp((char *) target->data,
421                                 (char *) candidate->data,
422                                 target->length) == 0) {
423                         /* Exact match stop searching and return */
424                         return result->msgs[x];
425                 }
426                 if (candidate->length > length) {
427                         matched = x;
428                         length  = candidate->length;
429                 }
430         }
431         return result->msgs[matched];
432 }
433
434 /*
435  * Look up a DNS entry, if an exact match does not exist, return the
436  * closest matching DNS wildcard entry if available
437  *
438  * Returns: LDB_ERR_NO_SUCH_OBJECT     If no matching record exists
439  *          LDB_ERR_OPERATIONS_ERROR   If the query fails
440  *          LDB_SUCCESS                If a matching record was retrieved
441  *
442  */
443 static int dns_wildcard_lookup(struct ldb_context *samdb,
444                                TALLOC_CTX *mem_ctx,
445                                struct ldb_dn *dn,
446                                struct ldb_message **msg)
447 {
448         static const char * const attrs[] = {
449                 "dnsRecord",
450                 "dNSTombstoned",
451                 NULL
452         };
453         struct ldb_dn *parent = NULL;     /* The parent dn                    */
454         struct ldb_result *result = NULL; /* Results of the search            */
455         int ret;                          /* Return code                      */
456         struct ldb_parse_tree *query = NULL; /* The query to run              */
457         struct ldb_request *request = NULL;  /* LDB request for the query op  */
458         struct ldb_message *match = NULL;    /* the best matching DNS record  */
459         TALLOC_CTX *frame = talloc_stackframe();
460
461         parent = ldb_dn_get_parent(frame, dn);
462         if (parent == NULL) {
463                 DBG_ERR("Unable to extract parent from dn\n");
464                 TALLOC_FREE(frame);
465                 return LDB_ERR_OPERATIONS_ERROR;
466         }
467
468         query = build_wildcard_query(frame, dn);
469         if (query == NULL) {
470                 TALLOC_FREE(frame);
471                 return LDB_ERR_OPERATIONS_ERROR;
472         }
473
474         result = talloc_zero(mem_ctx, struct ldb_result);
475         if (result == NULL) {
476                 TALLOC_FREE(frame);
477                 DBG_ERR("Unable to allocate ldb_result\n");
478                 return LDB_ERR_OPERATIONS_ERROR;
479         }
480
481         ret = ldb_build_search_req_ex(&request,
482                                       samdb,
483                                       frame,
484                                       parent,
485                                       LDB_SCOPE_ONELEVEL,
486                                       query,
487                                       attrs,
488                                       NULL,
489                                       result,
490                                       ldb_search_default_callback,
491                                       NULL);
492         if (ret != LDB_SUCCESS) {
493                 TALLOC_FREE(frame);
494                 DBG_ERR("ldb_build_search_req_ex returned %d\n", ret);
495                 return ret;
496         }
497
498         ret = ldb_request(samdb, request);
499         if (ret != LDB_SUCCESS) {
500                 TALLOC_FREE(frame);
501                 return ret;
502         }
503
504         ret = ldb_wait(request->handle, LDB_WAIT_ALL);
505         if (ret != LDB_SUCCESS) {
506                 TALLOC_FREE(frame);
507                 return ret;
508         }
509
510         if (result->count == 0) {
511                 TALLOC_FREE(frame);
512                 return LDB_ERR_NO_SUCH_OBJECT;
513         }
514
515         match = get_best_match(dn, result);
516         if (match == NULL) {
517                 TALLOC_FREE(frame);
518                 return LDB_ERR_OPERATIONS_ERROR;
519         }
520
521         *msg = talloc_move(mem_ctx, &match);
522         TALLOC_FREE(frame);
523         return LDB_SUCCESS;
524 }
525
526 /*
527  * Lookup a DNS record, will match DNS wild card records if an exact match
528  * is not found.
529  */
530 WERROR dns_common_wildcard_lookup(struct ldb_context *samdb,
531                                   TALLOC_CTX *mem_ctx,
532                                   struct ldb_dn *dn,
533                                   struct dnsp_DnssrvRpcRecord **records,
534                                   uint16_t *num_records)
535 {
536         int ret;
537         WERROR werr;
538         struct ldb_message *msg = NULL;
539         struct ldb_message_element *el = NULL;
540         const struct ldb_val *name = NULL;
541
542         *records = NULL;
543         *num_records = 0;
544
545         name = ldb_dn_get_rdn_val(dn);
546         if (name == NULL) {
547                 return DNS_ERR(NAME_ERROR);
548         }
549
550         /* Don't look for a wildcard for @ */
551         if (name->length == 1 && name->data[0] == '@') {
552                 return dns_common_lookup(samdb,
553                                          mem_ctx,
554                                          dn,
555                                          records,
556                                          num_records,
557                                          NULL);
558         }
559
560         werr =  dns_name_check(
561                         mem_ctx,
562                         strlen((const char*)name->data),
563                         (const char*) name->data);
564         if (!W_ERROR_IS_OK(werr)) {
565                 return werr;
566         }
567
568         /*
569          * Do a point search first, then fall back to a wildcard
570          * lookup if it does not exist
571          */
572         werr = dns_common_lookup(samdb,
573                                  mem_ctx,
574                                  dn,
575                                  records,
576                                  num_records,
577                                  NULL);
578         if (!W_ERROR_EQUAL(werr, WERR_DNS_ERROR_NAME_DOES_NOT_EXIST)) {
579                 return werr;
580         }
581
582         ret = dns_wildcard_lookup(samdb, mem_ctx, dn, &msg);
583         if (ret == LDB_ERR_OPERATIONS_ERROR) {
584                 return DNS_ERR(SERVER_FAILURE);
585         }
586         if (ret != LDB_SUCCESS) {
587                 return DNS_ERR(NAME_ERROR);
588         }
589
590         el = ldb_msg_find_element(msg, "dnsRecord");
591         if (el == NULL) {
592                 return WERR_DNS_ERROR_NAME_DOES_NOT_EXIST;
593         }
594
595         werr = dns_common_extract(samdb, el, mem_ctx, records, num_records);
596         TALLOC_FREE(msg);
597         if (!W_ERROR_IS_OK(werr)) {
598                 return werr;
599         }
600
601         return WERR_OK;
602 }
603
604 static int rec_cmp(const struct dnsp_DnssrvRpcRecord *r1,
605                    const struct dnsp_DnssrvRpcRecord *r2)
606 {
607         if (r1->wType != r2->wType) {
608                 /*
609                  * The records are sorted with higher types first
610                  */
611                 return r2->wType - r1->wType;
612         }
613
614         /*
615          * Then we need to sort from the oldest to newest timestamp
616          */
617         return r1->dwTimeStamp - r2->dwTimeStamp;
618 }
619
620 /*
621  * Check for valid DNS names. These are names which:
622  *   - are non-empty
623  *   - do not start with a dot
624  *   - do not have any empty labels
625  *   - have no more than 127 labels
626  *   - are no longer than 253 characters
627  *   - none of the labels exceed 63 characters
628  */
629 WERROR dns_name_check(TALLOC_CTX *mem_ctx, size_t len, const char *name)
630 {
631         size_t i;
632         unsigned int labels    = 0;
633         unsigned int label_len = 0;
634
635         if (len == 0) {
636                 return WERR_DS_INVALID_DN_SYNTAX;
637         }
638
639         if (len > 1 && name[0] == '.') {
640                 return WERR_DS_INVALID_DN_SYNTAX;
641         }
642
643         if ((len - 1) > DNS_MAX_DOMAIN_LENGTH) {
644                 return WERR_DS_INVALID_DN_SYNTAX;
645         }
646
647         for (i = 0; i < len - 1; i++) {
648                 if (name[i] == '.' && name[i+1] == '.') {
649                         return WERR_DS_INVALID_DN_SYNTAX;
650                 }
651                 if (name[i] == '.') {
652                         labels++;
653                         if (labels > DNS_MAX_LABELS) {
654                                 return WERR_DS_INVALID_DN_SYNTAX;
655                         }
656                         label_len = 0;
657                 } else {
658                         label_len++;
659                         if (label_len > DNS_MAX_LABEL_LENGTH) {
660                                 return WERR_DS_INVALID_DN_SYNTAX;
661                         }
662                 }
663         }
664
665         return WERR_OK;
666 }
667
668 static WERROR check_name_list(TALLOC_CTX *mem_ctx, uint16_t rec_count,
669                               struct dnsp_DnssrvRpcRecord *records)
670 {
671         WERROR werr;
672         uint16_t i;
673         size_t len;
674         struct dnsp_DnssrvRpcRecord record;
675
676         werr = WERR_OK;
677         for (i = 0; i < rec_count; i++) {
678                 record = records[i];
679
680                 switch (record.wType) {
681
682                 case DNS_TYPE_NS:
683                         len = strlen(record.data.ns);
684                         werr = dns_name_check(mem_ctx, len, record.data.ns);
685                         break;
686                 case DNS_TYPE_CNAME:
687                         len = strlen(record.data.cname);
688                         werr = dns_name_check(mem_ctx, len, record.data.cname);
689                         break;
690                 case DNS_TYPE_SOA:
691                         len = strlen(record.data.soa.mname);
692                         werr = dns_name_check(mem_ctx, len, record.data.soa.mname);
693                         if (!W_ERROR_IS_OK(werr)) {
694                                 break;
695                         }
696                         len = strlen(record.data.soa.rname);
697                         werr = dns_name_check(mem_ctx, len, record.data.soa.rname);
698                         break;
699                 case DNS_TYPE_PTR:
700                         len = strlen(record.data.ptr);
701                         werr = dns_name_check(mem_ctx, len, record.data.ptr);
702                         break;
703                 case DNS_TYPE_MX:
704                         len = strlen(record.data.mx.nameTarget);
705                         werr = dns_name_check(mem_ctx, len, record.data.mx.nameTarget);
706                         break;
707                 case DNS_TYPE_SRV:
708                         len = strlen(record.data.srv.nameTarget);
709                         werr = dns_name_check(mem_ctx, len,
710                                               record.data.srv.nameTarget);
711                         break;
712                 /*
713                  * In the default case, the record doesn't have a DN, so it
714                  * must be ok.
715                  */
716                 default:
717                         break;
718                 }
719
720                 if (!W_ERROR_IS_OK(werr)) {
721                         return werr;
722                 }
723         }
724
725         return WERR_OK;
726 }
727
728 bool dns_name_is_static(struct dnsp_DnssrvRpcRecord *records,
729                         uint16_t rec_count)
730 {
731         int i = 0;
732         for (i = 0; i < rec_count; i++) {
733                 if (records[i].wType == DNS_TYPE_TOMBSTONE) {
734                         continue;
735                 }
736
737                 if (records[i].wType == DNS_TYPE_SOA ||
738                     records[i].dwTimeStamp == 0) {
739                         return true;
740                 }
741         }
742         return false;
743 }
744
745 WERROR dns_get_zone_properties(struct ldb_context *samdb,
746                                TALLOC_CTX *mem_ctx,
747                                struct ldb_dn *zone_dn,
748                                struct dnsserver_zoneinfo *zoneinfo)
749 {
750
751         int ret, i;
752         struct dnsp_DnsProperty *prop = NULL;
753         struct ldb_message_element *element = NULL;
754         const char *const attrs[] = {"dNSProperty", NULL};
755         struct ldb_result *res = NULL;
756         enum ndr_err_code err;
757
758         ret = ldb_search(samdb,
759                          mem_ctx,
760                          &res,
761                          zone_dn,
762                          LDB_SCOPE_BASE,
763                          attrs,
764                          "(objectClass=dnsZone)");
765         if (ret != LDB_SUCCESS) {
766                 DBG_ERR("dnsserver: Failed to find DNS zone: %s\n",
767                         ldb_dn_get_linearized(zone_dn));
768                 return DNS_ERR(SERVER_FAILURE);
769         }
770
771         element = ldb_msg_find_element(res->msgs[0], "dNSProperty");
772         if (element == NULL) {
773                 return DNS_ERR(NOTZONE);
774         }
775
776         for (i = 0; i < element->num_values; i++) {
777                 prop = talloc_zero(mem_ctx, struct dnsp_DnsProperty);
778                 if (prop == NULL) {
779                         return WERR_NOT_ENOUGH_MEMORY;
780                 }
781                 err = ndr_pull_struct_blob(
782                     &(element->values[i]),
783                     mem_ctx,
784                     prop,
785                     (ndr_pull_flags_fn_t)ndr_pull_dnsp_DnsProperty);
786                 if (!NDR_ERR_CODE_IS_SUCCESS(err)) {
787                         return DNS_ERR(SERVER_FAILURE);
788                 }
789
790                 switch (prop->id) {
791                 case DSPROPERTY_ZONE_AGING_STATE:
792                         zoneinfo->fAging = prop->data.aging_enabled;
793                         break;
794                 case DSPROPERTY_ZONE_NOREFRESH_INTERVAL:
795                         zoneinfo->dwNoRefreshInterval =
796                             prop->data.norefresh_hours;
797                         break;
798                 case DSPROPERTY_ZONE_REFRESH_INTERVAL:
799                         zoneinfo->dwRefreshInterval = prop->data.refresh_hours;
800                         break;
801                 case DSPROPERTY_ZONE_ALLOW_UPDATE:
802                         zoneinfo->fAllowUpdate = prop->data.allow_update_flag;
803                         break;
804                 case DSPROPERTY_ZONE_AGING_ENABLED_TIME:
805                         zoneinfo->dwAvailForScavengeTime =
806                             prop->data.next_scavenging_cycle_hours;
807                         break;
808                 case DSPROPERTY_ZONE_SCAVENGING_SERVERS:
809                         zoneinfo->aipScavengeServers->AddrCount =
810                             prop->data.servers.addrCount;
811                         zoneinfo->aipScavengeServers->AddrArray =
812                             prop->data.servers.addr;
813                         break;
814                 case DSPROPERTY_ZONE_EMPTY:
815                 case DSPROPERTY_ZONE_TYPE:
816                 case DSPROPERTY_ZONE_SECURE_TIME:
817                 case DSPROPERTY_ZONE_DELETED_FROM_HOSTNAME:
818                 case DSPROPERTY_ZONE_MASTER_SERVERS:
819                 case DSPROPERTY_ZONE_AUTO_NS_SERVERS:
820                 case DSPROPERTY_ZONE_DCPROMO_CONVERT:
821                 case DSPROPERTY_ZONE_SCAVENGING_SERVERS_DA:
822                 case DSPROPERTY_ZONE_MASTER_SERVERS_DA:
823                 case DSPROPERTY_ZONE_NS_SERVERS_DA:
824                 case DSPROPERTY_ZONE_NODE_DBFLAGS:
825                         break;
826                 }
827         }
828
829         return WERR_OK;
830 }
831
832 WERROR dns_common_replace(struct ldb_context *samdb,
833                           TALLOC_CTX *mem_ctx,
834                           struct ldb_dn *dn,
835                           bool needs_add,
836                           uint32_t serial,
837                           struct dnsp_DnssrvRpcRecord *records,
838                           uint16_t rec_count)
839 {
840         struct ldb_message_element *el;
841         uint16_t i;
842         int ret;
843         WERROR werr;
844         struct ldb_message *msg = NULL;
845         bool was_tombstoned = false;
846         bool become_tombstoned = false;
847         struct ldb_dn *zone_dn = NULL;
848         struct dnsserver_zoneinfo *zoneinfo = NULL;
849         NTTIME t;
850
851         msg = ldb_msg_new(mem_ctx);
852         W_ERROR_HAVE_NO_MEMORY(msg);
853
854         msg->dn = dn;
855
856         zone_dn = ldb_dn_copy(mem_ctx, dn);
857         if (zone_dn == NULL) {
858                 return WERR_NOT_ENOUGH_MEMORY;
859         }
860         if (!ldb_dn_remove_child_components(zone_dn, 1)) {
861                 return DNS_ERR(SERVER_FAILURE);
862         }
863         zoneinfo = talloc(mem_ctx, struct dnsserver_zoneinfo);
864         if (zoneinfo == NULL) {
865                 return WERR_NOT_ENOUGH_MEMORY;
866         }
867         werr = dns_get_zone_properties(samdb, mem_ctx, zone_dn, zoneinfo);
868         if (W_ERROR_EQUAL(DNS_ERR(NOTZONE), werr)) {
869                 /*
870                  * We only got zoneinfo for aging so if we didn't find any
871                  * properties then just disable aging and keep going.
872                  */
873                 zoneinfo->fAging = 0;
874         } else if (!W_ERROR_IS_OK(werr)) {
875                 return werr;
876         }
877
878         werr = check_name_list(mem_ctx, rec_count, records);
879         if (!W_ERROR_IS_OK(werr)) {
880                 return werr;
881         }
882
883         ret = ldb_msg_add_empty(msg, "dnsRecord", LDB_FLAG_MOD_REPLACE, &el);
884         if (ret != LDB_SUCCESS) {
885                 return DNS_ERR(SERVER_FAILURE);
886         }
887
888         /*
889          * we have at least one value,
890          * which might be used for the tombstone marker
891          */
892         el->values = talloc_zero_array(el, struct ldb_val, MAX(1, rec_count));
893         if (rec_count > 0) {
894                 W_ERROR_HAVE_NO_MEMORY(el->values);
895
896                 /*
897                  * We store a sorted list with the high wType values first
898                  * that's what windows does. It also simplifies the
899                  * filtering of DNS_TYPE_TOMBSTONE records
900                  */
901                 TYPESAFE_QSORT(records, rec_count, rec_cmp);
902         }
903
904         for (i = 0; i < rec_count; i++) {
905                 struct ldb_val *v = &el->values[el->num_values];
906                 enum ndr_err_code ndr_err;
907
908                 if (records[i].wType == DNS_TYPE_TOMBSTONE) {
909                         if (records[i].data.timestamp != 0) {
910                                 was_tombstoned = true;
911                         }
912                         continue;
913                 }
914
915                 if (zoneinfo->fAging == 1 && records[i].dwTimeStamp != 0) {
916                         unix_to_nt_time(&t, time(NULL));
917                         t /= 10 * 1000 * 1000;
918                         t /= 3600;
919                         if (t - records[i].dwTimeStamp >
920                             zoneinfo->dwNoRefreshInterval) {
921                                 records[i].dwTimeStamp = t;
922                         }
923                 }
924
925                 records[i].dwSerial = serial;
926                 ndr_err = ndr_push_struct_blob(v, el->values, &records[i],
927                                 (ndr_push_flags_fn_t)ndr_push_dnsp_DnssrvRpcRecord);
928                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
929                         DEBUG(0, ("Failed to push dnsp_DnssrvRpcRecord\n"));
930                         return DNS_ERR(SERVER_FAILURE);
931                 }
932                 el->num_values++;
933         }
934
935         if (needs_add) {
936                 if (el->num_values == 0) {
937                         return WERR_OK;
938                 }
939
940                 ret = ldb_msg_add_string(msg, "objectClass", "dnsNode");
941                 if (ret != LDB_SUCCESS) {
942                         return DNS_ERR(SERVER_FAILURE);
943                 }
944
945                 ret = ldb_add(samdb, msg);
946                 if (ret != LDB_SUCCESS) {
947                         return DNS_ERR(SERVER_FAILURE);
948                 }
949
950                 return WERR_OK;
951         }
952
953         if (el->num_values == 0) {
954                 struct dnsp_DnssrvRpcRecord tbs;
955                 struct ldb_val *v = &el->values[el->num_values];
956                 enum ndr_err_code ndr_err;
957                 struct timeval tv;
958
959                 if (was_tombstoned) {
960                         /*
961                          * This is already a tombstoned object.
962                          * Just leave it instead of updating the time stamp.
963                          */
964                         return WERR_OK;
965                 }
966
967                 tv = timeval_current();
968                 tbs = (struct dnsp_DnssrvRpcRecord) {
969                         .wType = DNS_TYPE_TOMBSTONE,
970                         .dwSerial = serial,
971                         .data.timestamp = timeval_to_nttime(&tv),
972                 };
973
974                 ndr_err = ndr_push_struct_blob(v, el->values, &tbs,
975                                 (ndr_push_flags_fn_t)ndr_push_dnsp_DnssrvRpcRecord);
976                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
977                         DEBUG(0, ("Failed to push dnsp_DnssrvRpcRecord\n"));
978                         return DNS_ERR(SERVER_FAILURE);
979                 }
980                 el->num_values++;
981
982                 become_tombstoned = true;
983         }
984
985         if (was_tombstoned || become_tombstoned) {
986                 ret = ldb_msg_add_empty(msg, "dNSTombstoned",
987                                         LDB_FLAG_MOD_REPLACE, NULL);
988                 if (ret != LDB_SUCCESS) {
989                         return DNS_ERR(SERVER_FAILURE);
990                 }
991
992                 ret = ldb_msg_add_fmt(msg, "dNSTombstoned", "%s",
993                                       become_tombstoned ? "TRUE" : "FALSE");
994                 if (ret != LDB_SUCCESS) {
995                         return DNS_ERR(SERVER_FAILURE);
996                 }
997         }
998
999         ret = ldb_modify(samdb, msg);
1000         if (ret != LDB_SUCCESS) {
1001                 NTSTATUS nt = dsdb_ldb_err_to_ntstatus(ret);
1002                 return ntstatus_to_werror(nt);
1003         }
1004
1005         return WERR_OK;
1006 }
1007
1008 bool dns_name_match(const char *zone, const char *name, size_t *host_part_len)
1009 {
1010         size_t zl = strlen(zone);
1011         size_t nl = strlen(name);
1012         ssize_t zi, ni;
1013         static const size_t fixup = 'a' - 'A';
1014
1015         if (zl > nl) {
1016                 return false;
1017         }
1018
1019         for (zi = zl, ni = nl; zi >= 0; zi--, ni--) {
1020                 char zc = zone[zi];
1021                 char nc = name[ni];
1022
1023                 /* convert to lower case */
1024                 if (zc >= 'A' && zc <= 'Z') {
1025                         zc += fixup;
1026                 }
1027                 if (nc >= 'A' && nc <= 'Z') {
1028                         nc += fixup;
1029                 }
1030
1031                 if (zc != nc) {
1032                         return false;
1033                 }
1034         }
1035
1036         if (ni >= 0) {
1037                 if (name[ni] != '.') {
1038                         return false;
1039                 }
1040
1041                 ni--;
1042         }
1043
1044         *host_part_len = ni+1;
1045
1046         return true;
1047 }
1048
1049 WERROR dns_common_name2dn(struct ldb_context *samdb,
1050                           struct dns_server_zone *zones,
1051                           TALLOC_CTX *mem_ctx,
1052                           const char *name,
1053                           struct ldb_dn **_dn)
1054 {
1055         struct ldb_dn *base;
1056         struct ldb_dn *dn;
1057         const struct dns_server_zone *z;
1058         size_t host_part_len = 0;
1059         WERROR werr;
1060
1061         if (name == NULL) {
1062                 return DNS_ERR(FORMAT_ERROR);
1063         }
1064
1065         if (strcmp(name, "") == 0) {
1066                 base = ldb_get_default_basedn(samdb);
1067                 dn = ldb_dn_copy(mem_ctx, base);
1068                 ldb_dn_add_child_fmt(dn, "DC=@,DC=RootDNSServers,CN=MicrosoftDNS,CN=System");
1069                 *_dn = dn;
1070                 return WERR_OK;
1071         }
1072
1073         /* Check non-empty names */
1074         werr = dns_name_check(mem_ctx, strlen(name), name);
1075         if (!W_ERROR_IS_OK(werr)) {
1076                 return werr;
1077         }
1078
1079         for (z = zones; z != NULL; z = z->next) {
1080                 bool match;
1081
1082                 match = dns_name_match(z->name, name, &host_part_len);
1083                 if (match) {
1084                         break;
1085                 }
1086         }
1087
1088         if (z == NULL) {
1089                 return DNS_ERR(NAME_ERROR);
1090         }
1091
1092         if (host_part_len == 0) {
1093                 dn = ldb_dn_copy(mem_ctx, z->dn);
1094                 ldb_dn_add_child_fmt(dn, "DC=@");
1095                 *_dn = dn;
1096                 return WERR_OK;
1097         }
1098
1099         dn = ldb_dn_copy(mem_ctx, z->dn);
1100         ldb_dn_add_child_fmt(dn, "DC=%*.*s", (int)host_part_len, (int)host_part_len, name);
1101         *_dn = dn;
1102         return WERR_OK;
1103 }
1104
1105 static int dns_common_sort_zones(struct ldb_message **m1, struct ldb_message **m2)
1106 {
1107         const char *n1, *n2;
1108         size_t l1, l2;
1109
1110         n1 = ldb_msg_find_attr_as_string(*m1, "name", NULL);
1111         n2 = ldb_msg_find_attr_as_string(*m2, "name", NULL);
1112
1113         l1 = strlen(n1);
1114         l2 = strlen(n2);
1115
1116         /* If the string lengths are not equal just sort by length */
1117         if (l1 != l2) {
1118                 /* If m1 is the larger zone name, return it first */
1119                 return l2 - l1;
1120         }
1121
1122         /*TODO: We need to compare DNs here, we want the DomainDNSZones first */
1123         return 0;
1124 }
1125
1126 NTSTATUS dns_common_zones(struct ldb_context *samdb,
1127                           TALLOC_CTX *mem_ctx,
1128                           struct ldb_dn *base_dn,
1129                           struct dns_server_zone **zones_ret)
1130 {
1131         int ret;
1132         static const char * const attrs[] = { "name", NULL};
1133         struct ldb_result *res;
1134         int i;
1135         struct dns_server_zone *new_list = NULL;
1136         TALLOC_CTX *frame = talloc_stackframe();
1137
1138         if (base_dn) {
1139                 /* This search will work against windows */
1140                 ret = dsdb_search(samdb, frame, &res,
1141                                   base_dn, LDB_SCOPE_SUBTREE,
1142                                   attrs, 0, "(objectClass=dnsZone)");
1143         } else {
1144                 /* TODO: this search does not work against windows */
1145                 ret = dsdb_search(samdb, frame, &res, NULL,
1146                                   LDB_SCOPE_SUBTREE,
1147                                   attrs,
1148                                   DSDB_SEARCH_SEARCH_ALL_PARTITIONS,
1149                                   "(objectClass=dnsZone)");
1150         }
1151         if (ret != LDB_SUCCESS) {
1152                 TALLOC_FREE(frame);
1153                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1154         }
1155
1156         TYPESAFE_QSORT(res->msgs, res->count, dns_common_sort_zones);
1157
1158         for (i=0; i < res->count; i++) {
1159                 struct dns_server_zone *z;
1160
1161                 z = talloc_zero(mem_ctx, struct dns_server_zone);
1162                 if (z == NULL) {
1163                         TALLOC_FREE(frame);
1164                         return NT_STATUS_NO_MEMORY;
1165                 }
1166
1167                 z->name = ldb_msg_find_attr_as_string(res->msgs[i], "name", NULL);
1168                 talloc_steal(z, z->name);
1169                 z->dn = talloc_move(z, &res->msgs[i]->dn);
1170                 /*
1171                  * Ignore the RootDNSServers zone and zones that we don't support yet
1172                  * RootDNSServers should never be returned (Windows DNS server don't)
1173                  * ..TrustAnchors should never be returned as is, (Windows returns
1174                  * TrustAnchors) and for the moment we don't support DNSSEC so we'd better
1175                  * not return this zone.
1176                  */
1177                 if ((strcmp(z->name, "RootDNSServers") == 0) ||
1178                     (strcmp(z->name, "..TrustAnchors") == 0))
1179                 {
1180                         DEBUG(10, ("Ignoring zone %s\n", z->name));
1181                         talloc_free(z);
1182                         continue;
1183                 }
1184                 DLIST_ADD_END(new_list, z);
1185         }
1186
1187         *zones_ret = new_list;
1188         TALLOC_FREE(frame);
1189         return NT_STATUS_OK;
1190 }
1191
1192 /*
1193   see if two DNS names are the same
1194  */
1195 bool dns_name_equal(const char *name1, const char *name2)
1196 {
1197         size_t len1 = strlen(name1);
1198         size_t len2 = strlen(name2);
1199
1200         if (len1 > 0 && name1[len1 - 1] == '.') {
1201                 len1--;
1202         }
1203         if (len2 > 0 && name2[len2 - 1] == '.') {
1204                 len2--;
1205         }
1206         if (len1 != len2) {
1207                 return false;
1208         }
1209         return strncasecmp(name1, name2, len1) == 0;
1210 }