656d7ca6bff6a1fe82e3d7d85b16a6a1388c3d46
[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 /*
746  * Helper function to copy a dnsp_ip4_array struct to an IP4_ARRAY struct.
747  * The new structure and it's data are allocated on the supplied talloc context
748  */
749 static struct IP4_ARRAY *copy_ip4_array(TALLOC_CTX *ctx,
750                                         const char *name,
751                                         struct dnsp_ip4_array array)
752 {
753
754         struct IP4_ARRAY *ip4_array = NULL;
755         unsigned int i;
756
757         ip4_array = talloc_zero(ctx, struct IP4_ARRAY);
758         if (ip4_array == NULL) {
759                 DBG_ERR("Out of memory copying property [%s]\n", name);
760                 return NULL;
761         }
762
763         ip4_array->AddrCount = array.addrCount;
764         if (ip4_array->AddrCount == 0) {
765                 return ip4_array;
766         }
767
768         ip4_array->AddrArray =
769             talloc_array(ip4_array, uint32_t, ip4_array->AddrCount);
770         if (ip4_array->AddrArray == NULL) {
771                 TALLOC_FREE(ip4_array);
772                 DBG_ERR("Out of memory copying property [%s] values\n", name);
773                 return NULL;
774         }
775
776         for (i = 0; i < ip4_array->AddrCount; i++) {
777                 ip4_array->AddrArray[i] = array.addr[i];
778         }
779
780         return ip4_array;
781 }
782
783 bool dns_zoneinfo_load_zone_property(struct dnsserver_zoneinfo *zoneinfo,
784                                      struct dnsp_DnsProperty *prop)
785 {
786         switch (prop->id) {
787         case DSPROPERTY_ZONE_TYPE:
788                 zoneinfo->dwZoneType = prop->data.zone_type;
789                 break;
790         case DSPROPERTY_ZONE_ALLOW_UPDATE:
791                 zoneinfo->fAllowUpdate = prop->data.allow_update_flag;
792                 break;
793         case DSPROPERTY_ZONE_NOREFRESH_INTERVAL:
794                 zoneinfo->dwNoRefreshInterval = prop->data.norefresh_hours;
795                 break;
796         case DSPROPERTY_ZONE_REFRESH_INTERVAL:
797                 zoneinfo->dwRefreshInterval = prop->data.refresh_hours;
798                 break;
799         case DSPROPERTY_ZONE_AGING_STATE:
800                 zoneinfo->fAging = prop->data.aging_enabled;
801                 break;
802         case DSPROPERTY_ZONE_SCAVENGING_SERVERS:
803                 zoneinfo->aipScavengeServers = copy_ip4_array(
804                     zoneinfo, "ZONE_SCAVENGING_SERVERS", prop->data.servers);
805                 if (zoneinfo->aipScavengeServers == NULL) {
806                         return false;
807                 }
808                 break;
809         case DSPROPERTY_ZONE_AGING_ENABLED_TIME:
810                 zoneinfo->dwAvailForScavengeTime =
811                     prop->data.next_scavenging_cycle_hours;
812                 break;
813         case DSPROPERTY_ZONE_MASTER_SERVERS:
814                 zoneinfo->aipLocalMasters = copy_ip4_array(
815                     zoneinfo, "ZONE_MASTER_SERVERS", prop->data.master_servers);
816                 if (zoneinfo->aipLocalMasters == NULL) {
817                         return false;
818                 }
819                 break;
820         case DSPROPERTY_ZONE_EMPTY:
821         case DSPROPERTY_ZONE_SECURE_TIME:
822         case DSPROPERTY_ZONE_DELETED_FROM_HOSTNAME:
823         case DSPROPERTY_ZONE_AUTO_NS_SERVERS:
824         case DSPROPERTY_ZONE_DCPROMO_CONVERT:
825         case DSPROPERTY_ZONE_SCAVENGING_SERVERS_DA:
826         case DSPROPERTY_ZONE_MASTER_SERVERS_DA:
827         case DSPROPERTY_ZONE_NS_SERVERS_DA:
828         case DSPROPERTY_ZONE_NODE_DBFLAGS:
829                 break;
830         }
831         return true;
832 }
833 WERROR dns_get_zone_properties(struct ldb_context *samdb,
834                                TALLOC_CTX *mem_ctx,
835                                struct ldb_dn *zone_dn,
836                                struct dnsserver_zoneinfo *zoneinfo)
837 {
838
839         int ret, i;
840         struct dnsp_DnsProperty *prop = NULL;
841         struct ldb_message_element *element = NULL;
842         const char *const attrs[] = {"dNSProperty", NULL};
843         struct ldb_result *res = NULL;
844         enum ndr_err_code err;
845
846         ret = ldb_search(samdb,
847                          mem_ctx,
848                          &res,
849                          zone_dn,
850                          LDB_SCOPE_BASE,
851                          attrs,
852                          "(objectClass=dnsZone)");
853         if (ret != LDB_SUCCESS) {
854                 DBG_ERR("dnsserver: Failed to find DNS zone: %s\n",
855                         ldb_dn_get_linearized(zone_dn));
856                 return DNS_ERR(SERVER_FAILURE);
857         }
858
859         element = ldb_msg_find_element(res->msgs[0], "dNSProperty");
860         if (element == NULL) {
861                 return DNS_ERR(NOTZONE);
862         }
863
864         for (i = 0; i < element->num_values; i++) {
865                 bool valid_property;
866                 prop = talloc_zero(mem_ctx, struct dnsp_DnsProperty);
867                 if (prop == NULL) {
868                         return WERR_NOT_ENOUGH_MEMORY;
869                 }
870                 err = ndr_pull_struct_blob(
871                     &(element->values[i]),
872                     mem_ctx,
873                     prop,
874                     (ndr_pull_flags_fn_t)ndr_pull_dnsp_DnsProperty);
875                 if (!NDR_ERR_CODE_IS_SUCCESS(err)) {
876                         return DNS_ERR(SERVER_FAILURE);
877                 }
878
879                 valid_property =
880                     dns_zoneinfo_load_zone_property(zoneinfo, prop);
881                 if (!valid_property) {
882                         return DNS_ERR(SERVER_FAILURE);
883                 }
884         }
885
886         return WERR_OK;
887 }
888
889 WERROR dns_common_replace(struct ldb_context *samdb,
890                           TALLOC_CTX *mem_ctx,
891                           struct ldb_dn *dn,
892                           bool needs_add,
893                           uint32_t serial,
894                           struct dnsp_DnssrvRpcRecord *records,
895                           uint16_t rec_count)
896 {
897         struct ldb_message_element *el;
898         uint16_t i;
899         int ret;
900         WERROR werr;
901         struct ldb_message *msg = NULL;
902         bool was_tombstoned = false;
903         bool become_tombstoned = false;
904         struct ldb_dn *zone_dn = NULL;
905         struct dnsserver_zoneinfo *zoneinfo = NULL;
906         NTTIME t;
907
908         msg = ldb_msg_new(mem_ctx);
909         W_ERROR_HAVE_NO_MEMORY(msg);
910
911         msg->dn = dn;
912
913         zone_dn = ldb_dn_copy(mem_ctx, dn);
914         if (zone_dn == NULL) {
915                 return WERR_NOT_ENOUGH_MEMORY;
916         }
917         if (!ldb_dn_remove_child_components(zone_dn, 1)) {
918                 return DNS_ERR(SERVER_FAILURE);
919         }
920         zoneinfo = talloc(mem_ctx, struct dnsserver_zoneinfo);
921         if (zoneinfo == NULL) {
922                 return WERR_NOT_ENOUGH_MEMORY;
923         }
924         werr = dns_get_zone_properties(samdb, mem_ctx, zone_dn, zoneinfo);
925         if (W_ERROR_EQUAL(DNS_ERR(NOTZONE), werr)) {
926                 /*
927                  * We only got zoneinfo for aging so if we didn't find any
928                  * properties then just disable aging and keep going.
929                  */
930                 zoneinfo->fAging = 0;
931         } else if (!W_ERROR_IS_OK(werr)) {
932                 return werr;
933         }
934
935         werr = check_name_list(mem_ctx, rec_count, records);
936         if (!W_ERROR_IS_OK(werr)) {
937                 return werr;
938         }
939
940         ret = ldb_msg_add_empty(msg, "dnsRecord", LDB_FLAG_MOD_REPLACE, &el);
941         if (ret != LDB_SUCCESS) {
942                 return DNS_ERR(SERVER_FAILURE);
943         }
944
945         /*
946          * we have at least one value,
947          * which might be used for the tombstone marker
948          */
949         el->values = talloc_zero_array(el, struct ldb_val, MAX(1, rec_count));
950         if (rec_count > 0) {
951                 W_ERROR_HAVE_NO_MEMORY(el->values);
952
953                 /*
954                  * We store a sorted list with the high wType values first
955                  * that's what windows does. It also simplifies the
956                  * filtering of DNS_TYPE_TOMBSTONE records
957                  */
958                 TYPESAFE_QSORT(records, rec_count, rec_cmp);
959         }
960
961         for (i = 0; i < rec_count; i++) {
962                 struct ldb_val *v = &el->values[el->num_values];
963                 enum ndr_err_code ndr_err;
964
965                 if (records[i].wType == DNS_TYPE_TOMBSTONE) {
966                         if (records[i].data.timestamp != 0) {
967                                 was_tombstoned = true;
968                         }
969                         continue;
970                 }
971
972                 if (zoneinfo->fAging == 1 && records[i].dwTimeStamp != 0) {
973                         unix_to_nt_time(&t, time(NULL));
974                         t /= 10 * 1000 * 1000;
975                         t /= 3600;
976                         if (t - records[i].dwTimeStamp >
977                             zoneinfo->dwNoRefreshInterval) {
978                                 records[i].dwTimeStamp = t;
979                         }
980                 }
981
982                 records[i].dwSerial = serial;
983                 ndr_err = ndr_push_struct_blob(v, el->values, &records[i],
984                                 (ndr_push_flags_fn_t)ndr_push_dnsp_DnssrvRpcRecord);
985                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
986                         DEBUG(0, ("Failed to push dnsp_DnssrvRpcRecord\n"));
987                         return DNS_ERR(SERVER_FAILURE);
988                 }
989                 el->num_values++;
990         }
991
992         if (needs_add) {
993                 if (el->num_values == 0) {
994                         return WERR_OK;
995                 }
996
997                 ret = ldb_msg_add_string(msg, "objectClass", "dnsNode");
998                 if (ret != LDB_SUCCESS) {
999                         return DNS_ERR(SERVER_FAILURE);
1000                 }
1001
1002                 ret = ldb_add(samdb, msg);
1003                 if (ret != LDB_SUCCESS) {
1004                         return DNS_ERR(SERVER_FAILURE);
1005                 }
1006
1007                 return WERR_OK;
1008         }
1009
1010         if (el->num_values == 0) {
1011                 struct dnsp_DnssrvRpcRecord tbs;
1012                 struct ldb_val *v = &el->values[el->num_values];
1013                 enum ndr_err_code ndr_err;
1014                 struct timeval tv;
1015
1016                 if (was_tombstoned) {
1017                         /*
1018                          * This is already a tombstoned object.
1019                          * Just leave it instead of updating the time stamp.
1020                          */
1021                         return WERR_OK;
1022                 }
1023
1024                 tv = timeval_current();
1025                 tbs = (struct dnsp_DnssrvRpcRecord) {
1026                         .wType = DNS_TYPE_TOMBSTONE,
1027                         .dwSerial = serial,
1028                         .data.timestamp = timeval_to_nttime(&tv),
1029                 };
1030
1031                 ndr_err = ndr_push_struct_blob(v, el->values, &tbs,
1032                                 (ndr_push_flags_fn_t)ndr_push_dnsp_DnssrvRpcRecord);
1033                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1034                         DEBUG(0, ("Failed to push dnsp_DnssrvRpcRecord\n"));
1035                         return DNS_ERR(SERVER_FAILURE);
1036                 }
1037                 el->num_values++;
1038
1039                 become_tombstoned = true;
1040         }
1041
1042         if (was_tombstoned || become_tombstoned) {
1043                 ret = ldb_msg_add_empty(msg, "dNSTombstoned",
1044                                         LDB_FLAG_MOD_REPLACE, NULL);
1045                 if (ret != LDB_SUCCESS) {
1046                         return DNS_ERR(SERVER_FAILURE);
1047                 }
1048
1049                 ret = ldb_msg_add_fmt(msg, "dNSTombstoned", "%s",
1050                                       become_tombstoned ? "TRUE" : "FALSE");
1051                 if (ret != LDB_SUCCESS) {
1052                         return DNS_ERR(SERVER_FAILURE);
1053                 }
1054         }
1055
1056         ret = ldb_modify(samdb, msg);
1057         if (ret != LDB_SUCCESS) {
1058                 NTSTATUS nt = dsdb_ldb_err_to_ntstatus(ret);
1059                 return ntstatus_to_werror(nt);
1060         }
1061
1062         return WERR_OK;
1063 }
1064
1065 bool dns_name_match(const char *zone, const char *name, size_t *host_part_len)
1066 {
1067         size_t zl = strlen(zone);
1068         size_t nl = strlen(name);
1069         ssize_t zi, ni;
1070         static const size_t fixup = 'a' - 'A';
1071
1072         if (zl > nl) {
1073                 return false;
1074         }
1075
1076         for (zi = zl, ni = nl; zi >= 0; zi--, ni--) {
1077                 char zc = zone[zi];
1078                 char nc = name[ni];
1079
1080                 /* convert to lower case */
1081                 if (zc >= 'A' && zc <= 'Z') {
1082                         zc += fixup;
1083                 }
1084                 if (nc >= 'A' && nc <= 'Z') {
1085                         nc += fixup;
1086                 }
1087
1088                 if (zc != nc) {
1089                         return false;
1090                 }
1091         }
1092
1093         if (ni >= 0) {
1094                 if (name[ni] != '.') {
1095                         return false;
1096                 }
1097
1098                 ni--;
1099         }
1100
1101         *host_part_len = ni+1;
1102
1103         return true;
1104 }
1105
1106 WERROR dns_common_name2dn(struct ldb_context *samdb,
1107                           struct dns_server_zone *zones,
1108                           TALLOC_CTX *mem_ctx,
1109                           const char *name,
1110                           struct ldb_dn **_dn)
1111 {
1112         struct ldb_dn *base;
1113         struct ldb_dn *dn;
1114         const struct dns_server_zone *z;
1115         size_t host_part_len = 0;
1116         struct ldb_val host_part;
1117         WERROR werr;
1118         bool ok;
1119         const char *casefold = NULL;
1120
1121         if (name == NULL) {
1122                 return DNS_ERR(FORMAT_ERROR);
1123         }
1124
1125         if (strcmp(name, "") == 0) {
1126                 base = ldb_get_default_basedn(samdb);
1127                 dn = ldb_dn_copy(mem_ctx, base);
1128                 ok = ldb_dn_add_child_fmt(dn,
1129                                           "DC=@,DC=RootDNSServers,CN=MicrosoftDNS,CN=System");
1130                 if (ok == false) {
1131                         TALLOC_FREE(dn);
1132                         return WERR_NOT_ENOUGH_MEMORY;
1133                 }
1134
1135                 *_dn = dn;
1136                 return WERR_OK;
1137         }
1138
1139         /* Check non-empty names */
1140         werr = dns_name_check(mem_ctx, strlen(name), name);
1141         if (!W_ERROR_IS_OK(werr)) {
1142                 return werr;
1143         }
1144
1145         for (z = zones; z != NULL; z = z->next) {
1146                 bool match;
1147
1148                 match = dns_name_match(z->name, name, &host_part_len);
1149                 if (match) {
1150                         break;
1151                 }
1152         }
1153
1154         if (z == NULL) {
1155                 return DNS_ERR(NAME_ERROR);
1156         }
1157
1158         if (host_part_len == 0) {
1159                 dn = ldb_dn_copy(mem_ctx, z->dn);
1160                 ok = ldb_dn_add_child_fmt(dn, "DC=@");
1161                 if (! ok) {
1162                         TALLOC_FREE(dn);
1163                         return WERR_NOT_ENOUGH_MEMORY;
1164                 }
1165                 *_dn = dn;
1166                 return WERR_OK;
1167         }
1168
1169         dn = ldb_dn_copy(mem_ctx, z->dn);
1170         if (dn == NULL) {
1171                 TALLOC_FREE(dn);
1172                 return WERR_NOT_ENOUGH_MEMORY;
1173         }
1174
1175         host_part = data_blob_const(name, host_part_len);
1176
1177         ok = ldb_dn_add_child_val(dn, "DC", host_part);
1178
1179         if (ok == false) {
1180                 TALLOC_FREE(dn);
1181                 return WERR_NOT_ENOUGH_MEMORY;
1182         }
1183
1184         /*
1185          * Check the new DN here for validity, so as to catch errors
1186          * early
1187          */
1188         ok = ldb_dn_validate(dn);
1189         if (ok == false) {
1190                 TALLOC_FREE(dn);
1191                 return DNS_ERR(NAME_ERROR);
1192         }
1193
1194         /*
1195          * The value from this check is saved in the DN, and doing
1196          * this here allows an easy return here.
1197          */
1198         casefold = ldb_dn_get_casefold(dn);
1199         if (casefold == NULL) {
1200                 TALLOC_FREE(dn);
1201                 return DNS_ERR(NAME_ERROR);
1202         }
1203
1204         *_dn = dn;
1205         return WERR_OK;
1206 }
1207
1208 static int dns_common_sort_zones(struct ldb_message **m1, struct ldb_message **m2)
1209 {
1210         const char *n1, *n2;
1211         size_t l1, l2;
1212
1213         n1 = ldb_msg_find_attr_as_string(*m1, "name", NULL);
1214         n2 = ldb_msg_find_attr_as_string(*m2, "name", NULL);
1215
1216         l1 = strlen(n1);
1217         l2 = strlen(n2);
1218
1219         /* If the string lengths are not equal just sort by length */
1220         if (l1 != l2) {
1221                 /* If m1 is the larger zone name, return it first */
1222                 return l2 - l1;
1223         }
1224
1225         /*TODO: We need to compare DNs here, we want the DomainDNSZones first */
1226         return 0;
1227 }
1228
1229 NTSTATUS dns_common_zones(struct ldb_context *samdb,
1230                           TALLOC_CTX *mem_ctx,
1231                           struct ldb_dn *base_dn,
1232                           struct dns_server_zone **zones_ret)
1233 {
1234         int ret;
1235         static const char * const attrs[] = { "name", NULL};
1236         struct ldb_result *res;
1237         int i;
1238         struct dns_server_zone *new_list = NULL;
1239         TALLOC_CTX *frame = talloc_stackframe();
1240
1241         if (base_dn) {
1242                 /* This search will work against windows */
1243                 ret = dsdb_search(samdb, frame, &res,
1244                                   base_dn, LDB_SCOPE_SUBTREE,
1245                                   attrs, 0, "(objectClass=dnsZone)");
1246         } else {
1247                 /* TODO: this search does not work against windows */
1248                 ret = dsdb_search(samdb, frame, &res, NULL,
1249                                   LDB_SCOPE_SUBTREE,
1250                                   attrs,
1251                                   DSDB_SEARCH_SEARCH_ALL_PARTITIONS,
1252                                   "(objectClass=dnsZone)");
1253         }
1254         if (ret != LDB_SUCCESS) {
1255                 TALLOC_FREE(frame);
1256                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1257         }
1258
1259         TYPESAFE_QSORT(res->msgs, res->count, dns_common_sort_zones);
1260
1261         for (i=0; i < res->count; i++) {
1262                 struct dns_server_zone *z;
1263
1264                 z = talloc_zero(mem_ctx, struct dns_server_zone);
1265                 if (z == NULL) {
1266                         TALLOC_FREE(frame);
1267                         return NT_STATUS_NO_MEMORY;
1268                 }
1269
1270                 z->name = ldb_msg_find_attr_as_string(res->msgs[i], "name", NULL);
1271                 talloc_steal(z, z->name);
1272                 z->dn = talloc_move(z, &res->msgs[i]->dn);
1273                 /*
1274                  * Ignore the RootDNSServers zone and zones that we don't support yet
1275                  * RootDNSServers should never be returned (Windows DNS server don't)
1276                  * ..TrustAnchors should never be returned as is, (Windows returns
1277                  * TrustAnchors) and for the moment we don't support DNSSEC so we'd better
1278                  * not return this zone.
1279                  */
1280                 if ((strcmp(z->name, "RootDNSServers") == 0) ||
1281                     (strcmp(z->name, "..TrustAnchors") == 0))
1282                 {
1283                         DEBUG(10, ("Ignoring zone %s\n", z->name));
1284                         talloc_free(z);
1285                         continue;
1286                 }
1287                 DLIST_ADD_END(new_list, z);
1288         }
1289
1290         *zones_ret = new_list;
1291         TALLOC_FREE(frame);
1292         return NT_STATUS_OK;
1293 }
1294
1295 /*
1296   see if two DNS names are the same
1297  */
1298 bool dns_name_equal(const char *name1, const char *name2)
1299 {
1300         size_t len1 = strlen(name1);
1301         size_t len2 = strlen(name2);
1302
1303         if (len1 > 0 && name1[len1 - 1] == '.') {
1304                 len1--;
1305         }
1306         if (len2 > 0 && name2[len2 - 1] == '.') {
1307                 len2--;
1308         }
1309         if (len1 != len2) {
1310                 return false;
1311         }
1312         return strncasecmp(name1, name2, len1) == 0;
1313 }