a56ff08031ba77a1a0929c8f5bad5b6a8959dddd
[nivanova/samba-autobuild/.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 "lib/util/dlinklist.h"
35
36 #undef DBGC_CLASS
37 #define DBGC_CLASS DBGC_DNS
38
39 uint8_t werr_to_dns_err(WERROR werr)
40 {
41         if (W_ERROR_EQUAL(WERR_OK, werr)) {
42                 return DNS_RCODE_OK;
43         } else if (W_ERROR_EQUAL(DNS_ERR(FORMAT_ERROR), werr)) {
44                 return DNS_RCODE_FORMERR;
45         } else if (W_ERROR_EQUAL(DNS_ERR(SERVER_FAILURE), werr)) {
46                 return DNS_RCODE_SERVFAIL;
47         } else if (W_ERROR_EQUAL(DNS_ERR(NAME_ERROR), werr)) {
48                 return DNS_RCODE_NXDOMAIN;
49         } else if (W_ERROR_EQUAL(WERR_DNS_ERROR_NAME_DOES_NOT_EXIST, werr)) {
50                 return DNS_RCODE_NXDOMAIN;
51         } else if (W_ERROR_EQUAL(DNS_ERR(NOT_IMPLEMENTED), werr)) {
52                 return DNS_RCODE_NOTIMP;
53         } else if (W_ERROR_EQUAL(DNS_ERR(REFUSED), werr)) {
54                 return DNS_RCODE_REFUSED;
55         } else if (W_ERROR_EQUAL(DNS_ERR(YXDOMAIN), werr)) {
56                 return DNS_RCODE_YXDOMAIN;
57         } else if (W_ERROR_EQUAL(DNS_ERR(YXRRSET), werr)) {
58                 return DNS_RCODE_YXRRSET;
59         } else if (W_ERROR_EQUAL(DNS_ERR(NXRRSET), werr)) {
60                 return DNS_RCODE_NXRRSET;
61         } else if (W_ERROR_EQUAL(DNS_ERR(NOTAUTH), werr)) {
62                 return DNS_RCODE_NOTAUTH;
63         } else if (W_ERROR_EQUAL(DNS_ERR(NOTZONE), werr)) {
64                 return DNS_RCODE_NOTZONE;
65         } else if (W_ERROR_EQUAL(DNS_ERR(BADKEY), werr)) {
66                 return DNS_RCODE_BADKEY;
67         }
68         DEBUG(5, ("No mapping exists for %s\n", win_errstr(werr)));
69         return DNS_RCODE_SERVFAIL;
70 }
71
72 WERROR dns_common_extract(struct ldb_context *samdb,
73                           const struct ldb_message_element *el,
74                           TALLOC_CTX *mem_ctx,
75                           struct dnsp_DnssrvRpcRecord **records,
76                           uint16_t *num_records)
77 {
78         uint16_t ri;
79         struct dnsp_DnssrvRpcRecord *recs;
80
81         *records = NULL;
82         *num_records = 0;
83
84         recs = talloc_zero_array(mem_ctx, struct dnsp_DnssrvRpcRecord,
85                                  el->num_values);
86         if (recs == NULL) {
87                 return WERR_NOT_ENOUGH_MEMORY;
88         }
89         for (ri = 0; ri < el->num_values; ri++) {
90                 bool am_rodc;
91                 int ret;
92                 const char *dnsHostName = NULL;
93                 struct ldb_val *v = &el->values[ri];
94                 enum ndr_err_code ndr_err;
95                 ndr_err = ndr_pull_struct_blob(v, recs, &recs[ri],
96                                 (ndr_pull_flags_fn_t)ndr_pull_dnsp_DnssrvRpcRecord);
97                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
98                         TALLOC_FREE(recs);
99                         DEBUG(0, ("Failed to grab dnsp_DnssrvRpcRecord\n"));
100                         return DNS_ERR(SERVER_FAILURE);
101                 }
102
103                 /*
104                  * In AD, except on an RODC (where we should list a random RWDC,
105                  * we should over-stamp the MNAME with our own hostname
106                  */
107                 if (recs[ri].wType != DNS_TYPE_SOA) {
108                         continue;
109                 }
110
111                 ret = samdb_rodc(samdb, &am_rodc);
112                 if (ret != LDB_SUCCESS) {
113                         DEBUG(0, ("Failed to confirm we are not an RODC: %s\n",
114                                   ldb_errstring(samdb)));
115                         return DNS_ERR(SERVER_FAILURE);
116                 }
117
118                 if (am_rodc) {
119                         continue;
120                 }
121
122                 ret = samdb_dns_host_name(samdb, &dnsHostName);
123                 if (ret != LDB_SUCCESS || dnsHostName == NULL) {
124                         DEBUG(0, ("Failed to get dnsHostName from rootDSE"));
125                         return DNS_ERR(SERVER_FAILURE);
126                 }
127
128                 recs[ri].data.soa.mname = talloc_strdup(recs, dnsHostName);
129         }
130
131         *records = recs;
132         *num_records = el->num_values;
133         return WERR_OK;
134 }
135
136 WERROR dns_common_lookup(struct ldb_context *samdb,
137                          TALLOC_CTX *mem_ctx,
138                          struct ldb_dn *dn,
139                          struct dnsp_DnssrvRpcRecord **records,
140                          uint16_t *num_records,
141                          bool *tombstoned)
142 {
143         static const char * const attrs[] = {
144                 "dnsRecord",
145                 "dNSTombstoned",
146                 NULL
147         };
148         int ret;
149         WERROR werr;
150         struct ldb_message *msg = NULL;
151         struct ldb_message_element *el;
152
153         *records = NULL;
154         *num_records = 0;
155
156         if (tombstoned != NULL) {
157                 *tombstoned = false;
158                 ret = dsdb_search_one(samdb, mem_ctx, &msg, dn,
159                         LDB_SCOPE_BASE, attrs, 0,
160                         "(objectClass=dnsNode)");
161         } else {
162                 ret = dsdb_search_one(samdb, mem_ctx, &msg, dn,
163                         LDB_SCOPE_BASE, attrs, 0,
164                         "(&(objectClass=dnsNode)(!(dNSTombstoned=TRUE)))");
165         }
166         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
167                 return WERR_DNS_ERROR_NAME_DOES_NOT_EXIST;
168         }
169         if (ret != LDB_SUCCESS) {
170                 /* TODO: we need to check if there's a glue record we need to
171                  * create a referral to */
172                 return DNS_ERR(NAME_ERROR);
173         }
174
175         if (tombstoned != NULL) {
176                 *tombstoned = ldb_msg_find_attr_as_bool(msg,
177                                         "dNSTombstoned", false);
178         }
179
180         el = ldb_msg_find_element(msg, "dnsRecord");
181         if (el == NULL) {
182                 TALLOC_FREE(msg);
183                 /*
184                  * records produced by older Samba releases
185                  * keep dnsNode objects without dnsRecord and
186                  * without setting dNSTombstoned=TRUE.
187                  *
188                  * We just pretend they're tombstones.
189                  */
190                 if (tombstoned != NULL) {
191                         struct dnsp_DnssrvRpcRecord *recs;
192                         recs = talloc_array(mem_ctx,
193                                             struct dnsp_DnssrvRpcRecord,
194                                             1);
195                         if (recs == NULL) {
196                                 return WERR_NOT_ENOUGH_MEMORY;
197                         }
198                         recs[0] = (struct dnsp_DnssrvRpcRecord) {
199                                 .wType = DNS_TYPE_TOMBSTONE,
200                                 /*
201                                  * A value of timestamp != 0
202                                  * indicated that the object was already
203                                  * a tombstone, this will be used
204                                  * in dns_common_replace()
205                                  */
206                                 .data.timestamp = 1,
207                         };
208
209                         *tombstoned = true;
210                         *records = recs;
211                         *num_records = 1;
212                         return WERR_OK;
213                 } else {
214                         /*
215                          * Because we are not looking for a tombstone
216                          * in this codepath, we just pretend it does
217                          * not exist at all.
218                          */
219                         return WERR_DNS_ERROR_NAME_DOES_NOT_EXIST;
220                 }
221         }
222
223         werr = dns_common_extract(samdb, el, mem_ctx, records, num_records);
224         TALLOC_FREE(msg);
225         if (!W_ERROR_IS_OK(werr)) {
226                 return werr;
227         }
228
229         return WERR_OK;
230 }
231
232 static int rec_cmp(const struct dnsp_DnssrvRpcRecord *r1,
233                    const struct dnsp_DnssrvRpcRecord *r2)
234 {
235         if (r1->wType != r2->wType) {
236                 /*
237                  * The records are sorted with higher types first
238                  */
239                 return r2->wType - r1->wType;
240         }
241
242         /*
243          * Then we need to sort from the oldest to newest timestamp
244          */
245         return r1->dwTimeStamp - r2->dwTimeStamp;
246 }
247
248 /*
249  * Check for valid DNS names. These are names which are non-empty, do not
250  * start with a dot and do not have any empty segments.
251  */
252 WERROR dns_name_check(TALLOC_CTX *mem_ctx, size_t len, const char *name)
253 {
254         size_t i;
255
256         if (len == 0) {
257                 return WERR_DS_INVALID_DN_SYNTAX;
258         }
259
260         for (i = 0; i < len - 1; i++) {
261                 if (name[i] == '.' && name[i+1] == '.') {
262                         return WERR_DS_INVALID_DN_SYNTAX;
263                 }
264         }
265
266         if (len > 1 && name[0] == '.') {
267                 return WERR_DS_INVALID_DN_SYNTAX;
268         }
269
270         return WERR_OK;
271 }
272
273 static WERROR check_name_list(TALLOC_CTX *mem_ctx, uint16_t rec_count,
274                               struct dnsp_DnssrvRpcRecord *records)
275 {
276         WERROR werr;
277         uint16_t i;
278         size_t len;
279         struct dnsp_DnssrvRpcRecord record;
280
281         werr = WERR_OK;
282         for (i = 0; i < rec_count; i++) {
283                 record = records[i];
284
285                 switch (record.wType) {
286
287                 case DNS_TYPE_NS:
288                         len = strlen(record.data.ns);
289                         werr = dns_name_check(mem_ctx, len, record.data.ns);
290                         break;
291                 case DNS_TYPE_CNAME:
292                         len = strlen(record.data.cname);
293                         werr = dns_name_check(mem_ctx, len, record.data.cname);
294                         break;
295                 case DNS_TYPE_SOA:
296                         len = strlen(record.data.soa.mname);
297                         werr = dns_name_check(mem_ctx, len, record.data.soa.mname);
298                         if (!W_ERROR_IS_OK(werr)) {
299                                 break;
300                         }
301                         len = strlen(record.data.soa.rname);
302                         werr = dns_name_check(mem_ctx, len, record.data.soa.rname);
303                         break;
304                 case DNS_TYPE_PTR:
305                         len = strlen(record.data.ptr);
306                         werr = dns_name_check(mem_ctx, len, record.data.ptr);
307                         break;
308                 case DNS_TYPE_MX:
309                         len = strlen(record.data.mx.nameTarget);
310                         werr = dns_name_check(mem_ctx, len, record.data.mx.nameTarget);
311                         break;
312                 case DNS_TYPE_SRV:
313                         len = strlen(record.data.srv.nameTarget);
314                         werr = dns_name_check(mem_ctx, len,
315                                               record.data.srv.nameTarget);
316                         break;
317                 /*
318                  * In the default case, the record doesn't have a DN, so it
319                  * must be ok.
320                  */
321                 default:
322                         break;
323                 }
324
325                 if (!W_ERROR_IS_OK(werr)) {
326                         return werr;
327                 }
328         }
329
330         return WERR_OK;
331 }
332
333 WERROR dns_common_replace(struct ldb_context *samdb,
334                           TALLOC_CTX *mem_ctx,
335                           struct ldb_dn *dn,
336                           bool needs_add,
337                           uint32_t serial,
338                           struct dnsp_DnssrvRpcRecord *records,
339                           uint16_t rec_count)
340 {
341         struct ldb_message_element *el;
342         uint16_t i;
343         int ret;
344         WERROR werr;
345         struct ldb_message *msg = NULL;
346         bool was_tombstoned = false;
347         bool become_tombstoned = false;
348
349         msg = ldb_msg_new(mem_ctx);
350         W_ERROR_HAVE_NO_MEMORY(msg);
351
352         msg->dn = dn;
353
354         werr = check_name_list(mem_ctx, rec_count, records);
355         if (!W_ERROR_IS_OK(werr)) {
356                 return werr;
357         }
358
359         ret = ldb_msg_add_empty(msg, "dnsRecord", LDB_FLAG_MOD_REPLACE, &el);
360         if (ret != LDB_SUCCESS) {
361                 return DNS_ERR(SERVER_FAILURE);
362         }
363
364         /*
365          * we have at least one value,
366          * which might be used for the tombstone marker
367          */
368         el->values = talloc_zero_array(el, struct ldb_val, MAX(1, rec_count));
369         if (rec_count > 0) {
370                 W_ERROR_HAVE_NO_MEMORY(el->values);
371
372                 /*
373                  * We store a sorted list with the high wType values first
374                  * that's what windows does. It also simplifies the
375                  * filtering of DNS_TYPE_TOMBSTONE records
376                  */
377                 TYPESAFE_QSORT(records, rec_count, rec_cmp);
378         }
379
380         for (i = 0; i < rec_count; i++) {
381                 struct ldb_val *v = &el->values[el->num_values];
382                 enum ndr_err_code ndr_err;
383
384                 if (records[i].wType == DNS_TYPE_TOMBSTONE) {
385                         if (records[i].data.timestamp != 0) {
386                                 was_tombstoned = true;
387                         }
388                         continue;
389                 }
390
391                 records[i].dwSerial = serial;
392                 ndr_err = ndr_push_struct_blob(v, el->values, &records[i],
393                                 (ndr_push_flags_fn_t)ndr_push_dnsp_DnssrvRpcRecord);
394                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
395                         DEBUG(0, ("Failed to push dnsp_DnssrvRpcRecord\n"));
396                         return DNS_ERR(SERVER_FAILURE);
397                 }
398                 el->num_values++;
399         }
400
401         if (needs_add) {
402                 if (el->num_values == 0) {
403                         return WERR_OK;
404                 }
405
406                 ret = ldb_msg_add_string(msg, "objectClass", "dnsNode");
407                 if (ret != LDB_SUCCESS) {
408                         return DNS_ERR(SERVER_FAILURE);
409                 }
410
411                 ret = ldb_add(samdb, msg);
412                 if (ret != LDB_SUCCESS) {
413                         return DNS_ERR(SERVER_FAILURE);
414                 }
415
416                 return WERR_OK;
417         }
418
419         if (el->num_values == 0) {
420                 struct dnsp_DnssrvRpcRecord tbs;
421                 struct ldb_val *v = &el->values[el->num_values];
422                 enum ndr_err_code ndr_err;
423                 struct timeval tv;
424
425                 if (was_tombstoned) {
426                         /*
427                          * This is already a tombstoned object.
428                          * Just leave it instead of updating the time stamp.
429                          */
430                         return WERR_OK;
431                 }
432
433                 tv = timeval_current();
434                 tbs = (struct dnsp_DnssrvRpcRecord) {
435                         .wType = DNS_TYPE_TOMBSTONE,
436                         .dwSerial = serial,
437                         .data.timestamp = timeval_to_nttime(&tv),
438                 };
439
440                 ndr_err = ndr_push_struct_blob(v, el->values, &tbs,
441                                 (ndr_push_flags_fn_t)ndr_push_dnsp_DnssrvRpcRecord);
442                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
443                         DEBUG(0, ("Failed to push dnsp_DnssrvRpcRecord\n"));
444                         return DNS_ERR(SERVER_FAILURE);
445                 }
446                 el->num_values++;
447
448                 become_tombstoned = true;
449         }
450
451         if (was_tombstoned || become_tombstoned) {
452                 ret = ldb_msg_add_empty(msg, "dNSTombstoned",
453                                         LDB_FLAG_MOD_REPLACE, NULL);
454                 if (ret != LDB_SUCCESS) {
455                         return DNS_ERR(SERVER_FAILURE);
456                 }
457
458                 ret = ldb_msg_add_fmt(msg, "dNSTombstoned", "%s",
459                                       become_tombstoned ? "TRUE" : "FALSE");
460                 if (ret != LDB_SUCCESS) {
461                         return DNS_ERR(SERVER_FAILURE);
462                 }
463         }
464
465         ret = ldb_modify(samdb, msg);
466         if (ret != LDB_SUCCESS) {
467                 NTSTATUS nt = dsdb_ldb_err_to_ntstatus(ret);
468                 return ntstatus_to_werror(nt);
469         }
470
471         return WERR_OK;
472 }
473
474 bool dns_name_match(const char *zone, const char *name, size_t *host_part_len)
475 {
476         size_t zl = strlen(zone);
477         size_t nl = strlen(name);
478         ssize_t zi, ni;
479         static const size_t fixup = 'a' - 'A';
480
481         if (zl > nl) {
482                 return false;
483         }
484
485         for (zi = zl, ni = nl; zi >= 0; zi--, ni--) {
486                 char zc = zone[zi];
487                 char nc = name[ni];
488
489                 /* convert to lower case */
490                 if (zc >= 'A' && zc <= 'Z') {
491                         zc += fixup;
492                 }
493                 if (nc >= 'A' && nc <= 'Z') {
494                         nc += fixup;
495                 }
496
497                 if (zc != nc) {
498                         return false;
499                 }
500         }
501
502         if (ni >= 0) {
503                 if (name[ni] != '.') {
504                         return false;
505                 }
506
507                 ni--;
508         }
509
510         *host_part_len = ni+1;
511
512         return true;
513 }
514
515 WERROR dns_common_name2dn(struct ldb_context *samdb,
516                           struct dns_server_zone *zones,
517                           TALLOC_CTX *mem_ctx,
518                           const char *name,
519                           struct ldb_dn **_dn)
520 {
521         struct ldb_dn *base;
522         struct ldb_dn *dn;
523         const struct dns_server_zone *z;
524         size_t host_part_len = 0;
525         WERROR werr;
526
527         if (name == NULL) {
528                 return DNS_ERR(FORMAT_ERROR);
529         }
530
531         if (strcmp(name, "") == 0) {
532                 base = ldb_get_default_basedn(samdb);
533                 dn = ldb_dn_copy(mem_ctx, base);
534                 ldb_dn_add_child_fmt(dn, "DC=@,DC=RootDNSServers,CN=MicrosoftDNS,CN=System");
535                 *_dn = dn;
536                 return WERR_OK;
537         }
538
539         /* Check non-empty names */
540         werr = dns_name_check(mem_ctx, strlen(name), name);
541         if (!W_ERROR_IS_OK(werr)) {
542                 return werr;
543         }
544
545         for (z = zones; z != NULL; z = z->next) {
546                 bool match;
547
548                 match = dns_name_match(z->name, name, &host_part_len);
549                 if (match) {
550                         break;
551                 }
552         }
553
554         if (z == NULL) {
555                 return DNS_ERR(NAME_ERROR);
556         }
557
558         if (host_part_len == 0) {
559                 dn = ldb_dn_copy(mem_ctx, z->dn);
560                 ldb_dn_add_child_fmt(dn, "DC=@");
561                 *_dn = dn;
562                 return WERR_OK;
563         }
564
565         dn = ldb_dn_copy(mem_ctx, z->dn);
566         ldb_dn_add_child_fmt(dn, "DC=%*.*s", (int)host_part_len, (int)host_part_len, name);
567         *_dn = dn;
568         return WERR_OK;
569 }
570
571 static int dns_common_sort_zones(struct ldb_message **m1, struct ldb_message **m2)
572 {
573         const char *n1, *n2;
574         size_t l1, l2;
575
576         n1 = ldb_msg_find_attr_as_string(*m1, "name", NULL);
577         n2 = ldb_msg_find_attr_as_string(*m2, "name", NULL);
578
579         l1 = strlen(n1);
580         l2 = strlen(n2);
581
582         /* If the string lengths are not equal just sort by length */
583         if (l1 != l2) {
584                 /* If m1 is the larger zone name, return it first */
585                 return l2 - l1;
586         }
587
588         /*TODO: We need to compare DNs here, we want the DomainDNSZones first */
589         return 0;
590 }
591
592 NTSTATUS dns_common_zones(struct ldb_context *samdb,
593                           TALLOC_CTX *mem_ctx,
594                           struct ldb_dn *base_dn,
595                           struct dns_server_zone **zones_ret)
596 {
597         int ret;
598         static const char * const attrs[] = { "name", NULL};
599         struct ldb_result *res;
600         int i;
601         struct dns_server_zone *new_list = NULL;
602         TALLOC_CTX *frame = talloc_stackframe();
603
604         if (base_dn) {
605                 /* This search will work against windows */
606                 ret = dsdb_search(samdb, frame, &res,
607                                   base_dn, LDB_SCOPE_SUBTREE,
608                                   attrs, 0, "(objectClass=dnsZone)");
609         } else {
610                 /* TODO: this search does not work against windows */
611                 ret = dsdb_search(samdb, frame, &res, NULL,
612                                   LDB_SCOPE_SUBTREE,
613                                   attrs,
614                                   DSDB_SEARCH_SEARCH_ALL_PARTITIONS,
615                                   "(objectClass=dnsZone)");
616         }
617         if (ret != LDB_SUCCESS) {
618                 TALLOC_FREE(frame);
619                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
620         }
621
622         TYPESAFE_QSORT(res->msgs, res->count, dns_common_sort_zones);
623
624         for (i=0; i < res->count; i++) {
625                 struct dns_server_zone *z;
626
627                 z = talloc_zero(mem_ctx, struct dns_server_zone);
628                 if (z == NULL) {
629                         TALLOC_FREE(frame);
630                         return NT_STATUS_NO_MEMORY;
631                 }
632
633                 z->name = ldb_msg_find_attr_as_string(res->msgs[i], "name", NULL);
634                 talloc_steal(z, z->name);
635                 z->dn = talloc_move(z, &res->msgs[i]->dn);
636                 /*
637                  * Ignore the RootDNSServers zone and zones that we don't support yet
638                  * RootDNSServers should never be returned (Windows DNS server don't)
639                  * ..TrustAnchors should never be returned as is, (Windows returns
640                  * TrustAnchors) and for the moment we don't support DNSSEC so we'd better
641                  * not return this zone.
642                  */
643                 if ((strcmp(z->name, "RootDNSServers") == 0) ||
644                     (strcmp(z->name, "..TrustAnchors") == 0))
645                 {
646                         DEBUG(10, ("Ignoring zone %s\n", z->name));
647                         talloc_free(z);
648                         continue;
649                 }
650                 DLIST_ADD_END(new_list, z);
651         }
652
653         *zones_ret = new_list;
654         TALLOC_FREE(frame);
655         return NT_STATUS_OK;
656 }