dns_server: Avoid ldb_dn_add_child_fmt() on untrusted input
[samba.git] / source4 / dns_server / dlz_bind9.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    bind9 dlz driver for Samba
5
6    Copyright (C) 2010 Andrew Tridgell
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "includes.h"
23 #include "talloc.h"
24 #include "param/param.h"
25 #include "lib/events/events.h"
26 #include "dsdb/samdb/samdb.h"
27 #include "dsdb/common/util.h"
28 #include "auth/auth.h"
29 #include "auth/session.h"
30 #include "auth/gensec/gensec.h"
31 #include "librpc/gen_ndr/security.h"
32 #include "auth/credentials/credentials.h"
33 #include "system/kerberos.h"
34 #include "auth/kerberos/kerberos.h"
35 #include "gen_ndr/ndr_dnsp.h"
36 #include "gen_ndr/server_id.h"
37 #include "messaging/messaging.h"
38 #include <popt.h>
39 #include "lib/util/dlinklist.h"
40 #include "dlz_minimal.h"
41 #include "dnsserver_common.h"
42
43 struct b9_options {
44         const char *url;
45         const char *debug;
46 };
47
48 struct b9_zone {
49         char *name;
50         struct b9_zone *prev, *next;
51 };
52
53 struct dlz_bind9_data {
54         struct b9_options options;
55         struct ldb_context *samdb;
56         struct tevent_context *ev_ctx;
57         struct loadparm_context *lp;
58         int *transaction_token;
59         uint32_t soa_serial;
60         struct b9_zone *zonelist;
61
62         /* Used for dynamic update */
63         struct smb_krb5_context *smb_krb5_ctx;
64         struct auth4_context *auth_context;
65         struct auth_session_info *session_info;
66         char *update_name;
67
68         /* helper functions from the dlz_dlopen driver */
69         log_t *log;
70         dns_sdlz_putrr_t *putrr;
71         dns_sdlz_putnamedrr_t *putnamedrr;
72         dns_dlz_writeablezone_t *writeable_zone;
73 };
74
75 static struct dlz_bind9_data *dlz_bind9_state = NULL;
76 static int dlz_bind9_state_ref_count = 0;
77
78 static const char *zone_prefixes[] = {
79         "CN=MicrosoftDNS,DC=DomainDnsZones",
80         "CN=MicrosoftDNS,DC=ForestDnsZones",
81         "CN=MicrosoftDNS,CN=System",
82         NULL
83 };
84
85 /*
86   return the version of the API
87  */
88 _PUBLIC_ int dlz_version(unsigned int *flags)
89 {
90         return DLZ_DLOPEN_VERSION;
91 }
92
93 /*
94    remember a helper function from the bind9 dlz_dlopen driver
95  */
96 static void b9_add_helper(struct dlz_bind9_data *state, const char *helper_name, void *ptr)
97 {
98         if (strcmp(helper_name, "log") == 0) {
99                 state->log = ptr;
100         }
101         if (strcmp(helper_name, "putrr") == 0) {
102                 state->putrr = ptr;
103         }
104         if (strcmp(helper_name, "putnamedrr") == 0) {
105                 state->putnamedrr = ptr;
106         }
107         if (strcmp(helper_name, "writeable_zone") == 0) {
108                 state->writeable_zone = ptr;
109         }
110 }
111
112 /*
113  * Add a trailing '.' if it's missing
114  */
115 static const char *b9_format_fqdn(TALLOC_CTX *mem_ctx, const char *str)
116 {
117         size_t len;
118         const char *tmp;
119
120         if (str == NULL || str[0] == '\0') {
121                 return str;
122         }
123
124         len = strlen(str);
125         if (str[len-1] != '.') {
126                 tmp = talloc_asprintf(mem_ctx, "%s.", str);
127         } else {
128                 tmp = str;
129         }
130         return tmp;
131 }
132
133 /*
134   format a record for bind9
135  */
136 static bool b9_format(struct dlz_bind9_data *state,
137                       TALLOC_CTX *mem_ctx,
138                       struct dnsp_DnssrvRpcRecord *rec,
139                       const char **type, const char **data)
140 {
141         uint32_t i;
142         char *tmp;
143         const char *fqdn;
144
145         switch (rec->wType) {
146         case DNS_TYPE_A:
147                 *type = "a";
148                 *data = rec->data.ipv4;
149                 break;
150
151         case DNS_TYPE_AAAA:
152                 *type = "aaaa";
153                 *data = rec->data.ipv6;
154                 break;
155
156         case DNS_TYPE_CNAME:
157                 *type = "cname";
158                 *data = b9_format_fqdn(mem_ctx, rec->data.cname);
159                 break;
160
161         case DNS_TYPE_TXT:
162                 *type = "txt";
163                 tmp = talloc_asprintf(mem_ctx, "\"%s\"", rec->data.txt.str[0]);
164                 for (i=1; i<rec->data.txt.count; i++) {
165                         tmp = talloc_asprintf_append(tmp, " \"%s\"", rec->data.txt.str[i]);
166                 }
167                 *data = tmp;
168                 break;
169
170         case DNS_TYPE_PTR:
171                 *type = "ptr";
172                 *data = b9_format_fqdn(mem_ctx, rec->data.ptr);
173                 break;
174
175         case DNS_TYPE_SRV:
176                 *type = "srv";
177                 fqdn = b9_format_fqdn(mem_ctx, rec->data.srv.nameTarget);
178                 if (fqdn == NULL) {
179                         return false;
180                 }
181                 *data = talloc_asprintf(mem_ctx, "%u %u %u %s",
182                                         rec->data.srv.wPriority,
183                                         rec->data.srv.wWeight,
184                                         rec->data.srv.wPort,
185                                         fqdn);
186                 break;
187
188         case DNS_TYPE_MX:
189                 *type = "mx";
190                 fqdn = b9_format_fqdn(mem_ctx, rec->data.mx.nameTarget);
191                 if (fqdn == NULL) {
192                         return false;
193                 }
194                 *data = talloc_asprintf(mem_ctx, "%u %s",
195                                         rec->data.mx.wPriority, fqdn);
196                 break;
197
198         case DNS_TYPE_HINFO:
199                 *type = "hinfo";
200                 *data = talloc_asprintf(mem_ctx, "%s %s",
201                                         rec->data.hinfo.cpu,
202                                         rec->data.hinfo.os);
203                 break;
204
205         case DNS_TYPE_NS:
206                 *type = "ns";
207                 *data = b9_format_fqdn(mem_ctx, rec->data.ns);
208                 break;
209
210         case DNS_TYPE_SOA: {
211                 const char *mname;
212                 *type = "soa";
213
214                 /* we need to fake the authoritative nameserver to
215                  * point at ourselves. This is how AD DNS servers
216                  * force clients to send updates to the right local DC
217                  */
218                 mname = talloc_asprintf(mem_ctx, "%s.%s.",
219                                         lpcfg_netbios_name(state->lp),
220                                         lpcfg_dnsdomain(state->lp));
221                 if (mname == NULL) {
222                         return false;
223                 }
224                 mname = strlower_talloc(mem_ctx, mname);
225                 if (mname == NULL) {
226                         return false;
227                 }
228
229                 fqdn = b9_format_fqdn(mem_ctx, rec->data.soa.rname);
230                 if (fqdn == NULL) {
231                         return false;
232                 }
233
234                 state->soa_serial = rec->data.soa.serial;
235
236                 *data = talloc_asprintf(mem_ctx, "%s %s %u %u %u %u %u",
237                                         mname, fqdn,
238                                         rec->data.soa.serial,
239                                         rec->data.soa.refresh,
240                                         rec->data.soa.retry,
241                                         rec->data.soa.expire,
242                                         rec->data.soa.minimum);
243                 break;
244         }
245
246         default:
247                 state->log(ISC_LOG_ERROR, "samba_dlz b9_format: unhandled record type %u",
248                            rec->wType);
249                 return false;
250         }
251
252         return true;
253 }
254
255 static const struct {
256         enum dns_record_type dns_type;
257         const char *typestr;
258         bool single_valued;
259 } dns_typemap[] = {
260         { DNS_TYPE_A,     "A"     , false},
261         { DNS_TYPE_AAAA,  "AAAA"  , false},
262         { DNS_TYPE_CNAME, "CNAME" , true},
263         { DNS_TYPE_TXT,   "TXT"   , false},
264         { DNS_TYPE_PTR,   "PTR"   , false},
265         { DNS_TYPE_SRV,   "SRV"   , false},
266         { DNS_TYPE_MX,    "MX"    , false},
267         { DNS_TYPE_HINFO, "HINFO" , false},
268         { DNS_TYPE_NS,    "NS"    , false},
269         { DNS_TYPE_SOA,   "SOA"   , true},
270 };
271
272
273 /*
274   see if a DNS type is single valued
275  */
276 static bool b9_single_valued(enum dns_record_type dns_type)
277 {
278         int i;
279         for (i=0; i<ARRAY_SIZE(dns_typemap); i++) {
280                 if (dns_typemap[i].dns_type == dns_type) {
281                         return dns_typemap[i].single_valued;
282                 }
283         }
284         return false;
285 }
286
287 /*
288   see if a DNS type is single valued
289  */
290 static bool b9_dns_type(const char *type, enum dns_record_type *dtype)
291 {
292         int i;
293         for (i=0; i<ARRAY_SIZE(dns_typemap); i++) {
294                 if (strcasecmp(dns_typemap[i].typestr, type) == 0) {
295                         *dtype = dns_typemap[i].dns_type;
296                         return true;
297                 }
298         }
299         return false;
300 }
301
302
303 #define DNS_PARSE_STR(ret, str, sep, saveptr) do {      \
304         (ret) = strtok_r(str, sep, &saveptr); \
305         if ((ret) == NULL) return false; \
306         } while (0)
307
308 #define DNS_PARSE_UINT(ret, str, sep, saveptr) do {  \
309         char *istr = strtok_r(str, sep, &saveptr); \
310         if ((istr) == NULL) return false; \
311         (ret) = strtoul(istr, NULL, 10); \
312         } while (0)
313
314 /*
315   parse a record from bind9
316  */
317 static bool b9_parse(struct dlz_bind9_data *state,
318                      const char *rdatastr,
319                      struct dnsp_DnssrvRpcRecord *rec)
320 {
321         char *full_name, *dclass, *type;
322         char *str, *tmp, *saveptr=NULL;
323         int i;
324
325         str = talloc_strdup(rec, rdatastr);
326         if (str == NULL) {
327                 return false;
328         }
329
330         /* parse the SDLZ string form */
331         DNS_PARSE_STR(full_name, str, "\t", saveptr);
332         DNS_PARSE_UINT(rec->dwTtlSeconds, NULL, "\t", saveptr);
333         DNS_PARSE_STR(dclass, NULL, "\t", saveptr);
334         DNS_PARSE_STR(type, NULL, "\t", saveptr);
335
336         /* construct the record */
337         for (i=0; i<ARRAY_SIZE(dns_typemap); i++) {
338                 if (strcasecmp(type, dns_typemap[i].typestr) == 0) {
339                         rec->wType = dns_typemap[i].dns_type;
340                         break;
341                 }
342         }
343         if (i == ARRAY_SIZE(dns_typemap)) {
344                 state->log(ISC_LOG_ERROR, "samba_dlz: unsupported record type '%s' for '%s'",
345                            type, full_name);
346                 return false;
347         }
348
349         switch (rec->wType) {
350         case DNS_TYPE_A:
351                 DNS_PARSE_STR(rec->data.ipv4, NULL, " ", saveptr);
352                 break;
353
354         case DNS_TYPE_AAAA:
355                 DNS_PARSE_STR(rec->data.ipv6, NULL, " ", saveptr);
356                 break;
357
358         case DNS_TYPE_CNAME:
359                 DNS_PARSE_STR(rec->data.cname, NULL, " ", saveptr);
360                 break;
361
362         case DNS_TYPE_TXT:
363                 rec->data.txt.count = 0;
364                 rec->data.txt.str = talloc_array(rec, const char *, rec->data.txt.count);
365                 tmp = strtok_r(NULL, "\t", &saveptr);
366                 while (tmp) {
367                         rec->data.txt.str = talloc_realloc(rec, rec->data.txt.str, const char *,
368                                                         rec->data.txt.count+1);
369                         if (tmp[0] == '"') {
370                                 /* Strip quotes */
371                                 rec->data.txt.str[rec->data.txt.count] = talloc_strndup(rec, &tmp[1], strlen(tmp)-2);
372                         } else {
373                                 rec->data.txt.str[rec->data.txt.count] = talloc_strdup(rec, tmp);
374                         }
375                         rec->data.txt.count++;
376                         tmp = strtok_r(NULL, " ", &saveptr);
377                 }
378                 break;
379
380         case DNS_TYPE_PTR:
381                 DNS_PARSE_STR(rec->data.ptr, NULL, " ", saveptr);
382                 break;
383
384         case DNS_TYPE_SRV:
385                 DNS_PARSE_UINT(rec->data.srv.wPriority, NULL, " ", saveptr);
386                 DNS_PARSE_UINT(rec->data.srv.wWeight, NULL, " ", saveptr);
387                 DNS_PARSE_UINT(rec->data.srv.wPort, NULL, " ", saveptr);
388                 DNS_PARSE_STR(rec->data.srv.nameTarget, NULL, " ", saveptr);
389                 break;
390
391         case DNS_TYPE_MX:
392                 DNS_PARSE_UINT(rec->data.mx.wPriority, NULL, " ", saveptr);
393                 DNS_PARSE_STR(rec->data.mx.nameTarget, NULL, " ", saveptr);
394                 break;
395
396         case DNS_TYPE_HINFO:
397                 DNS_PARSE_STR(rec->data.hinfo.cpu, NULL, " ", saveptr);
398                 DNS_PARSE_STR(rec->data.hinfo.os, NULL, " ", saveptr);
399                 break;
400
401         case DNS_TYPE_NS:
402                 DNS_PARSE_STR(rec->data.ns, NULL, " ", saveptr);
403                 break;
404
405         case DNS_TYPE_SOA:
406                 DNS_PARSE_STR(rec->data.soa.mname, NULL, " ", saveptr);
407                 DNS_PARSE_STR(rec->data.soa.rname, NULL, " ", saveptr);
408                 DNS_PARSE_UINT(rec->data.soa.serial, NULL, " ", saveptr);
409                 DNS_PARSE_UINT(rec->data.soa.refresh, NULL, " ", saveptr);
410                 DNS_PARSE_UINT(rec->data.soa.retry, NULL, " ", saveptr);
411                 DNS_PARSE_UINT(rec->data.soa.expire, NULL, " ", saveptr);
412                 DNS_PARSE_UINT(rec->data.soa.minimum, NULL, " ", saveptr);
413                 break;
414
415         default:
416                 state->log(ISC_LOG_ERROR, "samba_dlz b9_parse: unhandled record type %u",
417                            rec->wType);
418                 return false;
419         }
420
421         /* we should be at the end of the buffer now */
422         if (strtok_r(NULL, "\t ", &saveptr) != NULL) {
423                 state->log(ISC_LOG_ERROR, "samba_dlz b9_parse: unexpected data at end of string for '%s'",
424                            rdatastr);
425                 return false;
426         }
427
428         return true;
429 }
430
431 /*
432   send a resource record to bind9
433  */
434 static isc_result_t b9_putrr(struct dlz_bind9_data *state,
435                              void *handle, struct dnsp_DnssrvRpcRecord *rec,
436                              const char **types)
437 {
438         isc_result_t result;
439         const char *type, *data;
440         TALLOC_CTX *tmp_ctx = talloc_new(state);
441
442         if (!b9_format(state, tmp_ctx, rec, &type, &data)) {
443                 return ISC_R_FAILURE;
444         }
445
446         if (data == NULL) {
447                 talloc_free(tmp_ctx);
448                 return ISC_R_NOMEMORY;
449         }
450
451         if (types) {
452                 int i;
453                 for (i=0; types[i]; i++) {
454                         if (strcmp(types[i], type) == 0) break;
455                 }
456                 if (types[i] == NULL) {
457                         /* skip it */
458                         return ISC_R_SUCCESS;
459                 }
460         }
461
462         result = state->putrr(handle, type, rec->dwTtlSeconds, data);
463         if (result != ISC_R_SUCCESS) {
464                 state->log(ISC_LOG_ERROR, "Failed to put rr");
465         }
466         talloc_free(tmp_ctx);
467         return result;
468 }
469
470
471 /*
472   send a named resource record to bind9
473  */
474 static isc_result_t b9_putnamedrr(struct dlz_bind9_data *state,
475                                   void *handle, const char *name,
476                                   struct dnsp_DnssrvRpcRecord *rec)
477 {
478         isc_result_t result;
479         const char *type, *data;
480         TALLOC_CTX *tmp_ctx = talloc_new(state);
481
482         if (!b9_format(state, tmp_ctx, rec, &type, &data)) {
483                 return ISC_R_FAILURE;
484         }
485
486         if (data == NULL) {
487                 talloc_free(tmp_ctx);
488                 return ISC_R_NOMEMORY;
489         }
490
491         result = state->putnamedrr(handle, name, type, rec->dwTtlSeconds, data);
492         if (result != ISC_R_SUCCESS) {
493                 state->log(ISC_LOG_ERROR, "Failed to put named rr '%s'", name);
494         }
495         talloc_free(tmp_ctx);
496         return result;
497 }
498
499 /*
500    parse options
501  */
502 static isc_result_t parse_options(struct dlz_bind9_data *state,
503                                   unsigned int argc, const char **argv,
504                                   struct b9_options *options)
505 {
506         int opt;
507         poptContext pc;
508         struct poptOption long_options[] = {
509                 { "url", 'H', POPT_ARG_STRING, &options->url, 0, "database URL", "URL" },
510                 { "debug", 'd', POPT_ARG_STRING, &options->debug, 0, "debug level", "DEBUG" },
511                 { NULL }
512         };
513
514         pc = poptGetContext("dlz_bind9", argc, argv, long_options,
515                         POPT_CONTEXT_KEEP_FIRST);
516         while ((opt = poptGetNextOpt(pc)) != -1) {
517                 switch (opt) {
518                 default:
519                         state->log(ISC_LOG_ERROR, "dlz_bind9: Invalid option %s: %s",
520                                    poptBadOption(pc, 0), poptStrerror(opt));
521                         return ISC_R_FAILURE;
522                 }
523         }
524
525         return ISC_R_SUCCESS;
526 }
527
528
529 /*
530  * Create session info from PAC
531  * This is called as auth_context->generate_session_info_pac()
532  */
533 static NTSTATUS b9_generate_session_info_pac(struct auth4_context *auth_context,
534                                              TALLOC_CTX *mem_ctx,
535                                              struct smb_krb5_context *smb_krb5_context,
536                                              DATA_BLOB *pac_blob,
537                                              const char *principal_name,
538                                              const struct tsocket_address *remote_addr,
539                                              uint32_t session_info_flags,
540                                              struct auth_session_info **session_info)
541 {
542         NTSTATUS status;
543         struct auth_user_info_dc *user_info_dc;
544         TALLOC_CTX *tmp_ctx;
545
546         tmp_ctx = talloc_new(mem_ctx);
547         NT_STATUS_HAVE_NO_MEMORY(tmp_ctx);
548
549         status = kerberos_pac_blob_to_user_info_dc(tmp_ctx,
550                                                    *pac_blob,
551                                                    smb_krb5_context->krb5_context,
552                                                    &user_info_dc,
553                                                    NULL,
554                                                    NULL);
555         if (!NT_STATUS_IS_OK(status)) {
556                 talloc_free(tmp_ctx);
557                 return status;
558         }
559
560         if (user_info_dc->info->authenticated) {
561                 session_info_flags |= AUTH_SESSION_INFO_AUTHENTICATED;
562         }
563
564         session_info_flags |= AUTH_SESSION_INFO_SIMPLE_PRIVILEGES;
565
566         status = auth_generate_session_info(mem_ctx, NULL, NULL, user_info_dc,
567                                             session_info_flags, session_info);
568         if (!NT_STATUS_IS_OK(status)) {
569                 talloc_free(tmp_ctx);
570                 return status;
571         }
572
573         talloc_free(tmp_ctx);
574         return status;
575 }
576
577 /* Callback for the DEBUG() system, to catch the remaining messages */
578 static void b9_debug(void *private_ptr, int msg_level, const char *msg)
579 {
580         static const int isc_log_map[] = {
581                 ISC_LOG_CRITICAL, /* 0 */
582                 ISC_LOG_ERROR,    /* 1 */
583                 ISC_LOG_WARNING,   /* 2 */
584                 ISC_LOG_NOTICE    /* 3 */
585         };
586         struct dlz_bind9_data *state = private_ptr;
587         int     isc_log_level;
588         
589         if (msg_level >= ARRAY_SIZE(isc_log_map) || msg_level < 0) {
590                 isc_log_level = ISC_LOG_INFO;
591         } else {
592                 isc_log_level = isc_log_map[msg_level];
593         }
594         state->log(isc_log_level, "samba_dlz: %s", msg);
595 }
596
597 static int dlz_state_debug_unregister(struct dlz_bind9_data *state)
598 {
599         /* Stop logging (to the bind9 logs) */
600         debug_set_callback(NULL, NULL);
601         return 0;
602 }
603
604 /*
605   called to initialise the driver
606  */
607 _PUBLIC_ isc_result_t dlz_create(const char *dlzname,
608                                  unsigned int argc, const char **argv,
609                                  void **dbdata, ...)
610 {
611         struct dlz_bind9_data *state;
612         const char *helper_name;
613         va_list ap;
614         isc_result_t result;
615         struct ldb_dn *dn;
616         NTSTATUS nt_status;
617         int ret;
618         char *errstring = NULL;
619
620         if (dlz_bind9_state != NULL) {
621                 *dbdata = dlz_bind9_state;
622                 dlz_bind9_state_ref_count++;
623                 return ISC_R_SUCCESS;
624         }
625
626         state = talloc_zero(NULL, struct dlz_bind9_data);
627         if (state == NULL) {
628                 return ISC_R_NOMEMORY;
629         }
630
631         talloc_set_destructor(state, dlz_state_debug_unregister);
632
633         /* fill in the helper functions */
634         va_start(ap, dbdata);
635         while ((helper_name = va_arg(ap, const char *)) != NULL) {
636                 b9_add_helper(state, helper_name, va_arg(ap, void*));
637         }
638         va_end(ap);
639
640         /* Do not install samba signal handlers */
641         fault_setup_disable();
642
643         /* Start logging (to the bind9 logs) */
644         debug_set_callback(state, b9_debug);
645
646         state->ev_ctx = s4_event_context_init(state);
647         if (state->ev_ctx == NULL) {
648                 result = ISC_R_NOMEMORY;
649                 goto failed;
650         }
651
652         result = parse_options(state, argc, argv, &state->options);
653         if (result != ISC_R_SUCCESS) {
654                 goto failed;
655         }
656
657         state->lp = loadparm_init_global(true);
658         if (state->lp == NULL) {
659                 result = ISC_R_NOMEMORY;
660                 goto failed;
661         }
662
663         if (state->options.debug) {
664                 lpcfg_do_global_parameter(state->lp, "log level", state->options.debug);
665         } else {
666                 lpcfg_do_global_parameter(state->lp, "log level", "0");
667         }
668
669         if (smb_krb5_init_context(state, state->lp, &state->smb_krb5_ctx) != 0) {
670                 result = ISC_R_NOMEMORY;
671                 goto failed;
672         }
673
674         nt_status = gensec_init();
675         if (!NT_STATUS_IS_OK(nt_status)) {
676                 result = ISC_R_NOMEMORY;
677                 goto failed;
678         }
679
680         state->auth_context = talloc_zero(state, struct auth4_context);
681         if (state->auth_context == NULL) {
682                 result = ISC_R_NOMEMORY;
683                 goto failed;
684         }
685
686         if (state->options.url == NULL) {
687                 state->options.url = talloc_asprintf(state,
688                                                      "%s/dns/sam.ldb",
689                                                      lpcfg_binddns_dir(state->lp));
690                 if (state->options.url == NULL) {
691                         result = ISC_R_NOMEMORY;
692                         goto failed;
693                 }
694
695                 if (!file_exist(state->options.url)) {
696                         state->options.url = talloc_asprintf(state,
697                                                              "%s/dns/sam.ldb",
698                                                              lpcfg_private_dir(state->lp));
699                         if (state->options.url == NULL) {
700                                 result = ISC_R_NOMEMORY;
701                                 goto failed;
702                         }
703                 }
704         }
705
706         ret = samdb_connect_url(state,
707                                 state->ev_ctx,
708                                 state->lp,
709                                 system_session(state->lp),
710                                 0,
711                                 state->options.url,
712                                 NULL,
713                                 &state->samdb,
714                                 &errstring);
715         if (ret != LDB_SUCCESS) {
716                 state->log(ISC_LOG_ERROR,
717                            "samba_dlz: Failed to connect to %s: %s",
718                            errstring, ldb_strerror(ret));
719                 result = ISC_R_FAILURE;
720                 goto failed;
721         }
722
723         dn = ldb_get_default_basedn(state->samdb);
724         if (dn == NULL) {
725                 state->log(ISC_LOG_ERROR, "samba_dlz: Unable to get basedn for %s - %s",
726                            state->options.url, ldb_errstring(state->samdb));
727                 result = ISC_R_FAILURE;
728                 goto failed;
729         }
730
731         state->log(ISC_LOG_INFO, "samba_dlz: started for DN %s",
732                    ldb_dn_get_linearized(dn));
733
734         state->auth_context->event_ctx = state->ev_ctx;
735         state->auth_context->lp_ctx = state->lp;
736         state->auth_context->sam_ctx = state->samdb;
737         state->auth_context->generate_session_info_pac = b9_generate_session_info_pac;
738
739         *dbdata = state;
740         dlz_bind9_state = state;
741         dlz_bind9_state_ref_count++;
742
743         return ISC_R_SUCCESS;
744
745 failed:
746         talloc_free(state);
747         return result;
748 }
749
750 /*
751   shutdown the backend
752  */
753 _PUBLIC_ void dlz_destroy(void *dbdata)
754 {
755         struct dlz_bind9_data *state = talloc_get_type_abort(dbdata, struct dlz_bind9_data);
756         state->log(ISC_LOG_INFO, "samba_dlz: shutting down");
757
758         dlz_bind9_state_ref_count--;
759         if (dlz_bind9_state_ref_count == 0) {
760                 talloc_unlink(state, state->samdb);
761                 talloc_free(state);
762                 dlz_bind9_state = NULL;
763         }
764 }
765
766
767 /*
768   return the base DN for a zone
769  */
770 static isc_result_t b9_find_zone_dn(struct dlz_bind9_data *state, const char *zone_name,
771                                     TALLOC_CTX *mem_ctx, struct ldb_dn **zone_dn)
772 {
773         int ret;
774         TALLOC_CTX *tmp_ctx = talloc_new(state);
775         const char *attrs[] = { NULL };
776         int i;
777
778         for (i=0; zone_prefixes[i]; i++) {
779                 const char *casefold;
780                 struct ldb_dn *dn;
781                 struct ldb_result *res;
782                 struct ldb_val zone_name_val
783                         = data_blob_string_const(zone_name);
784
785                 dn = ldb_dn_copy(tmp_ctx, ldb_get_default_basedn(state->samdb));
786                 if (dn == NULL) {
787                         talloc_free(tmp_ctx);
788                         return ISC_R_NOMEMORY;
789                 }
790
791                 /*
792                  * This dance ensures that it is not possible to put
793                  * (eg) an extra DC=x, into the DNS name being
794                  * queried
795                  */
796
797                 if (!ldb_dn_add_child_fmt(dn,
798                                           "DC=X,%s",
799                                           zone_prefixes[i])) {
800                         talloc_free(tmp_ctx);
801                         return ISC_R_NOMEMORY;
802                 }
803
804                 ret = ldb_dn_set_component(dn,
805                                            0,
806                                            "DC",
807                                            zone_name_val);
808                 if (ret != LDB_SUCCESS) {
809                         talloc_free(tmp_ctx);
810                         return ISC_R_NOMEMORY;
811                 }
812
813                 /*
814                  * Check if this is a plausibly valid DN early
815                  * (time spent here will be saved during the
816                  * search due to an internal cache)
817                  */
818                 casefold = ldb_dn_get_casefold(dn);
819
820                 if (casefold == NULL) {
821                         talloc_free(tmp_ctx);
822                         return ISC_R_NOTFOUND;
823                 }
824
825                 ret = ldb_search(state->samdb, tmp_ctx, &res, dn, LDB_SCOPE_BASE, attrs, "objectClass=dnsZone");
826                 if (ret == LDB_SUCCESS) {
827                         if (zone_dn != NULL) {
828                                 *zone_dn = talloc_steal(mem_ctx, dn);
829                         }
830                         talloc_free(tmp_ctx);
831                         return ISC_R_SUCCESS;
832                 }
833                 talloc_free(dn);
834         }
835
836         talloc_free(tmp_ctx);
837         return ISC_R_NOTFOUND;
838 }
839
840
841 /*
842   return the DN for a name. The record does not need to exist, but the
843   zone must exist
844  */
845 static isc_result_t b9_find_name_dn(struct dlz_bind9_data *state, const char *name,
846                                     TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
847 {
848         const char *p;
849
850         /* work through the name piece by piece, until we find a zone */
851         for (p=name; p; ) {
852                 isc_result_t result;
853                 result = b9_find_zone_dn(state, p, mem_ctx, dn);
854                 if (result == ISC_R_SUCCESS) {
855                         const char *casefold;
856
857                         /* we found a zone, now extend the DN to get
858                          * the full DN
859                          */
860                         bool ret;
861                         if (p == name) {
862                                 ret = ldb_dn_add_child_fmt(*dn, "DC=@");
863                                 if (ret == false) {
864                                         talloc_free(*dn);
865                                         return ISC_R_NOMEMORY;
866                                 }
867                         } else {
868                                 struct ldb_val name_val
869                                         = data_blob_const(name,
870                                                           (int)(p-name)-1);
871
872                                 if (!ldb_dn_add_child_val(*dn,
873                                                           "DC",
874                                                           name_val)) {
875                                         talloc_free(*dn);
876                                         return ISC_R_NOMEMORY;
877                                 }
878                         }
879
880                         /*
881                          * Check if this is a plausibly valid DN early
882                          * (time spent here will be saved during the
883                          * search due to an internal cache)
884                          */
885                         casefold = ldb_dn_get_casefold(*dn);
886
887                         if (casefold == NULL) {
888                                 return ISC_R_NOTFOUND;
889                         }
890
891                         return ISC_R_SUCCESS;
892                 }
893                 p = strchr(p, '.');
894                 if (p == NULL) {
895                         break;
896                 }
897                 p++;
898         }
899         return ISC_R_NOTFOUND;
900 }
901
902
903 /*
904   see if we handle a given zone
905  */
906 #if DLZ_DLOPEN_VERSION < 3
907 _PUBLIC_ isc_result_t dlz_findzonedb(void *dbdata, const char *name)
908 #else
909 _PUBLIC_ isc_result_t dlz_findzonedb(void *dbdata, const char *name,
910                                      dns_clientinfomethods_t *methods,
911                                      dns_clientinfo_t *clientinfo)
912 #endif
913 {
914         struct dlz_bind9_data *state = talloc_get_type_abort(dbdata, struct dlz_bind9_data);
915         return b9_find_zone_dn(state, name, NULL, NULL);
916 }
917
918
919 /*
920   lookup one record
921  */
922 static isc_result_t dlz_lookup_types(struct dlz_bind9_data *state,
923                                      const char *zone, const char *name,
924                                      dns_sdlzlookup_t *lookup,
925                                      const char **types)
926 {
927         TALLOC_CTX *tmp_ctx = talloc_new(state);
928         struct ldb_dn *dn;
929         WERROR werr = WERR_DNS_ERROR_NAME_DOES_NOT_EXIST;
930         struct dnsp_DnssrvRpcRecord *records = NULL;
931         uint16_t num_records = 0, i;
932         struct ldb_val zone_name_val
933                 = data_blob_string_const(zone);
934         struct ldb_val name_val
935                 = data_blob_string_const(name);
936
937         for (i=0; zone_prefixes[i]; i++) {
938                 int ret;
939                 const char *casefold;
940                 dn = ldb_dn_copy(tmp_ctx, ldb_get_default_basedn(state->samdb));
941                 if (dn == NULL) {
942                         talloc_free(tmp_ctx);
943                         return ISC_R_NOMEMORY;
944                 }
945
946                 /*
947                  * This dance ensures that it is not possible to put
948                  * (eg) an extra DC=x, into the DNS name being
949                  * queried
950                  */
951
952                 if (!ldb_dn_add_child_fmt(dn,
953                                           "DC=X,DC=X,%s",
954                                           zone_prefixes[i])) {
955                         talloc_free(tmp_ctx);
956                         return ISC_R_NOMEMORY;
957                 }
958
959                 ret = ldb_dn_set_component(dn,
960                                            1,
961                                            "DC",
962                                            zone_name_val);
963                 if (ret != LDB_SUCCESS) {
964                         talloc_free(tmp_ctx);
965                         return ISC_R_NOMEMORY;
966                 }
967
968                 ret = ldb_dn_set_component(dn,
969                                            0,
970                                            "DC",
971                                            name_val);
972                 if (ret != LDB_SUCCESS) {
973                         talloc_free(tmp_ctx);
974                         return ISC_R_NOMEMORY;
975                 }
976
977                 /*
978                  * Check if this is a plausibly valid DN early
979                  * (time spent here will be saved during the
980                  * search due to an internal cache)
981                  */
982                 casefold = ldb_dn_get_casefold(dn);
983
984                 if (casefold == NULL) {
985                         talloc_free(tmp_ctx);
986                         return ISC_R_NOTFOUND;
987                 }
988
989                 werr = dns_common_wildcard_lookup(state->samdb, tmp_ctx, dn,
990                                          &records, &num_records);
991                 if (W_ERROR_IS_OK(werr)) {
992                         break;
993                 }
994         }
995         if (!W_ERROR_IS_OK(werr)) {
996                 talloc_free(tmp_ctx);
997                 return ISC_R_NOTFOUND;
998         }
999
1000         for (i=0; i < num_records; i++) {
1001                 isc_result_t result;
1002
1003                 result = b9_putrr(state, lookup, &records[i], types);
1004                 if (result != ISC_R_SUCCESS) {
1005                         talloc_free(tmp_ctx);
1006                         return result;
1007                 }
1008         }
1009
1010         talloc_free(tmp_ctx);
1011         return ISC_R_SUCCESS;
1012 }
1013
1014 /*
1015   lookup one record
1016  */
1017 #if DLZ_DLOPEN_VERSION == 1
1018 _PUBLIC_ isc_result_t dlz_lookup(const char *zone, const char *name,
1019                                  void *dbdata, dns_sdlzlookup_t *lookup)
1020 #else
1021 _PUBLIC_ isc_result_t dlz_lookup(const char *zone, const char *name,
1022                                  void *dbdata, dns_sdlzlookup_t *lookup,
1023                                  dns_clientinfomethods_t *methods,
1024                                  dns_clientinfo_t *clientinfo)
1025 #endif
1026 {
1027         struct dlz_bind9_data *state = talloc_get_type_abort(dbdata, struct dlz_bind9_data);
1028         return dlz_lookup_types(state, zone, name, lookup, NULL);
1029 }
1030
1031
1032 /*
1033   see if a zone transfer is allowed
1034  */
1035 _PUBLIC_ isc_result_t dlz_allowzonexfr(void *dbdata, const char *name, const char *client)
1036 {
1037         /* just say yes for all our zones for now */
1038         struct dlz_bind9_data *state = talloc_get_type(
1039                 dbdata, struct dlz_bind9_data);
1040         return b9_find_zone_dn(state, name, NULL, NULL);
1041 }
1042
1043 /*
1044   perform a zone transfer
1045  */
1046 _PUBLIC_ isc_result_t dlz_allnodes(const char *zone, void *dbdata,
1047                                    dns_sdlzallnodes_t *allnodes)
1048 {
1049         struct dlz_bind9_data *state = talloc_get_type_abort(dbdata, struct dlz_bind9_data);
1050         const char *attrs[] = { "dnsRecord", NULL };
1051         int ret = LDB_SUCCESS, i, j;
1052         struct ldb_dn *dn;
1053         struct ldb_result *res;
1054         TALLOC_CTX *tmp_ctx = talloc_new(state);
1055         struct ldb_val zone_name_val = data_blob_string_const(zone);
1056
1057         for (i=0; zone_prefixes[i]; i++) {
1058                 const char *casefold;
1059
1060                 dn = ldb_dn_copy(tmp_ctx, ldb_get_default_basedn(state->samdb));
1061                 if (dn == NULL) {
1062                         talloc_free(tmp_ctx);
1063                         return ISC_R_NOMEMORY;
1064                 }
1065
1066                 /*
1067                  * This dance ensures that it is not possible to put
1068                  * (eg) an extra DC=x, into the DNS name being
1069                  * queried
1070                  */
1071
1072                 if (!ldb_dn_add_child_fmt(dn,
1073                                           "DC=X,%s",
1074                                           zone_prefixes[i])) {
1075                         talloc_free(tmp_ctx);
1076                         return ISC_R_NOMEMORY;
1077                 }
1078
1079                 ret = ldb_dn_set_component(dn,
1080                                            0,
1081                                            "DC",
1082                                            zone_name_val);
1083                 if (ret != LDB_SUCCESS) {
1084                         talloc_free(tmp_ctx);
1085                         return ISC_R_NOMEMORY;
1086                 }
1087
1088                 /*
1089                  * Check if this is a plausibly valid DN early
1090                  * (time spent here will be saved during the
1091                  * search due to an internal cache)
1092                  */
1093                 casefold = ldb_dn_get_casefold(dn);
1094
1095                 if (casefold == NULL) {
1096                         return ISC_R_NOTFOUND;
1097                 }
1098
1099                 ret = ldb_search(state->samdb, tmp_ctx, &res, dn, LDB_SCOPE_SUBTREE,
1100                                  attrs, "objectClass=dnsNode");
1101                 if (ret == LDB_SUCCESS) {
1102                         break;
1103                 }
1104         }
1105         if (ret != LDB_SUCCESS) {
1106                 talloc_free(tmp_ctx);
1107                 return ISC_R_NOTFOUND;
1108         }
1109
1110         for (i=0; i<res->count; i++) {
1111                 struct ldb_message_element *el;
1112                 TALLOC_CTX *el_ctx = talloc_new(tmp_ctx);
1113                 const char *rdn, *name;
1114                 const struct ldb_val *v;
1115                 WERROR werr;
1116                 struct dnsp_DnssrvRpcRecord *recs = NULL;
1117                 uint16_t num_recs = 0;
1118
1119                 el = ldb_msg_find_element(res->msgs[i], "dnsRecord");
1120                 if (el == NULL || el->num_values == 0) {
1121                         state->log(ISC_LOG_INFO, "failed to find dnsRecord for %s",
1122                                    ldb_dn_get_linearized(dn));
1123                         talloc_free(el_ctx);
1124                         continue;
1125                 }
1126
1127                 v = ldb_dn_get_rdn_val(res->msgs[i]->dn);
1128                 if (v == NULL) {
1129                         state->log(ISC_LOG_INFO, "failed to find RDN for %s",
1130                                    ldb_dn_get_linearized(dn));
1131                         talloc_free(el_ctx);
1132                         continue;
1133                 }
1134
1135                 rdn = talloc_strndup(el_ctx, (char *)v->data, v->length);
1136                 if (rdn == NULL) {
1137                         talloc_free(tmp_ctx);
1138                         return ISC_R_NOMEMORY;
1139                 }
1140
1141                 if (strcmp(rdn, "@") == 0) {
1142                         name = zone;
1143                 } else {
1144                         name = talloc_asprintf(el_ctx, "%s.%s", rdn, zone);
1145                 }
1146                 name = b9_format_fqdn(el_ctx, name);
1147                 if (name == NULL) {
1148                         talloc_free(tmp_ctx);
1149                         return ISC_R_NOMEMORY;
1150                 }
1151
1152                 werr = dns_common_extract(state->samdb, el, el_ctx, &recs, &num_recs);
1153                 if (!W_ERROR_IS_OK(werr)) {
1154                         state->log(ISC_LOG_ERROR, "samba_dlz: failed to parse dnsRecord for %s, %s",
1155                                    ldb_dn_get_linearized(dn), win_errstr(werr));
1156                         talloc_free(el_ctx);
1157                         continue;
1158                 }
1159
1160                 for (j=0; j < num_recs; j++) {
1161                         isc_result_t result;
1162
1163                         result = b9_putnamedrr(state, allnodes, name, &recs[j]);
1164                         if (result != ISC_R_SUCCESS) {
1165                                 continue;
1166                         }
1167                 }
1168
1169                 talloc_free(el_ctx);
1170         }
1171
1172         talloc_free(tmp_ctx);
1173
1174         return ISC_R_SUCCESS;
1175 }
1176
1177
1178 /*
1179   start a transaction
1180  */
1181 _PUBLIC_ isc_result_t dlz_newversion(const char *zone, void *dbdata, void **versionp)
1182 {
1183         struct dlz_bind9_data *state = talloc_get_type_abort(dbdata, struct dlz_bind9_data);
1184
1185         state->log(ISC_LOG_INFO, "samba_dlz: starting transaction on zone %s", zone);
1186
1187         if (state->transaction_token != NULL) {
1188                 state->log(ISC_LOG_INFO, "samba_dlz: transaction already started for zone %s", zone);
1189                 return ISC_R_FAILURE;
1190         }
1191
1192         state->transaction_token = talloc_zero(state, int);
1193         if (state->transaction_token == NULL) {
1194                 return ISC_R_NOMEMORY;
1195         }
1196
1197         if (ldb_transaction_start(state->samdb) != LDB_SUCCESS) {
1198                 state->log(ISC_LOG_INFO, "samba_dlz: failed to start a transaction for zone %s", zone);
1199                 talloc_free(state->transaction_token);
1200                 state->transaction_token = NULL;
1201                 return ISC_R_FAILURE;
1202         }
1203
1204         *versionp = (void *)state->transaction_token;
1205
1206         return ISC_R_SUCCESS;
1207 }
1208
1209 /*
1210   end a transaction
1211  */
1212 _PUBLIC_ void dlz_closeversion(const char *zone, isc_boolean_t commit,
1213                                void *dbdata, void **versionp)
1214 {
1215         struct dlz_bind9_data *state = talloc_get_type_abort(dbdata, struct dlz_bind9_data);
1216
1217         if (state->transaction_token != (int *)*versionp) {
1218                 state->log(ISC_LOG_INFO, "samba_dlz: transaction not started for zone %s", zone);
1219                 return;
1220         }
1221
1222         if (commit) {
1223                 if (ldb_transaction_commit(state->samdb) != LDB_SUCCESS) {
1224                         state->log(ISC_LOG_INFO, "samba_dlz: failed to commit a transaction for zone %s", zone);
1225                         return;
1226                 }
1227                 state->log(ISC_LOG_INFO, "samba_dlz: committed transaction on zone %s", zone);
1228         } else {
1229                 if (ldb_transaction_cancel(state->samdb) != LDB_SUCCESS) {
1230                         state->log(ISC_LOG_INFO, "samba_dlz: failed to cancel a transaction for zone %s", zone);
1231                         return;
1232                 }
1233                 state->log(ISC_LOG_INFO, "samba_dlz: cancelling transaction on zone %s", zone);
1234         }
1235
1236         talloc_free(state->transaction_token);
1237         state->transaction_token = NULL;
1238         *versionp = NULL;
1239 }
1240
1241
1242 /*
1243   see if there is a SOA record for a zone
1244  */
1245 static bool b9_has_soa(struct dlz_bind9_data *state, struct ldb_dn *dn, const char *zone)
1246 {
1247         TALLOC_CTX *tmp_ctx = talloc_new(state);
1248         WERROR werr;
1249         struct dnsp_DnssrvRpcRecord *records = NULL;
1250         uint16_t num_records = 0, i;
1251         struct ldb_val zone_name_val
1252                 = data_blob_string_const(zone);
1253
1254         /*
1255          * This dance ensures that it is not possible to put
1256          * (eg) an extra DC=x, into the DNS name being
1257          * queried
1258          */
1259
1260         if (!ldb_dn_add_child_val(dn,
1261                                   "DC",
1262                                   zone_name_val)) {
1263                 talloc_free(tmp_ctx);
1264                 return false;
1265         }
1266
1267         werr = dns_common_lookup(state->samdb, tmp_ctx, dn,
1268                                  &records, &num_records, NULL);
1269         if (!W_ERROR_IS_OK(werr)) {
1270                 talloc_free(tmp_ctx);
1271                 return false;
1272         }
1273
1274         for (i=0; i < num_records; i++) {
1275                 if (records[i].wType == DNS_TYPE_SOA) {
1276                         talloc_free(tmp_ctx);
1277                         return true;
1278                 }
1279         }
1280
1281         talloc_free(tmp_ctx);
1282         return false;
1283 }
1284
1285 static bool b9_zone_add(struct dlz_bind9_data *state, const char *name)
1286 {
1287         struct b9_zone *zone;
1288
1289         zone = talloc_zero(state, struct b9_zone);
1290         if (zone == NULL) {
1291                 return false;
1292         }
1293
1294         zone->name = talloc_strdup(zone, name);
1295         if (zone->name == NULL) {
1296                 talloc_free(zone);
1297                 return false;
1298         }
1299
1300         DLIST_ADD(state->zonelist, zone);
1301         return true;
1302 }
1303
1304 static bool b9_zone_exists(struct dlz_bind9_data *state, const char *name)
1305 {
1306         struct b9_zone *zone = state->zonelist;
1307         bool found = false;
1308
1309         while (zone != NULL) {
1310                 if (strcasecmp(name, zone->name) == 0) {
1311                         found = true;
1312                         break;
1313                 }
1314                 zone = zone->next;
1315         }
1316
1317         return found;
1318 }
1319
1320
1321 /*
1322   configure a writeable zone
1323  */
1324 #if DLZ_DLOPEN_VERSION < 3
1325 _PUBLIC_ isc_result_t dlz_configure(dns_view_t *view, void *dbdata)
1326 #else
1327 _PUBLIC_ isc_result_t dlz_configure(dns_view_t *view, dns_dlzdb_t *dlzdb,
1328                                     void *dbdata)
1329 #endif
1330 {
1331         struct dlz_bind9_data *state = talloc_get_type_abort(dbdata, struct dlz_bind9_data);
1332         TALLOC_CTX *tmp_ctx;
1333         struct ldb_dn *dn;
1334         int i;
1335
1336         state->log(ISC_LOG_INFO, "samba_dlz: starting configure");
1337         if (state->writeable_zone == NULL) {
1338                 state->log(ISC_LOG_INFO, "samba_dlz: no writeable_zone method available");
1339                 return ISC_R_FAILURE;
1340         }
1341
1342         tmp_ctx = talloc_new(state);
1343
1344         for (i=0; zone_prefixes[i]; i++) {
1345                 const char *attrs[] = { "name", NULL };
1346                 int j, ret;
1347                 struct ldb_result *res;
1348
1349                 dn = ldb_dn_copy(tmp_ctx, ldb_get_default_basedn(state->samdb));
1350                 if (dn == NULL) {
1351                         talloc_free(tmp_ctx);
1352                         return ISC_R_NOMEMORY;
1353                 }
1354
1355                 if (!ldb_dn_add_child_fmt(dn, "%s", zone_prefixes[i])) {
1356                         talloc_free(tmp_ctx);
1357                         return ISC_R_NOMEMORY;
1358                 }
1359
1360                 ret = ldb_search(state->samdb, tmp_ctx, &res, dn, LDB_SCOPE_SUBTREE,
1361                                  attrs, "objectClass=dnsZone");
1362                 if (ret != LDB_SUCCESS) {
1363                         continue;
1364                 }
1365
1366                 for (j=0; j<res->count; j++) {
1367                         isc_result_t result;
1368                         const char *zone = ldb_msg_find_attr_as_string(res->msgs[j], "name", NULL);
1369                         struct ldb_dn *zone_dn;
1370
1371                         if (zone == NULL) {
1372                                 continue;
1373                         }
1374                         /* Ignore zones that are not handled in BIND */
1375                         if ((strcmp(zone, "RootDNSServers") == 0) ||
1376                             (strcmp(zone, "..TrustAnchors") == 0)) {
1377                                 continue;
1378                         }
1379                         zone_dn = ldb_dn_copy(tmp_ctx, dn);
1380                         if (zone_dn == NULL) {
1381                                 talloc_free(tmp_ctx);
1382                                 return ISC_R_NOMEMORY;
1383                         }
1384
1385                         if (!b9_has_soa(state, zone_dn, zone)) {
1386                                 continue;
1387                         }
1388
1389                         if (b9_zone_exists(state, zone)) {
1390                                 state->log(ISC_LOG_WARNING, "samba_dlz: Ignoring duplicate zone '%s' from '%s'",
1391                                            zone, ldb_dn_get_linearized(zone_dn));
1392                                 continue;
1393                         }
1394
1395                         if (!b9_zone_add(state, zone)) {
1396                                 talloc_free(tmp_ctx);
1397                                 return ISC_R_NOMEMORY;
1398                         }
1399
1400 #if DLZ_DLOPEN_VERSION < 3
1401                         result = state->writeable_zone(view, zone);
1402 #else
1403                         result = state->writeable_zone(view, dlzdb, zone);
1404 #endif
1405                         if (result != ISC_R_SUCCESS) {
1406                                 state->log(ISC_LOG_ERROR, "samba_dlz: Failed to configure zone '%s'",
1407                                            zone);
1408                                 talloc_free(tmp_ctx);
1409                                 return result;
1410                         }
1411                         state->log(ISC_LOG_INFO, "samba_dlz: configured writeable zone '%s'", zone);
1412                 }
1413         }
1414
1415         talloc_free(tmp_ctx);
1416         return ISC_R_SUCCESS;
1417 }
1418
1419 /*
1420   authorize a zone update
1421  */
1422 _PUBLIC_ isc_boolean_t dlz_ssumatch(const char *signer, const char *name, const char *tcpaddr,
1423                                     const char *type, const char *key, uint32_t keydatalen, uint8_t *keydata,
1424                                     void *dbdata)
1425 {
1426         struct dlz_bind9_data *state = talloc_get_type_abort(dbdata, struct dlz_bind9_data);
1427         TALLOC_CTX *tmp_ctx;
1428         DATA_BLOB ap_req;
1429         struct cli_credentials *server_credentials;
1430         char *keytab_name;
1431         char *keytab_file = NULL;
1432         int ret;
1433         int ldb_ret;
1434         NTSTATUS nt_status;
1435         struct gensec_security *gensec_ctx;
1436         struct auth_session_info *session_info;
1437         struct ldb_dn *dn;
1438         isc_result_t result;
1439         struct ldb_result *res;
1440         const char * attrs[] = { NULL };
1441         uint32_t access_mask;
1442         struct gensec_settings *settings = NULL;
1443         const struct gensec_security_ops **backends = NULL;
1444         size_t idx = 0;
1445
1446         /* Remove cached credentials, if any */
1447         if (state->session_info) {
1448                 talloc_free(state->session_info);
1449                 state->session_info = NULL;
1450         }
1451         if (state->update_name) {
1452                 talloc_free(state->update_name);
1453                 state->update_name = NULL;
1454         }
1455
1456         tmp_ctx = talloc_new(NULL);
1457         if (tmp_ctx == NULL) {
1458                 state->log(ISC_LOG_ERROR, "samba_dlz: no memory");
1459                 return ISC_FALSE;
1460         }
1461
1462         ap_req = data_blob_const(keydata, keydatalen);
1463         server_credentials = cli_credentials_init(tmp_ctx);
1464         if (!server_credentials) {
1465                 state->log(ISC_LOG_ERROR, "samba_dlz: failed to init server credentials");
1466                 talloc_free(tmp_ctx);
1467                 return ISC_FALSE;
1468         }
1469
1470         cli_credentials_set_krb5_context(server_credentials, state->smb_krb5_ctx);
1471         cli_credentials_set_conf(server_credentials, state->lp);
1472
1473         keytab_file = talloc_asprintf(tmp_ctx,
1474                                       "%s/dns.keytab",
1475                                       lpcfg_binddns_dir(state->lp));
1476         if (keytab_file == NULL) {
1477                 state->log(ISC_LOG_ERROR, "samba_dlz: Out of memory!");
1478                 talloc_free(tmp_ctx);
1479                 return ISC_FALSE;
1480         }
1481
1482         if (!file_exist(keytab_file)) {
1483                 keytab_file = talloc_asprintf(tmp_ctx,
1484                                               "%s/dns.keytab",
1485                                               lpcfg_private_dir(state->lp));
1486                 if (keytab_file == NULL) {
1487                         state->log(ISC_LOG_ERROR, "samba_dlz: Out of memory!");
1488                         talloc_free(tmp_ctx);
1489                         return ISC_FALSE;
1490                 }
1491         }
1492
1493         keytab_name = talloc_asprintf(tmp_ctx, "FILE:%s", keytab_file);
1494         if (keytab_name == NULL) {
1495                 state->log(ISC_LOG_ERROR, "samba_dlz: Out of memory!");
1496                 talloc_free(tmp_ctx);
1497                 return ISC_FALSE;
1498         }
1499
1500         ret = cli_credentials_set_keytab_name(server_credentials, state->lp, keytab_name,
1501                                                 CRED_SPECIFIED);
1502         if (ret != 0) {
1503                 state->log(ISC_LOG_ERROR, "samba_dlz: failed to obtain server credentials from %s",
1504                            keytab_name);
1505                 talloc_free(tmp_ctx);
1506                 return ISC_FALSE;
1507         }
1508         talloc_free(keytab_name);
1509
1510         settings = lpcfg_gensec_settings(tmp_ctx, state->lp);
1511         if (settings == NULL) {
1512                 state->log(ISC_LOG_ERROR, "samba_dlz: lpcfg_gensec_settings failed");
1513                 talloc_free(tmp_ctx);
1514                 return ISC_FALSE;
1515         }
1516         backends = talloc_zero_array(settings,
1517                                      const struct gensec_security_ops *, 3);
1518         if (backends == NULL) {
1519                 state->log(ISC_LOG_ERROR, "samba_dlz: talloc_zero_array gensec_security_ops failed");
1520                 talloc_free(tmp_ctx);
1521                 return ISC_FALSE;
1522         }
1523         settings->backends = backends;
1524
1525         gensec_init();
1526
1527         backends[idx++] = gensec_security_by_oid(NULL, GENSEC_OID_KERBEROS5);
1528         backends[idx++] = gensec_security_by_oid(NULL, GENSEC_OID_SPNEGO);
1529
1530         nt_status = gensec_server_start(tmp_ctx, settings,
1531                                         state->auth_context, &gensec_ctx);
1532         if (!NT_STATUS_IS_OK(nt_status)) {
1533                 state->log(ISC_LOG_ERROR, "samba_dlz: failed to start gensec server");
1534                 talloc_free(tmp_ctx);
1535                 return ISC_FALSE;
1536         }
1537
1538         gensec_set_credentials(gensec_ctx, server_credentials);
1539
1540         nt_status = gensec_start_mech_by_oid(gensec_ctx, GENSEC_OID_SPNEGO);
1541         if (!NT_STATUS_IS_OK(nt_status)) {
1542                 state->log(ISC_LOG_ERROR, "samba_dlz: failed to start spnego");
1543                 talloc_free(tmp_ctx);
1544                 return ISC_FALSE;
1545         }
1546
1547         /*
1548          * We only allow SPNEGO/KRB5 and make sure the backend
1549          * to is RPC/IPC free.
1550          *
1551          * See gensec_gssapi_update_internal() as
1552          * GENSEC_SERVER.
1553          *
1554          * It allows gensec_update() not to block.
1555          *
1556          * If that changes in future we need to use
1557          * gensec_update_send/recv here!
1558          */
1559         nt_status = gensec_update(gensec_ctx, tmp_ctx, ap_req, &ap_req);
1560         if (!NT_STATUS_IS_OK(nt_status)) {
1561                 state->log(ISC_LOG_ERROR, "samba_dlz: spnego update failed");
1562                 talloc_free(tmp_ctx);
1563                 return ISC_FALSE;
1564         }
1565
1566         nt_status = gensec_session_info(gensec_ctx, tmp_ctx, &session_info);
1567         if (!NT_STATUS_IS_OK(nt_status)) {
1568                 state->log(ISC_LOG_ERROR, "samba_dlz: failed to create session info");
1569                 talloc_free(tmp_ctx);
1570                 return ISC_FALSE;
1571         }
1572
1573         /* Get the DN from name */
1574         result = b9_find_name_dn(state, name, tmp_ctx, &dn);
1575         if (result != ISC_R_SUCCESS) {
1576                 state->log(ISC_LOG_ERROR, "samba_dlz: failed to find name %s", name);
1577                 talloc_free(tmp_ctx);
1578                 return ISC_FALSE;
1579         }
1580
1581         /* make sure the dn exists, or find parent dn in case new object is being added */
1582         ldb_ret = ldb_search(state->samdb, tmp_ctx, &res, dn, LDB_SCOPE_BASE,
1583                                 attrs, "objectClass=dnsNode");
1584         if (ldb_ret == LDB_ERR_NO_SUCH_OBJECT) {
1585                 ldb_dn_remove_child_components(dn, 1);
1586                 access_mask = SEC_ADS_CREATE_CHILD;
1587                 talloc_free(res);
1588         } else if (ldb_ret == LDB_SUCCESS) {
1589                 access_mask = SEC_STD_REQUIRED | SEC_ADS_SELF_WRITE;
1590                 talloc_free(res);
1591         } else {
1592                 talloc_free(tmp_ctx);
1593                 return ISC_FALSE;
1594         }
1595
1596         /* Do ACL check */
1597         ldb_ret = dsdb_check_access_on_dn(state->samdb, tmp_ctx, dn,
1598                                                 session_info->security_token,
1599                                                 access_mask, NULL);
1600         if (ldb_ret != LDB_SUCCESS) {
1601                 state->log(ISC_LOG_INFO,
1602                         "samba_dlz: disallowing update of signer=%s name=%s type=%s error=%s",
1603                         signer, name, type, ldb_strerror(ldb_ret));
1604                 talloc_free(tmp_ctx);
1605                 return ISC_FALSE;
1606         }
1607
1608         /* Cache session_info, so it can be used in the actual add/delete operation */
1609         state->update_name = talloc_strdup(state, name);
1610         if (state->update_name == NULL) {
1611                 state->log(ISC_LOG_ERROR, "samba_dlz: memory allocation error");
1612                 talloc_free(tmp_ctx);
1613                 return ISC_FALSE;
1614         }
1615         state->session_info = talloc_steal(state, session_info);
1616
1617         state->log(ISC_LOG_INFO, "samba_dlz: allowing update of signer=%s name=%s tcpaddr=%s type=%s key=%s",
1618                    signer, name, tcpaddr, type, key);
1619
1620         talloc_free(tmp_ctx);
1621         return ISC_TRUE;
1622 }
1623
1624 /*
1625   see if two dns records match
1626  */
1627 static bool b9_record_match(struct dlz_bind9_data *state,
1628                             struct dnsp_DnssrvRpcRecord *rec1, struct dnsp_DnssrvRpcRecord *rec2)
1629 {
1630         bool status;
1631         int i;
1632         struct in6_addr rec1_in_addr6;
1633         struct in6_addr rec2_in_addr6;
1634
1635         if (rec1->wType != rec2->wType) {
1636                 return false;
1637         }
1638         /* see if this type is single valued */
1639         if (b9_single_valued(rec1->wType)) {
1640                 return true;
1641         }
1642
1643         /* see if the data matches */
1644         switch (rec1->wType) {
1645         case DNS_TYPE_A:
1646                 return strcmp(rec1->data.ipv4, rec2->data.ipv4) == 0;
1647         case DNS_TYPE_AAAA: {
1648                 int ret;
1649
1650                 ret = inet_pton(AF_INET6, rec1->data.ipv6, &rec1_in_addr6);
1651                 if (ret != 1) {
1652                         return false;
1653                 }
1654                 ret = inet_pton(AF_INET6, rec2->data.ipv6, &rec2_in_addr6);
1655                 if (ret != 1) {
1656                         return false;
1657                 }
1658
1659                 return memcmp(&rec1_in_addr6, &rec2_in_addr6, sizeof(rec1_in_addr6)) == 0;
1660         }
1661         case DNS_TYPE_CNAME:
1662                 return dns_name_equal(rec1->data.cname, rec2->data.cname);
1663         case DNS_TYPE_TXT:
1664                 status = (rec1->data.txt.count == rec2->data.txt.count);
1665                 if (!status) return status;
1666                 for (i=0; i<rec1->data.txt.count; i++) {
1667                         status &= (strcmp(rec1->data.txt.str[i], rec2->data.txt.str[i]) == 0);
1668                 }
1669                 return status;
1670         case DNS_TYPE_PTR:
1671                 return dns_name_equal(rec1->data.ptr, rec2->data.ptr);
1672         case DNS_TYPE_NS:
1673                 return dns_name_equal(rec1->data.ns, rec2->data.ns);
1674
1675         case DNS_TYPE_SRV:
1676                 return rec1->data.srv.wPriority == rec2->data.srv.wPriority &&
1677                         rec1->data.srv.wWeight  == rec2->data.srv.wWeight &&
1678                         rec1->data.srv.wPort    == rec2->data.srv.wPort &&
1679                         dns_name_equal(rec1->data.srv.nameTarget, rec2->data.srv.nameTarget);
1680
1681         case DNS_TYPE_MX:
1682                 return rec1->data.mx.wPriority == rec2->data.mx.wPriority &&
1683                         dns_name_equal(rec1->data.mx.nameTarget, rec2->data.mx.nameTarget);
1684
1685         case DNS_TYPE_HINFO:
1686                 return strcmp(rec1->data.hinfo.cpu, rec2->data.hinfo.cpu) == 0 &&
1687                         strcmp(rec1->data.hinfo.os, rec2->data.hinfo.os) == 0;
1688
1689         case DNS_TYPE_SOA:
1690                 return dns_name_equal(rec1->data.soa.mname, rec2->data.soa.mname) &&
1691                         dns_name_equal(rec1->data.soa.rname, rec2->data.soa.rname) &&
1692                         rec1->data.soa.serial == rec2->data.soa.serial &&
1693                         rec1->data.soa.refresh == rec2->data.soa.refresh &&
1694                         rec1->data.soa.retry == rec2->data.soa.retry &&
1695                         rec1->data.soa.expire == rec2->data.soa.expire &&
1696                         rec1->data.soa.minimum == rec2->data.soa.minimum;
1697         default:
1698                 state->log(ISC_LOG_ERROR, "samba_dlz b9_record_match: unhandled record type %u",
1699                            rec1->wType);
1700                 break;
1701         }
1702
1703         return false;
1704 }
1705
1706 /*
1707  * Update session_info on samdb using the cached credentials
1708  */
1709 static bool b9_set_session_info(struct dlz_bind9_data *state, const char *name)
1710 {
1711         int ret;
1712
1713         if (state->update_name == NULL || state->session_info == NULL) {
1714                 state->log(ISC_LOG_ERROR, "samba_dlz: invalid credentials");
1715                 return false;
1716         }
1717
1718         /* Do not use client credentials, if we're not updating the client specified name */
1719         if (strcmp(state->update_name, name) != 0) {
1720                 return true;
1721         }
1722
1723         ret = ldb_set_opaque(
1724                 state->samdb,
1725                 DSDB_SESSION_INFO,
1726                 state->session_info);
1727         if (ret != LDB_SUCCESS) {
1728                 state->log(ISC_LOG_ERROR, "samba_dlz: unable to set session info");
1729                 return false;
1730         }
1731
1732         return true;
1733 }
1734
1735 /*
1736  * Reset session_info on samdb as system session
1737  */
1738 static void b9_reset_session_info(struct dlz_bind9_data *state)
1739 {
1740         ldb_set_opaque(
1741                 state->samdb,
1742                 DSDB_SESSION_INFO,
1743                 system_session(state->lp));
1744 }
1745
1746 /*
1747   add or modify a rdataset
1748  */
1749 _PUBLIC_ isc_result_t dlz_addrdataset(const char *name, const char *rdatastr, void *dbdata, void *version)
1750 {
1751         struct dlz_bind9_data *state = talloc_get_type_abort(dbdata, struct dlz_bind9_data);
1752         struct dnsp_DnssrvRpcRecord *rec;
1753         struct ldb_dn *dn;
1754         isc_result_t result;
1755         bool tombstoned = false;
1756         bool needs_add = false;
1757         struct dnsp_DnssrvRpcRecord *recs = NULL;
1758         uint16_t num_recs = 0;
1759         uint16_t first = 0;
1760         uint16_t i;
1761         NTTIME t;
1762         WERROR werr;
1763
1764         if (state->transaction_token != (void*)version) {
1765                 state->log(ISC_LOG_INFO, "samba_dlz: bad transaction version");
1766                 return ISC_R_FAILURE;
1767         }
1768
1769         rec = talloc_zero(state, struct dnsp_DnssrvRpcRecord);
1770         if (rec == NULL) {
1771                 return ISC_R_NOMEMORY;
1772         }
1773
1774         rec->rank        = DNS_RANK_ZONE;
1775
1776         if (!b9_parse(state, rdatastr, rec)) {
1777                 state->log(ISC_LOG_INFO, "samba_dlz: failed to parse rdataset '%s'", rdatastr);
1778                 talloc_free(rec);
1779                 return ISC_R_FAILURE;
1780         }
1781
1782         /* find the DN of the record */
1783         result = b9_find_name_dn(state, name, rec, &dn);
1784         if (result != ISC_R_SUCCESS) {
1785                 talloc_free(rec);
1786                 return result;
1787         }
1788
1789         /* get any existing records */
1790         werr = dns_common_lookup(state->samdb, rec, dn,
1791                                  &recs, &num_recs, &tombstoned);
1792         if (W_ERROR_EQUAL(werr, WERR_DNS_ERROR_NAME_DOES_NOT_EXIST)) {
1793                 needs_add = true;
1794                 werr = WERR_OK;
1795         }
1796         if (!W_ERROR_IS_OK(werr)) {
1797                 state->log(ISC_LOG_ERROR, "samba_dlz: failed to parse dnsRecord for %s, %s",
1798                            ldb_dn_get_linearized(dn), win_errstr(werr));
1799                 talloc_free(rec);
1800                 return ISC_R_FAILURE;
1801         }
1802
1803         if (tombstoned) {
1804                 /*
1805                  * we need to keep the existing tombstone record
1806                  * and ignore it
1807                  */
1808                 first = num_recs;
1809         }
1810
1811         /* there are existing records. We need to see if this will
1812          * replace a record or add to it
1813          */
1814         for (i=first; i < num_recs; i++) {
1815                 if (b9_record_match(state, rec, &recs[i])) {
1816                         break;
1817                 }
1818         }
1819         if (i == UINT16_MAX) {
1820                 state->log(ISC_LOG_ERROR, "samba_dlz: failed to already %u dnsRecord values for %s",
1821                            i, ldb_dn_get_linearized(dn));
1822                 talloc_free(rec);
1823                 return ISC_R_FAILURE;
1824         }
1825
1826         if (i == num_recs) {
1827                 /* adding a new value */
1828                 recs = talloc_realloc(rec, recs,
1829                                       struct dnsp_DnssrvRpcRecord,
1830                                       num_recs + 1);
1831                 if (recs == NULL) {
1832                         talloc_free(rec);
1833                         return ISC_R_NOMEMORY;
1834                 }
1835                 num_recs++;
1836
1837                 if (dns_name_is_static(recs, num_recs)) {
1838                         rec->dwTimeStamp = 0;
1839                 } else {
1840                         unix_to_nt_time(&t, time(NULL));
1841                         t /= 10 * 1000 * 1000; /* convert to seconds */
1842                         t /= 3600;           /* convert to hours */
1843                         rec->dwTimeStamp = (uint32_t)t;
1844                 }
1845         }
1846
1847         recs[i] = *rec;
1848
1849         if (!b9_set_session_info(state, name)) {
1850                 talloc_free(rec);
1851                 return ISC_R_FAILURE;
1852         }
1853
1854         /* modify the record */
1855         werr = dns_common_replace(state->samdb, rec, dn,
1856                                   needs_add,
1857                                   state->soa_serial,
1858                                   recs, num_recs);
1859         b9_reset_session_info(state);
1860         if (!W_ERROR_IS_OK(werr)) {
1861                 state->log(ISC_LOG_ERROR, "samba_dlz: failed to %s %s - %s",
1862                            needs_add ? "add" : "modify",
1863                            ldb_dn_get_linearized(dn), win_errstr(werr));
1864                 talloc_free(rec);
1865                 return ISC_R_FAILURE;
1866         }
1867
1868         state->log(ISC_LOG_INFO, "samba_dlz: added rdataset %s '%s'", name, rdatastr);
1869
1870         talloc_free(rec);
1871         return ISC_R_SUCCESS;
1872 }
1873
1874 /*
1875   remove a rdataset
1876  */
1877 _PUBLIC_ isc_result_t dlz_subrdataset(const char *name, const char *rdatastr, void *dbdata, void *version)
1878 {
1879         struct dlz_bind9_data *state = talloc_get_type_abort(dbdata, struct dlz_bind9_data);
1880         struct dnsp_DnssrvRpcRecord *rec;
1881         struct ldb_dn *dn;
1882         isc_result_t result;
1883         struct dnsp_DnssrvRpcRecord *recs = NULL;
1884         uint16_t num_recs = 0;
1885         uint16_t i;
1886         WERROR werr;
1887
1888         if (state->transaction_token != (void*)version) {
1889                 state->log(ISC_LOG_ERROR, "samba_dlz: bad transaction version");
1890                 return ISC_R_FAILURE;
1891         }
1892
1893         rec = talloc_zero(state, struct dnsp_DnssrvRpcRecord);
1894         if (rec == NULL) {
1895                 return ISC_R_NOMEMORY;
1896         }
1897
1898         if (!b9_parse(state, rdatastr, rec)) {
1899                 state->log(ISC_LOG_ERROR, "samba_dlz: failed to parse rdataset '%s'", rdatastr);
1900                 talloc_free(rec);
1901                 return ISC_R_FAILURE;
1902         }
1903
1904         /* find the DN of the record */
1905         result = b9_find_name_dn(state, name, rec, &dn);
1906         if (result != ISC_R_SUCCESS) {
1907                 talloc_free(rec);
1908                 return result;
1909         }
1910
1911         /* get the existing records */
1912         werr = dns_common_lookup(state->samdb, rec, dn,
1913                                  &recs, &num_recs, NULL);
1914         if (!W_ERROR_IS_OK(werr)) {
1915                 talloc_free(rec);
1916                 return ISC_R_NOTFOUND;
1917         }
1918
1919         for (i=0; i < num_recs; i++) {
1920                 if (b9_record_match(state, rec, &recs[i])) {
1921                         recs[i] = (struct dnsp_DnssrvRpcRecord) {
1922                                 .wType = DNS_TYPE_TOMBSTONE,
1923                         };
1924                         break;
1925                 }
1926         }
1927         if (i == num_recs) {
1928                 talloc_free(rec);
1929                 return ISC_R_NOTFOUND;
1930         }
1931
1932         if (!b9_set_session_info(state, name)) {
1933                 talloc_free(rec);
1934                 return ISC_R_FAILURE;
1935         }
1936
1937         /* modify the record */
1938         werr = dns_common_replace(state->samdb, rec, dn,
1939                                   false,/* needs_add */
1940                                   state->soa_serial,
1941                                   recs, num_recs);
1942         b9_reset_session_info(state);
1943         if (!W_ERROR_IS_OK(werr)) {
1944                 state->log(ISC_LOG_ERROR, "samba_dlz: failed to modify %s - %s",
1945                            ldb_dn_get_linearized(dn), win_errstr(werr));
1946                 talloc_free(rec);
1947                 return ISC_R_FAILURE;
1948         }
1949
1950         state->log(ISC_LOG_INFO, "samba_dlz: subtracted rdataset %s '%s'", name, rdatastr);
1951
1952         talloc_free(rec);
1953         return ISC_R_SUCCESS;
1954 }
1955
1956
1957 /*
1958   delete all records of the given type
1959  */
1960 _PUBLIC_ isc_result_t dlz_delrdataset(const char *name, const char *type, void *dbdata, void *version)
1961 {
1962         struct dlz_bind9_data *state = talloc_get_type_abort(dbdata, struct dlz_bind9_data);
1963         TALLOC_CTX *tmp_ctx;
1964         struct ldb_dn *dn;
1965         isc_result_t result;
1966         enum dns_record_type dns_type;
1967         bool found = false;
1968         struct dnsp_DnssrvRpcRecord *recs = NULL;
1969         uint16_t num_recs = 0;
1970         uint16_t ri = 0;
1971         WERROR werr;
1972
1973         if (state->transaction_token != (void*)version) {
1974                 state->log(ISC_LOG_ERROR, "samba_dlz: bad transaction version");
1975                 return ISC_R_FAILURE;
1976         }
1977
1978         if (!b9_dns_type(type, &dns_type)) {
1979                 state->log(ISC_LOG_ERROR, "samba_dlz: bad dns type %s in delete", type);
1980                 return ISC_R_FAILURE;
1981         }
1982
1983         tmp_ctx = talloc_new(state);
1984
1985         /* find the DN of the record */
1986         result = b9_find_name_dn(state, name, tmp_ctx, &dn);
1987         if (result != ISC_R_SUCCESS) {
1988                 talloc_free(tmp_ctx);
1989                 return result;
1990         }
1991
1992         /* get the existing records */
1993         werr = dns_common_lookup(state->samdb, tmp_ctx, dn,
1994                                  &recs, &num_recs, NULL);
1995         if (!W_ERROR_IS_OK(werr)) {
1996                 talloc_free(tmp_ctx);
1997                 return ISC_R_NOTFOUND;
1998         }
1999
2000         for (ri=0; ri < num_recs; ri++) {
2001                 if (dns_type != recs[ri].wType) {
2002                         continue;
2003                 }
2004
2005                 found = true;
2006                 recs[ri] = (struct dnsp_DnssrvRpcRecord) {
2007                         .wType = DNS_TYPE_TOMBSTONE,
2008                 };
2009         }
2010
2011         if (!found) {
2012                 talloc_free(tmp_ctx);
2013                 return ISC_R_FAILURE;
2014         }
2015
2016         if (!b9_set_session_info(state, name)) {
2017                 talloc_free(tmp_ctx);
2018                 return ISC_R_FAILURE;
2019         }
2020
2021         /* modify the record */
2022         werr = dns_common_replace(state->samdb, tmp_ctx, dn,
2023                                   false,/* needs_add */
2024                                   state->soa_serial,
2025                                   recs, num_recs);
2026         b9_reset_session_info(state);
2027         if (!W_ERROR_IS_OK(werr)) {
2028                 state->log(ISC_LOG_ERROR, "samba_dlz: failed to modify %s - %s",
2029                            ldb_dn_get_linearized(dn), win_errstr(werr));
2030                 talloc_free(tmp_ctx);
2031                 return ISC_R_FAILURE;
2032         }
2033
2034         state->log(ISC_LOG_INFO, "samba_dlz: deleted rdataset %s of type %s", name, type);
2035
2036         talloc_free(tmp_ctx);
2037         return ISC_R_SUCCESS;
2038 }