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