Coverage Report

Created: 2026-10-28 06:54

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/bind9/lib/dns/zone.c
Line
Count
Source
1
/*
2
 * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
3
 *
4
 * SPDX-License-Identifier: MPL-2.0
5
 *
6
 * This Source Code Form is subject to the terms of the Mozilla Public
7
 * License, v. 2.0. If a copy of the MPL was not distributed with this
8
 * file, you can obtain one at https://mozilla.org/MPL/2.0/.
9
 *
10
 * See the COPYRIGHT file distributed with this work for additional
11
 * information regarding copyright ownership.
12
 */
13
14
/*! \file */
15
16
#include <errno.h>
17
#include <inttypes.h>
18
#include <stdbool.h>
19
20
#include <isc/async.h>
21
#include <isc/atomic.h>
22
#include <isc/file.h>
23
#include <isc/hash.h>
24
#include <isc/hex.h>
25
#include <isc/list.h>
26
#include <isc/log.h>
27
#include <isc/loop.h>
28
#include <isc/md.h>
29
#include <isc/mutex.h>
30
#include <isc/netmgr.h>
31
#include <isc/os.h>
32
#include <isc/overflow.h>
33
#include <isc/random.h>
34
#include <isc/ratelimiter.h>
35
#include <isc/refcount.h>
36
#include <isc/result.h>
37
#include <isc/rwlock.h>
38
#include <isc/serial.h>
39
#include <isc/stats.h>
40
#include <isc/stdtime.h>
41
#include <isc/strerr.h>
42
#include <isc/string.h>
43
#include <isc/thread.h>
44
#include <isc/tid.h>
45
#include <isc/timer.h>
46
#include <isc/tls.h>
47
#include <isc/util.h>
48
49
#include <dns/acl.h>
50
#include <dns/adb.h>
51
#include <dns/callbacks.h>
52
#include <dns/catz.h>
53
#include <dns/db.h>
54
#include <dns/dbiterator.h>
55
#include <dns/dlz.h>
56
#include <dns/dnssec.h>
57
#include <dns/dsync.h>
58
#include <dns/journal.h>
59
#include <dns/kasp.h>
60
#include <dns/keydata.h>
61
#include <dns/keymgr.h>
62
#include <dns/keytable.h>
63
#include <dns/keyvalues.h>
64
#include <dns/master.h>
65
#include <dns/masterdump.h>
66
#include <dns/message.h>
67
#include <dns/name.h>
68
#include <dns/notify.h>
69
#include <dns/nsec.h>
70
#include <dns/nsec3.h>
71
#include <dns/opcode.h>
72
#include <dns/peer.h>
73
#include <dns/private.h>
74
#include <dns/rcode.h>
75
#include <dns/rdata.h>
76
#include <dns/rdataclass.h>
77
#include <dns/rdatalist.h>
78
#include <dns/rdataset.h>
79
#include <dns/rdatasetiter.h>
80
#include <dns/rdatastruct.h>
81
#include <dns/rdatatype.h>
82
#include <dns/remote.h>
83
#include <dns/request.h>
84
#include <dns/resolver.h>
85
#include <dns/rriterator.h>
86
#include <dns/skr.h>
87
#include <dns/soa.h>
88
#include <dns/ssu.h>
89
#include <dns/stats.h>
90
#include <dns/time.h>
91
#include <dns/tsig.h>
92
#include <dns/ttl.h>
93
#include <dns/unreachcache.h>
94
#include <dns/update.h>
95
#include <dns/xfrin.h>
96
#include <dns/zone.h>
97
#include <dns/zonefetch.h>
98
#include <dns/zonemgr.h>
99
#include <dns/zoneproperties.h>
100
#include <dns/zoneverify.h>
101
#include <dns/zt.h>
102
103
#include <dst/dst.h>
104
105
#include "zone_p.h"
106
107
/*%
108
 * Ensure 'a' is at least 'min' but not more than 'max'.
109
 */
110
0
#define RANGE(a, min, max) (((a) < (min)) ? (min) : ((a) < (max) ? (a) : (max)))
111
112
0
#define NSEC3REMOVE(x) (((x) & DNS_NSEC3FLAG_REMOVE) != 0)
113
114
/*%
115
 * Key flags
116
 */
117
0
#define REVOKE(x)  ((dst_key_flags(x) & DNS_KEYFLAG_REVOKE) != 0)
118
0
#define KSK(x)     ((dst_key_flags(x) & DNS_KEYFLAG_KSK) != 0)
119
0
#define ADT(x)     ((dst_key_flags(x) & DNS_KEYFLAG_ADT) != 0)
120
0
#define ZONEKEY(x) ((dst_key_flags(x) & DNS_KEYOWNER_ZONE) != 0)
121
0
#define ID(x)    dst_key_id(x)
122
0
#define ALG(x)     dst_key_alg(x)
123
124
/*%
125
 * KASP flags
126
 */
127
#define KASP_LOCK(k)                \
128
0
  if ((k) != NULL) {          \
129
0
    LOCK(&((k)->lock)); \
130
0
  }
131
132
#define KASP_UNLOCK(k)                \
133
0
  if ((k) != NULL) {            \
134
0
    UNLOCK(&((k)->lock)); \
135
0
  }
136
137
typedef struct dns_stub dns_stub_t;
138
typedef struct dns_load dns_load_t;
139
typedef struct dns_asyncload dns_asyncload_t;
140
141
#ifdef ENABLE_AFL
142
extern bool dns_fuzzing_resolver;
143
#endif /* ifdef ENABLE_AFL */
144
145
/*%
146
 * Key file I/O lock pool.
147
 */
148
typedef struct dns_keymgmt_bucket {
149
  isc_mutex_t lock;
150
  uint8_t __padding[ISC_OS_CACHELINE_SIZE -
151
        sizeof(isc_mutex_t) % ISC_OS_CACHELINE_SIZE];
152
} dns_keymgmt_bucket_t;
153
154
static dns_keymgmt_bucket_t keymgmt_buckets_g[1024];
155
156
#define zonediff_init(z, d)                \
157
0
  do {                               \
158
0
    dns__zonediff_t *_z = (z); \
159
0
    (_z)->diff = (d);          \
160
0
    (_z)->offline = false;     \
161
0
  } while (0)
162
163
/* Flags for zone_load() */
164
typedef enum {
165
  DNS_ZONELOADFLAG_NOSTAT = 0x00000001U, /* Do not stat() master files */
166
  DNS_ZONELOADFLAG_THAW = 0x00000002U,   /* Thaw the zone on successful
167
            * load. */
168
} dns_zoneloadflag_t;
169
170
/*%
171
 *  dns_stub holds state while performing a 'stub' transfer.
172
 *  'db' is the zone's 'db' or a new one if this is the initial
173
 *  transfer.
174
 */
175
176
struct dns_stub {
177
  unsigned int magic;
178
  isc_mem_t *mctx;
179
  dns_zone_t *zone;
180
  dns_db_t *db;
181
  dns_dbversion_t *version;
182
  atomic_uint_fast32_t pending_requests;
183
};
184
185
/*%
186
 *  Hold load state.
187
 */
188
struct dns_load {
189
  dns_zone_t *zone;
190
  dns_db_t *db;
191
  isc_time_t loadtime;
192
  dns_rdatacallbacks_t callbacks;
193
};
194
195
/*%
196
 * Hold state for an asynchronous load
197
 */
198
struct dns_asyncload {
199
  dns_zone_t *zone;
200
  unsigned int flags;
201
  dns_zt_callback_t *loaded;
202
  void *loaded_arg;
203
};
204
205
/*
206
 * These can be overridden by the -T mkeytimers option on the command
207
 * line, so that we can test with shorter periods than specified in
208
 * RFC 5011.
209
 */
210
#define HOUR  3600
211
#define DAY   (24 * HOUR)
212
#define MONTH (30 * DAY)
213
unsigned int dns_zone_mkey_hour = HOUR;
214
unsigned int dns_zone_mkey_day = DAY;
215
unsigned int dns_zone_mkey_month = MONTH;
216
217
0
#define SEND_BUFFER_SIZE 2048
218
219
static void
220
zone_timer_set(dns_zone_t *zone, isc_time_t *next, isc_time_t *now);
221
222
static void
223
cancel_refresh(dns_zone_t *);
224
static void
225
zone_debuglogc(dns_zone_t *zone, isc_logcategory_t category, const char *me,
226
         int debuglevel, const char *fmt, ...);
227
static void
228
zone_debuglog(dns_zone_t *zone, const char *, int debuglevel, const char *msg,
229
        ...) ISC_FORMAT_PRINTF(4, 5);
230
static void
231
dnssec_log(dns_zone_t *zone, int level, const char *fmt, ...)
232
  ISC_FORMAT_PRINTF(3, 4);
233
234
typedef struct nsec3param nsec3param_t;
235
236
static void
237
queue_xfrin(dns_zone_t *zone);
238
static isc_result_t
239
update_one_rr(dns_db_t *db, dns_dbversion_t *ver, dns_diff_t *diff,
240
        dns_diffop_t op, dns_name_t *name, dns_ttl_t ttl,
241
        dns_rdata_t *rdata);
242
static void
243
zone_unload(dns_zone_t *zone);
244
static void
245
zone_expire(dns_zone_t *zone);
246
static void
247
zone_refresh(dns_zone_t *zone);
248
static void
249
zone_iattach(dns_zone_t *source, dns_zone_t **target);
250
static void
251
zone_idetach(dns_zone_t **zonep);
252
static isc_result_t
253
zone_replacedb(dns_zone_t *zone, dns_db_t *db, bool dump);
254
static void
255
zone_attachdb(dns_zone_t *zone, dns_db_t *db);
256
static void
257
zone_detachdb(dns_zone_t *zone);
258
static void
259
zone_catz_enable(dns_zone_t *zone, dns_catz_zones_t *catzs);
260
static void
261
zone_catz_disable(dns_zone_t *zone);
262
static isc_result_t
263
zone_postload(dns_zone_t *zone, dns_db_t *db, isc_time_t loadtime,
264
        isc_result_t result);
265
static void
266
zone_needdump(dns_zone_t *zone, unsigned int delay);
267
static void
268
zone_shutdown(void *arg);
269
static void
270
zone_loaddone(void *arg, isc_result_t result);
271
static isc_result_t
272
zone_startload(dns_db_t *db, dns_zone_t *zone, isc_time_t loadtime);
273
static void
274
zone_namerd_tostr(dns_zone_t *zone, char *buf, size_t length);
275
static void
276
zone_schedule_inline_sync(dns_zone_t *zone, inline_sync_phase_t state);
277
static void
278
refresh_callback(void *arg);
279
static void
280
stub_callback(void *arg);
281
static void
282
queue_soa_query(dns_zone_t *zone);
283
static void
284
soa_query(void *arg);
285
static void
286
ns_query(dns_zone_t *zone, dns_rdataset_t *soardataset, dns_stub_t *stub);
287
static int
288
message_count(dns_message_t *msg, dns_section_t section, dns_rdatatype_t type);
289
static void
290
checkds_cancel(dns_zone_t *zone);
291
static void
292
checkds_find_address(dns_checkds_t *checkds);
293
static void
294
checkds_send(dns_zone_t *zone);
295
static void
296
checkds_createmessage(dns_zone_t *zone, dns_message_t **messagep);
297
static void
298
checkds_done(void *arg);
299
static void
300
checkds_send_tons(dns_checkds_t *checkds);
301
static void
302
checkds_send_toaddr(void *arg);
303
static isc_result_t
304
zone_dump(dns_zone_t *, bool);
305
static void
306
rss_post(dns_zone_t *zone, nsec3param_t *np);
307
static void
308
zone_process_maintenance_request(dns_zone_t *zone);
309
310
static isc_result_t
311
zone_get_from_db(dns_zone_t *zone, dns_db_t *db, unsigned int *nscount,
312
     unsigned int *soacount, uint32_t *soattl, uint32_t *serial,
313
     uint32_t *refresh, uint32_t *retry, uint32_t *expire,
314
     uint32_t *minimum, unsigned int *errors);
315
316
static void
317
forward_callback(void *arg);
318
static void
319
zone_saveunique(dns_zone_t *zone, const char *path, const char *templat);
320
static void
321
zone_maintenance(dns_zone_t *zone);
322
323
static void
324
inline_sync_run(dns_zone_t *zone);
325
static void
326
inline_sync_resume(dns_zone_t *zone);
327
static void
328
zone_clear_inline_sync(dns_zone_t *zone);
329
static void
330
inline_secure_bootstrap(dns_zone_t *zone);
331
static isc_result_t
332
secure_db_create_from_raw(dns_zone_t *zone, dns_db_t *rawdb, dns_db_t **dbp);
333
static void
334
zone_notify(dns_zone_t *zone, isc_time_t *now);
335
static void
336
zone_notifycds(dns_zone_t *zone);
337
static void
338
dump_done(void *arg, isc_result_t result);
339
static isc_result_t
340
zone_signwithkey(dns_zone_t *zone, dst_algorithm_t algorithm, uint16_t keyid,
341
     bool deleteit, bool fullsign);
342
static isc_result_t
343
delete_nsec(dns_db_t *db, dns_dbversion_t *ver, dns_dbnode_t *node,
344
      dns_name_t *name, dns_diff_t *diff);
345
static void
346
zone_rekey(dns_zone_t *zone);
347
static dns_ttl_t
348
zone_nsecttl(dns_zone_t *zone);
349
static void
350
zone_journal_compact(dns_zone_t *zone, dns_db_t *db, uint32_t serial);
351
static isc_result_t
352
zone_journal_rollforward(dns_zone_t *zone, dns_db_t *db, bool *needdump,
353
       bool *fixjournal);
354
0
#define ENTER zone_debuglog(zone, __func__, 1, "enter")
355
356
static const unsigned int dbargc_default = 1;
357
static const char *dbargv_default[] = { ZONEDB_DEFAULT };
358
359
#define DNS_ZONE_JITTER_ADD(a, b, c)                                         \
360
0
  do {                                                                 \
361
0
    isc_interval_t _i;                                           \
362
0
    uint32_t _j;                                                 \
363
0
    _j = (b) - isc_random_uniform((b) / 4);                      \
364
0
    isc_interval_set(&_i, _j, 0);                                \
365
0
    if (isc_time_add((a), &_i, (c)) != ISC_R_SUCCESS) {          \
366
0
      dns_zone_log(zone, ISC_LOG_WARNING,                  \
367
0
             "epoch approaching: upgrade required: " \
368
0
             "now + %s failed",                      \
369
0
             #b);                                    \
370
0
      isc_interval_set(&_i, _j / 2, 0);                    \
371
0
      (void)isc_time_add((a), &_i, (c));                   \
372
0
    }                                                            \
373
0
  } while (0)
374
375
#define DNS_ZONE_TIME_ADD(a, b, c)                                           \
376
0
  do {                                                                 \
377
0
    isc_interval_t _i;                                           \
378
0
    isc_interval_set(&_i, (b), 0);                               \
379
0
    if (isc_time_add((a), &_i, (c)) != ISC_R_SUCCESS) {          \
380
0
      dns_zone_log(zone, ISC_LOG_WARNING,                  \
381
0
             "epoch approaching: upgrade required: " \
382
0
             "now + %s failed",                      \
383
0
             #b);                                    \
384
0
      isc_interval_set(&_i, (b) / 2, 0);                   \
385
0
      (void)isc_time_add((a), &_i, (c));                   \
386
0
    }                                                            \
387
0
  } while (0)
388
389
#define DNS_ZONE_TIME_SUBTRACT(a, b, c)                                      \
390
0
  do {                                                                 \
391
0
    isc_interval_t _i;                                           \
392
0
    isc_interval_set(&_i, (b), 0);                               \
393
0
    if (isc_time_subtract((a), &_i, (c)) != ISC_R_SUCCESS) {     \
394
0
      dns_zone_log(zone, ISC_LOG_WARNING,                  \
395
0
             "epoch approaching: upgrade required: " \
396
0
             "isc_time_subtract() failed");          \
397
0
      isc_interval_set(&_i, (b) / 2, 0);                   \
398
0
      (void)isc_time_subtract((a), &_i, (c));              \
399
0
    }                                                            \
400
0
  } while (0)
401
402
struct nsec3param {
403
  dns_rdata_nsec3param_t rdata;
404
  unsigned char data[DNS_NSEC3PARAM_BUFFERSIZE + 1];
405
  unsigned int length;
406
  bool nsec;
407
  bool replace;
408
  bool resalt;
409
  bool lookup;
410
  ISC_LINK(nsec3param_t) link;
411
};
412
typedef ISC_LIST(nsec3param_t) nsec3paramlist_t;
413
414
0
#define OLD_SIGNING_RECORD_SIZE 5
415
0
#define SIGNING_RECORD_SIZE 7
416
417
typedef enum zone_maintenance_request_type {
418
  zone_maintenance_request_setnsec3param,
419
  zone_maintenance_request_keydone,
420
  zone_maintenance_request_setserial,
421
} zone_maintenance_request_type_t;
422
423
typedef struct zone_maintenance_request {
424
  ISC_LINK(struct zone_maintenance_request) link;
425
  zone_maintenance_request_type_t type;
426
  union {
427
    nsec3param_t nsec3param;
428
    struct {
429
      bool all;
430
      unsigned char data[SIGNING_RECORD_SIZE];
431
    } keydone;
432
    struct {
433
      uint32_t serial;
434
    } setserial;
435
  } u;
436
} zone_maintenance_request_t;
437
438
struct stub_cb_args {
439
  dns_stub_t *stub;
440
  dns_tsigkey_t *tsig_key;
441
  uint16_t udpsize;
442
  unsigned int connect_timeout;
443
  unsigned int timeout;
444
  bool reqnsid;
445
};
446
447
struct stub_glue_request {
448
  dns_request_t *request;
449
  dns_name_t name;
450
  struct stub_cb_args *args;
451
  bool ipv4;
452
};
453
454
/*%
455
 * Increment resolver-related statistics counters.  Zone must be locked.
456
 */
457
static void
458
0
inc_stats(dns_zone_t *zone, isc_statscounter_t counter) {
459
0
  if (zone->stats != NULL) {
460
0
    isc_stats_increment(zone->stats, counter);
461
0
  }
462
0
}
463
464
/***
465
 ***  Public functions.
466
 ***/
467
468
void
469
0
dns_zone_create(dns_zone_t **zonep, isc_mem_t *mctx, isc_tid_t tid) {
470
0
  isc_time_t now;
471
0
  dns_zone_t *zone = NULL;
472
473
0
  REQUIRE(zonep != NULL && *zonep == NULL);
474
0
  REQUIRE(mctx != NULL);
475
476
0
  now = isc_time_now();
477
0
  zone = isc_mem_getx(mctx, sizeof(*zone),
478
0
          ISC_MEM_ALIGN(ISC_OS_CACHELINE_SIZE));
479
0
  *zone = (dns_zone_t){
480
0
    .masterformat = dns_masterformat_none,
481
0
    .journalsize = -1,
482
0
    .rdclass = dns_rdataclass_none,
483
0
    .type = dns_zone_none,
484
0
    .refresh = DNS_ZONE_DEFAULTREFRESH,
485
0
    .retry = DNS_ZONE_DEFAULTRETRY,
486
0
    .maxrefresh = DNS_ZONE_MAXREFRESH,
487
0
    .minrefresh = DNS_ZONE_MINREFRESH,
488
0
    .maxretry = DNS_ZONE_MAXRETRY,
489
0
    .minretry = DNS_ZONE_MINRETRY,
490
0
    .checkdstype = dns_checkdstype_yes,
491
0
    .zero_no_soa_ttl = true,
492
0
    .idlein = DNS_DEFAULT_IDLEIN,
493
0
    .idleout = DNS_DEFAULT_IDLEOUT,
494
0
    .maxxfrin = MAX_XFER_TIME,
495
0
    .maxxfrout = MAX_XFER_TIME,
496
0
    .sigvalidityinterval = 30 * 24 * 3600,
497
0
    .sigresigninginterval = 7 * 24 * 3600,
498
0
    .statlevel = dns_zonestat_none,
499
0
    .signatures = 10,
500
0
    .nodes = 100,
501
0
    .privatetype = (dns_rdatatype_t)0xffffU,
502
0
    .rpz_num = DNS_RPZ_INVALID_NUM,
503
0
    .requestixfr = true,
504
0
    .ixfr_ratio = 100,
505
0
    .requestexpire = true,
506
0
    .updatemethod = dns_updatemethod_increment,
507
0
    .tid = tid,
508
0
    .notifytime = now,
509
0
    .newincludes = ISC_LIST_INITIALIZER,
510
0
    .checkds_requests = ISC_LIST_INITIALIZER,
511
0
    .signing = ISC_LIST_INITIALIZER,
512
0
    .nsec3chain = ISC_LIST_INITIALIZER,
513
0
    .maintenance_queue = ISC_LIST_INITIALIZER,
514
0
    .forwards = ISC_LIST_INITIALIZER,
515
0
    .statelink = ISC_LINK_INITIALIZER,
516
0
  };
517
0
  dns_remote_t r = {
518
0
    .magic = DNS_REMOTE_MAGIC,
519
0
  };
520
521
0
  isc_mem_attach(mctx, &zone->mctx);
522
0
  isc_mutex_init(&zone->lock);
523
0
  ZONEDB_INITLOCK(&zone->dblock);
524
525
0
  isc_refcount_init(&zone->references, 1);
526
0
  isc_refcount_init(&zone->irefs, 0);
527
0
  dns_name_init(&zone->origin);
528
529
0
  zone->primaries = r;
530
0
  zone->parentals = r;
531
0
  zone->alsonotify = r;
532
0
  zone->cds_endpoints = r;
533
0
  zone->defaultkasp = NULL;
534
0
  ISC_LIST_INIT(zone->keyring);
535
536
0
  dns_notifyctx_init(&zone->notifysoa, dns_rdatatype_soa);
537
0
  dns_notifyctx_init(&zone->notifycds, dns_rdatatype_cds);
538
539
0
  isc_stats_create(mctx, &zone->gluecachestats,
540
0
       dns_gluecachestatscounter_max);
541
542
0
  zone->magic = ZONE_MAGIC;
543
544
  /* Must be after magic is set. */
545
0
  dns_zone_setdbtype(zone, dbargc_default, dbargv_default);
546
547
0
  *zonep = zone;
548
0
}
549
550
static void
551
0
clear_keylist(dns_dnsseckeylist_t *list, isc_mem_t *mctx) {
552
0
  ISC_LIST_FOREACH(*list, key, link) {
553
0
    ISC_LIST_UNLINK(*list, key, link);
554
0
    dns_dnsseckey_destroy(mctx, &key);
555
0
  }
556
0
}
557
558
void
559
0
dns__zone_free(dns_zone_t *zone) {
560
0
  REQUIRE(DNS_ZONE_VALID(zone));
561
0
  REQUIRE(!LOCKED_ZONE(zone));
562
0
  REQUIRE(zone->timer == NULL);
563
564
0
  dns_zone_unloadplugins(zone);
565
566
0
  isc_refcount_destroy(&zone->references);
567
0
  isc_refcount_destroy(&zone->irefs);
568
569
  /*
570
   * Managed objects.  Order is important.
571
   */
572
0
  if (zone->request != NULL) {
573
0
    dns_request_destroy(&zone->request); /* XXXMPA */
574
0
  }
575
0
  INSIST(zone->statelist == NULL);
576
0
  INSIST(zone->view == NULL);
577
0
  INSIST(zone->prev_view == NULL);
578
579
  /* Unmanaged objects */
580
0
  ISC_LIST_FOREACH(zone->maintenance_queue, request, link) {
581
0
    ISC_LIST_UNLINK(zone->maintenance_queue, request, link);
582
0
    isc_mem_put(zone->mctx, request, sizeof(*request));
583
0
  }
584
585
0
  ISC_LIST_FOREACH(zone->signing, signing, link) {
586
0
    ISC_LIST_UNLINK(zone->signing, signing, link);
587
0
    dns_db_detach(&signing->db);
588
0
    dns_dbiterator_destroy(&signing->dbiterator);
589
0
    isc_mem_put(zone->mctx, signing, sizeof *signing);
590
0
  }
591
592
0
  ISC_LIST_FOREACH(zone->nsec3chain, nsec3chain, link) {
593
0
    ISC_LIST_UNLINK(zone->nsec3chain, nsec3chain, link);
594
0
    dns_db_detach(&nsec3chain->db);
595
0
    dns_dbiterator_destroy(&nsec3chain->dbiterator);
596
0
    isc_mem_put(zone->mctx, nsec3chain, sizeof *nsec3chain);
597
0
  }
598
599
0
  ISC_LIST_FOREACH(zone->includes, include, link) {
600
0
    ISC_LIST_UNLINK(zone->includes, include, link);
601
0
    isc_mem_free(zone->mctx, include->name);
602
0
    isc_mem_put(zone->mctx, include, sizeof *include);
603
0
  }
604
605
0
  ISC_LIST_FOREACH(zone->newincludes, include, link) {
606
0
    ISC_LIST_UNLINK(zone->newincludes, include, link);
607
0
    isc_mem_free(zone->mctx, include->name);
608
0
    isc_mem_put(zone->mctx, include, sizeof *include);
609
0
  }
610
611
0
  zone_clear_inline_sync(zone);
612
0
  INSIST(zone->iss == NULL);
613
614
0
  if (zone->masterfile != NULL) {
615
0
    isc_mem_free(zone->mctx, zone->masterfile);
616
0
  }
617
0
  if (zone->initfile != NULL) {
618
0
    isc_mem_free(zone->mctx, zone->initfile);
619
0
  }
620
0
  if (zone->keydirectory != NULL) {
621
0
    isc_mem_free(zone->mctx, zone->keydirectory);
622
0
  }
623
624
0
  if (zone->kasp != NULL) {
625
0
    dns_kasp_detach(&zone->kasp);
626
0
  }
627
0
  if (zone->defaultkasp != NULL) {
628
0
    dns_kasp_detach(&zone->defaultkasp);
629
0
  }
630
0
  if (!ISC_LIST_EMPTY(zone->keyring)) {
631
0
    clear_keylist(&zone->keyring, zone->mctx);
632
0
  }
633
0
  if (!ISC_LIST_EMPTY(zone->checkds_ok)) {
634
0
    clear_keylist(&zone->checkds_ok, zone->mctx);
635
0
  }
636
0
  if (zone->skr != NULL) {
637
0
    zone->skrbundle = NULL;
638
0
    dns_skr_detach(&zone->skr);
639
0
  }
640
641
0
  zone->journalsize = -1;
642
0
  if (zone->journal != NULL) {
643
0
    isc_mem_free(zone->mctx, zone->journal);
644
0
  }
645
0
  if (zone->stats != NULL) {
646
0
    isc_stats_detach(&zone->stats);
647
0
  }
648
0
  if (zone->requeststats != NULL) {
649
0
    isc_stats_detach(&zone->requeststats);
650
0
  }
651
0
  if (zone->rcvquerystats != NULL) {
652
0
    isc_statsmulti_detach(&zone->rcvquerystats);
653
0
  }
654
0
  if (zone->dnssecsignstats != NULL) {
655
0
    dns_stats_detach(&zone->dnssecsignstats);
656
0
  }
657
0
  if (zone->db != NULL) {
658
0
    zone_detachdb(zone);
659
0
  }
660
0
  if (zone->rpzs != NULL) {
661
0
    REQUIRE(zone->rpz_num < zone->rpzs->p.num_zones);
662
0
    dns_rpz_zones_detach(&zone->rpzs);
663
0
    zone->rpz_num = DNS_RPZ_INVALID_NUM;
664
0
  }
665
0
  if (zone->catzs != NULL) {
666
0
    dns_catz_zones_detach(&zone->catzs);
667
0
  }
668
0
  dns__zone_freedbargs(zone);
669
670
0
  dns_zone_setparentals(zone, NULL, NULL, NULL, NULL, 0);
671
0
  dns_zone_setprimaries(zone, NULL, NULL, NULL, NULL, 0);
672
0
  dns_zone_setalsonotify(zone, NULL, NULL, NULL, NULL, 0);
673
0
  dns_zone_setcdsendpoints(zone, NULL, NULL, NULL, NULL, 0);
674
675
0
  if (zone->update_acl != NULL) {
676
0
    dns_acl_detach(&zone->update_acl);
677
0
  }
678
0
  if (zone->forward_acl != NULL) {
679
0
    dns_acl_detach(&zone->forward_acl);
680
0
  }
681
0
  if (zone->notifysoa.notify_acl != NULL) {
682
0
    dns_acl_detach(&zone->notifysoa.notify_acl);
683
0
  }
684
0
  if (zone->notifycds.notify_acl != NULL) {
685
0
    dns_acl_detach(&zone->notifycds.notify_acl);
686
0
  }
687
0
  if (zone->query_acl != NULL) {
688
0
    dns_acl_detach(&zone->query_acl);
689
0
  }
690
0
  if (zone->queryon_acl != NULL) {
691
0
    dns_acl_detach(&zone->queryon_acl);
692
0
  }
693
0
  if (zone->xfr_acl != NULL) {
694
0
    dns_acl_detach(&zone->xfr_acl);
695
0
  }
696
0
  if (dns_name_dynamic(&zone->origin)) {
697
0
    dns_name_free(&zone->origin, zone->mctx);
698
0
  }
699
700
0
  dns_zone_setrad(zone, NULL);
701
0
  dns__viewname_free(&zone->viewname, zone->mctx);
702
703
0
  if (zone->ssutable != NULL) {
704
0
    dns_ssutable_detach(&zone->ssutable);
705
0
  }
706
0
  if (zone->gluecachestats != NULL) {
707
0
    isc_stats_detach(&zone->gluecachestats);
708
0
  }
709
710
  /* last stuff */
711
0
  if (zone->loop != NULL) {
712
0
    isc_loop_detach(&zone->loop);
713
0
  }
714
0
  ZONEDB_DESTROYLOCK(&zone->dblock);
715
0
  isc_mutex_destroy(&zone->lock);
716
0
  zone->magic = 0;
717
0
  isc_mem_t *mctx = zone->mctx;
718
0
  isc_mem_putx(mctx, zone, sizeof(*zone),
719
0
         ISC_MEM_ALIGN(ISC_OS_CACHELINE_SIZE));
720
0
  isc_mem_detach(&mctx);
721
0
}
722
723
/*
724
 * Returns true iff this the signed side of an inline-signing zone.
725
 * Caller should hold zone lock.
726
 */
727
bool
728
0
dns__zone_inline_secure(dns_zone_t *zone) {
729
0
  REQUIRE(DNS_ZONE_VALID(zone));
730
0
  REQUIRE(LOCKED_ZONE(zone));
731
0
  if (zone->raw != NULL) {
732
0
    return true;
733
0
  }
734
0
  return false;
735
0
}
736
737
/*
738
 * Returns true iff this the unsigned side of an inline-signing zone
739
 * Caller should hold zone lock.
740
 */
741
bool
742
0
dns__zone_inline_raw(dns_zone_t *zone) {
743
0
  REQUIRE(DNS_ZONE_VALID(zone));
744
0
  REQUIRE(LOCKED_ZONE(zone));
745
0
  if (zone->secure != NULL) {
746
0
    return true;
747
0
  }
748
0
  return false;
749
0
}
750
751
isc_result_t
752
0
dns_zone_getserial(dns_zone_t *zone, uint32_t *serialp) {
753
0
  isc_result_t result;
754
0
  unsigned int soacount;
755
756
0
  REQUIRE(DNS_ZONE_VALID(zone));
757
0
  REQUIRE(serialp != NULL);
758
759
0
  LOCK_ZONE(zone);
760
0
  ZONEDB_LOCK(&zone->dblock, isc_rwlocktype_read);
761
0
  if (zone->db != NULL) {
762
0
    result = zone_get_from_db(zone, zone->db, NULL, &soacount, NULL,
763
0
            serialp, NULL, NULL, NULL, NULL,
764
0
            NULL);
765
0
    if (result == ISC_R_SUCCESS && soacount == 0) {
766
0
      result = ISC_R_FAILURE;
767
0
    }
768
0
  } else {
769
0
    result = DNS_R_NOTLOADED;
770
0
  }
771
0
  ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_read);
772
0
  UNLOCK_ZONE(zone);
773
774
0
  return result;
775
0
}
776
777
isc_result_t
778
0
dns_zone_getzoneversion(dns_zone_t *zone, isc_buffer_t *b) {
779
0
  isc_result_t result = DNS_R_NOTLOADED;
780
0
  unsigned int soacount;
781
0
  uint32_t serial;
782
0
  dns_zone_t *mayberaw = zone;
783
784
0
  REQUIRE(DNS_ZONE_VALID(zone));
785
0
  REQUIRE(b != NULL);
786
787
0
  LOCK_ZONE(zone);
788
0
  if (zone->raw != NULL) {
789
0
    LOCK_ZONE(zone->raw);
790
0
    mayberaw = zone->raw;
791
0
  }
792
0
  ZONEDB_LOCK(&mayberaw->dblock, isc_rwlocktype_read);
793
0
  if (DNS_ZONE_OPTION(mayberaw, DNS_ZONEOPT_ZONEVERSION) &&
794
0
      mayberaw->db != NULL)
795
0
  {
796
0
    result = dns_db_getzoneversion(mayberaw->db, b);
797
0
    if (result == ISC_R_NOTIMPLEMENTED) {
798
0
      result = zone_get_from_db(mayberaw, mayberaw->db, NULL,
799
0
              &soacount, NULL, &serial,
800
0
              NULL, NULL, NULL, NULL, NULL);
801
0
      if (result == ISC_R_SUCCESS && soacount == 0) {
802
0
        result = ISC_R_FAILURE;
803
0
      }
804
0
      if (result == ISC_R_SUCCESS) {
805
0
        if (isc_buffer_availablelength(b) >= 6) {
806
0
          isc_buffer_putuint8(
807
0
            b, dns_name_countlabels(
808
0
                 &mayberaw->origin) -
809
0
                 1);
810
0
          isc_buffer_putuint8(b, 0);
811
0
          isc_buffer_putuint32(b, serial);
812
0
        } else {
813
0
          result = ISC_R_NOSPACE;
814
0
        }
815
0
      }
816
0
    }
817
0
  }
818
0
  ZONEDB_UNLOCK(&mayberaw->dblock, isc_rwlocktype_read);
819
0
  if (zone->raw != NULL) {
820
0
    UNLOCK_ZONE(zone->raw);
821
0
  }
822
0
  UNLOCK_ZONE(zone);
823
824
0
  return result;
825
0
}
826
827
void
828
0
dns__zone_freedbargs(dns_zone_t *zone) {
829
0
  unsigned int i;
830
831
  /* Free the old database argument list. */
832
0
  if (zone->db_argv != NULL) {
833
0
    for (i = 0; i < zone->db_argc; i++) {
834
0
      isc_mem_free(zone->mctx, zone->db_argv[i]);
835
0
    }
836
0
    isc_mem_cput(zone->mctx, zone->db_argv, zone->db_argc,
837
0
           sizeof(*zone->db_argv));
838
0
  }
839
0
  zone->db_argc = 0;
840
0
  zone->db_argv = NULL;
841
0
}
842
843
void
844
0
dns__zone_setview_helper(dns_zone_t *zone, dns_view_t *view) {
845
0
  dns__viewname_set(&zone->viewname, zone->mctx, view->name);
846
0
  if (zone->prev_view == NULL && zone->view != NULL) {
847
0
    dns_view_weakattach(zone->view, &zone->prev_view);
848
0
  }
849
850
0
  INSIST(zone != zone->raw);
851
0
  if (zone->view != NULL) {
852
0
    dns_view_sfd_del(zone->view, &zone->origin);
853
0
    dns_view_weakdetach(&zone->view);
854
0
  }
855
0
  dns_view_weakattach(view, &zone->view);
856
0
  dns_view_sfd_add(view, &zone->origin);
857
858
0
  if (dns__zone_inline_secure(zone)) {
859
0
    dns_zone_setview(zone->raw, view);
860
0
  }
861
0
}
862
863
void
864
0
dns_zone_setviewcommit(dns_zone_t *zone) {
865
0
  REQUIRE(DNS_ZONE_VALID(zone));
866
867
0
  LOCK_ZONE(zone);
868
0
  if (zone->prev_view != NULL) {
869
0
    dns_view_weakdetach(&zone->prev_view);
870
0
  }
871
0
  if (dns__zone_inline_secure(zone)) {
872
0
    dns_zone_setviewcommit(zone->raw);
873
0
  }
874
0
  UNLOCK_ZONE(zone);
875
0
}
876
877
void
878
0
dns_zone_setviewrevert(dns_zone_t *zone) {
879
0
  REQUIRE(DNS_ZONE_VALID(zone));
880
881
0
  LOCK_ZONE(zone);
882
0
  if (zone->prev_view != NULL) {
883
0
    dns__zone_setview_helper(zone, zone->prev_view);
884
0
    dns_view_weakdetach(&zone->prev_view);
885
0
  }
886
0
  if (zone->catzs != NULL) {
887
0
    zone_catz_enable(zone, zone->catzs);
888
0
  }
889
0
  if (dns__zone_inline_secure(zone)) {
890
0
    dns_zone_setviewrevert(zone->raw);
891
0
  }
892
0
  UNLOCK_ZONE(zone);
893
0
}
894
895
/*
896
 * Return true iff the zone is "dynamic", in the sense that the zone's
897
 * master file (if any) is written by the server, rather than being
898
 * updated manually and read by the server.
899
 *
900
 * This is true for secondary zones, mirror zones, stub zones, key zones,
901
 * and zones that allow dynamic updates either by having an update
902
 * policy ("ssutable") or an "allow-update" ACL with a value other than
903
 * exactly "{ none; }".
904
 */
905
bool
906
0
dns_zone_isdynamic(dns_zone_t *zone, bool ignore_freeze) {
907
0
  REQUIRE(DNS_ZONE_VALID(zone));
908
909
0
  if (zone->type == dns_zone_secondary || zone->type == dns_zone_mirror ||
910
0
      zone->type == dns_zone_stub || zone->type == dns_zone_key ||
911
0
      (zone->type == dns_zone_redirect &&
912
0
       dns_remote_addresses(&zone->primaries) != NULL))
913
0
  {
914
0
    return true;
915
0
  }
916
917
  /* Inline zones are always dynamic. */
918
0
  if (zone->type == dns_zone_primary && zone->raw != NULL) {
919
0
    return true;
920
0
  }
921
922
  /* If !ignore_freeze, we need check whether updates are disabled.  */
923
0
  if (zone->type == dns_zone_primary &&
924
0
      (!zone->update_disabled || ignore_freeze) &&
925
0
      ((zone->ssutable != NULL) ||
926
0
       (zone->update_acl != NULL && !dns_acl_isnone(zone->update_acl))))
927
0
  {
928
0
    return true;
929
0
  }
930
931
0
  return false;
932
0
}
933
934
/*
935
 * Set the response policy index and information for a zone.
936
 */
937
isc_result_t
938
dns_zone_rpz_enable(dns_zone_t *zone, dns_rpz_zones_t *rpzs,
939
0
        dns_rpz_num_t rpz_num) {
940
  /*
941
   * This must happen only once or be redundant.
942
   */
943
0
  LOCK_ZONE(zone);
944
0
  if (zone->rpzs != NULL) {
945
0
    REQUIRE(zone->rpzs == rpzs && zone->rpz_num == rpz_num);
946
0
  } else {
947
0
    REQUIRE(zone->rpz_num == DNS_RPZ_INVALID_NUM);
948
0
    dns_rpz_zones_attach(rpzs, &zone->rpzs);
949
0
    zone->rpz_num = rpz_num;
950
0
  }
951
0
  rpzs->defined |= DNS_RPZ_ZBIT(rpz_num);
952
0
  UNLOCK_ZONE(zone);
953
954
0
  return ISC_R_SUCCESS;
955
0
}
956
957
dns_rpz_num_t
958
0
dns_zone_get_rpz_num(dns_zone_t *zone) {
959
0
  return zone->rpz_num;
960
0
}
961
962
/*
963
 * If a zone is a response policy zone, mark its new database.
964
 */
965
void
966
0
dns_zone_rpz_enable_db(dns_zone_t *zone, dns_db_t *db) {
967
0
  if (zone->rpz_num == DNS_RPZ_INVALID_NUM) {
968
0
    return;
969
0
  }
970
0
  REQUIRE(zone->rpzs != NULL);
971
0
  dns_rpz_dbupdate_register(db, zone->rpzs->zones[zone->rpz_num]);
972
0
}
973
974
static void
975
0
dns_zone_rpz_disable_db(dns_zone_t *zone, dns_db_t *db) {
976
0
  if (zone->rpz_num == DNS_RPZ_INVALID_NUM) {
977
0
    return;
978
0
  }
979
0
  REQUIRE(zone->rpzs != NULL);
980
0
  dns_rpz_dbupdate_unregister(db, zone->rpzs->zones[zone->rpz_num]);
981
0
}
982
983
/*
984
 * If a zone is a catalog zone, attach it to update notification in database.
985
 */
986
void
987
0
dns_zone_catz_enable_db(dns_zone_t *zone, dns_db_t *db) {
988
0
  REQUIRE(DNS_ZONE_VALID(zone));
989
0
  REQUIRE(db != NULL);
990
991
0
  if (zone->catzs != NULL) {
992
0
    dns_catz_dbupdate_register(db, zone->catzs);
993
0
  }
994
0
}
995
996
static void
997
0
dns_zone_catz_disable_db(dns_zone_t *zone, dns_db_t *db) {
998
0
  REQUIRE(DNS_ZONE_VALID(zone));
999
0
  REQUIRE(db != NULL);
1000
1001
0
  if (zone->catzs != NULL) {
1002
0
    dns_catz_dbupdate_unregister(db, zone->catzs);
1003
0
  }
1004
0
}
1005
1006
static void
1007
0
zone_catz_enable(dns_zone_t *zone, dns_catz_zones_t *catzs) {
1008
0
  REQUIRE(DNS_ZONE_VALID(zone));
1009
0
  REQUIRE(catzs != NULL);
1010
1011
0
  INSIST(zone->catzs == NULL || zone->catzs == catzs);
1012
0
  dns_catz_catzs_set_view(catzs, zone->view);
1013
0
  if (zone->catzs == NULL) {
1014
0
    dns_catz_zones_attach(catzs, &zone->catzs);
1015
0
  }
1016
0
}
1017
1018
void
1019
0
dns_zone_catz_enable(dns_zone_t *zone, dns_catz_zones_t *catzs) {
1020
0
  REQUIRE(DNS_ZONE_VALID(zone));
1021
1022
0
  LOCK_ZONE(zone);
1023
0
  zone_catz_enable(zone, catzs);
1024
0
  UNLOCK_ZONE(zone);
1025
0
}
1026
1027
static void
1028
0
zone_catz_disable(dns_zone_t *zone) {
1029
0
  REQUIRE(DNS_ZONE_VALID(zone));
1030
1031
0
  if (zone->catzs != NULL) {
1032
0
    if (zone->db != NULL) {
1033
0
      dns_zone_catz_disable_db(zone, zone->db);
1034
0
    }
1035
0
    dns_catz_zones_detach(&zone->catzs);
1036
0
  }
1037
0
}
1038
1039
void
1040
0
dns_zone_catz_disable(dns_zone_t *zone) {
1041
0
  REQUIRE(DNS_ZONE_VALID(zone));
1042
1043
0
  LOCK_ZONE(zone);
1044
0
  zone_catz_disable(zone);
1045
0
  UNLOCK_ZONE(zone);
1046
0
}
1047
1048
bool
1049
0
dns_zone_catz_is_enabled(dns_zone_t *zone) {
1050
0
  REQUIRE(DNS_ZONE_VALID(zone));
1051
1052
0
  return zone->catzs != NULL;
1053
0
}
1054
1055
/*
1056
 * Set catalog zone ownership of the zone
1057
 */
1058
void
1059
0
dns_zone_set_parentcatz(dns_zone_t *zone, dns_catz_zone_t *catz) {
1060
0
  REQUIRE(DNS_ZONE_VALID(zone));
1061
0
  REQUIRE(catz != NULL);
1062
0
  LOCK_ZONE(zone);
1063
0
  INSIST(zone->parentcatz == NULL || zone->parentcatz == catz);
1064
0
  zone->parentcatz = catz;
1065
0
  UNLOCK_ZONE(zone);
1066
0
}
1067
1068
dns_catz_zone_t *
1069
0
dns_zone_get_parentcatz(dns_zone_t *zone) {
1070
0
  REQUIRE(DNS_ZONE_VALID(zone));
1071
1072
0
  dns_catz_zone_t *parentcatz = NULL;
1073
1074
0
  LOCK_ZONE(zone);
1075
0
  parentcatz = zone->parentcatz;
1076
0
  UNLOCK_ZONE(zone);
1077
1078
0
  return parentcatz;
1079
0
}
1080
1081
static bool
1082
0
zone_touched(dns_zone_t *zone) {
1083
0
  isc_result_t result;
1084
0
  isc_time_t modtime;
1085
1086
0
  REQUIRE(DNS_ZONE_VALID(zone));
1087
1088
0
  result = isc_file_getmodtime(zone->masterfile, &modtime);
1089
0
  if (result != ISC_R_SUCCESS ||
1090
0
      isc_time_compare(&modtime, &zone->loadtime) > 0)
1091
0
  {
1092
0
    return true;
1093
0
  }
1094
1095
0
  ISC_LIST_FOREACH(zone->includes, include, link) {
1096
0
    result = isc_file_getmodtime(include->name, &modtime);
1097
0
    if (result != ISC_R_SUCCESS ||
1098
0
        isc_time_compare(&modtime, &include->filetime) > 0)
1099
0
    {
1100
0
      return true;
1101
0
    }
1102
0
  }
1103
1104
0
  return false;
1105
0
}
1106
1107
static isc_result_t
1108
0
copy_initfile(dns_zone_t *zone) {
1109
0
  isc_result_t result;
1110
0
  FILE *input = NULL, *output = NULL;
1111
0
  off_t len;
1112
1113
0
  CHECK(isc_stdio_open(zone->initfile, "r", &input));
1114
0
  CHECK(isc_stdio_open(zone->masterfile, "w", &output));
1115
1116
0
  CHECK(isc_file_getsizefd(fileno(input), &len));
1117
1118
0
  do {
1119
0
    char buf[BUFSIZ];
1120
0
    size_t rval;
1121
1122
0
    result = isc_stdio_read(buf, 1, sizeof(buf), input, &rval);
1123
0
    if (result != ISC_R_EOF) {
1124
0
      CHECK(result);
1125
0
    }
1126
0
    CHECK(isc_stdio_write(buf, rval, 1, output, NULL));
1127
0
    len -= rval;
1128
0
  } while (len > 0);
1129
1130
0
cleanup:
1131
0
  if (input != NULL) {
1132
0
    isc_stdio_close(input);
1133
0
  }
1134
0
  if (output != NULL) {
1135
0
    if (result != ISC_R_SUCCESS) {
1136
0
      isc_file_remove(zone->masterfile);
1137
0
    }
1138
0
    isc_stdio_close(output);
1139
0
  }
1140
0
  return result;
1141
0
}
1142
1143
/*
1144
 * Note: when dealing with inline-signed zones, external callers will always
1145
 * call zone_load() for the secure zone; zone_load() calls itself recursively
1146
 * in order to load the raw zone.
1147
 */
1148
static isc_result_t
1149
0
zone_load(dns_zone_t *zone, unsigned int flags, bool locked) {
1150
0
  isc_result_t result;
1151
0
  isc_time_t now;
1152
0
  isc_time_t loadtime;
1153
0
  dns_db_t *db = NULL;
1154
0
  bool rbt, hasraw, is_dynamic;
1155
1156
0
  REQUIRE(DNS_ZONE_VALID(zone));
1157
1158
0
  if (!locked) {
1159
0
    LOCK_ZONE(zone);
1160
0
  }
1161
1162
0
  INSIST(zone != zone->raw);
1163
0
  hasraw = dns__zone_inline_secure(zone);
1164
0
  if (hasraw) {
1165
    /*
1166
     * We are trying to load an inline-signed zone.  First call
1167
     * self recursively to try loading the raw version of the zone.
1168
     * Assuming the raw zone file is readable, there are two
1169
     * possibilities:
1170
     *
1171
     *  a) the raw zone was not yet loaded and thus it will be
1172
     *     loaded now, synchronously; if this succeeds, a
1173
     *     subsequent attempt to load the signed zone file will
1174
     *     take place and thus zone_postload() will be called
1175
     *     twice: first for the raw zone and then for the secure
1176
     *     zone; the latter call will be followed by scheduling
1177
     *     secure maintenance to sync against the raw version,
1178
     *
1179
     *  b) the raw zone was already loaded and we are trying to
1180
     *     reload it, which will happen asynchronously; this means
1181
     *     zone_postload() will only be called for the raw zone
1182
     *     because "result" returned by the zone_load() call below
1183
     *     will not be ISC_R_SUCCESS but rather DNS_R_CONTINUE;
1184
     *     zone_postload() called for the raw zone will schedule
1185
     *     secure maintenance to sync against the raw version.
1186
     */
1187
0
    result = zone_load(zone->raw, flags, false);
1188
0
    if (result != ISC_R_SUCCESS) {
1189
0
      if (!locked) {
1190
0
        UNLOCK_ZONE(zone);
1191
0
      }
1192
0
      return result;
1193
0
    }
1194
0
  }
1195
1196
0
  now = isc_time_now();
1197
1198
0
  INSIST(zone->type != dns_zone_none);
1199
1200
  /* load was already in progress */
1201
0
  if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_LOADING)) {
1202
0
    if ((flags & DNS_ZONELOADFLAG_THAW) != 0) {
1203
0
      DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_THAW);
1204
0
    }
1205
0
    CLEANUP(ISC_R_LOADING);
1206
0
  }
1207
1208
0
  INSIST(zone->db_argc >= 1);
1209
1210
0
  rbt = strcmp(zone->db_argv[0], ZONEDB_DEFAULT) == 0;
1211
1212
0
  if (zone->db != NULL && zone->masterfile == NULL && rbt) {
1213
    /*
1214
     * The zone has no master file configured.
1215
     */
1216
0
    result = ISC_R_SUCCESS;
1217
0
    goto cleanup;
1218
0
  }
1219
1220
0
  is_dynamic = dns_zone_isdynamic(zone, false);
1221
0
  if (zone->db != NULL && is_dynamic) {
1222
    /*
1223
     * This is a secondary, stub, or dynamically updated zone
1224
     * being reloaded.  Do nothing - the database we already
1225
     * have is guaranteed to be up-to-date.
1226
     */
1227
0
    if (zone->type == dns_zone_primary && !hasraw) {
1228
0
      result = DNS_R_DYNAMIC;
1229
0
    } else {
1230
0
      result = ISC_R_SUCCESS;
1231
0
    }
1232
0
    goto cleanup;
1233
0
  }
1234
1235
  /*
1236
   * Store the current time before the zone is loaded, so that if the
1237
   * file changes between the time of the load and the time that
1238
   * zone->loadtime is set, then the file will still be reloaded
1239
   * the next time dns_zone_load is called.
1240
   */
1241
0
  loadtime = isc_time_now();
1242
1243
  /*
1244
   * Don't do the load if the file that stores the zone is older
1245
   * than the last time the zone was loaded.  If the zone has not
1246
   * been loaded yet, zone->loadtime will be the epoch.
1247
   */
1248
0
  if (zone->masterfile != NULL) {
1249
0
    isc_time_t filetime;
1250
1251
    /*
1252
     * The file is already loaded.  If we are just doing a
1253
     * "rndc reconfig", we are done.
1254
     */
1255
0
    if (!isc_time_isepoch(&zone->loadtime) &&
1256
0
        (flags & DNS_ZONELOADFLAG_NOSTAT) != 0)
1257
0
    {
1258
0
      result = ISC_R_SUCCESS;
1259
0
      goto cleanup;
1260
0
    }
1261
1262
0
    if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_LOADED) &&
1263
0
        !zone_touched(zone))
1264
0
    {
1265
0
      dns_zone_logc(zone, DNS_LOGCATEGORY_ZONELOAD,
1266
0
              ISC_LOG_DEBUG(1),
1267
0
              "skipping load: master file "
1268
0
              "older than last load");
1269
0
      CLEANUP(DNS_R_UPTODATE);
1270
0
    }
1271
1272
    /*
1273
     * If the file modification time is in the past
1274
     * set loadtime to that value.
1275
     */
1276
0
    result = isc_file_getmodtime(zone->masterfile, &filetime);
1277
0
    if (result == ISC_R_SUCCESS &&
1278
0
        isc_time_compare(&loadtime, &filetime) > 0)
1279
0
    {
1280
0
      loadtime = filetime;
1281
0
    }
1282
0
  }
1283
1284
  /*
1285
   * Built in zones (with the exception of empty zones) don't need
1286
   * to be reloaded.
1287
   */
1288
0
  if (zone->type == dns_zone_primary &&
1289
0
      strcmp(zone->db_argv[0], "_builtin") == 0 &&
1290
0
      (zone->db_argc < 2 || strcmp(zone->db_argv[1], "empty") != 0) &&
1291
0
      DNS_ZONE_FLAG(zone, DNS_ZONEFLG_LOADED))
1292
0
  {
1293
0
    result = ISC_R_SUCCESS;
1294
0
    goto cleanup;
1295
0
  }
1296
1297
  /*
1298
   * Zones associated with a DLZ don't need to be loaded either,
1299
   * but we need to associate the database with the zone object.
1300
   */
1301
0
  if (strcmp(zone->db_argv[0], "dlz") == 0) {
1302
0
    dns_dlzdb_t *dlzdb = NULL;
1303
0
    dns_dlzfindzone_t findzone;
1304
1305
0
    ISC_LIST_FOREACH(zone->view->dlz_unsearched, d, link) {
1306
0
      INSIST(DNS_DLZ_VALID(d));
1307
0
      if (strcmp(zone->db_argv[1], d->dlzname) == 0) {
1308
0
        dlzdb = d;
1309
0
        break;
1310
0
      }
1311
0
    }
1312
1313
0
    if (dlzdb == NULL) {
1314
0
      dns_zone_logc(zone, DNS_LOGCATEGORY_ZONELOAD,
1315
0
              ISC_LOG_ERROR,
1316
0
              "DLZ %s does not exist or is set "
1317
0
              "to 'search yes;'",
1318
0
              zone->db_argv[1]);
1319
0
      CLEANUP(ISC_R_NOTFOUND);
1320
0
    }
1321
1322
0
    ZONEDB_LOCK(&zone->dblock, isc_rwlocktype_write);
1323
    /* ask SDLZ driver if the zone is supported */
1324
0
    findzone = dlzdb->implementation->methods->findzone;
1325
0
    result = (*findzone)(dlzdb->implementation->driverarg,
1326
0
             dlzdb->dbdata, dlzdb->mctx,
1327
0
             zone->view->rdclass, &zone->origin, NULL,
1328
0
             NULL, &db);
1329
0
    if (result != ISC_R_NOTFOUND) {
1330
0
      if (zone->db != NULL) {
1331
0
        zone_detachdb(zone);
1332
0
      }
1333
0
      zone_attachdb(zone, db);
1334
0
      dns_db_detach(&db);
1335
0
      result = ISC_R_SUCCESS;
1336
0
    }
1337
0
    ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_write);
1338
1339
0
    if (result == ISC_R_SUCCESS) {
1340
0
      if (dlzdb->configure_callback == NULL) {
1341
0
        goto cleanup;
1342
0
      }
1343
1344
0
      result = (*dlzdb->configure_callback)(zone->view, dlzdb,
1345
0
                    zone);
1346
0
      if (result != ISC_R_SUCCESS) {
1347
0
        dns_zone_logc(zone, DNS_LOGCATEGORY_ZONELOAD,
1348
0
                ISC_LOG_ERROR,
1349
0
                "DLZ configuration callback: %s",
1350
0
                isc_result_totext(result));
1351
0
      }
1352
0
    }
1353
0
    goto cleanup;
1354
0
  }
1355
1356
0
  if ((zone->type == dns_zone_secondary ||
1357
0
       zone->type == dns_zone_mirror || zone->type == dns_zone_stub ||
1358
0
       (zone->type == dns_zone_redirect &&
1359
0
        dns_remote_addresses(&zone->primaries) != NULL)) &&
1360
0
      rbt)
1361
0
  {
1362
0
    DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_FIRSTREFRESH);
1363
1364
0
    if (zone->stream == NULL &&
1365
0
        (zone->masterfile == NULL ||
1366
0
         !isc_file_exists(zone->masterfile)))
1367
0
    {
1368
0
      if (zone->masterfile != NULL) {
1369
0
        dns_zone_logc(zone, DNS_LOGCATEGORY_ZONELOAD,
1370
0
                ISC_LOG_DEBUG(1),
1371
0
                "no master file");
1372
0
      }
1373
0
      zone->refreshtime = now;
1374
0
      if (zone->loop != NULL) {
1375
0
        dns__zone_settimer(zone, now);
1376
0
      }
1377
0
      result = ISC_R_SUCCESS;
1378
0
      goto cleanup;
1379
0
    }
1380
0
  }
1381
1382
0
  if (zone->type == dns_zone_primary && zone->masterfile != NULL &&
1383
0
      !isc_file_exists(zone->masterfile) && zone->initfile != NULL)
1384
0
  {
1385
0
    dns_zone_logc(zone, DNS_LOGCATEGORY_ZONELOAD, ISC_LOG_INFO,
1386
0
            "zone file %s not found; copying initial "
1387
0
            "file %s",
1388
0
            zone->masterfile, zone->initfile);
1389
0
    result = copy_initfile(zone);
1390
0
    if (result != ISC_R_SUCCESS) {
1391
0
      dns_zone_logc(zone, DNS_LOGCATEGORY_ZONELOAD,
1392
0
              ISC_LOG_ERROR, "copy from %s failed: %s",
1393
0
              zone->initfile,
1394
0
              isc_result_totext(result));
1395
0
    }
1396
0
  }
1397
1398
0
  dns_zone_logc(zone, DNS_LOGCATEGORY_ZONELOAD, ISC_LOG_DEBUG(1),
1399
0
          "starting load");
1400
1401
0
  result = dns_zone_makedb(zone, &db);
1402
0
  if (result != ISC_R_SUCCESS) {
1403
0
    dns_zone_logc(zone, DNS_LOGCATEGORY_ZONELOAD, ISC_LOG_ERROR,
1404
0
            "loading zone: creating database: %s",
1405
0
            isc_result_totext(result));
1406
0
    goto cleanup;
1407
0
  }
1408
1409
0
  if (!dns_db_ispersistent(db)) {
1410
0
    if (zone->masterfile != NULL || zone->stream != NULL) {
1411
0
      result = zone_startload(db, zone, loadtime);
1412
0
    } else {
1413
0
      result = DNS_R_NOMASTERFILE;
1414
0
      if (zone->type == dns_zone_primary ||
1415
0
          (zone->type == dns_zone_redirect &&
1416
0
           dns_remote_addresses(&zone->primaries) == NULL))
1417
0
      {
1418
0
        dns_zone_logc(zone, DNS_LOGCATEGORY_ZONELOAD,
1419
0
                ISC_LOG_ERROR,
1420
0
                "loading zone: "
1421
0
                "no master file configured");
1422
0
        goto cleanup;
1423
0
      }
1424
0
      dns_zone_logc(zone, DNS_LOGCATEGORY_ZONELOAD,
1425
0
              ISC_LOG_INFO,
1426
0
              "loading zone: "
1427
0
              "no master file configured: continuing");
1428
0
    }
1429
0
  }
1430
1431
0
  if (result == DNS_R_CONTINUE) {
1432
0
    DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_LOADING);
1433
0
    if ((flags & DNS_ZONELOADFLAG_THAW) != 0) {
1434
0
      DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_THAW);
1435
0
    }
1436
0
    goto cleanup;
1437
0
  }
1438
1439
0
  result = zone_postload(zone, db, loadtime, result);
1440
0
  if (hasraw && result == ISC_R_SUCCESS) {
1441
0
    zone_schedule_inline_sync(zone, inline_sync_incremental);
1442
0
  }
1443
1444
0
cleanup:
1445
0
  if (!locked) {
1446
0
    UNLOCK_ZONE(zone);
1447
0
  }
1448
0
  if (db != NULL) {
1449
0
    dns_db_detach(&db);
1450
0
  }
1451
0
  return result;
1452
0
}
1453
1454
isc_result_t
1455
0
dns_zone_load(dns_zone_t *zone, bool newonly) {
1456
0
  return zone_load(zone, newonly ? DNS_ZONELOADFLAG_NOSTAT : 0, false);
1457
0
}
1458
1459
static void
1460
0
zone_asyncload(void *arg) {
1461
0
  dns_asyncload_t *asl = arg;
1462
0
  dns_zone_t *zone = asl->zone;
1463
0
  isc_result_t result;
1464
1465
0
  REQUIRE(DNS_ZONE_VALID(zone));
1466
1467
0
  LOCK_ZONE(zone);
1468
0
  result = zone_load(zone, asl->flags, true);
1469
0
  if (result != DNS_R_CONTINUE && result != ISC_R_LOADING) {
1470
0
    DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_LOADPENDING);
1471
0
  }
1472
0
  UNLOCK_ZONE(zone);
1473
1474
  /* Inform the zone table we've finished loading */
1475
0
  if (asl->loaded != NULL) {
1476
0
    asl->loaded(asl->loaded_arg);
1477
0
  }
1478
1479
0
  isc_mem_put(zone->mctx, asl, sizeof(*asl));
1480
0
  dns_zone_idetach(&zone);
1481
0
}
1482
1483
isc_result_t
1484
dns_zone_asyncload(dns_zone_t *zone, bool newonly, dns_zt_callback_t *done,
1485
0
       void *arg) {
1486
0
  dns_asyncload_t *asl = NULL;
1487
1488
0
  REQUIRE(DNS_ZONE_VALID(zone));
1489
1490
0
  if (zone->loop == NULL) {
1491
0
    return ISC_R_FAILURE;
1492
0
  }
1493
1494
  /* If we already have a load pending, stop now */
1495
0
  LOCK_ZONE(zone);
1496
0
  if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_LOADPENDING)) {
1497
0
    UNLOCK_ZONE(zone);
1498
0
    return ISC_R_ALREADYRUNNING;
1499
0
  }
1500
1501
0
  asl = isc_mem_get(zone->mctx, sizeof(*asl));
1502
1503
0
  asl->zone = NULL;
1504
0
  asl->flags = newonly ? DNS_ZONELOADFLAG_NOSTAT : 0;
1505
0
  asl->loaded = done;
1506
0
  asl->loaded_arg = arg;
1507
1508
0
  zone_iattach(zone, &asl->zone);
1509
0
  DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_LOADPENDING);
1510
0
  isc_async_run(zone->loop, zone_asyncload, asl);
1511
0
  UNLOCK_ZONE(zone);
1512
1513
0
  return ISC_R_SUCCESS;
1514
0
}
1515
1516
bool
1517
0
dns__zone_loadpending(dns_zone_t *zone) {
1518
0
  REQUIRE(DNS_ZONE_VALID(zone));
1519
1520
0
  return DNS_ZONE_FLAG(zone, DNS_ZONEFLG_LOADPENDING);
1521
0
}
1522
1523
isc_result_t
1524
0
dns_zone_loadandthaw(dns_zone_t *zone) {
1525
0
  isc_result_t result;
1526
0
  bool inline_raw;
1527
1528
0
  LOCK_ZONE(zone);
1529
0
  inline_raw = dns__zone_inline_raw(zone);
1530
0
  UNLOCK_ZONE(zone);
1531
1532
0
  if (inline_raw) {
1533
0
    result = zone_load(zone->secure, DNS_ZONELOADFLAG_THAW, false);
1534
0
  } else {
1535
    /*
1536
     * When thawing a zone, we don't know what changes
1537
     * have been made. If we do DNSSEC maintenance on this
1538
     * zone, schedule a full sign for this zone.
1539
     */
1540
0
    if (zone->type == dns_zone_primary && zone->kasp != NULL) {
1541
0
      DNS_ZONE_SETOPTION(zone, DNS_ZONEOPT_FULLSIGN);
1542
0
    }
1543
0
    result = zone_load(zone, DNS_ZONELOADFLAG_THAW, false);
1544
0
  }
1545
1546
0
  switch (result) {
1547
0
  case DNS_R_CONTINUE:
1548
0
  case ISC_R_LOADING:
1549
    /* Deferred thaw. */
1550
0
    break;
1551
0
  case DNS_R_UPTODATE:
1552
0
  case ISC_R_SUCCESS:
1553
0
  case DNS_R_SEENINCLUDE:
1554
0
    zone->update_disabled = false;
1555
0
    break;
1556
0
  case DNS_R_NOMASTERFILE:
1557
0
    zone->update_disabled = false;
1558
0
    break;
1559
0
  default:
1560
    /* Error, remain in disabled state. */
1561
0
    break;
1562
0
  }
1563
0
  return result;
1564
0
}
1565
1566
static unsigned int
1567
0
get_primary_options(dns_zone_t *zone) {
1568
0
  unsigned int options;
1569
1570
0
  options = DNS_MASTER_ZONE | DNS_MASTER_RESIGN;
1571
0
  if (zone->type == dns_zone_secondary || zone->type == dns_zone_mirror ||
1572
0
      (zone->type == dns_zone_redirect &&
1573
0
       dns_remote_addresses(&zone->primaries) == NULL))
1574
0
  {
1575
0
    options |= DNS_MASTER_SECONDARY;
1576
0
  }
1577
0
  if (zone->type == dns_zone_key) {
1578
0
    options |= DNS_MASTER_KEY;
1579
0
  }
1580
0
  if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_CHECKNS)) {
1581
0
    options |= DNS_MASTER_CHECKNS;
1582
0
  }
1583
0
  if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_FATALNS)) {
1584
0
    options |= DNS_MASTER_FATALNS;
1585
0
  }
1586
0
  if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_CHECKNAMES)) {
1587
0
    options |= DNS_MASTER_CHECKNAMES;
1588
0
  }
1589
0
  if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_CHECKNAMESFAIL)) {
1590
0
    options |= DNS_MASTER_CHECKNAMESFAIL;
1591
0
  }
1592
0
  if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_CHECKMX)) {
1593
0
    options |= DNS_MASTER_CHECKMX;
1594
0
  }
1595
0
  if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_CHECKMXFAIL)) {
1596
0
    options |= DNS_MASTER_CHECKMXFAIL;
1597
0
  }
1598
0
  if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_CHECKWILDCARD)) {
1599
0
    options |= DNS_MASTER_CHECKWILDCARD;
1600
0
  }
1601
0
  if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_CHECKTTL)) {
1602
0
    options |= DNS_MASTER_CHECKTTL;
1603
0
  }
1604
0
  if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_CHECKSVCB)) {
1605
0
    options |= DNS_MASTER_CHECKSVCB;
1606
0
  }
1607
1608
0
  return options;
1609
0
}
1610
1611
static void
1612
0
zone_registerinclude(const char *filename, void *arg) {
1613
0
  isc_result_t result;
1614
0
  dns_zone_t *zone = (dns_zone_t *)arg;
1615
1616
0
  REQUIRE(DNS_ZONE_VALID(zone));
1617
1618
0
  if (filename == NULL) {
1619
0
    return;
1620
0
  }
1621
1622
  /*
1623
   * Suppress duplicates.
1624
   */
1625
0
  ISC_LIST_FOREACH(zone->newincludes, inc, link) {
1626
0
    if (strcmp(filename, inc->name) == 0) {
1627
0
      return;
1628
0
    }
1629
0
  }
1630
1631
0
  dns_include_t *inc = isc_mem_get(zone->mctx, sizeof(dns_include_t));
1632
0
  inc->name = isc_mem_strdup(zone->mctx, filename);
1633
0
  ISC_LINK_INIT(inc, link);
1634
1635
0
  result = isc_file_getmodtime(filename, &inc->filetime);
1636
0
  if (result != ISC_R_SUCCESS) {
1637
0
    isc_time_settoepoch(&inc->filetime);
1638
0
  }
1639
1640
0
  ISC_LIST_APPEND(zone->newincludes, inc, link);
1641
0
}
1642
1643
static void
1644
0
get_raw_serial(dns_zone_t *raw, dns_masterrawheader_t *rawdata) {
1645
0
  isc_result_t result;
1646
0
  unsigned int soacount;
1647
1648
0
  LOCK(&raw->lock);
1649
0
  if (raw->db != NULL) {
1650
0
    result = zone_get_from_db(raw, raw->db, NULL, &soacount, NULL,
1651
0
            &rawdata->sourceserial, NULL, NULL,
1652
0
            NULL, NULL, NULL);
1653
0
    if (result == ISC_R_SUCCESS && soacount > 0U) {
1654
0
      rawdata->flags |= DNS_MASTERRAW_SOURCESERIALSET;
1655
0
    }
1656
0
  }
1657
0
  UNLOCK(&raw->lock);
1658
0
}
1659
1660
/*
1661
 * Save the raw serial number for inline-signing zones.
1662
 * (XXX: Other information from the header will be used
1663
 * for other purposes in the future, but for now this is
1664
 * all we're interested in.)
1665
 */
1666
static void
1667
0
zone_setrawdata(dns_zone_t *zone, dns_masterrawheader_t *header) {
1668
0
  if ((header->flags & DNS_MASTERRAW_SOURCESERIALSET) == 0) {
1669
0
    return;
1670
0
  }
1671
1672
0
  zone->sourceserial = header->sourceserial;
1673
0
  zone->sourceserialset = true;
1674
0
}
1675
1676
void
1677
0
dns_zone_setrawdata(dns_zone_t *zone, dns_masterrawheader_t *header) {
1678
0
  if (zone == NULL) {
1679
0
    return;
1680
0
  }
1681
1682
0
  LOCK_ZONE(zone);
1683
0
  zone_setrawdata(zone, header);
1684
0
  UNLOCK_ZONE(zone);
1685
0
}
1686
1687
static isc_result_t
1688
0
zone_startload(dns_db_t *db, dns_zone_t *zone, isc_time_t loadtime) {
1689
0
  isc_result_t result;
1690
0
  isc_result_t tresult;
1691
0
  unsigned int options;
1692
0
  dns_load_t *load = isc_mem_get(zone->mctx, sizeof(*load));
1693
1694
0
  ENTER;
1695
1696
0
  *load = (dns_load_t){
1697
0
    .loadtime = loadtime,
1698
0
  };
1699
1700
0
  dns_zone_rpz_enable_db(zone, db);
1701
0
  dns_zone_catz_enable_db(zone, db);
1702
1703
0
  options = get_primary_options(zone);
1704
0
  if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_MANYERRORS)) {
1705
0
    options |= DNS_MASTER_MANYERRORS;
1706
0
  }
1707
1708
0
  zone_iattach(zone, &load->zone);
1709
0
  dns_db_attach(db, &load->db);
1710
1711
0
  dns_rdatacallbacks_init(&load->callbacks);
1712
0
  load->callbacks.rawdata = zone_setrawdata;
1713
0
  zone_iattach(zone, &load->callbacks.zone);
1714
1715
0
  CHECK(dns_db_beginload(db, &load->callbacks));
1716
1717
0
  if (zone->loop != NULL && zone->db != NULL) {
1718
0
    CHECK(dns_master_loadfileasync(
1719
0
      zone->masterfile, dns_db_origin(db), dns_db_origin(db),
1720
0
      zone->rdclass, options, 0, &load->callbacks, zone->loop,
1721
0
      zone_loaddone, load, &zone->loadctx,
1722
0
      zone_registerinclude, zone, zone->mctx,
1723
0
      zone->masterformat, zone->maxttl));
1724
1725
0
    return DNS_R_CONTINUE;
1726
0
  } else if (zone->stream != NULL) {
1727
0
    FILE *stream = UNCONST(zone->stream);
1728
0
    result = dns_master_loadstream(
1729
0
      stream, &zone->origin, &zone->origin, zone->rdclass,
1730
0
      options, &load->callbacks, zone->mctx);
1731
0
  } else {
1732
0
    result = dns_master_loadfile(
1733
0
      zone->masterfile, &zone->origin, &zone->origin,
1734
0
      zone->rdclass, options, 0, &load->callbacks,
1735
0
      zone_registerinclude, zone, zone->mctx,
1736
0
      zone->masterformat, zone->maxttl);
1737
0
  }
1738
1739
0
cleanup:
1740
0
  if (result != ISC_R_SUCCESS && result != DNS_R_SEENINCLUDE) {
1741
0
    dns_zone_rpz_disable_db(zone, load->db);
1742
0
    dns_zone_catz_disable_db(zone, load->db);
1743
0
  }
1744
1745
0
  tresult = dns_db_endload(db, &load->callbacks);
1746
0
  if (result == ISC_R_SUCCESS || result == DNS_R_SEENINCLUDE) {
1747
0
    result = tresult;
1748
0
  }
1749
1750
0
  zone_idetach(&load->callbacks.zone);
1751
0
  dns_db_detach(&load->db);
1752
0
  zone_idetach(&load->zone);
1753
1754
0
  isc_mem_put(zone->mctx, load, sizeof(*load));
1755
0
  return result;
1756
0
}
1757
1758
static bool
1759
zone_check_mx(dns_zone_t *zone, dns_db_t *db, dns_name_t *name,
1760
0
        dns_name_t *owner) {
1761
0
  isc_result_t result;
1762
0
  char ownerbuf[DNS_NAME_FORMATSIZE];
1763
0
  char namebuf[DNS_NAME_FORMATSIZE];
1764
0
  char altbuf[DNS_NAME_FORMATSIZE];
1765
0
  dns_fixedname_t fixed;
1766
0
  dns_name_t *foundname;
1767
0
  int level;
1768
1769
  /*
1770
   * "." means the services does not exist.
1771
   */
1772
0
  if (dns_name_isroot(name)) {
1773
0
    return true;
1774
0
  }
1775
1776
  /*
1777
   * Outside of zone.
1778
   */
1779
0
  if (!dns_name_issubdomain(name, &zone->origin)) {
1780
0
    if (zone->checkmx) {
1781
0
      return (zone->ops->checkmx)(zone, name, owner);
1782
0
    }
1783
0
    return true;
1784
0
  }
1785
1786
0
  if (zone->type == dns_zone_primary) {
1787
0
    level = ISC_LOG_ERROR;
1788
0
  } else {
1789
0
    level = ISC_LOG_WARNING;
1790
0
  }
1791
1792
0
  foundname = dns_fixedname_initname(&fixed);
1793
1794
0
  result = dns_db_find(db, name, NULL, dns_rdatatype_a, 0, 0, foundname,
1795
0
           NULL, NULL);
1796
0
  if (result == ISC_R_SUCCESS) {
1797
0
    return true;
1798
0
  }
1799
1800
0
  if (result == DNS_R_NXRRSET) {
1801
0
    result = dns_db_find(db, name, NULL, dns_rdatatype_aaaa, 0, 0,
1802
0
             foundname, NULL, NULL);
1803
0
    if (result == ISC_R_SUCCESS) {
1804
0
      return true;
1805
0
    }
1806
0
  }
1807
1808
0
  dns_name_format(owner, ownerbuf, sizeof ownerbuf);
1809
0
  dns_name_format(name, namebuf, sizeof namebuf);
1810
0
  if (result == DNS_R_NXRRSET || result == DNS_R_NXDOMAIN ||
1811
0
      result == DNS_R_EMPTYNAME)
1812
0
  {
1813
0
    if (!DNS_ZONE_OPTION(zone, DNS_ZONEOPT_CHECKMXFAIL)) {
1814
0
      level = ISC_LOG_WARNING;
1815
0
    }
1816
0
    dns_zone_log(zone, level,
1817
0
           "%s/MX '%s' has no address records (A or AAAA)",
1818
0
           ownerbuf, namebuf);
1819
0
    return (level == ISC_LOG_WARNING) ? true : false;
1820
0
  }
1821
1822
0
  if (result == DNS_R_CNAME) {
1823
0
    if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_WARNMXCNAME) ||
1824
0
        DNS_ZONE_OPTION(zone, DNS_ZONEOPT_IGNOREMXCNAME))
1825
0
    {
1826
0
      level = ISC_LOG_WARNING;
1827
0
    }
1828
0
    if (!DNS_ZONE_OPTION(zone, DNS_ZONEOPT_IGNOREMXCNAME)) {
1829
0
      dns_zone_log(zone, level,
1830
0
             "%s/MX '%s' is a CNAME (illegal)",
1831
0
             ownerbuf, namebuf);
1832
0
    }
1833
0
    return (level == ISC_LOG_WARNING) ? true : false;
1834
0
  }
1835
1836
0
  if (result == DNS_R_DNAME) {
1837
0
    if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_WARNMXCNAME) ||
1838
0
        DNS_ZONE_OPTION(zone, DNS_ZONEOPT_IGNOREMXCNAME))
1839
0
    {
1840
0
      level = ISC_LOG_WARNING;
1841
0
    }
1842
0
    if (!DNS_ZONE_OPTION(zone, DNS_ZONEOPT_IGNOREMXCNAME)) {
1843
0
      dns_name_format(foundname, altbuf, sizeof altbuf);
1844
0
      dns_zone_log(zone, level,
1845
0
             "%s/MX '%s' is below a DNAME"
1846
0
             " '%s' (illegal)",
1847
0
             ownerbuf, namebuf, altbuf);
1848
0
    }
1849
0
    return (level == ISC_LOG_WARNING) ? true : false;
1850
0
  }
1851
1852
0
  if (zone->checkmx && result == DNS_R_DELEGATION) {
1853
0
    return (zone->ops->checkmx)(zone, name, owner);
1854
0
  }
1855
1856
0
  return true;
1857
0
}
1858
1859
static bool
1860
zone_check_srv(dns_zone_t *zone, dns_db_t *db, dns_name_t *name,
1861
0
         dns_name_t *owner) {
1862
0
  isc_result_t result;
1863
0
  char ownerbuf[DNS_NAME_FORMATSIZE];
1864
0
  char namebuf[DNS_NAME_FORMATSIZE];
1865
0
  char altbuf[DNS_NAME_FORMATSIZE];
1866
0
  dns_fixedname_t fixed;
1867
0
  dns_name_t *foundname;
1868
0
  int level;
1869
1870
  /*
1871
   * "." means the services does not exist.
1872
   */
1873
0
  if (dns_name_isroot(name)) {
1874
0
    return true;
1875
0
  }
1876
1877
  /*
1878
   * Outside of zone.
1879
   */
1880
0
  if (!dns_name_issubdomain(name, &zone->origin)) {
1881
0
    if (zone->checksrv) {
1882
0
      return (zone->ops->checksrv)(zone, name, owner);
1883
0
    }
1884
0
    return true;
1885
0
  }
1886
1887
0
  if (zone->type == dns_zone_primary) {
1888
0
    level = ISC_LOG_ERROR;
1889
0
  } else {
1890
0
    level = ISC_LOG_WARNING;
1891
0
  }
1892
1893
0
  foundname = dns_fixedname_initname(&fixed);
1894
1895
0
  result = dns_db_find(db, name, NULL, dns_rdatatype_a, 0, 0, foundname,
1896
0
           NULL, NULL);
1897
0
  if (result == ISC_R_SUCCESS) {
1898
0
    return true;
1899
0
  }
1900
1901
0
  if (result == DNS_R_NXRRSET) {
1902
0
    result = dns_db_find(db, name, NULL, dns_rdatatype_aaaa, 0, 0,
1903
0
             foundname, NULL, NULL);
1904
0
    if (result == ISC_R_SUCCESS) {
1905
0
      return true;
1906
0
    }
1907
0
  }
1908
1909
0
  dns_name_format(owner, ownerbuf, sizeof ownerbuf);
1910
0
  dns_name_format(name, namebuf, sizeof namebuf);
1911
0
  if (result == DNS_R_NXRRSET || result == DNS_R_NXDOMAIN ||
1912
0
      result == DNS_R_EMPTYNAME)
1913
0
  {
1914
0
    dns_zone_log(zone, level,
1915
0
           "%s/SRV '%s' has no address records (A or AAAA)",
1916
0
           ownerbuf, namebuf);
1917
    /* XXX950 make fatal for 9.5.0. */
1918
0
    return true;
1919
0
  }
1920
1921
0
  if (result == DNS_R_CNAME) {
1922
0
    if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_WARNSRVCNAME) ||
1923
0
        DNS_ZONE_OPTION(zone, DNS_ZONEOPT_IGNORESRVCNAME))
1924
0
    {
1925
0
      level = ISC_LOG_WARNING;
1926
0
    }
1927
0
    if (!DNS_ZONE_OPTION(zone, DNS_ZONEOPT_IGNORESRVCNAME)) {
1928
0
      dns_zone_log(zone, level,
1929
0
             "%s/SRV '%s' is a CNAME (illegal)",
1930
0
             ownerbuf, namebuf);
1931
0
    }
1932
0
    return (level == ISC_LOG_WARNING) ? true : false;
1933
0
  }
1934
1935
0
  if (result == DNS_R_DNAME) {
1936
0
    if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_WARNSRVCNAME) ||
1937
0
        DNS_ZONE_OPTION(zone, DNS_ZONEOPT_IGNORESRVCNAME))
1938
0
    {
1939
0
      level = ISC_LOG_WARNING;
1940
0
    }
1941
0
    if (!DNS_ZONE_OPTION(zone, DNS_ZONEOPT_IGNORESRVCNAME)) {
1942
0
      dns_name_format(foundname, altbuf, sizeof altbuf);
1943
0
      dns_zone_log(zone, level,
1944
0
             "%s/SRV '%s' is below a "
1945
0
             "DNAME '%s' (illegal)",
1946
0
             ownerbuf, namebuf, altbuf);
1947
0
    }
1948
0
    return (level == ISC_LOG_WARNING) ? true : false;
1949
0
  }
1950
1951
0
  if (zone->checksrv && result == DNS_R_DELEGATION) {
1952
0
    return (zone->ops->checksrv)(zone, name, owner);
1953
0
  }
1954
1955
0
  return true;
1956
0
}
1957
1958
static bool
1959
zone_check_glue(dns_zone_t *zone, dns_db_t *db, bool *has_a, bool *has_aaaa,
1960
0
    dns_name_t *name, dns_name_t *owner) {
1961
0
  bool answer = true;
1962
0
  isc_result_t result, tresult;
1963
0
  char ownerbuf[DNS_NAME_FORMATSIZE];
1964
0
  char namebuf[DNS_NAME_FORMATSIZE];
1965
0
  char altbuf[DNS_NAME_FORMATSIZE];
1966
0
  dns_fixedname_t fixed;
1967
0
  dns_name_t *foundname;
1968
0
  dns_rdataset_t a;
1969
0
  dns_rdataset_t aaaa;
1970
0
  int level;
1971
1972
  /*
1973
   * Outside of zone.
1974
   */
1975
0
  if (!dns_name_issubdomain(name, &zone->origin)) {
1976
0
    if (zone->checkns) {
1977
0
      return (zone->ops->checkns)(zone, name, owner, NULL,
1978
0
                NULL);
1979
0
    }
1980
0
    return true;
1981
0
  }
1982
1983
0
  if (zone->type == dns_zone_primary) {
1984
0
    level = ISC_LOG_ERROR;
1985
0
  } else {
1986
0
    level = ISC_LOG_WARNING;
1987
0
  }
1988
1989
0
  foundname = dns_fixedname_initname(&fixed);
1990
0
  dns_rdataset_init(&a);
1991
0
  dns_rdataset_init(&aaaa);
1992
1993
  /*
1994
   * Perform a regular lookup to catch DNAME records then look
1995
   * for glue.
1996
   */
1997
0
  result = dns_db_find(db, name, NULL, dns_rdatatype_a, 0, 0, foundname,
1998
0
           &a, NULL);
1999
0
  switch (result) {
2000
0
  case ISC_R_SUCCESS:
2001
0
  case DNS_R_DNAME:
2002
0
  case DNS_R_CNAME:
2003
0
    break;
2004
0
  default:
2005
0
    dns_rdataset_cleanup(&a);
2006
0
    result = dns_db_find(db, name, NULL, dns_rdatatype_a,
2007
0
             DNS_DBFIND_GLUEOK, 0, foundname, &a, NULL);
2008
0
  }
2009
0
  if (result == ISC_R_SUCCESS) {
2010
0
    SET_IF_NOT_NULL(has_a, true);
2011
0
    dns_rdataset_disassociate(&a);
2012
0
    if (has_aaaa != NULL && !*has_aaaa) {
2013
0
      result = dns_db_find(db, name, NULL, dns_rdatatype_aaaa,
2014
0
               DNS_DBFIND_GLUEOK, 0, foundname,
2015
0
               &aaaa, NULL);
2016
0
      if (result == ISC_R_SUCCESS) {
2017
0
        *has_aaaa = true;
2018
0
      }
2019
0
      dns_rdataset_cleanup(&aaaa);
2020
0
    }
2021
0
    return true;
2022
0
  } else if (result == DNS_R_GLUE && has_a != NULL) {
2023
0
    *has_a = true;
2024
0
  } else if (result == DNS_R_DELEGATION) {
2025
0
    dns_rdataset_disassociate(&a);
2026
0
  }
2027
2028
0
  if (result == DNS_R_NXRRSET || result == DNS_R_DELEGATION ||
2029
0
      result == DNS_R_GLUE)
2030
0
  {
2031
0
    tresult = dns_db_find(db, name, NULL, dns_rdatatype_aaaa,
2032
0
              DNS_DBFIND_GLUEOK, 0, foundname, &aaaa,
2033
0
              NULL);
2034
0
    if (tresult == ISC_R_SUCCESS) {
2035
0
      dns_rdataset_cleanup(&a);
2036
0
      SET_IF_NOT_NULL(has_aaaa, true);
2037
0
      dns_rdataset_disassociate(&aaaa);
2038
0
      return true;
2039
0
    }
2040
0
    if (tresult == DNS_R_DELEGATION || tresult == DNS_R_DNAME) {
2041
0
      dns_rdataset_disassociate(&aaaa);
2042
0
    }
2043
0
    if (tresult == DNS_R_GLUE && has_aaaa != NULL) {
2044
0
      *has_aaaa = true;
2045
0
    }
2046
0
    if (result == DNS_R_GLUE || tresult == DNS_R_GLUE) {
2047
      /*
2048
       * Check glue against child zone.
2049
       */
2050
0
      if (zone->checkns) {
2051
0
        answer = (zone->ops->checkns)(zone, name, owner,
2052
0
                    &a, &aaaa);
2053
0
      }
2054
0
      dns_rdataset_cleanup(&a);
2055
0
      dns_rdataset_cleanup(&aaaa);
2056
0
      return answer;
2057
0
    }
2058
0
  }
2059
2060
0
  dns_name_format(owner, ownerbuf, sizeof ownerbuf);
2061
0
  dns_name_format(name, namebuf, sizeof namebuf);
2062
0
  if (result == DNS_R_NXRRSET || result == DNS_R_NXDOMAIN ||
2063
0
      result == DNS_R_EMPTYNAME || result == DNS_R_DELEGATION)
2064
0
  {
2065
0
    const char *what;
2066
0
    bool required = false;
2067
0
    if (dns_name_issubdomain(name, owner)) {
2068
0
      what = "REQUIRED GLUE ";
2069
0
      required = true;
2070
0
    } else if (result == DNS_R_DELEGATION) {
2071
0
      what = "SIBLING GLUE ";
2072
0
    } else {
2073
0
      what = "";
2074
0
    }
2075
2076
0
    if (result != DNS_R_DELEGATION || required ||
2077
0
        DNS_ZONE_OPTION(zone, DNS_ZONEOPT_CHECKSIBLING))
2078
0
    {
2079
0
      dns_zone_log(zone, level,
2080
0
             "%s/NS '%s' has no %s"
2081
0
             "address records (A or AAAA)",
2082
0
             ownerbuf, namebuf, what);
2083
      /*
2084
       * Log missing address record.
2085
       */
2086
0
      if (result == DNS_R_DELEGATION && zone->checkns) {
2087
0
        (void)(zone->ops->checkns)(zone, name, owner,
2088
0
                 &a, &aaaa);
2089
0
      }
2090
      /* XXX950 make fatal for 9.5.0. */
2091
      /* answer = false; */
2092
0
    }
2093
0
  } else if (result == DNS_R_CNAME) {
2094
0
    dns_zone_log(zone, level, "%s/NS '%s' is a CNAME (illegal)",
2095
0
           ownerbuf, namebuf);
2096
    /* XXX950 make fatal for 9.5.0. */
2097
    /* answer = false; */
2098
0
  } else if (result == DNS_R_DNAME) {
2099
0
    dns_name_format(foundname, altbuf, sizeof altbuf);
2100
0
    dns_zone_log(zone, level,
2101
0
           "%s/NS '%s' is below a DNAME '%s' (illegal)",
2102
0
           ownerbuf, namebuf, altbuf);
2103
    /* XXX950 make fatal for 9.5.0. */
2104
    /* answer = false; */
2105
0
  }
2106
2107
0
  dns_rdataset_cleanup(&a);
2108
0
  dns_rdataset_cleanup(&aaaa);
2109
0
  return answer;
2110
0
}
2111
2112
static bool
2113
zone_rrset_check_dup(dns_zone_t *zone, dns_name_t *owner,
2114
0
         dns_rdataset_t *rdataset) {
2115
0
  dns_rdataset_t tmprdataset;
2116
0
  bool answer = true;
2117
0
  bool format = true;
2118
0
  int level = ISC_LOG_WARNING;
2119
0
  char ownerbuf[DNS_NAME_FORMATSIZE];
2120
0
  char typebuf[DNS_RDATATYPE_FORMATSIZE];
2121
0
  unsigned int count1 = 0;
2122
2123
0
  if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_CHECKDUPRRFAIL)) {
2124
0
    level = ISC_LOG_ERROR;
2125
0
  }
2126
2127
0
  dns_rdataset_init(&tmprdataset);
2128
0
  DNS_RDATASET_FOREACH(rdataset) {
2129
0
    dns_rdata_t rdata1 = DNS_RDATA_INIT;
2130
0
    unsigned int count2 = 0;
2131
2132
0
    count1++;
2133
0
    dns_rdataset_current(rdataset, &rdata1);
2134
0
    dns_rdataset_clone(rdataset, &tmprdataset);
2135
0
    DNS_RDATASET_FOREACH(&tmprdataset) {
2136
0
      dns_rdata_t rdata2 = DNS_RDATA_INIT;
2137
0
      count2++;
2138
0
      if (count1 >= count2) {
2139
0
        continue;
2140
0
      }
2141
0
      dns_rdataset_current(&tmprdataset, &rdata2);
2142
0
      if (dns_rdata_casecompare(&rdata1, &rdata2) == 0) {
2143
0
        if (format) {
2144
0
          dns_name_format(owner, ownerbuf,
2145
0
              sizeof ownerbuf);
2146
0
          dns_rdatatype_format(rdata1.type,
2147
0
                   typebuf,
2148
0
                   sizeof(typebuf));
2149
0
          format = false;
2150
0
        }
2151
0
        dns_zone_log(zone, level,
2152
0
               "%s/%s has "
2153
0
               "semantically identical records",
2154
0
               ownerbuf, typebuf);
2155
0
        if (level == ISC_LOG_ERROR) {
2156
0
          answer = false;
2157
0
        }
2158
0
        break;
2159
0
      }
2160
0
    }
2161
0
    dns_rdataset_disassociate(&tmprdataset);
2162
0
    if (!format) {
2163
0
      break;
2164
0
    }
2165
0
  }
2166
0
  return answer;
2167
0
}
2168
2169
static bool
2170
0
zone_check_dup(dns_zone_t *zone, dns_db_t *db) {
2171
0
  dns_dbiterator_t *dbiterator = NULL;
2172
0
  dns_dbnode_t *node = NULL;
2173
0
  dns_fixedname_t fixed;
2174
0
  dns_name_t *name = dns_fixedname_initname(&fixed);
2175
0
  dns_rdatasetiter_t *rdsit = NULL;
2176
0
  bool ok = true;
2177
0
  isc_result_t result;
2178
2179
0
  result = dns_db_createiterator(db, 0, &dbiterator);
2180
0
  if (result != ISC_R_SUCCESS) {
2181
0
    return true;
2182
0
  }
2183
2184
0
  DNS_DBITERATOR_FOREACH(dbiterator) {
2185
0
    result = dns_dbiterator_current(dbiterator, &node, name);
2186
0
    if (result != ISC_R_SUCCESS) {
2187
0
      continue;
2188
0
    }
2189
2190
0
    result = dns_db_allrdatasets(db, node, NULL, 0, 0, &rdsit);
2191
0
    if (result != ISC_R_SUCCESS) {
2192
0
      continue;
2193
0
    }
2194
2195
0
    DNS_RDATASETITER_FOREACH(rdsit) {
2196
0
      dns_rdataset_t rdataset = DNS_RDATASET_INIT;
2197
0
      dns_rdatasetiter_current(rdsit, &rdataset);
2198
0
      if (!zone_rrset_check_dup(zone, name, &rdataset)) {
2199
0
        ok = false;
2200
0
      }
2201
0
      dns_rdataset_disassociate(&rdataset);
2202
0
    }
2203
0
    dns_rdatasetiter_destroy(&rdsit);
2204
0
    dns_db_detachnode(&node);
2205
0
  }
2206
2207
0
  if (node != NULL) {
2208
0
    dns_db_detachnode(&node);
2209
0
  }
2210
0
  dns_dbiterator_destroy(&dbiterator);
2211
2212
0
  return ok;
2213
0
}
2214
2215
static bool
2216
0
isspf(const dns_rdata_t *rdata) {
2217
0
  char buf[1024];
2218
0
  const char *tail;
2219
0
  const unsigned char *data = rdata->data;
2220
0
  unsigned int rdl = rdata->length, i = 0, tl, len;
2221
2222
0
  while (rdl > 0U) {
2223
0
    len = tl = *data;
2224
0
    ++data;
2225
0
    --rdl;
2226
0
    INSIST(tl <= rdl);
2227
0
    if (len > sizeof(buf) - i - 1) {
2228
0
      len = sizeof(buf) - i - 1;
2229
0
    }
2230
0
    memmove(buf + i, data, len);
2231
0
    i += len;
2232
0
    data += tl;
2233
0
    rdl -= tl;
2234
0
  }
2235
2236
0
  if (i < 6U) {
2237
0
    return false;
2238
0
  }
2239
2240
0
  buf[i] = 0;
2241
0
  tail = isc_string_stripprefix(buf, "v=spf1");
2242
0
  if (tail != NULL && (*tail == 0 || *tail == ' ')) {
2243
0
    return true;
2244
0
  }
2245
0
  return false;
2246
0
}
2247
2248
static bool
2249
zone_is_served_by(dns_zone_t *zone, dns_db_t *db, dns_rdatatype_t type,
2250
0
      dns_name_t *name) {
2251
0
  dns_rdataset_t rdataset;
2252
0
  dns_fixedname_t found;
2253
0
  dns_name_t *foundname = dns_fixedname_initname(&found);
2254
0
  isc_result_t result;
2255
2256
  /*
2257
   * Outside of zone, assume good when loading in named.
2258
   */
2259
0
  if (!dns_name_issubdomain(name, &zone->origin)) {
2260
0
    if (zone->checkns) {
2261
0
      return zone->ops->checkisservedby(zone, type, name);
2262
0
    }
2263
0
    return true;
2264
0
  }
2265
2266
0
  dns_rdataset_init(&rdataset);
2267
0
  result = dns_db_find(db, name, NULL, type, 0, 0, foundname, &rdataset,
2268
0
           NULL);
2269
0
  dns_rdataset_cleanup(&rdataset);
2270
0
  switch (result) {
2271
0
  case DNS_R_DELEGATION:
2272
0
    if (zone->checkns) {
2273
0
      return zone->ops->checkisservedby(zone, type, name);
2274
0
    }
2275
    /*
2276
     * Treat as success.
2277
     */
2278
0
    return true;
2279
0
  case ISC_R_SUCCESS:
2280
0
    return true;
2281
0
  default:
2282
0
    return false;
2283
0
  }
2284
0
}
2285
2286
static bool
2287
0
integrity_checks(dns_zone_t *zone, dns_db_t *db) {
2288
0
  dns_dbiterator_t *dbiterator = NULL;
2289
0
  dns_dbnode_t *node = NULL;
2290
0
  dns_rdataset_t rdataset = DNS_RDATASET_INIT;
2291
0
  dns_fixedname_t fixed;
2292
0
  dns_fixedname_t fixedbottom;
2293
0
  dns_name_t *name = dns_fixedname_initname(&fixed);
2294
0
  dns_name_t *bottom = dns_fixedname_initname(&fixedbottom);
2295
0
  dns_rdata_mx_t mx;
2296
0
  dns_rdata_ns_t ns;
2297
0
  dns_rdata_in_srv_t srv;
2298
0
  isc_result_t result;
2299
0
  bool ok = true;
2300
0
  bool has_a = false, has_aaaa = false;
2301
0
  char namebuf[DNS_NAME_FORMATSIZE];
2302
0
  bool logged_algorithm[DST_MAX_ALGS];
2303
0
  bool logged_digest_type[DNS_DSDIGEST_MAX + 1];
2304
2305
0
  result = dns_db_createiterator(db, 0, &dbiterator);
2306
0
  if (result != ISC_R_SUCCESS) {
2307
0
    return true;
2308
0
  }
2309
2310
0
  DNS_DBITERATOR_FOREACH(dbiterator) {
2311
0
    bool have_ns = false, have_deleg = false;
2312
0
    bool have_spf = false, have_txt = false;
2313
2314
0
    CHECK(dns_dbiterator_current(dbiterator, &node, name));
2315
2316
    /*
2317
     * Is this name visible in the zone?
2318
     */
2319
0
    if (!dns_name_issubdomain(name, &zone->origin) ||
2320
0
        (!dns_name_empty(bottom) &&
2321
0
         dns_name_issubdomain(name, bottom)))
2322
0
    {
2323
0
      goto next;
2324
0
    }
2325
2326
0
    dns_dbiterator_pause(dbiterator);
2327
2328
    /*
2329
     * Check for deprecated KEY algorithms
2330
     */
2331
0
    result = dns_db_findrdataset(db, node, NULL, dns_rdatatype_key,
2332
0
               0, 0, &rdataset, NULL);
2333
0
    if (result != ISC_R_SUCCESS) {
2334
0
      goto checkforns;
2335
0
    }
2336
2337
0
    memset(logged_algorithm, 0, sizeof(logged_algorithm));
2338
0
    DNS_RDATASET_FOREACH(&rdataset) {
2339
0
      dns_rdata_t rdata = DNS_RDATA_INIT;
2340
0
      dns_rdata_key_t key;
2341
0
      dns_rdataset_current(&rdataset, &rdata);
2342
2343
0
      result = dns_rdata_tostruct(&rdata, &key);
2344
0
      RUNTIME_CHECK(result == ISC_R_SUCCESS);
2345
2346
      /*
2347
       * If we ever deprecate a private algorithm use
2348
       * dst_algorithm_fromdata() here.
2349
       */
2350
0
      switch (key.algorithm) {
2351
0
      case DNS_KEYALG_RSASHA1:
2352
0
      case DNS_KEYALG_NSEC3RSASHA1:
2353
0
        if (!logged_algorithm[key.algorithm]) {
2354
0
          char algbuf[DNS_SECALG_FORMATSIZE];
2355
0
          dns_name_format(name, namebuf,
2356
0
              sizeof(namebuf));
2357
0
          dns_secalg_format(key.algorithm, algbuf,
2358
0
                sizeof(algbuf));
2359
0
          dnssec_log(zone, ISC_LOG_WARNING,
2360
0
               "%s/KEY deprecated "
2361
0
               "algorithm %u (%s)",
2362
0
               namebuf, key.algorithm,
2363
0
               algbuf);
2364
0
          logged_algorithm[key.algorithm] = true;
2365
0
        }
2366
0
        break;
2367
0
      default:
2368
0
        break;
2369
0
      }
2370
0
    }
2371
0
    dns_rdataset_disassociate(&rdataset);
2372
2373
0
  checkforns:
2374
    /*
2375
     * Skip checking NS records at the apex.
2376
     */
2377
0
    if (dns_name_equal(name, &zone->origin)) {
2378
0
      goto checkfordeleg;
2379
0
    }
2380
2381
0
    result = dns_db_findrdataset(db, node, NULL, dns_rdatatype_ns,
2382
0
               0, 0, &rdataset, NULL);
2383
0
    if (result != ISC_R_SUCCESS) {
2384
0
      goto checkfordeleg;
2385
0
    }
2386
2387
    /*
2388
     * Remember bottom of zone due to NS.
2389
     */
2390
0
    dns_name_copy(name, bottom);
2391
0
    have_ns = true;
2392
2393
    /* Check glue correctness */
2394
0
    DNS_RDATASET_FOREACH(&rdataset) {
2395
0
      dns_rdata_t rdata = DNS_RDATA_INIT;
2396
0
      dns_rdataset_current(&rdataset, &rdata);
2397
2398
0
      result = dns_rdata_tostruct(&rdata, &ns);
2399
0
      RUNTIME_CHECK(result == ISC_R_SUCCESS);
2400
0
      if (!zone_check_glue(zone, db, &has_a, &has_aaaa,
2401
0
               &ns.name, name))
2402
0
      {
2403
0
        ok = false;
2404
0
      }
2405
0
    }
2406
0
    dns_rdataset_disassociate(&rdataset);
2407
2408
0
  checkfordeleg:
2409
0
    result = dns_db_findrdataset(db, node, NULL,
2410
0
               dns_rdatatype_deleg, 0, 0,
2411
0
               &rdataset, NULL);
2412
0
    if (result != ISC_R_SUCCESS) {
2413
0
      goto checkfords;
2414
0
    }
2415
2416
    /* DELEG is not allowed at the apex and is class-IN only. */
2417
0
    if (dns_name_equal(name, &zone->origin)) {
2418
0
      dns_name_format(name, namebuf, sizeof(namebuf));
2419
0
      dns_zone_log(zone, ISC_LOG_ERROR,
2420
0
             "DELEG at zone apex (%s)", namebuf);
2421
0
      dns_rdataset_disassociate(&rdataset);
2422
0
      ok = false;
2423
0
      goto checkfords;
2424
0
    } else if (zone->rdclass != dns_rdataclass_in) {
2425
0
      dns_zone_log(zone, ISC_LOG_ERROR, "DELEG: bad class");
2426
0
      ok = false;
2427
0
      goto checkfords;
2428
0
    }
2429
2430
    /*
2431
     * check the DELEG rrset for server-name and
2432
     * include-delegparam paramters, and reject if they're
2433
     * below the owner name.
2434
     */
2435
0
    DNS_RDATASET_FOREACH(&rdataset) {
2436
0
      dns_rdata_t rdata = DNS_RDATA_INIT;
2437
0
      dns_rdataset_current(&rdataset, &rdata);
2438
0
      dns_fixedname_t fbad;
2439
0
      dns_name_t *bad = dns_fixedname_initname(&fbad);
2440
2441
0
      if (!dns_rdata_checknames(&rdata, name, bad)) {
2442
0
        dns_name_format(bad, namebuf, sizeof(namebuf));
2443
0
        dns_zone_log(zone, ISC_LOG_ERROR,
2444
0
               "DELEG: invalid target name '%s'",
2445
0
               namebuf);
2446
0
        ok = false;
2447
0
        dns_rdataset_disassociate(&rdataset);
2448
0
        goto checkfords;
2449
0
      }
2450
0
    }
2451
2452
    /*
2453
     * Remember bottom of zone due to DELEG.
2454
     */
2455
0
    dns_name_copy(name, bottom);
2456
0
    have_deleg = true;
2457
0
    dns_rdataset_disassociate(&rdataset);
2458
2459
0
  checkfords:
2460
    /*
2461
     * DS is only allowed at a delegation point (i.e.,
2462
     * coexisting with NS or DELEG and not at the apex).
2463
     */
2464
0
    result = dns_db_findrdataset(db, node, NULL, dns_rdatatype_ds,
2465
0
               0, 0, &rdataset, NULL);
2466
0
    if (result != ISC_R_SUCCESS) {
2467
0
      goto checkfordname;
2468
0
    }
2469
2470
0
    if (!have_ns && !have_deleg) {
2471
0
      int level = ISC_LOG_WARNING;
2472
0
      if (zone->type == dns_zone_primary) {
2473
0
        level = ISC_LOG_ERROR;
2474
0
        ok = false;
2475
0
      }
2476
0
      dns_name_format(name, namebuf, sizeof(namebuf));
2477
0
      dns_zone_log(zone, level,
2478
0
             "DS not at delegation point (%s)",
2479
0
             namebuf);
2480
0
      dns_rdataset_disassociate(&rdataset);
2481
0
      goto checkfordname;
2482
0
    }
2483
2484
    /*
2485
     * Check for deprecated DS digest types.
2486
     */
2487
0
    memset(logged_algorithm, 0, sizeof(logged_algorithm));
2488
0
    memset(logged_digest_type, 0, sizeof(logged_digest_type));
2489
0
    DNS_RDATASET_FOREACH(&rdataset) {
2490
0
      dns_rdata_t rdata = DNS_RDATA_INIT;
2491
0
      dns_rdataset_current(&rdataset, &rdata);
2492
0
      dns_rdata_ds_t ds;
2493
2494
0
      result = dns_rdata_tostruct(&rdata, &ds);
2495
0
      RUNTIME_CHECK(result == ISC_R_SUCCESS);
2496
0
      switch (ds.digest_type) {
2497
0
      case DNS_DSDIGEST_SHA1:
2498
0
      case DNS_DSDIGEST_GOST:
2499
0
        if (!logged_digest_type[ds.digest_type]) {
2500
0
          char algbuf[DNS_DSDIGEST_FORMATSIZE];
2501
0
          dns_name_format(name, namebuf,
2502
0
              sizeof(namebuf));
2503
0
          dns_dsdigest_format(ds.digest_type,
2504
0
                  algbuf,
2505
0
                  sizeof(algbuf));
2506
0
          dnssec_log(zone, ISC_LOG_WARNING,
2507
0
               "%s/DS deprecated digest "
2508
0
               "type %u (%s)",
2509
0
               namebuf, ds.digest_type,
2510
0
               algbuf);
2511
0
          logged_digest_type[ds.digest_type] =
2512
0
            true;
2513
0
        }
2514
0
        break;
2515
0
      }
2516
2517
      /*
2518
       * If we ever deprecate a private algorithm use
2519
       * dst_algorithm_fromdata() here.
2520
       */
2521
0
      switch (ds.algorithm) {
2522
0
      case DNS_KEYALG_RSASHA1:
2523
0
      case DNS_KEYALG_NSEC3RSASHA1:
2524
0
        if (!logged_algorithm[ds.algorithm]) {
2525
0
          char algbuf[DNS_SECALG_FORMATSIZE];
2526
0
          dns_name_format(name, namebuf,
2527
0
              sizeof(namebuf));
2528
0
          dns_secalg_format(ds.algorithm, algbuf,
2529
0
                sizeof(algbuf));
2530
0
          dnssec_log(zone, ISC_LOG_WARNING,
2531
0
               "%s/DS deprecated algorithm "
2532
0
               "%u (%s)",
2533
0
               namebuf, ds.algorithm,
2534
0
               algbuf);
2535
0
          logged_algorithm[ds.algorithm] = true;
2536
0
        }
2537
0
        break;
2538
0
      }
2539
0
    }
2540
0
    dns_rdataset_disassociate(&rdataset);
2541
2542
0
  checkfordname:
2543
0
    result = dns_db_findrdataset(db, node, NULL,
2544
0
               dns_rdatatype_dname, 0, 0,
2545
0
               &rdataset, NULL);
2546
0
    if (result != ISC_R_SUCCESS) {
2547
0
      goto checkformx;
2548
0
    }
2549
2550
    /*
2551
     * Remember bottom of zone due to DNAME.
2552
     */
2553
0
    dns_name_copy(name, bottom);
2554
0
    dns_rdataset_disassociate(&rdataset);
2555
2556
0
  checkformx:
2557
0
    result = dns_db_findrdataset(db, node, NULL, dns_rdatatype_mx,
2558
0
               0, 0, &rdataset, NULL);
2559
0
    if (result != ISC_R_SUCCESS) {
2560
0
      goto checksrv;
2561
0
    }
2562
0
    DNS_RDATASET_FOREACH(&rdataset) {
2563
0
      dns_rdata_t rdata = DNS_RDATA_INIT;
2564
0
      dns_rdataset_current(&rdataset, &rdata);
2565
2566
0
      result = dns_rdata_tostruct(&rdata, &mx);
2567
0
      RUNTIME_CHECK(result == ISC_R_SUCCESS);
2568
0
      if (!zone_check_mx(zone, db, &mx.mx, name)) {
2569
0
        ok = false;
2570
0
      }
2571
0
    }
2572
0
    dns_rdataset_disassociate(&rdataset);
2573
2574
0
  checksrv:
2575
0
    if (zone->rdclass != dns_rdataclass_in) {
2576
      /* All the remaining tests are for class IN only */
2577
0
      goto next;
2578
0
    }
2579
0
    result = dns_db_findrdataset(db, node, NULL, dns_rdatatype_srv,
2580
0
               0, 0, &rdataset, NULL);
2581
0
    if (result != ISC_R_SUCCESS) {
2582
0
      goto checkforaaaa;
2583
0
    }
2584
0
    DNS_RDATASET_FOREACH(&rdataset) {
2585
0
      dns_rdata_t rdata = DNS_RDATA_INIT;
2586
0
      dns_rdataset_current(&rdataset, &rdata);
2587
2588
0
      result = dns_rdata_tostruct(&rdata, &srv);
2589
0
      RUNTIME_CHECK(result == ISC_R_SUCCESS);
2590
0
      if (!zone_check_srv(zone, db, &srv.target, name)) {
2591
0
        ok = false;
2592
0
      }
2593
0
    }
2594
0
    dns_rdataset_disassociate(&rdataset);
2595
2596
0
  checkforaaaa:
2597
    /*
2598
     * Check if there is an A or AAAA RRset anywhere in
2599
     * the zone.
2600
     */
2601
0
    if (!has_a) {
2602
0
      result = dns_db_findrdataset(db, node, NULL,
2603
0
                 dns_rdatatype_a, 0, 0,
2604
0
                 &rdataset, NULL);
2605
0
      if (result == ISC_R_SUCCESS) {
2606
0
        has_a = true;
2607
0
        dns_rdataset_disassociate(&rdataset);
2608
0
      }
2609
0
    }
2610
0
    if (!has_aaaa) {
2611
0
      result = dns_db_findrdataset(db, node, NULL,
2612
0
                 dns_rdatatype_aaaa, 0, 0,
2613
0
                 &rdataset, NULL);
2614
0
      if (result == ISC_R_SUCCESS) {
2615
0
        has_aaaa = true;
2616
0
        dns_rdataset_disassociate(&rdataset);
2617
0
      }
2618
0
    }
2619
2620
    /*
2621
     * Check if there is a type SPF record without an
2622
     * SPF-formatted type TXT record also being present.
2623
     */
2624
0
    if (!DNS_ZONE_OPTION(zone, DNS_ZONEOPT_CHECKSPF)) {
2625
0
      goto next;
2626
0
    }
2627
0
    if (zone->rdclass != dns_rdataclass_in) {
2628
0
      goto next;
2629
0
    }
2630
2631
0
    result = dns_db_findrdataset(db, node, NULL, dns_rdatatype_spf,
2632
0
               0, 0, &rdataset, NULL);
2633
0
    if (result == ISC_R_SUCCESS) {
2634
0
      dns_rdataset_disassociate(&rdataset);
2635
0
      have_spf = true;
2636
0
    }
2637
0
    result = dns_db_findrdataset(db, node, NULL, dns_rdatatype_txt,
2638
0
               0, 0, &rdataset, NULL);
2639
0
    if (result != ISC_R_SUCCESS) {
2640
0
      goto notxt;
2641
0
    }
2642
0
    DNS_RDATASET_FOREACH(&rdataset) {
2643
0
      dns_rdata_t rdata = DNS_RDATA_INIT;
2644
0
      dns_rdataset_current(&rdataset, &rdata);
2645
2646
0
      have_txt = isspf(&rdata);
2647
0
      if (have_txt) {
2648
0
        break;
2649
0
      }
2650
0
    }
2651
0
    dns_rdataset_disassociate(&rdataset);
2652
2653
0
  notxt:
2654
0
    if (have_spf && !have_txt) {
2655
0
      dns_name_format(name, namebuf, sizeof(namebuf));
2656
0
      dns_zone_log(zone, ISC_LOG_WARNING,
2657
0
             "'%s' found type "
2658
0
             "SPF record but no SPF TXT record found, "
2659
0
             "add matching type TXT record",
2660
0
             namebuf);
2661
0
    }
2662
2663
0
  next:
2664
0
    dns_db_detachnode(&node);
2665
0
  }
2666
2667
0
  if (has_a) {
2668
0
    has_a = false;
2669
0
    result = dns_db_find(db, &zone->origin, NULL, dns_rdatatype_ns,
2670
0
             0, 0, name, &rdataset, NULL);
2671
0
    if (result != ISC_R_SUCCESS) {
2672
0
      dns_rdataset_cleanup(&rdataset);
2673
0
      goto cleanup;
2674
0
    }
2675
2676
0
    DNS_RDATASET_FOREACH(&rdataset) {
2677
0
      dns_rdata_t rdata = DNS_RDATA_INIT;
2678
0
      dns_rdataset_current(&rdataset, &rdata);
2679
2680
0
      result = dns_rdata_tostruct(&rdata, &ns);
2681
0
      RUNTIME_CHECK(result == ISC_R_SUCCESS);
2682
0
      if (zone_is_served_by(zone, db, dns_rdatatype_a,
2683
0
                &ns.name))
2684
0
      {
2685
0
        has_a = true;
2686
0
        break;
2687
0
      }
2688
0
    }
2689
0
    dns_rdataset_disassociate(&rdataset);
2690
0
    if (!has_a) {
2691
0
      dns_zone_log(zone, ISC_LOG_WARNING,
2692
0
             "zone has A records but is not served "
2693
0
             "by IPv4 servers");
2694
0
    }
2695
0
  }
2696
2697
0
  if (has_aaaa) {
2698
0
    has_aaaa = false;
2699
0
    result = dns_db_find(db, &zone->origin, NULL, dns_rdatatype_ns,
2700
0
             0, 0, name, &rdataset, NULL);
2701
0
    if (result != ISC_R_SUCCESS) {
2702
0
      dns_rdataset_cleanup(&rdataset);
2703
0
      goto cleanup;
2704
0
    }
2705
2706
0
    DNS_RDATASET_FOREACH(&rdataset) {
2707
0
      dns_rdata_t rdata = DNS_RDATA_INIT;
2708
0
      dns_rdataset_current(&rdataset, &rdata);
2709
2710
0
      result = dns_rdata_tostruct(&rdata, &ns);
2711
0
      RUNTIME_CHECK(result == ISC_R_SUCCESS);
2712
0
      if (zone_is_served_by(zone, db, dns_rdatatype_aaaa,
2713
0
                &ns.name))
2714
0
      {
2715
0
        has_aaaa = true;
2716
0
        break;
2717
0
      }
2718
0
    }
2719
0
    dns_rdataset_disassociate(&rdataset);
2720
0
    if (!has_aaaa) {
2721
0
      dns_zone_log(zone, ISC_LOG_WARNING,
2722
0
             "zone has AAAA records but is not served "
2723
0
             "by IPv6 servers");
2724
0
    }
2725
0
  }
2726
2727
0
cleanup:
2728
0
  if (node != NULL) {
2729
0
    dns_db_detachnode(&node);
2730
0
  }
2731
0
  dns_dbiterator_destroy(&dbiterator);
2732
2733
0
  return ok;
2734
0
}
2735
2736
/*
2737
 * OpenSSL verification of RSA keys with exponent 3 is known to be
2738
 * broken prior OpenSSL 0.9.8c/0.9.7k.  Look for such keys and warn
2739
 * if they are in use.
2740
 */
2741
static void
2742
0
zone_check_dnskeys(dns_zone_t *zone, dns_db_t *db) {
2743
0
  dns_dbnode_t *node = NULL;
2744
0
  dns_dbversion_t *version = NULL;
2745
0
  dns_rdata_dnskey_t dnskey;
2746
0
  dns_rdataset_t rdataset;
2747
0
  isc_result_t result;
2748
0
  bool logged_algorithm[DST_MAX_ALGS] = { 0 };
2749
0
  bool alldeprecated = true;
2750
2751
0
  CHECK(dns_db_findnode(db, &zone->origin, false, &node));
2752
2753
0
  dns_db_currentversion(db, &version);
2754
0
  dns_rdataset_init(&rdataset);
2755
0
  CHECK(dns_db_findrdataset(db, node, version, dns_rdatatype_dnskey,
2756
0
          dns_rdatatype_none, 0, &rdataset, NULL));
2757
2758
0
  DNS_RDATASET_FOREACH(&rdataset) {
2759
0
    char algbuf[DNS_SECALG_FORMATSIZE];
2760
0
    dns_rdata_t rdata = DNS_RDATA_INIT;
2761
0
    dns_rdataset_current(&rdataset, &rdata);
2762
0
    result = dns_rdata_tostruct(&rdata, &dnskey);
2763
0
    INSIST(result == ISC_R_SUCCESS);
2764
2765
    /*
2766
     * RFC 3110, section 4: Performance Considerations:
2767
     *
2768
     * A public exponent of 3 minimizes the effort needed to verify
2769
     * a signature.  Use of 3 as the public exponent is weak for
2770
     * confidentiality uses since, if the same data can be collected
2771
     * encrypted under three different keys with an exponent of 3
2772
     * then, using the Chinese Remainder Theorem [NETSEC], the
2773
     * original plain text can be easily recovered.  If a key is
2774
     * known to be used only for authentication, as is the case with
2775
     * DNSSEC, then an exponent of 3 is acceptable.  However other
2776
     * applications in the future may wish to leverage DNS
2777
     * distributed keys for applications that do require
2778
     * confidentiality.  For keys which might have such other uses,
2779
     * a more conservative choice would be 65537 (F4, the fourth
2780
     * fermat number).
2781
     */
2782
0
    if (dnskey.datalen > 1 && dnskey.data[0] == 1 &&
2783
0
        dnskey.data[1] == 3 &&
2784
0
        (dnskey.algorithm == DNS_KEYALG_RSAMD5 ||
2785
0
         dnskey.algorithm == DNS_KEYALG_RSASHA1 ||
2786
0
         dnskey.algorithm == DNS_KEYALG_NSEC3RSASHA1 ||
2787
0
         dnskey.algorithm == DNS_KEYALG_RSASHA256 ||
2788
0
         dnskey.algorithm == DNS_KEYALG_RSASHA512))
2789
0
    {
2790
0
      char algorithm[DNS_SECALG_FORMATSIZE];
2791
0
      isc_region_t r;
2792
2793
0
      dns_rdata_toregion(&rdata, &r);
2794
0
      dns_secalg_format(dnskey.algorithm, algorithm,
2795
0
            sizeof(algorithm));
2796
2797
0
      dnssec_log(zone, ISC_LOG_WARNING,
2798
0
           "weak %s (%u) key found (exponent=3, id=%u)",
2799
0
           algorithm, dnskey.algorithm,
2800
0
           dst_region_computeid(&r));
2801
0
    }
2802
0
    switch (dnskey.algorithm) {
2803
0
    case DNS_KEYALG_RSAMD5:
2804
0
    case DNS_KEYALG_DSA:
2805
0
    case DNS_KEYALG_RSASHA1:
2806
0
    case DNS_KEYALG_NSEC3DSA:
2807
0
    case DNS_KEYALG_NSEC3RSASHA1:
2808
0
    case DNS_KEYALG_ECCGOST:
2809
0
      if (!logged_algorithm[dnskey.algorithm]) {
2810
0
        dns_secalg_format(dnskey.algorithm, algbuf,
2811
0
              sizeof(algbuf));
2812
0
        dnssec_log(zone, ISC_LOG_WARNING,
2813
0
             "deprecated DNSKEY algorithm found: "
2814
0
             "%u (%s)\n",
2815
0
             dnskey.algorithm, algbuf);
2816
0
        logged_algorithm[dnskey.algorithm] = true;
2817
0
      }
2818
0
      break;
2819
0
    default:
2820
0
      alldeprecated = false;
2821
0
      break;
2822
0
    }
2823
0
  }
2824
0
  dns_rdataset_disassociate(&rdataset);
2825
2826
0
  if (alldeprecated) {
2827
0
    dnssec_log(zone, ISC_LOG_WARNING,
2828
0
         "all DNSKEY algorithms found are deprecated");
2829
0
  }
2830
2831
0
cleanup:
2832
0
  if (node != NULL) {
2833
0
    dns_db_detachnode(&node);
2834
0
  }
2835
0
  if (version != NULL) {
2836
0
    dns_db_closeversion(db, &version, false);
2837
0
  }
2838
0
}
2839
2840
static void
2841
0
resume_signingwithkey(dns_zone_t *zone) {
2842
0
  dns_dbnode_t *node = NULL;
2843
0
  dns_dbversion_t *version = NULL;
2844
0
  dns_rdataset_t rdataset;
2845
0
  isc_result_t result;
2846
0
  dns_db_t *db = NULL;
2847
2848
0
  ZONEDB_LOCK(&zone->dblock, isc_rwlocktype_read);
2849
0
  if (zone->db != NULL) {
2850
0
    dns_db_attach(zone->db, &db);
2851
0
  }
2852
0
  ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_read);
2853
0
  if (db == NULL) {
2854
0
    goto cleanup;
2855
0
  }
2856
2857
0
  CHECK(dns_db_findnode(db, &zone->origin, false, &node));
2858
2859
0
  dns_db_currentversion(db, &version);
2860
0
  dns_rdataset_init(&rdataset);
2861
0
  result = dns_db_findrdataset(db, node, version, zone->privatetype,
2862
0
             dns_rdatatype_none, 0, &rdataset, NULL);
2863
0
  if (result != ISC_R_SUCCESS) {
2864
0
    INSIST(!dns_rdataset_isassociated(&rdataset));
2865
0
    goto cleanup;
2866
0
  }
2867
2868
0
  DNS_RDATASET_FOREACH(&rdataset) {
2869
0
    dns_rdata_t rdata = DNS_RDATA_INIT;
2870
0
    dst_algorithm_t alg;
2871
2872
0
    dns_rdataset_current(&rdataset, &rdata);
2873
    /*
2874
     * Old or New Forms
2875
     */
2876
0
    if ((rdata.length != OLD_SIGNING_RECORD_SIZE &&
2877
0
         rdata.length != SIGNING_RECORD_SIZE) ||
2878
0
        rdata.data[0] == 0 || rdata.data[4] != 0)
2879
0
    {
2880
0
      continue;
2881
0
    }
2882
0
    alg = (rdata.length == OLD_SIGNING_RECORD_SIZE)
2883
0
            ? rdata.data[0]
2884
0
            : ((rdata.data[5] << 8) | rdata.data[6]);
2885
0
    result = zone_signwithkey(zone, alg,
2886
0
            (rdata.data[1] << 8) | rdata.data[2],
2887
0
            rdata.data[3], false);
2888
0
    if (result != ISC_R_SUCCESS) {
2889
0
      dnssec_log(zone, ISC_LOG_ERROR,
2890
0
           "zone_signwithkey failed: %s",
2891
0
           isc_result_totext(result));
2892
0
    }
2893
0
  }
2894
0
  dns_rdataset_disassociate(&rdataset);
2895
2896
0
cleanup:
2897
0
  if (db != NULL) {
2898
0
    if (node != NULL) {
2899
0
      dns_db_detachnode(&node);
2900
0
    }
2901
0
    if (version != NULL) {
2902
0
      dns_db_closeversion(db, &version, false);
2903
0
    }
2904
0
    dns_db_detach(&db);
2905
0
  }
2906
0
}
2907
2908
/*
2909
 * Initiate adding/removing NSEC3 records belonging to the chain defined by the
2910
 * supplied NSEC3PARAM RDATA.
2911
 *
2912
 * Zone must be locked by caller.
2913
 */
2914
static isc_result_t
2915
0
zone_addnsec3chain(dns_zone_t *zone, dns_rdata_nsec3param_t *nsec3param) {
2916
0
  dns_nsec3chain_t *nsec3chain;
2917
0
  dns_dbversion_t *version = NULL;
2918
0
  bool nseconly = false, nsec3ok = false;
2919
0
  isc_result_t result;
2920
0
  isc_time_t now;
2921
0
  unsigned int options = 0;
2922
0
  char saltbuf[255 * 2 + 1];
2923
0
  char flags[sizeof("INITIAL|REMOVE|CREATE|NONSEC|OPTOUT")];
2924
0
  dns_db_t *db = NULL;
2925
2926
0
  ZONEDB_LOCK(&zone->dblock, isc_rwlocktype_read);
2927
0
  if (zone->db != NULL) {
2928
0
    dns_db_attach(zone->db, &db);
2929
0
  }
2930
0
  ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_read);
2931
2932
0
  if (db == NULL) {
2933
0
    result = ISC_R_SUCCESS;
2934
0
    goto cleanup;
2935
0
  }
2936
2937
  /*
2938
   * If this zone is not NSEC3-capable, attempting to remove any NSEC3
2939
   * chain from it is pointless as it would not be possible for the
2940
   * latter to exist in the first place.
2941
   */
2942
0
  dns_db_currentversion(db, &version);
2943
0
  result = dns_nsec_nseconly(db, version, NULL, &nseconly);
2944
0
  nsec3ok = (result == ISC_R_SUCCESS && !nseconly);
2945
0
  dns_db_closeversion(db, &version, false);
2946
0
  if (!nsec3ok && (nsec3param->flags & DNS_NSEC3FLAG_REMOVE) == 0) {
2947
0
    result = ISC_R_SUCCESS;
2948
0
    goto cleanup;
2949
0
  }
2950
2951
  /*
2952
   * Allocate and initialize structure preserving state of
2953
   * adding/removing records belonging to this NSEC3 chain between
2954
   * separate zone_nsec3chain() calls.
2955
   */
2956
0
  nsec3chain = isc_mem_get(zone->mctx, sizeof *nsec3chain);
2957
2958
0
  nsec3chain->magic = 0;
2959
0
  nsec3chain->done = false;
2960
0
  nsec3chain->db = NULL;
2961
0
  nsec3chain->dbiterator = NULL;
2962
0
  nsec3chain->nsec3param.common.rdclass = nsec3param->common.rdclass;
2963
0
  nsec3chain->nsec3param.common.rdtype = nsec3param->common.rdtype;
2964
0
  nsec3chain->nsec3param.hash = nsec3param->hash;
2965
0
  nsec3chain->nsec3param.iterations = nsec3param->iterations;
2966
0
  nsec3chain->nsec3param.flags = nsec3param->flags;
2967
0
  nsec3chain->nsec3param.salt.length = nsec3param->salt.length;
2968
0
  memmove(nsec3chain->salt, nsec3param->salt.base,
2969
0
    nsec3param->salt.length);
2970
0
  nsec3chain->nsec3param.salt.base = nsec3chain->salt;
2971
0
  nsec3chain->seen_nsec = false;
2972
0
  nsec3chain->delete_nsec = false;
2973
0
  nsec3chain->save_delete_nsec = false;
2974
2975
  /*
2976
   * Log NSEC3 parameters defined by supplied NSEC3PARAM RDATA.
2977
   */
2978
0
  if (nsec3param->flags == 0) {
2979
0
    strlcpy(flags, "NONE", sizeof(flags));
2980
0
  } else {
2981
0
    flags[0] = '\0';
2982
0
    if ((nsec3param->flags & DNS_NSEC3FLAG_REMOVE) != 0) {
2983
0
      strlcat(flags, "REMOVE", sizeof(flags));
2984
0
    }
2985
0
    if ((nsec3param->flags & DNS_NSEC3FLAG_INITIAL) != 0) {
2986
0
      if (flags[0] == '\0') {
2987
0
        strlcpy(flags, "INITIAL", sizeof(flags));
2988
0
      } else {
2989
0
        strlcat(flags, "|INITIAL", sizeof(flags));
2990
0
      }
2991
0
    }
2992
0
    if ((nsec3param->flags & DNS_NSEC3FLAG_CREATE) != 0) {
2993
0
      if (flags[0] == '\0') {
2994
0
        strlcpy(flags, "CREATE", sizeof(flags));
2995
0
      } else {
2996
0
        strlcat(flags, "|CREATE", sizeof(flags));
2997
0
      }
2998
0
    }
2999
0
    if ((nsec3param->flags & DNS_NSEC3FLAG_NONSEC) != 0) {
3000
0
      if (flags[0] == '\0') {
3001
0
        strlcpy(flags, "NONSEC", sizeof(flags));
3002
0
      } else {
3003
0
        strlcat(flags, "|NONSEC", sizeof(flags));
3004
0
      }
3005
0
    }
3006
0
    if ((nsec3param->flags & DNS_NSEC3FLAG_OPTOUT) != 0) {
3007
0
      if (flags[0] == '\0') {
3008
0
        strlcpy(flags, "OPTOUT", sizeof(flags));
3009
0
      } else {
3010
0
        strlcat(flags, "|OPTOUT", sizeof(flags));
3011
0
      }
3012
0
    }
3013
0
  }
3014
0
  result = dns_nsec3param_salttotext(nsec3param, saltbuf,
3015
0
             sizeof(saltbuf));
3016
0
  RUNTIME_CHECK(result == ISC_R_SUCCESS);
3017
0
  dnssec_log(zone, ISC_LOG_INFO, "zone_addnsec3chain(%u,%s,%u,%s)",
3018
0
       nsec3param->hash, flags, nsec3param->iterations, saltbuf);
3019
3020
  /*
3021
   * If the NSEC3 chain defined by the supplied NSEC3PARAM RDATA is
3022
   * currently being processed, interrupt its processing to avoid
3023
   * simultaneously adding and removing records for the same NSEC3 chain.
3024
   */
3025
0
  ISC_LIST_FOREACH(zone->nsec3chain, current, link) {
3026
0
    if ((current->db == db) &&
3027
0
        (current->nsec3param.hash == nsec3param->hash) &&
3028
0
        (current->nsec3param.iterations ==
3029
0
         nsec3param->iterations) &&
3030
0
        (current->nsec3param.salt.length ==
3031
0
         nsec3param->salt.length) &&
3032
0
        memcmp(current->nsec3param.salt.base, nsec3param->salt.base,
3033
0
         nsec3param->salt.length) == 0)
3034
0
    {
3035
0
      current->done = true;
3036
0
    }
3037
0
  }
3038
3039
  /*
3040
   * Attach zone database to the structure initialized above and create
3041
   * an iterator for it with appropriate options in order to avoid
3042
   * creating NSEC3 records for NSEC3 records.
3043
   */
3044
0
  dns_db_attach(db, &nsec3chain->db);
3045
0
  if ((nsec3chain->nsec3param.flags & DNS_NSEC3FLAG_CREATE) != 0) {
3046
0
    options = DNS_DB_NONSEC3;
3047
0
  }
3048
0
  result = dns_db_createiterator(nsec3chain->db, options,
3049
0
               &nsec3chain->dbiterator);
3050
0
  if (result == ISC_R_SUCCESS) {
3051
0
    result = dns_dbiterator_first(nsec3chain->dbiterator);
3052
0
  }
3053
0
  if (result == ISC_R_SUCCESS) {
3054
    /*
3055
     * Database iterator initialization succeeded.  We are now
3056
     * ready to kick off adding/removing records belonging to this
3057
     * NSEC3 chain.  Append the structure initialized above to the
3058
     * "nsec3chain" list for the zone and set the appropriate zone
3059
     * timer so that zone_nsec3chain() is called as soon as
3060
     * possible.
3061
     */
3062
0
    dns_dbiterator_pause(nsec3chain->dbiterator);
3063
0
    ISC_LIST_INITANDAPPEND(zone->nsec3chain, nsec3chain, link);
3064
0
    nsec3chain = NULL;
3065
0
    if (isc_time_isepoch(&zone->nsec3chaintime)) {
3066
0
      now = isc_time_now();
3067
0
      zone->nsec3chaintime = now;
3068
0
      if (zone->loop != NULL) {
3069
0
        dns__zone_settimer(zone, now);
3070
0
      }
3071
0
    }
3072
0
  }
3073
3074
0
  if (nsec3chain != NULL) {
3075
0
    if (nsec3chain->db != NULL) {
3076
0
      dns_db_detach(&nsec3chain->db);
3077
0
    }
3078
0
    if (nsec3chain->dbiterator != NULL) {
3079
0
      dns_dbiterator_destroy(&nsec3chain->dbiterator);
3080
0
    }
3081
0
    isc_mem_put(zone->mctx, nsec3chain, sizeof *nsec3chain);
3082
0
  }
3083
3084
0
cleanup:
3085
0
  if (db != NULL) {
3086
0
    dns_db_detach(&db);
3087
0
  }
3088
0
  return result;
3089
0
}
3090
3091
/*
3092
 * Find private-type records at the zone apex which signal that an NSEC3 chain
3093
 * should be added or removed.  For each such record, extract NSEC3PARAM RDATA
3094
 * and pass it to zone_addnsec3chain().
3095
 *
3096
 * Zone must be locked by caller.
3097
 */
3098
static void
3099
0
resume_addnsec3chain(dns_zone_t *zone) {
3100
0
  dns_dbnode_t *node = NULL;
3101
0
  dns_dbversion_t *version = NULL;
3102
0
  dns_rdataset_t rdataset;
3103
0
  isc_result_t result;
3104
0
  dns_rdata_nsec3param_t nsec3param;
3105
0
  bool nseconly = false, nsec3ok = false;
3106
0
  dns_db_t *db = NULL;
3107
3108
0
  INSIST(LOCKED_ZONE(zone));
3109
3110
0
  if (zone->privatetype == 0) {
3111
0
    return;
3112
0
  }
3113
3114
0
  ZONEDB_LOCK(&zone->dblock, isc_rwlocktype_read);
3115
0
  if (zone->db != NULL) {
3116
0
    dns_db_attach(zone->db, &db);
3117
0
  }
3118
0
  ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_read);
3119
0
  if (db == NULL) {
3120
0
    goto cleanup;
3121
0
  }
3122
3123
0
  CHECK(dns_db_findnode(db, &zone->origin, false, &node));
3124
3125
0
  dns_db_currentversion(db, &version);
3126
3127
  /*
3128
   * In order to create NSEC3 chains we need the DNSKEY RRset at zone
3129
   * apex to exist and contain no keys using NSEC-only algorithms.
3130
   */
3131
0
  result = dns_nsec_nseconly(db, version, NULL, &nseconly);
3132
0
  nsec3ok = (result == ISC_R_SUCCESS && !nseconly);
3133
3134
  /*
3135
   * Get the RRset containing all private-type records at the zone apex.
3136
   */
3137
0
  dns_rdataset_init(&rdataset);
3138
0
  result = dns_db_findrdataset(db, node, version, zone->privatetype,
3139
0
             dns_rdatatype_none, 0, &rdataset, NULL);
3140
0
  if (result != ISC_R_SUCCESS) {
3141
0
    INSIST(!dns_rdataset_isassociated(&rdataset));
3142
0
    goto cleanup;
3143
0
  }
3144
3145
0
  DNS_RDATASET_FOREACH(&rdataset) {
3146
0
    unsigned char buf[DNS_NSEC3PARAM_BUFFERSIZE];
3147
0
    dns_rdata_t rdata = DNS_RDATA_INIT;
3148
0
    dns_rdata_t private = DNS_RDATA_INIT;
3149
3150
0
    dns_rdataset_current(&rdataset, &private);
3151
    /*
3152
     * Try extracting NSEC3PARAM RDATA from this private-type
3153
     * record.  Failure means this private-type record does not
3154
     * represent an NSEC3PARAM record, so skip it.
3155
     */
3156
0
    if (!dns_nsec3param_fromprivate(&private, &rdata, buf,
3157
0
            sizeof(buf)))
3158
0
    {
3159
0
      continue;
3160
0
    }
3161
0
    result = dns_rdata_tostruct(&rdata, &nsec3param);
3162
0
    RUNTIME_CHECK(result == ISC_R_SUCCESS);
3163
0
    if (((nsec3param.flags & DNS_NSEC3FLAG_REMOVE) != 0) ||
3164
0
        ((nsec3param.flags & DNS_NSEC3FLAG_CREATE) != 0 && nsec3ok))
3165
0
    {
3166
      /*
3167
       * Pass the NSEC3PARAM RDATA contained in this
3168
       * private-type record to zone_addnsec3chain() so that
3169
       * it can kick off adding or removing NSEC3 records.
3170
       */
3171
0
      result = zone_addnsec3chain(zone, &nsec3param);
3172
0
      if (result != ISC_R_SUCCESS) {
3173
0
        dnssec_log(zone, ISC_LOG_ERROR,
3174
0
             "zone_addnsec3chain failed: %s",
3175
0
             isc_result_totext(result));
3176
0
      }
3177
0
    }
3178
0
  }
3179
0
  dns_rdataset_disassociate(&rdataset);
3180
3181
0
cleanup:
3182
0
  if (db != NULL) {
3183
0
    if (node != NULL) {
3184
0
      dns_db_detachnode(&node);
3185
0
    }
3186
0
    if (version != NULL) {
3187
0
      dns_db_closeversion(db, &version, false);
3188
0
    }
3189
0
    dns_db_detach(&db);
3190
0
  }
3191
0
}
3192
3193
void
3194
0
dns__zone_set_resigntime(dns_zone_t *zone) {
3195
0
  dns_fixedname_t fixed;
3196
0
  isc_stdtime_t resign;
3197
0
  isc_result_t result;
3198
0
  uint32_t nanosecs;
3199
0
  dns_db_t *db = NULL;
3200
0
  dns_typepair_t typepair;
3201
3202
0
  REQUIRE(DNS_ZONE_VALID(zone));
3203
0
  REQUIRE(LOCKED_ZONE(zone));
3204
3205
  /* We only re-sign zones that can be dynamically updated */
3206
0
  if (!dns_zone_isdynamic(zone, false)) {
3207
0
    return;
3208
0
  }
3209
3210
0
  if (dns__zone_inline_raw(zone)) {
3211
0
    return;
3212
0
  }
3213
3214
0
  dns_fixedname_init(&fixed);
3215
3216
0
  ZONEDB_LOCK(&zone->dblock, isc_rwlocktype_read);
3217
0
  if (zone->db != NULL) {
3218
0
    dns_db_attach(zone->db, &db);
3219
0
  }
3220
0
  ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_read);
3221
0
  if (db == NULL) {
3222
0
    isc_time_settoepoch(&zone->resigntime);
3223
0
    return;
3224
0
  }
3225
3226
0
  result = dns_db_getsigningtime(db, &resign, dns_name(&fixed),
3227
0
               &typepair);
3228
0
  if (result != ISC_R_SUCCESS) {
3229
0
    isc_time_settoepoch(&zone->resigntime);
3230
0
    goto cleanup;
3231
0
  }
3232
3233
0
  resign -= dns_zone_getsigresigninginterval(zone);
3234
0
  nanosecs = isc_random_uniform(1000000000);
3235
0
  isc_time_set(&zone->resigntime, resign, nanosecs);
3236
3237
0
cleanup:
3238
0
  dns_db_detach(&db);
3239
0
  return;
3240
0
}
3241
3242
static isc_result_t
3243
0
check_nsec3param(dns_zone_t *zone, dns_db_t *db) {
3244
0
  bool ok = false;
3245
0
  dns_dbnode_t *node = NULL;
3246
0
  dns_dbversion_t *version = NULL;
3247
0
  dns_rdata_nsec3param_t nsec3param;
3248
0
  dns_rdataset_t rdataset;
3249
0
  isc_result_t result;
3250
0
  bool dynamic = (zone->type == dns_zone_primary)
3251
0
             ? dns_zone_isdynamic(zone, false)
3252
0
             : false;
3253
3254
0
  dns_rdataset_init(&rdataset);
3255
0
  result = dns_db_findnode(db, &zone->origin, false, &node);
3256
0
  if (result != ISC_R_SUCCESS) {
3257
0
    dns_zone_log(zone, ISC_LOG_ERROR,
3258
0
           "nsec3param lookup failure: %s",
3259
0
           isc_result_totext(result));
3260
0
    return result;
3261
0
  }
3262
0
  dns_db_currentversion(db, &version);
3263
3264
0
  result = dns_db_findrdataset(db, node, version,
3265
0
             dns_rdatatype_nsec3param,
3266
0
             dns_rdatatype_none, 0, &rdataset, NULL);
3267
0
  if (result == ISC_R_NOTFOUND) {
3268
0
    INSIST(!dns_rdataset_isassociated(&rdataset));
3269
0
    result = ISC_R_SUCCESS;
3270
0
    goto cleanup;
3271
0
  }
3272
0
  if (result != ISC_R_SUCCESS) {
3273
0
    INSIST(!dns_rdataset_isassociated(&rdataset));
3274
0
    dns_zone_log(zone, ISC_LOG_ERROR,
3275
0
           "nsec3param lookup failure: %s",
3276
0
           isc_result_totext(result));
3277
0
    goto cleanup;
3278
0
  }
3279
3280
0
  DNS_RDATASET_FOREACH(&rdataset) {
3281
0
    dns_rdata_t rdata = DNS_RDATA_INIT;
3282
3283
0
    dns_rdataset_current(&rdataset, &rdata);
3284
0
    result = dns_rdata_tostruct(&rdata, &nsec3param);
3285
0
    RUNTIME_CHECK(result == ISC_R_SUCCESS);
3286
3287
    /*
3288
     * For dynamic zones we must support every algorithm so we
3289
     * can regenerate all the NSEC3 chains.
3290
     * For non-dynamic zones we only need to find a supported
3291
     * algorithm.
3292
     */
3293
0
    if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_NSEC3TESTZONE) &&
3294
0
        nsec3param.hash == DNS_NSEC3_UNKNOWNALG && !dynamic)
3295
0
    {
3296
0
      dns_zone_log(zone, ISC_LOG_WARNING,
3297
0
             "nsec3 test \"unknown\" hash algorithm "
3298
0
             "found: %u",
3299
0
             nsec3param.hash);
3300
0
      ok = true;
3301
0
    } else if (!dns_nsec3_supportedhash(nsec3param.hash)) {
3302
0
      if (dynamic) {
3303
0
        dns_zone_log(zone, ISC_LOG_ERROR,
3304
0
               "unsupported nsec3 hash algorithm"
3305
0
               " in dynamic zone: %u",
3306
0
               nsec3param.hash);
3307
0
        result = DNS_R_BADZONE;
3308
        /* Stop second error message. */
3309
0
        ok = true;
3310
0
        break;
3311
0
      } else {
3312
0
        dns_zone_log(zone, ISC_LOG_WARNING,
3313
0
               "unsupported nsec3 hash "
3314
0
               "algorithm: %u",
3315
0
               nsec3param.hash);
3316
0
      }
3317
0
    } else {
3318
0
      ok = true;
3319
0
    }
3320
3321
    /*
3322
     * Warn if the zone has excessive NSEC3 iterations.
3323
     */
3324
0
    if (nsec3param.iterations > dns_nsec3_maxiterations()) {
3325
0
      dnssec_log(zone, ISC_LOG_WARNING,
3326
0
           "excessive NSEC3PARAM iterations %u > %u",
3327
0
           nsec3param.iterations,
3328
0
           dns_nsec3_maxiterations());
3329
0
    }
3330
0
  }
3331
3332
0
  if (!ok) {
3333
0
    result = DNS_R_BADZONE;
3334
0
    dns_zone_log(zone, ISC_LOG_ERROR,
3335
0
           "no supported nsec3 hash algorithm");
3336
0
  }
3337
3338
0
cleanup:
3339
0
  dns_rdataset_cleanup(&rdataset);
3340
0
  dns_db_closeversion(db, &version, false);
3341
0
  dns_db_detachnode(&node);
3342
0
  return result;
3343
0
}
3344
3345
/*
3346
 * Set the timer for refreshing the key zone to the soonest future time
3347
 * of the set (current timer, keydata->refresh, keydata->addhd,
3348
 * keydata->removehd).
3349
 */
3350
static void
3351
set_refreshkeytimer(dns_zone_t *zone, dns_rdata_keydata_t *key,
3352
0
        isc_stdtime_t now, bool force) {
3353
0
  isc_stdtime_t then;
3354
0
  isc_time_t timenow, timethen;
3355
0
  char timebuf[80];
3356
3357
0
  ENTER;
3358
0
  then = key->refresh;
3359
0
  if (force) {
3360
0
    then = now;
3361
0
  }
3362
0
  if (key->addhd > now && key->addhd < then) {
3363
0
    then = key->addhd;
3364
0
  }
3365
0
  if (key->removehd > now && key->removehd < then) {
3366
0
    then = key->removehd;
3367
0
  }
3368
3369
0
  timenow = isc_time_now();
3370
0
  if (then > now) {
3371
0
    DNS_ZONE_TIME_ADD(&timenow, then - now, &timethen);
3372
0
  } else {
3373
0
    timethen = timenow;
3374
0
  }
3375
0
  if (isc_time_compare(&zone->refreshkeytime, &timenow) < 0 ||
3376
0
      isc_time_compare(&timethen, &zone->refreshkeytime) < 0)
3377
0
  {
3378
0
    zone->refreshkeytime = timethen;
3379
0
  }
3380
3381
0
  isc_time_formattimestamp(&zone->refreshkeytime, timebuf, 80);
3382
0
  dns_zone_log(zone, ISC_LOG_DEBUG(1), "next key refresh: %s", timebuf);
3383
0
  dns__zone_settimer(zone, timenow);
3384
0
}
3385
3386
/*
3387
 * If keynode references a key or a DS rdataset, and if the key
3388
 * zone does not contain a KEYDATA record for the corresponding name,
3389
 * then create an empty KEYDATA and push it into the zone as a placeholder,
3390
 * then schedule a key refresh immediately. This new KEYDATA record will be
3391
 * updated during the refresh.
3392
 *
3393
 * If the key zone is changed, set '*changed' to true.
3394
 */
3395
static isc_result_t
3396
create_keydata(dns_zone_t *zone, dns_db_t *db, dns_dbversion_t *ver,
3397
         dns_diff_t *diff, dns_keynode_t *keynode, dns_name_t *keyname,
3398
0
         bool *changed) {
3399
0
  isc_result_t result = ISC_R_SUCCESS;
3400
0
  dns_rdata_t rdata = DNS_RDATA_INIT;
3401
0
  dns_rdata_keydata_t kd;
3402
0
  unsigned char rrdata[4096];
3403
0
  isc_buffer_t rrdatabuf;
3404
0
  isc_stdtime_t now = isc_stdtime_now();
3405
3406
0
  REQUIRE(keynode != NULL);
3407
3408
0
  ENTER;
3409
3410
  /*
3411
   * If the keynode has no trust anchor set, we shouldn't be here.
3412
   */
3413
0
  if (!dns_keynode_dsset(keynode, NULL)) {
3414
0
    return ISC_R_FAILURE;
3415
0
  }
3416
3417
0
  memset(&kd, 0, sizeof(kd));
3418
0
  kd.common.rdclass = zone->rdclass;
3419
0
  kd.common.rdtype = dns_rdatatype_keydata;
3420
3421
0
  isc_buffer_init(&rrdatabuf, rrdata, sizeof(rrdata));
3422
3423
0
  CHECK(dns_rdata_fromstruct(&rdata, zone->rdclass, dns_rdatatype_keydata,
3424
0
           &kd, &rrdatabuf));
3425
  /* Add rdata to zone. */
3426
0
  CHECK(update_one_rr(db, ver, diff, DNS_DIFFOP_ADD, keyname, 0, &rdata));
3427
0
  *changed = true;
3428
3429
  /* Refresh new keys from the zone apex as soon as possible. */
3430
0
  set_refreshkeytimer(zone, &kd, now, true);
3431
0
  return ISC_R_SUCCESS;
3432
3433
0
cleanup:
3434
0
  return result;
3435
0
}
3436
3437
/*
3438
 * Remove from the key zone all the KEYDATA records found in rdataset.
3439
 */
3440
static isc_result_t
3441
delete_keydata(dns_db_t *db, dns_dbversion_t *ver, dns_diff_t *diff,
3442
0
         dns_name_t *name, dns_rdataset_t *rdataset) {
3443
0
  DNS_RDATASET_FOREACH(rdataset) {
3444
0
    dns_rdata_t rdata = DNS_RDATA_INIT;
3445
0
    dns_rdataset_current(rdataset, &rdata);
3446
0
    RETERR(update_one_rr(db, ver, diff, DNS_DIFFOP_DEL, name, 0,
3447
0
             &rdata));
3448
0
  }
3449
3450
0
  return ISC_R_SUCCESS;
3451
0
}
3452
3453
/*
3454
 * Compute the DNSSEC key ID for a DNSKEY record.
3455
 */
3456
static isc_result_t
3457
0
compute_tag(dns_rdata_dnskey_t *dnskey, dns_keytag_t *tag) {
3458
0
  isc_result_t result;
3459
0
  isc_region_t r;
3460
0
  dns_rdata_t rdata = DNS_RDATA_INIT;
3461
0
  unsigned char data[DNS_RDATA_MAXLENGTH];
3462
0
  isc_buffer_t buffer;
3463
3464
0
  isc_buffer_init(&buffer, data, sizeof(data));
3465
3466
0
  CHECK(dns_rdata_fromstruct(&rdata, dnskey->common.rdclass,
3467
0
           dns_rdatatype_dnskey, dnskey, &buffer));
3468
0
  dns_rdata_toregion(&rdata, &r);
3469
0
  *tag = dst_region_computeid(&r);
3470
3471
0
cleanup:
3472
0
  return result;
3473
0
}
3474
3475
/*
3476
 * Synth-from-dnssec callbacks to add/delete names from namespace tree.
3477
 */
3478
static void
3479
0
sfd_add(const dns_name_t *name, void *arg) {
3480
0
  if (arg != NULL) {
3481
0
    dns_view_sfd_add(arg, name);
3482
0
  }
3483
0
}
3484
3485
static void
3486
0
sfd_del(const dns_name_t *name, void *arg) {
3487
0
  if (arg != NULL) {
3488
0
    dns_view_sfd_del(arg, name);
3489
0
  }
3490
0
}
3491
3492
/*
3493
 * Add key to the security roots.
3494
 */
3495
static void
3496
trust_key(dns_zone_t *zone, dns_name_t *keyname, dns_rdata_dnskey_t *dnskey,
3497
0
    bool initial) {
3498
0
  isc_result_t result;
3499
0
  dns_rdata_t rdata = DNS_RDATA_INIT;
3500
0
  unsigned char data[DNS_RDATA_MAXLENGTH];
3501
0
  unsigned char digest[DNS_DS_BUFFERSIZE];
3502
0
  isc_buffer_t buffer;
3503
0
  dns_keytable_t *sr = NULL;
3504
0
  dns_rdata_ds_t ds;
3505
3506
0
  CHECK(dns_view_getsecroots(zone->view, &sr));
3507
3508
  /* Build DS record for key. */
3509
0
  isc_buffer_init(&buffer, data, sizeof(data));
3510
0
  CHECK(dns_rdata_fromstruct(&rdata, dnskey->common.rdclass,
3511
0
           dns_rdatatype_dnskey, dnskey, &buffer));
3512
0
  CHECK(dns_ds_fromkeyrdata(keyname, &rdata, DNS_DSDIGEST_SHA256, digest,
3513
0
          sizeof(digest), &ds));
3514
0
  CHECK(dns_keytable_add(sr, true, initial, keyname, &ds, sfd_add,
3515
0
             zone->view));
3516
3517
0
  dns_keytable_detach(&sr);
3518
3519
0
cleanup:
3520
0
  if (sr != NULL) {
3521
0
    dns_keytable_detach(&sr);
3522
0
  }
3523
0
  return;
3524
0
}
3525
3526
/*
3527
 * Add a null key to the security roots for so that all queries
3528
 * to the zone will fail.
3529
 */
3530
static void
3531
0
fail_secure(dns_zone_t *zone, dns_name_t *keyname) {
3532
0
  isc_result_t result;
3533
0
  dns_keytable_t *sr = NULL;
3534
3535
0
  result = dns_view_getsecroots(zone->view, &sr);
3536
0
  if (result == ISC_R_SUCCESS) {
3537
0
    dns_keytable_marksecure(sr, keyname);
3538
0
    dns_keytable_detach(&sr);
3539
0
  }
3540
0
}
3541
3542
/*
3543
 * Scan a set of KEYDATA records from the key zone.  The ones that are
3544
 * valid (i.e., the add holddown timer has expired) become trusted keys.
3545
 */
3546
static void
3547
0
load_secroots(dns_zone_t *zone, dns_name_t *name, dns_rdataset_t *rdataset) {
3548
0
  isc_result_t result;
3549
0
  dns_rdata_keydata_t keydata;
3550
0
  dns_rdata_dnskey_t dnskey;
3551
0
  int trusted = 0, revoked = 0, pending = 0;
3552
0
  isc_stdtime_t now = isc_stdtime_now();
3553
0
  dns_keytable_t *sr = NULL;
3554
3555
0
  result = dns_view_getsecroots(zone->view, &sr);
3556
0
  if (result == ISC_R_SUCCESS) {
3557
0
    dns_keytable_delete(sr, name, sfd_del, zone->view);
3558
0
    dns_keytable_detach(&sr);
3559
0
  }
3560
3561
  /* Now insert all the accepted trust anchors from this keydata set. */
3562
0
  DNS_RDATASET_FOREACH(rdataset) {
3563
0
    dns_rdata_t rdata = DNS_RDATA_INIT;
3564
0
    dns_rdataset_current(rdataset, &rdata);
3565
3566
    /* Convert rdata to keydata. */
3567
0
    result = dns_rdata_tostruct(&rdata, &keydata);
3568
0
    if (result == ISC_R_NOTIMPLEMENTED) {
3569
0
      continue;
3570
0
    }
3571
0
    RUNTIME_CHECK(result == ISC_R_SUCCESS);
3572
3573
    /* Set the key refresh timer to force a fast refresh. */
3574
0
    set_refreshkeytimer(zone, &keydata, now, true);
3575
3576
    /* If the removal timer is nonzero, this key was revoked. */
3577
0
    if (keydata.removehd != 0) {
3578
0
      revoked++;
3579
0
      continue;
3580
0
    }
3581
3582
    /*
3583
     * If the add timer is still pending, this key is not
3584
     * trusted yet.
3585
     */
3586
0
    if (now < keydata.addhd) {
3587
0
      pending++;
3588
0
      continue;
3589
0
    }
3590
3591
    /* Convert keydata to dnskey. */
3592
0
    dns_keydata_todnskey(&keydata, &dnskey);
3593
3594
    /* Add to keytables. */
3595
0
    trusted++;
3596
0
    trust_key(zone, name, &dnskey, keydata.addhd == 0);
3597
0
  }
3598
3599
0
  if (trusted == 0 && pending != 0) {
3600
0
    char namebuf[DNS_NAME_FORMATSIZE];
3601
0
    dns_name_format(name, namebuf, sizeof namebuf);
3602
0
    dnssec_log(zone, ISC_LOG_ERROR,
3603
0
         "No valid trust anchors for '%s'!", namebuf);
3604
0
    dnssec_log(zone, ISC_LOG_ERROR,
3605
0
         "%d key(s) revoked, %d still pending", revoked,
3606
0
         pending);
3607
0
    dnssec_log(zone, ISC_LOG_ERROR, "All queries to '%s' will fail",
3608
0
         namebuf);
3609
0
    fail_secure(zone, name);
3610
0
  }
3611
0
}
3612
3613
static isc_result_t
3614
update_one_rr(dns_db_t *db, dns_dbversion_t *ver, dns_diff_t *diff,
3615
        dns_diffop_t op, dns_name_t *name, dns_ttl_t ttl,
3616
0
        dns_rdata_t *rdata) {
3617
0
  dns_difftuple_t *tuple = NULL;
3618
3619
0
  dns_difftuple_create(diff->mctx, op, name, ttl, rdata, &tuple);
3620
0
  return dns_diff_applytuple(&tuple, db, ver, diff);
3621
0
}
3622
3623
static isc_result_t
3624
update_soa_serial(dns_zone_t *zone, dns_db_t *db, dns_dbversion_t *ver,
3625
      dns_diff_t *diff, isc_mem_t *mctx,
3626
0
      dns_updatemethod_t method) {
3627
0
  dns_difftuple_t *deltuple = NULL;
3628
0
  dns_difftuple_t *addtuple = NULL;
3629
0
  uint32_t serial;
3630
0
  isc_result_t result;
3631
0
  dns_updatemethod_t used = dns_updatemethod_none;
3632
3633
0
  INSIST(method != dns_updatemethod_none);
3634
3635
0
  CHECK(dns_db_createsoatuple(db, ver, mctx, DNS_DIFFOP_DEL, &deltuple));
3636
0
  dns_difftuple_copy(deltuple, &addtuple);
3637
0
  addtuple->op = DNS_DIFFOP_ADD;
3638
3639
0
  serial = dns_soa_getserial(&addtuple->rdata);
3640
0
  serial = dns_update_soaserial(serial, method, &used);
3641
0
  if (method != used) {
3642
0
    dns_zone_log(zone, ISC_LOG_WARNING,
3643
0
           "update_soa_serial:new serial would be lower than "
3644
0
           "old serial, using increment method instead");
3645
0
  }
3646
0
  dns_soa_setserial(serial, &addtuple->rdata);
3647
0
  CHECK(dns_diff_applytuple(&deltuple, db, ver, diff));
3648
0
  CHECK(dns_diff_applytuple(&addtuple, db, ver, diff));
3649
0
  result = ISC_R_SUCCESS;
3650
3651
0
cleanup:
3652
0
  if (addtuple != NULL) {
3653
0
    dns_difftuple_free(&addtuple);
3654
0
  }
3655
0
  if (deltuple != NULL) {
3656
0
    dns_difftuple_free(&deltuple);
3657
0
  }
3658
0
  return result;
3659
0
}
3660
3661
/*
3662
 * Write all transactions in 'diff' to the zone journal file.
3663
 */
3664
static isc_result_t
3665
zone_journal(dns_zone_t *zone, dns_diff_t *diff, uint32_t *sourceserial,
3666
0
       const char *caller) {
3667
0
  const char *journalfile;
3668
0
  isc_result_t result = ISC_R_SUCCESS;
3669
0
  dns_journal_t *journal = NULL;
3670
0
  unsigned int mode = DNS_JOURNAL_CREATE | DNS_JOURNAL_WRITE;
3671
3672
0
  ENTER;
3673
0
  journalfile = dns_zone_getjournal(zone);
3674
0
  if (journalfile != NULL) {
3675
0
    result = dns_journal_open(zone->mctx, journalfile, mode,
3676
0
            &journal);
3677
0
    if (result != ISC_R_SUCCESS) {
3678
0
      dns_zone_log(zone, ISC_LOG_ERROR,
3679
0
             "%s:dns_journal_open -> %s", caller,
3680
0
             isc_result_totext(result));
3681
0
      return result;
3682
0
    }
3683
3684
0
    if (sourceserial != NULL) {
3685
0
      dns_journal_set_sourceserial(journal, *sourceserial);
3686
0
    }
3687
3688
0
    result = dns_journal_write_transaction(journal, diff);
3689
0
    if (result != ISC_R_SUCCESS) {
3690
0
      dns_zone_log(zone, ISC_LOG_ERROR,
3691
0
             "%s:dns_journal_write_transaction -> %s",
3692
0
             caller, isc_result_totext(result));
3693
0
    }
3694
0
    dns_journal_destroy(&journal);
3695
0
  }
3696
3697
0
  return result;
3698
0
}
3699
3700
/*
3701
 * Create an SOA record for a newly-created zone
3702
 */
3703
static isc_result_t
3704
0
add_soa(dns_zone_t *zone, dns_db_t *db) {
3705
0
  isc_result_t result;
3706
0
  dns_rdata_t rdata = DNS_RDATA_INIT;
3707
0
  unsigned char buf[DNS_SOA_BUFFERSIZE];
3708
0
  dns_dbversion_t *ver = NULL;
3709
0
  dns_diff_t diff;
3710
3711
0
  dns_zone_log(zone, ISC_LOG_DEBUG(1), "creating SOA");
3712
3713
0
  dns_diff_init(zone->mctx, &diff);
3714
0
  result = dns_db_newversion(db, &ver);
3715
0
  if (result != ISC_R_SUCCESS) {
3716
0
    dns_zone_log(zone, ISC_LOG_ERROR,
3717
0
           "add_soa:dns_db_newversion -> %s",
3718
0
           isc_result_totext(result));
3719
0
    goto cleanup;
3720
0
  }
3721
3722
  /* Build SOA record */
3723
0
  result = dns_soa_buildrdata(&zone->origin, dns_rootname, zone->rdclass,
3724
0
            0, 0, 0, 0, 0, buf, &rdata);
3725
0
  if (result != ISC_R_SUCCESS) {
3726
0
    dns_zone_log(zone, ISC_LOG_ERROR,
3727
0
           "add_soa:dns_soa_buildrdata -> %s",
3728
0
           isc_result_totext(result));
3729
0
    goto cleanup;
3730
0
  }
3731
3732
0
  result = update_one_rr(db, ver, &diff, DNS_DIFFOP_ADD, &zone->origin, 0,
3733
0
             &rdata);
3734
3735
0
cleanup:
3736
0
  dns_diff_clear(&diff);
3737
0
  if (ver != NULL) {
3738
0
    dns_db_closeversion(db, &ver, result == ISC_R_SUCCESS);
3739
0
  }
3740
3741
0
  INSIST(ver == NULL);
3742
3743
0
  return result;
3744
0
}
3745
3746
struct addifmissing_arg {
3747
  dns_db_t *db;
3748
  dns_dbversion_t *ver;
3749
  dns_diff_t *diff;
3750
  dns_zone_t *zone;
3751
  bool *changed;
3752
  isc_result_t result;
3753
};
3754
3755
static void
3756
addifmissing(dns_keytable_t *keytable, dns_keynode_t *keynode,
3757
0
       dns_name_t *keyname, void *arg) {
3758
0
  dns_db_t *db = ((struct addifmissing_arg *)arg)->db;
3759
0
  dns_dbversion_t *ver = ((struct addifmissing_arg *)arg)->ver;
3760
0
  dns_diff_t *diff = ((struct addifmissing_arg *)arg)->diff;
3761
0
  dns_zone_t *zone = ((struct addifmissing_arg *)arg)->zone;
3762
0
  bool *changed = ((struct addifmissing_arg *)arg)->changed;
3763
0
  isc_result_t result;
3764
0
  dns_fixedname_t fname;
3765
3766
0
  UNUSED(keytable);
3767
3768
0
  if (((struct addifmissing_arg *)arg)->result != ISC_R_SUCCESS) {
3769
0
    return;
3770
0
  }
3771
3772
0
  if (!dns_keynode_managed(keynode)) {
3773
0
    return;
3774
0
  }
3775
3776
  /*
3777
   * If the keynode has no trust anchor set, return.
3778
   */
3779
0
  if (!dns_keynode_dsset(keynode, NULL)) {
3780
0
    return;
3781
0
  }
3782
3783
  /*
3784
   * Check whether there's already a KEYDATA entry for this name;
3785
   * if so, we don't need to add another.
3786
   */
3787
0
  dns_fixedname_init(&fname);
3788
0
  result = dns_db_find(db, keyname, ver, dns_rdatatype_keydata,
3789
0
           DNS_DBFIND_NOWILD, 0, dns_name(&fname), NULL,
3790
0
           NULL);
3791
0
  if (result == ISC_R_SUCCESS) {
3792
0
    return;
3793
0
  }
3794
3795
  /*
3796
   * Create the keydata.
3797
   */
3798
0
  result = create_keydata(zone, db, ver, diff, keynode, keyname, changed);
3799
0
  if (result != ISC_R_SUCCESS && result != ISC_R_NOMORE) {
3800
0
    ((struct addifmissing_arg *)arg)->result = result;
3801
0
  }
3802
0
}
3803
3804
/*
3805
 * Synchronize the set of initializing keys found in trust-anchors {}
3806
 * statements with the set of trust anchors found in the managed-keys.bind
3807
 * zone.  If a domain is no longer named in trust-anchors, delete all keys
3808
 * from that domain from the key zone.  If a domain is configured as an
3809
 * initial-key in trust-anchors, but there are no references to it in the
3810
 * key zone, load the key zone with the initializing key(s) for that
3811
 * domain and schedule a key refresh. If a domain is configured as
3812
 * an initial-ds in trust-anchors, fetch the DNSKEY RRset, load the key
3813
 * zone with the matching key, and schedule a key refresh.
3814
 */
3815
static isc_result_t
3816
0
sync_keyzone(dns_zone_t *zone, dns_db_t *db) {
3817
0
  isc_result_t result = ISC_R_SUCCESS;
3818
0
  bool changed = false;
3819
0
  bool commit = false;
3820
0
  dns_keynode_t *keynode = NULL;
3821
0
  dns_view_t *view = zone->view;
3822
0
  dns_keytable_t *sr = NULL;
3823
0
  dns_dbversion_t *ver = NULL;
3824
0
  dns_diff_t diff;
3825
0
  dns_rriterator_t rrit;
3826
0
  struct addifmissing_arg arg;
3827
3828
0
  dns_zone_log(zone, ISC_LOG_DEBUG(1), "synchronizing trusted keys");
3829
3830
0
  dns_diff_init(zone->mctx, &diff);
3831
3832
0
  CHECK(dns_view_getsecroots(view, &sr));
3833
3834
0
  result = dns_db_newversion(db, &ver);
3835
0
  if (result != ISC_R_SUCCESS) {
3836
0
    dnssec_log(zone, ISC_LOG_ERROR,
3837
0
         "sync_keyzone:dns_db_newversion -> %s",
3838
0
         isc_result_totext(result));
3839
0
    goto cleanup;
3840
0
  }
3841
3842
  /*
3843
   * Walk the zone DB.  If we find any keys whose names are no longer
3844
   * in trust-anchors, or which have been changed from initial to static,
3845
   * (meaning they are permanent and not RFC5011-maintained), delete
3846
   * them from the zone.  Otherwise call load_secroots(), which
3847
   * loads keys into secroots as appropriate.
3848
   */
3849
0
  dns_rriterator_init(&rrit, db, ver, 0);
3850
0
  for (result = dns_rriterator_first(&rrit); result == ISC_R_SUCCESS;
3851
0
       result = dns_rriterator_nextrrset(&rrit))
3852
0
  {
3853
0
    dns_rdataset_t *rdataset = NULL;
3854
0
    dns_rdata_keydata_t keydata;
3855
0
    isc_stdtime_t now = isc_stdtime_now();
3856
0
    bool load = true;
3857
0
    dns_name_t *rrname = NULL;
3858
0
    uint32_t ttl;
3859
3860
0
    dns_rriterator_current(&rrit, &rrname, &ttl, &rdataset, NULL);
3861
0
    if (!dns_rdataset_isassociated(rdataset)) {
3862
0
      dns_rriterator_destroy(&rrit);
3863
0
      goto cleanup;
3864
0
    }
3865
3866
0
    if (rdataset->type != dns_rdatatype_keydata) {
3867
0
      continue;
3868
0
    }
3869
3870
    /*
3871
     * The managed-keys zone can contain a placeholder instead of
3872
     * legitimate data, in which case we will not use it, and we
3873
     * will try to refresh it.
3874
     */
3875
0
    DNS_RDATASET_FOREACH(rdataset) {
3876
0
      isc_result_t iresult;
3877
0
      dns_rdata_t rdata = DNS_RDATA_INIT;
3878
3879
0
      dns_rdataset_current(rdataset, &rdata);
3880
3881
0
      iresult = dns_rdata_tostruct(&rdata, &keydata);
3882
      /* Do we have a valid placeholder KEYDATA record? */
3883
0
      if (iresult == ISC_R_SUCCESS && keydata.flags == 0 &&
3884
0
          keydata.protocol == 0 && keydata.algorithm == 0)
3885
0
      {
3886
0
        set_refreshkeytimer(zone, &keydata, now, true);
3887
0
        load = false;
3888
0
      }
3889
0
    }
3890
3891
    /*
3892
     * Release db wrlock to prevent LOR reports against
3893
     * dns_keytable_forall() call below.
3894
     */
3895
0
    dns_rriterator_pause(&rrit);
3896
0
    result = dns_keytable_find(sr, rrname, &keynode);
3897
0
    if (result != ISC_R_SUCCESS || !dns_keynode_managed(keynode)) {
3898
0
      CHECK(delete_keydata(db, ver, &diff, rrname, rdataset));
3899
0
      changed = true;
3900
0
    } else if (load) {
3901
0
      load_secroots(zone, rrname, rdataset);
3902
0
    }
3903
3904
0
    if (keynode != NULL) {
3905
0
      dns_keynode_detach(&keynode);
3906
0
    }
3907
0
  }
3908
0
  dns_rriterator_destroy(&rrit);
3909
3910
  /*
3911
   * Walk secroots to find any initial keys that aren't in
3912
   * the zone.  If we find any, add them to the zone directly.
3913
   * If any DS-style initial keys are found, refresh the key
3914
   * zone so that they'll be looked up.
3915
   */
3916
0
  arg.db = db;
3917
0
  arg.ver = ver;
3918
0
  arg.result = ISC_R_SUCCESS;
3919
0
  arg.diff = &diff;
3920
0
  arg.zone = zone;
3921
0
  arg.changed = &changed;
3922
0
  dns_keytable_forall(sr, addifmissing, &arg);
3923
0
  result = arg.result;
3924
0
  if (changed) {
3925
    /* Write changes to journal file. */
3926
0
    CHECK(update_soa_serial(zone, db, ver, &diff, zone->mctx,
3927
0
          zone->updatemethod));
3928
0
    CHECK(zone_journal(zone, &diff, NULL, "sync_keyzone"));
3929
3930
0
    DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_LOADED);
3931
0
    zone_needdump(zone, 30);
3932
0
    commit = true;
3933
0
  }
3934
3935
0
cleanup:
3936
0
  if (result != ISC_R_SUCCESS) {
3937
0
    dnssec_log(zone, ISC_LOG_ERROR,
3938
0
         "unable to synchronize managed keys: %s",
3939
0
         isc_result_totext(result));
3940
0
    isc_time_settoepoch(&zone->refreshkeytime);
3941
0
  }
3942
0
  if (keynode != NULL) {
3943
0
    dns_keynode_detach(&keynode);
3944
0
  }
3945
0
  if (sr != NULL) {
3946
0
    dns_keytable_detach(&sr);
3947
0
  }
3948
0
  if (ver != NULL) {
3949
0
    dns_db_closeversion(db, &ver, commit);
3950
0
  }
3951
0
  dns_diff_clear(&diff);
3952
3953
0
  INSIST(ver == NULL);
3954
3955
0
  return result;
3956
0
}
3957
3958
isc_result_t
3959
0
dns_zone_synckeyzone(dns_zone_t *zone) {
3960
0
  isc_result_t result;
3961
0
  dns_db_t *db = NULL;
3962
3963
0
  if (zone->type != dns_zone_key) {
3964
0
    return DNS_R_BADZONE;
3965
0
  }
3966
3967
0
  CHECK(dns_zone_getdb(zone, &db));
3968
3969
0
  LOCK_ZONE(zone);
3970
0
  result = sync_keyzone(zone, db);
3971
0
  UNLOCK_ZONE(zone);
3972
3973
0
cleanup:
3974
0
  if (db != NULL) {
3975
0
    dns_db_detach(&db);
3976
0
  }
3977
0
  return result;
3978
0
}
3979
3980
static bool
3981
0
zone_unchanged(dns_db_t *db1, dns_db_t *db2, isc_mem_t *mctx) {
3982
0
  isc_result_t result;
3983
0
  bool answer = false;
3984
0
  dns_diff_t diff;
3985
3986
0
  dns_diff_init(mctx, &diff);
3987
0
  result = dns_db_diffx(&diff, db1, NULL, db2, NULL, NULL);
3988
0
  if (result == ISC_R_SUCCESS && ISC_LIST_EMPTY(diff.tuples)) {
3989
0
    answer = true;
3990
0
  }
3991
0
  dns_diff_clear(&diff);
3992
0
  return answer;
3993
0
}
3994
3995
/*
3996
 * Compare times treating epoch as "unset".
3997
 */
3998
static inline bool
3999
0
time_greater_equal(isc_time_t a, isc_time_t b) {
4000
0
  return !isc_time_isepoch(&b) && isc_time_compare(&a, &b) >= 0;
4001
0
}
4002
4003
static inline isc_time_t
4004
0
time_min(isc_time_t a, isc_time_t b) {
4005
0
  if (isc_time_isepoch(&b)) {
4006
0
    return a;
4007
0
  }
4008
0
  return isc_time_isepoch(&a) || isc_time_compare(&b, &a) < 0 ? b : a;
4009
0
}
4010
4011
static bool
4012
0
zone_maintenance_request_pending(dns_zone_t *zone) {
4013
0
  REQUIRE(LOCKED_ZONE(zone));
4014
4015
0
  return zone->iss == NULL && DNS_ZONE_FLAG(zone, DNS_ZONEFLG_LOADED) &&
4016
0
         !ISC_LIST_EMPTY(zone->maintenance_queue);
4017
0
}
4018
4019
static unsigned char er_ndata[] = "\001*\003_er";
4020
static dns_name_t er = DNS_NAME_INITNONABSOLUTE(er_ndata);
4021
4022
static isc_result_t
4023
0
check_reportchannel(dns_zone_t *zone, dns_db_t *db) {
4024
0
  isc_result_t result;
4025
0
  dns_rdataset_t rdataset = DNS_RDATASET_INIT;
4026
0
  dns_dbnode_t *node = NULL;
4027
0
  dns_dbversion_t *version = NULL;
4028
0
  dns_fixedname_t fixed;
4029
0
  dns_name_t *name = NULL;
4030
4031
  /*
4032
   * If this zone isn't logging reports, it's fine.
4033
   */
4034
0
  if (!DNS_ZONE_OPTION(zone, DNS_ZONEOPT_LOGREPORTS)) {
4035
0
    return ISC_R_SUCCESS;
4036
0
  }
4037
4038
  /*
4039
   * Otherwise, we need a '*._er' wildcard with a TXT rdataset.
4040
   */
4041
0
  name = dns_fixedname_initname(&fixed);
4042
0
  CHECK(dns_name_concatenate(&er, &zone->origin, name));
4043
0
  CHECK(dns_db_findnode(db, name, false, &node));
4044
4045
0
  dns_db_currentversion(db, &version);
4046
4047
0
  result = dns_db_findrdataset(db, node, version, dns_rdatatype_txt,
4048
0
             dns_rdatatype_none, 0, &rdataset, NULL);
4049
0
  dns_db_closeversion(db, &version, false);
4050
0
  dns_db_detachnode(&node);
4051
0
  if (result == ISC_R_SUCCESS) {
4052
0
    dns_rdataset_disassociate(&rdataset);
4053
0
  }
4054
4055
0
cleanup:
4056
0
  return result;
4057
0
}
4058
4059
/*
4060
 * The zone is presumed to be locked.
4061
 * If this is a inline_raw zone the secure version is also locked.
4062
 */
4063
static isc_result_t
4064
zone_postload(dns_zone_t *zone, dns_db_t *db, isc_time_t loadtime,
4065
0
        isc_result_t result) {
4066
0
  unsigned int soacount = 0;
4067
0
  unsigned int nscount = 0;
4068
0
  unsigned int errors = 0;
4069
0
  uint32_t serial, oldserial, refresh, retry, expire, minimum, soattl;
4070
0
  isc_time_t now;
4071
0
  bool needdump = false;
4072
0
  bool fixjournal = false;
4073
0
  bool hasinclude = DNS_ZONE_FLAG(zone, DNS_ZONEFLG_HASINCLUDE);
4074
0
  bool noprimary = false;
4075
0
  bool had_db = false;
4076
0
  bool is_dynamic = false;
4077
4078
0
  INSIST(LOCKED_ZONE(zone));
4079
0
  if (dns__zone_inline_raw(zone)) {
4080
0
    INSIST(LOCKED_ZONE(zone->secure));
4081
0
  }
4082
4083
0
  now = isc_time_now();
4084
4085
  /*
4086
   * Initiate zone transfer?  We may need a error code that
4087
   * indicates that the "permanent" form does not exist.
4088
   * XXX better error feedback to log.
4089
   */
4090
0
  if (result != ISC_R_SUCCESS && result != DNS_R_SEENINCLUDE) {
4091
0
    if (zone->type == dns_zone_secondary ||
4092
0
        zone->type == dns_zone_mirror ||
4093
0
        zone->type == dns_zone_stub ||
4094
0
        (zone->type == dns_zone_redirect &&
4095
0
         dns_remote_addresses(&zone->primaries) == NULL))
4096
0
    {
4097
0
      if (result == ISC_R_FILENOTFOUND) {
4098
0
        dns_zone_logc(zone, DNS_LOGCATEGORY_ZONELOAD,
4099
0
                ISC_LOG_DEBUG(1),
4100
0
                "no master file");
4101
0
      } else if (result != DNS_R_NOMASTERFILE) {
4102
0
        dns_zone_logc(zone, DNS_LOGCATEGORY_ZONELOAD,
4103
0
                ISC_LOG_ERROR,
4104
0
                "loading from master file %s "
4105
0
                "failed: %s",
4106
0
                zone->masterfile,
4107
0
                isc_result_totext(result));
4108
0
      }
4109
0
    } else if (zone->type == dns_zone_primary &&
4110
0
         dns__zone_inline_secure(zone) &&
4111
0
         result == ISC_R_FILENOTFOUND)
4112
0
    {
4113
0
      dns_zone_logc(zone, DNS_LOGCATEGORY_ZONELOAD,
4114
0
              ISC_LOG_DEBUG(1),
4115
0
              "no master file; secure db will be "
4116
0
              "bootstrapped from raw zone");
4117
0
    } else {
4118
0
      int level = ISC_LOG_ERROR;
4119
0
      if (zone->type == dns_zone_key &&
4120
0
          result == ISC_R_FILENOTFOUND)
4121
0
      {
4122
0
        level = ISC_LOG_DEBUG(1);
4123
0
      }
4124
0
      dns_zone_logc(zone, DNS_LOGCATEGORY_ZONELOAD, level,
4125
0
              "loading from master file %s failed: %s",
4126
0
              zone->masterfile,
4127
0
              isc_result_totext(result));
4128
0
      noprimary = true;
4129
0
    }
4130
4131
0
    if (zone->type != dns_zone_key) {
4132
0
      goto cleanup;
4133
0
    }
4134
0
  }
4135
4136
0
  dns_zone_logc(zone, DNS_LOGCATEGORY_ZONELOAD, ISC_LOG_DEBUG(2),
4137
0
          "number of nodes in database: %u", dns_db_nodecount(db));
4138
4139
0
  if (result == DNS_R_SEENINCLUDE) {
4140
0
    DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_HASINCLUDE);
4141
0
  } else {
4142
0
    DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_HASINCLUDE);
4143
0
  }
4144
4145
  /*
4146
   * If there's no master file for a key zone, then the zone is new:
4147
   * create an SOA record.  (We do this now, instead of later, so that
4148
   * if there happens to be a journal file, we can roll forward from
4149
   * a sane starting point.)
4150
   */
4151
0
  if (noprimary && zone->type == dns_zone_key) {
4152
0
    CHECK(add_soa(zone, db));
4153
0
  }
4154
4155
  /*
4156
   * Apply update log, if any, on initial load.
4157
   */
4158
0
  if (zone->journal != NULL &&
4159
0
      !DNS_ZONE_OPTION(zone, DNS_ZONEOPT_NOMERGE) &&
4160
0
      !DNS_ZONE_FLAG(zone, DNS_ZONEFLG_LOADED))
4161
0
  {
4162
0
    CHECK(zone_journal_rollforward(zone, db, &needdump,
4163
0
                 &fixjournal));
4164
0
  }
4165
4166
  /*
4167
   * Obtain ns, soa and cname counts for top of zone.
4168
   */
4169
0
  INSIST(db != NULL);
4170
0
  result = zone_get_from_db(zone, db, &nscount, &soacount, &soattl,
4171
0
          &serial, &refresh, &retry, &expire, &minimum,
4172
0
          &errors);
4173
0
  if (result != ISC_R_SUCCESS && zone->type != dns_zone_key) {
4174
0
    dns_zone_logc(zone, DNS_LOGCATEGORY_ZONELOAD, ISC_LOG_ERROR,
4175
0
            "could not find NS and/or SOA records");
4176
0
  }
4177
4178
0
  is_dynamic = dns_zone_isdynamic(zone, true);
4179
4180
  /*
4181
   * Check to make sure the journal is up to date, and remove the
4182
   * journal file if it isn't, as we wouldn't be able to apply
4183
   * updates otherwise.
4184
   */
4185
0
  if (zone->journal != NULL && is_dynamic &&
4186
0
      !DNS_ZONE_OPTION(zone, DNS_ZONEOPT_IXFRFROMDIFFS))
4187
0
  {
4188
0
    uint32_t jserial;
4189
0
    dns_journal_t *journal = NULL;
4190
0
    bool empty = false;
4191
4192
0
    result = dns_journal_open(zone->mctx, zone->journal,
4193
0
            DNS_JOURNAL_READ, &journal);
4194
0
    if (result == ISC_R_SUCCESS) {
4195
0
      jserial = dns_journal_last_serial(journal);
4196
0
      empty = dns_journal_empty(journal);
4197
0
      dns_journal_destroy(&journal);
4198
0
    } else {
4199
0
      jserial = serial;
4200
0
    }
4201
4202
0
    if (jserial != serial) {
4203
0
      if (!empty) {
4204
0
        dns_zone_logc(zone, DNS_LOGCATEGORY_ZONELOAD,
4205
0
                ISC_LOG_INFO,
4206
0
                "journal file is out of date: "
4207
0
                "removing journal file");
4208
0
      }
4209
0
      if (remove(zone->journal) < 0 && errno != ENOENT) {
4210
0
        char strbuf[ISC_STRERRORSIZE];
4211
0
        strerror_r(errno, strbuf, sizeof(strbuf));
4212
0
        isc_log_write(DNS_LOGCATEGORY_GENERAL,
4213
0
                DNS_LOGMODULE_ZONE,
4214
0
                ISC_LOG_WARNING,
4215
0
                "unable to remove journal "
4216
0
                "'%s': '%s'",
4217
0
                zone->journal, strbuf);
4218
0
      }
4219
0
    }
4220
0
  }
4221
4222
0
  dns_zone_logc(zone, DNS_LOGCATEGORY_ZONELOAD, ISC_LOG_DEBUG(1),
4223
0
          "loaded; checking validity");
4224
4225
  /*
4226
   * Primary / Secondary / Mirror / Stub zones require both NS and SOA
4227
   * records at the top of the zone.
4228
   */
4229
4230
0
  switch (zone->type) {
4231
0
  case dns_zone_dlz:
4232
0
  case dns_zone_primary:
4233
0
  case dns_zone_secondary:
4234
0
  case dns_zone_mirror:
4235
0
  case dns_zone_stub:
4236
0
  case dns_zone_redirect:
4237
0
    if (soacount != 1) {
4238
0
      dns_zone_logc(zone, DNS_LOGCATEGORY_ZONELOAD,
4239
0
              ISC_LOG_ERROR, "has %d SOA records",
4240
0
              soacount);
4241
0
      RETERR(DNS_R_BADZONE);
4242
0
    }
4243
0
    if (nscount == 0 && DNS_ZONE_OPTION(zone, DNS_ZONEOPT_CHECKNS))
4244
0
    {
4245
0
      dns_zone_logc(zone, DNS_LOGCATEGORY_ZONELOAD,
4246
0
              ISC_LOG_WARNING, "has no NS records");
4247
0
      if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_FATALNS)) {
4248
0
        RETERR(DNS_R_BADZONE);
4249
0
      }
4250
0
    }
4251
0
    if (zone->type == dns_zone_primary && errors != 0) {
4252
0
      CLEANUP(DNS_R_BADZONE);
4253
0
    }
4254
0
    if (zone->type != dns_zone_stub &&
4255
0
        zone->type != dns_zone_redirect)
4256
0
    {
4257
0
      CHECK(check_nsec3param(zone, db));
4258
0
    }
4259
0
    if (zone->type == dns_zone_primary &&
4260
0
        DNS_ZONE_OPTION(zone, DNS_ZONEOPT_CHECKINTEGRITY) &&
4261
0
        !integrity_checks(zone, db))
4262
0
    {
4263
0
      CLEANUP(DNS_R_BADZONE);
4264
0
    }
4265
0
    if (zone->type == dns_zone_primary &&
4266
0
        DNS_ZONE_OPTION(zone, DNS_ZONEOPT_CHECKDUPRR) &&
4267
0
        !zone_check_dup(zone, db))
4268
0
    {
4269
0
      CLEANUP(DNS_R_BADZONE);
4270
0
    }
4271
4272
0
    if (zone->type == dns_zone_primary) {
4273
0
      result = dns_zone_cdscheck(zone, db, NULL);
4274
0
      if (result != ISC_R_SUCCESS) {
4275
0
        dns_zone_log(zone, ISC_LOG_ERROR,
4276
0
               "CDS/CDNSKEY consistency checks "
4277
0
               "failed");
4278
0
        goto cleanup;
4279
0
      }
4280
0
    }
4281
4282
0
    result = check_reportchannel(zone, db);
4283
0
    if (result != ISC_R_SUCCESS) {
4284
0
      dns_zone_log(zone, ISC_LOG_ERROR,
4285
0
             "'log-report-channel' is set, but no "
4286
0
             "'*._er/TXT' wildcard found");
4287
0
      CLEANUP(DNS_R_BADZONE);
4288
0
    }
4289
4290
0
    if (zone->type == dns_zone_mirror) {
4291
0
      CHECK(dns_zone_verifydb(zone->view, db, NULL));
4292
0
    }
4293
4294
0
    if (zone->db != NULL) {
4295
0
      unsigned int oldsoacount;
4296
4297
      /*
4298
       * This is checked in zone_replacedb() for
4299
       * secondary zones as they don't reload from disk.
4300
       */
4301
0
      result = zone_get_from_db(
4302
0
        zone, zone->db, NULL, &oldsoacount, NULL,
4303
0
        &oldserial, NULL, NULL, NULL, NULL, NULL);
4304
0
      RUNTIME_CHECK(result == ISC_R_SUCCESS);
4305
0
      RUNTIME_CHECK(oldsoacount > 0U);
4306
0
      if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_IXFRFROMDIFFS) &&
4307
0
          !isc_serial_gt(serial, oldserial))
4308
0
      {
4309
0
        uint32_t serialmin, serialmax;
4310
4311
0
        INSIST(zone->type == dns_zone_primary);
4312
0
        INSIST(zone->raw == NULL);
4313
4314
0
        if (serial == oldserial &&
4315
0
            zone_unchanged(zone->db, db, zone->mctx))
4316
0
        {
4317
0
          dns_zone_logc(zone,
4318
0
                  DNS_LOGCATEGORY_ZONELOAD,
4319
0
                  ISC_LOG_INFO,
4320
0
                  "ixfr-from-differences: "
4321
0
                  "unchanged");
4322
0
          zone->loadtime = loadtime;
4323
0
          goto done;
4324
0
        }
4325
4326
0
        serialmin = (oldserial + 1) & 0xffffffffU;
4327
0
        serialmax = (oldserial + 0x7fffffffU) &
4328
0
              0xffffffffU;
4329
0
        dns_zone_logc(zone, DNS_LOGCATEGORY_ZONELOAD,
4330
0
                ISC_LOG_ERROR,
4331
0
                "ixfr-from-differences: "
4332
0
                "new serial (%u) out of range "
4333
0
                "[%u - %u]",
4334
0
                serial, serialmin, serialmax);
4335
0
        CLEANUP(DNS_R_BADZONE);
4336
0
      } else if (!isc_serial_ge(serial, oldserial)) {
4337
0
        dns_zone_logc(zone, DNS_LOGCATEGORY_ZONELOAD,
4338
0
                ISC_LOG_ERROR,
4339
0
                "zone serial (%u/%u) has gone "
4340
0
                "backwards",
4341
0
                serial, oldserial);
4342
0
      } else if (serial == oldserial && !hasinclude &&
4343
0
           strcmp(zone->db_argv[0], "_builtin") != 0)
4344
0
      {
4345
0
        dns_zone_logc(zone, DNS_LOGCATEGORY_ZONELOAD,
4346
0
                ISC_LOG_ERROR,
4347
0
                "zone serial (%u) unchanged. "
4348
0
                "zone may fail to transfer "
4349
0
                "to secondaries.",
4350
0
                serial);
4351
0
      }
4352
0
    }
4353
4354
0
    if (zone->type == dns_zone_primary &&
4355
0
        (zone->update_acl != NULL || zone->ssutable != NULL) &&
4356
0
        dns_zone_getsigresigninginterval(zone) < (3 * refresh) &&
4357
0
        dns_db_issecure(db))
4358
0
    {
4359
0
      dns_zone_logc(zone, DNS_LOGCATEGORY_ZONELOAD,
4360
0
              ISC_LOG_WARNING,
4361
0
              "sig-re-signing-interval less than "
4362
0
              "3 * refresh.");
4363
0
    }
4364
4365
0
    zone->refresh = RANGE(refresh, zone->minrefresh,
4366
0
              zone->maxrefresh);
4367
0
    zone->retry = RANGE(retry, zone->minretry, zone->maxretry);
4368
0
    zone->expire = RANGE(expire, zone->refresh + zone->retry,
4369
0
             DNS_MAX_EXPIRE);
4370
0
    zone->soattl = soattl;
4371
0
    zone->minimum = minimum;
4372
0
    DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_HAVETIMERS);
4373
4374
0
    if (zone->type == dns_zone_secondary ||
4375
0
        zone->type == dns_zone_mirror ||
4376
0
        zone->type == dns_zone_stub ||
4377
0
        (zone->type == dns_zone_redirect &&
4378
0
         dns_remote_addresses(&zone->primaries) != NULL))
4379
0
    {
4380
0
      isc_time_t t;
4381
0
      uint32_t delay;
4382
4383
0
      result = isc_file_getmodtime(zone->journal, &t);
4384
0
      if (result != ISC_R_SUCCESS) {
4385
0
        result = isc_file_getmodtime(zone->masterfile,
4386
0
                   &t);
4387
0
      }
4388
0
      if (result == ISC_R_SUCCESS) {
4389
0
        DNS_ZONE_TIME_ADD(&t, zone->expire,
4390
0
              &zone->expiretime);
4391
0
      } else {
4392
0
        DNS_ZONE_TIME_ADD(&now, zone->retry,
4393
0
              &zone->expiretime);
4394
0
      }
4395
4396
0
      delay = (zone->retry -
4397
0
         isc_random_uniform((zone->retry * 3) / 4));
4398
0
      DNS_ZONE_TIME_ADD(&now, delay, &zone->refreshtime);
4399
0
      if (isc_time_compare(&zone->refreshtime,
4400
0
               &zone->expiretime) >= 0)
4401
0
      {
4402
0
        DNS_ZONE_SETFLAG(zone,
4403
0
             DNS_ZONEFLG_FIRSTREFRESH);
4404
0
        zone->refreshtime = now;
4405
0
      } else {
4406
        /* The zone is up to date. */
4407
0
        DNS_ZONE_CLRFLAG(zone,
4408
0
             DNS_ZONEFLG_FIRSTREFRESH);
4409
0
      }
4410
0
    }
4411
4412
0
    break;
4413
4414
0
  case dns_zone_key:
4415
    /* Nothing needs to be done now */
4416
0
    break;
4417
4418
0
  default:
4419
0
    UNEXPECTED_ERROR("unexpected zone type %d", zone->type);
4420
0
    CLEANUP(ISC_R_UNEXPECTED);
4421
0
  }
4422
4423
  /*
4424
   * Check for weak DNSKEY's.
4425
   */
4426
0
  if (zone->type == dns_zone_primary) {
4427
0
    zone_check_dnskeys(zone, db);
4428
0
  }
4429
4430
  /*
4431
   * Schedule DNSSEC key refresh.
4432
   */
4433
0
  if (zone->type == dns_zone_primary && zone->kasp != NULL) {
4434
0
    zone->refreshkeytime = now;
4435
0
  }
4436
4437
0
  ZONEDB_LOCK(&zone->dblock, isc_rwlocktype_write);
4438
0
  if (zone->db != NULL) {
4439
0
    had_db = true;
4440
0
    result = zone_replacedb(zone, db, false);
4441
0
    ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_write);
4442
0
    if (result != ISC_R_SUCCESS) {
4443
0
      goto cleanup;
4444
0
    }
4445
0
  } else {
4446
0
    zone_attachdb(zone, db);
4447
0
    ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_write);
4448
0
    DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_LOADED |
4449
0
                 DNS_ZONEFLG_NEEDSTARTUPNOTIFY);
4450
0
    if (dns__zone_inline_raw(zone)) {
4451
0
      zone_schedule_inline_sync(zone->secure,
4452
0
              inline_sync_incremental);
4453
0
    }
4454
0
  }
4455
4456
0
  result = ISC_R_SUCCESS;
4457
4458
0
  if (fixjournal) {
4459
0
    DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_FIXJOURNAL);
4460
0
    zone_journal_compact(zone, zone->db, 0);
4461
0
  }
4462
0
  if (needdump) {
4463
0
    if (zone->type == dns_zone_key) {
4464
0
      zone_needdump(zone, 30);
4465
0
    } else {
4466
0
      zone_needdump(zone, DNS_DUMP_DELAY);
4467
0
    }
4468
0
  }
4469
4470
0
  if (zone->loop != NULL) {
4471
0
    if (zone->type == dns_zone_primary) {
4472
0
      dns__zone_set_resigntime(zone);
4473
0
      resume_signingwithkey(zone);
4474
0
      resume_addnsec3chain(zone);
4475
0
    }
4476
4477
0
    is_dynamic = dns_zone_isdynamic(zone, false);
4478
0
    if (zone->type == dns_zone_primary && is_dynamic &&
4479
0
        dns_db_issecure(db) && !dns__zone_inline_raw(zone))
4480
0
    {
4481
0
      isc_stdtime_t resign;
4482
0
      dns_name_t *name;
4483
0
      dns_fixedname_t fixed;
4484
0
      dns_typepair_t typepair;
4485
4486
0
      name = dns_fixedname_initname(&fixed);
4487
4488
0
      result = dns_db_getsigningtime(db, &resign, name,
4489
0
                   &typepair);
4490
0
      if (result == ISC_R_SUCCESS) {
4491
0
        isc_stdtime_t timenow = isc_stdtime_now();
4492
0
        char namebuf[DNS_NAME_FORMATSIZE];
4493
0
        char typebuf[DNS_RDATATYPE_FORMATSIZE];
4494
4495
0
        dns_name_format(name, namebuf, sizeof(namebuf));
4496
0
        dns_rdatatype_format(
4497
0
          DNS_TYPEPAIR_COVERS(typepair), typebuf,
4498
0
          sizeof(typebuf));
4499
0
        dnssec_log(
4500
0
          zone, ISC_LOG_DEBUG(3),
4501
0
          "next resign: %s/%s "
4502
0
          "in %d seconds",
4503
0
          namebuf, typebuf,
4504
0
          resign - timenow -
4505
0
            dns_zone_getsigresigninginterval(
4506
0
              zone));
4507
0
      } else {
4508
0
        dnssec_log(zone, ISC_LOG_WARNING,
4509
0
             "signed dynamic zone has no "
4510
0
             "resign event scheduled");
4511
0
      }
4512
0
    }
4513
4514
0
    dns__zone_settimer(zone, now);
4515
0
  }
4516
4517
  /*
4518
   * Clear old include list.
4519
   */
4520
0
  ISC_LIST_FOREACH(zone->includes, inc, link) {
4521
0
    ISC_LIST_UNLINK(zone->includes, inc, link);
4522
0
    isc_mem_free(zone->mctx, inc->name);
4523
0
    isc_mem_put(zone->mctx, inc, sizeof(*inc));
4524
0
  }
4525
4526
  /*
4527
   * Transfer new include list.
4528
   */
4529
0
  ISC_LIST_FOREACH(zone->newincludes, inc, link) {
4530
0
    ISC_LIST_UNLINK(zone->newincludes, inc, link);
4531
0
    ISC_LIST_APPEND(zone->includes, inc, link);
4532
0
  }
4533
4534
0
  if (!dns_db_ispersistent(db)) {
4535
0
    dns_zone_logc(zone, DNS_LOGCATEGORY_ZONELOAD, ISC_LOG_INFO,
4536
0
            "loaded serial %u%s", serial,
4537
0
            dns_db_issecure(db) ? " (DNSSEC signed)" : "");
4538
0
  }
4539
4540
0
  if (!had_db && zone->type == dns_zone_mirror) {
4541
0
    dns_zone_logc(zone, DNS_LOGCATEGORY_ZONELOAD, ISC_LOG_INFO,
4542
0
            "mirror zone is now in use");
4543
0
  }
4544
4545
0
  zone->loadtime = loadtime;
4546
0
  goto done;
4547
4548
0
cleanup:
4549
0
  if (result != ISC_R_SUCCESS) {
4550
0
    dns_zone_rpz_disable_db(zone, db);
4551
0
    dns_zone_catz_disable_db(zone, db);
4552
0
  }
4553
4554
0
  ISC_LIST_FOREACH(zone->newincludes, inc, link) {
4555
0
    ISC_LIST_UNLINK(zone->newincludes, inc, link);
4556
0
    isc_mem_free(zone->mctx, inc->name);
4557
0
    isc_mem_put(zone->mctx, inc, sizeof(*inc));
4558
0
  }
4559
0
  if (zone->type == dns_zone_secondary || zone->type == dns_zone_mirror ||
4560
0
      zone->type == dns_zone_stub || zone->type == dns_zone_key ||
4561
0
      (zone->type == dns_zone_redirect &&
4562
0
       dns_remote_addresses(&zone->primaries) != NULL))
4563
0
  {
4564
0
    DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_FIRSTREFRESH);
4565
4566
0
    if (zone->journal != NULL) {
4567
0
      zone_saveunique(zone, zone->journal, "jn-XXXXXXXX");
4568
0
    }
4569
0
    if (zone->masterfile != NULL) {
4570
0
      zone_saveunique(zone, zone->masterfile, "db-XXXXXXXX");
4571
0
    }
4572
4573
    /* Mark the zone for immediate refresh. */
4574
0
    zone->refreshtime = now;
4575
0
    if (zone->loop != NULL) {
4576
0
      dns__zone_settimer(zone, now);
4577
0
    }
4578
0
    result = ISC_R_SUCCESS;
4579
0
  } else if (zone->type == dns_zone_primary ||
4580
0
       zone->type == dns_zone_redirect)
4581
0
  {
4582
0
    if (!(dns__zone_inline_secure(zone) &&
4583
0
          result == ISC_R_FILENOTFOUND))
4584
0
    {
4585
0
      dns_zone_logc(zone, DNS_LOGCATEGORY_ZONELOAD,
4586
0
              ISC_LOG_ERROR,
4587
0
              "not loaded due to errors.");
4588
0
    } else if (zone->type == dns_zone_primary) {
4589
0
      result = ISC_R_SUCCESS;
4590
0
    }
4591
0
  }
4592
4593
0
done:
4594
0
  DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_LOADPENDING);
4595
  /*
4596
   * If this is an inline-signed zone and we were called for the raw
4597
   * zone, we need to clear DNS_ZONEFLG_LOADPENDING for the secure zone
4598
   * as well, but only if this is a reload, not an initial zone load: in
4599
   * the former case, zone_postload() will not be run for the secure
4600
   * zone; in the latter case, it will be.  Check which case we are
4601
   * dealing with by consulting the DNS_ZONEFLG_LOADED flag for the
4602
   * secure zone: if it is set, this must be a reload.
4603
   */
4604
0
  if (dns__zone_inline_raw(zone) &&
4605
0
      DNS_ZONE_FLAG(zone->secure, DNS_ZONEFLG_LOADED))
4606
0
  {
4607
0
    DNS_ZONE_CLRFLAG(zone->secure, DNS_ZONEFLG_LOADPENDING);
4608
    /*
4609
     * Re-start zone maintenance if it had been stalled
4610
     * due to DNS_ZONEFLG_LOADPENDING being set when
4611
     * zone_maintenance was called.
4612
     */
4613
0
    if (zone->secure->loop != NULL) {
4614
0
      dns__zone_settimer(zone->secure, now);
4615
0
    }
4616
0
  }
4617
4618
0
  zone_debuglog(zone, __func__, 99, "done");
4619
4620
0
  return result;
4621
0
}
4622
4623
bool
4624
0
dns__zone_free_check(dns_zone_t *zone) {
4625
0
  REQUIRE(LOCKED_ZONE(zone));
4626
4627
0
  if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_SHUTDOWN) &&
4628
0
      isc_refcount_current(&zone->irefs) == 0)
4629
0
  {
4630
    /*
4631
     * DNS_ZONEFLG_SHUTDOWN can only be set if references == 0.
4632
     */
4633
0
    INSIST(isc_refcount_current(&zone->references) == 0);
4634
0
    return true;
4635
0
  }
4636
0
  return false;
4637
0
}
4638
4639
void
4640
0
dns_zone_forcemaint(dns_zone_t *zone) {
4641
0
  REQUIRE(DNS_ZONE_VALID(zone));
4642
0
  LOCK_ZONE(zone);
4643
0
  dns__zone_settimer(zone, isc_time_now());
4644
0
  UNLOCK_ZONE(zone);
4645
0
}
4646
4647
unsigned int
4648
0
dns_zone_getcount(dns_zone_t *zone, dns_zonestate_t state) {
4649
0
  unsigned int count = 0;
4650
0
  REQUIRE(DNS_ZONE_VALID(zone));
4651
0
  LOCK_ZONE(zone);
4652
0
  switch (state) {
4653
0
  case DNS_ZONESTATE_XFERFIRSTREFRESH:
4654
0
    count = DNS_ZONE_FLAG(zone, DNS_ZONEFLG_FIRSTREFRESH);
4655
0
    break;
4656
0
  case DNS_ZONESTATE_SOAQUERY:
4657
0
    count = DNS_ZONE_FLAG(zone, DNS_ZONEFLG_REFRESH);
4658
0
    break;
4659
0
  case DNS_ZONESTATE_ANY:
4660
0
  case DNS_ZONESTATE_AUTOMATIC:
4661
0
    if (zone->view == NULL ||
4662
0
        strcmp(zone->view->name, "_bind") != 0)
4663
0
    {
4664
0
      count = state == DNS_ZONESTATE_ANY || zone->automatic;
4665
0
    }
4666
0
    break;
4667
0
  default:
4668
0
    UNREACHABLE();
4669
0
  }
4670
0
  UNLOCK_ZONE(zone);
4671
0
  return count;
4672
0
}
4673
4674
static bool
4675
zone_check_ns(dns_zone_t *zone, dns_db_t *db, dns_dbversion_t *version,
4676
0
        dns_name_t *name, bool logit) {
4677
0
  isc_result_t result;
4678
0
  char namebuf[DNS_NAME_FORMATSIZE];
4679
0
  char altbuf[DNS_NAME_FORMATSIZE];
4680
0
  dns_fixedname_t fixed;
4681
0
  dns_name_t *foundname;
4682
0
  int level;
4683
4684
0
  if (!DNS_ZONE_OPTION(zone, DNS_ZONEOPT_CHECKNS)) {
4685
0
    return true;
4686
0
  }
4687
4688
0
  if (zone->type == dns_zone_primary) {
4689
0
    level = ISC_LOG_ERROR;
4690
0
  } else {
4691
0
    level = ISC_LOG_WARNING;
4692
0
  }
4693
4694
0
  foundname = dns_fixedname_initname(&fixed);
4695
4696
0
  result = dns_db_find(db, name, version, dns_rdatatype_a, 0, 0,
4697
0
           foundname, NULL, NULL);
4698
0
  if (result == ISC_R_SUCCESS) {
4699
0
    return true;
4700
0
  }
4701
4702
0
  if (result == DNS_R_NXRRSET) {
4703
0
    result = dns_db_find(db, name, version, dns_rdatatype_aaaa, 0,
4704
0
             0, foundname, NULL, NULL);
4705
0
    if (result == ISC_R_SUCCESS) {
4706
0
      return true;
4707
0
    }
4708
0
  }
4709
4710
0
  if (result == DNS_R_NXRRSET || result == DNS_R_NXDOMAIN ||
4711
0
      result == DNS_R_EMPTYNAME)
4712
0
  {
4713
0
    if (logit) {
4714
0
      dns_name_format(name, namebuf, sizeof namebuf);
4715
0
      dns_zone_log(zone, level,
4716
0
             "NS '%s' has no address "
4717
0
             "records (A or AAAA)",
4718
0
             namebuf);
4719
0
    }
4720
0
    return false;
4721
0
  }
4722
4723
0
  if (result == DNS_R_CNAME) {
4724
0
    if (logit) {
4725
0
      dns_name_format(name, namebuf, sizeof namebuf);
4726
0
      dns_zone_log(zone, level,
4727
0
             "NS '%s' is a CNAME "
4728
0
             "(illegal)",
4729
0
             namebuf);
4730
0
    }
4731
0
    return false;
4732
0
  }
4733
4734
0
  if (result == DNS_R_DNAME) {
4735
0
    if (logit) {
4736
0
      dns_name_format(name, namebuf, sizeof namebuf);
4737
0
      dns_name_format(foundname, altbuf, sizeof altbuf);
4738
0
      dns_zone_log(zone, level,
4739
0
             "NS '%s' is below a DNAME "
4740
0
             "'%s' (illegal)",
4741
0
             namebuf, altbuf);
4742
0
    }
4743
0
    return false;
4744
0
  }
4745
4746
0
  return true;
4747
0
}
4748
4749
static isc_result_t
4750
zone_count_ns_rr(dns_zone_t *zone, dns_db_t *db, dns_dbnode_t *node,
4751
     dns_dbversion_t *version, unsigned int *nscount,
4752
0
     unsigned int *errors, bool logit) {
4753
0
  isc_result_t result;
4754
0
  unsigned int count = 0;
4755
0
  unsigned int ecount = 0;
4756
0
  dns_rdataset_t rdataset;
4757
0
  dns_rdata_ns_t ns;
4758
4759
0
  dns_rdataset_init(&rdataset);
4760
0
  result = dns_db_findrdataset(db, node, version, dns_rdatatype_ns,
4761
0
             dns_rdatatype_none, 0, &rdataset, NULL);
4762
0
  if (result == ISC_R_NOTFOUND) {
4763
0
    INSIST(!dns_rdataset_isassociated(&rdataset));
4764
0
    goto success;
4765
0
  }
4766
0
  if (result != ISC_R_SUCCESS) {
4767
0
    INSIST(!dns_rdataset_isassociated(&rdataset));
4768
0
    goto invalidate_rdataset;
4769
0
  }
4770
4771
0
  DNS_RDATASET_FOREACH(&rdataset) {
4772
0
    if (errors != NULL && zone->rdclass == dns_rdataclass_in &&
4773
0
        (zone->type == dns_zone_primary ||
4774
0
         zone->type == dns_zone_secondary ||
4775
0
         zone->type == dns_zone_mirror))
4776
0
    {
4777
0
      dns_rdata_t rdata = DNS_RDATA_INIT;
4778
0
      dns_rdataset_current(&rdataset, &rdata);
4779
4780
0
      result = dns_rdata_tostruct(&rdata, &ns);
4781
0
      RUNTIME_CHECK(result == ISC_R_SUCCESS);
4782
0
      if (dns_name_issubdomain(&ns.name, &zone->origin) &&
4783
0
          !zone_check_ns(zone, db, version, &ns.name, logit))
4784
0
      {
4785
0
        ecount++;
4786
0
      }
4787
0
    }
4788
0
    count++;
4789
0
  }
4790
0
  dns_rdataset_disassociate(&rdataset);
4791
4792
0
success:
4793
0
  SET_IF_NOT_NULL(nscount, count);
4794
0
  SET_IF_NOT_NULL(errors, ecount);
4795
4796
0
  result = ISC_R_SUCCESS;
4797
4798
0
invalidate_rdataset:
4799
0
  dns_rdataset_invalidate(&rdataset);
4800
4801
0
  return result;
4802
0
}
4803
4804
#define SET_SOA_VALUES(soattl_v, serial_v, refresh_v, retry_v, expire_v, \
4805
           minimum_v)                                        \
4806
0
  {                                                                \
4807
0
    SET_IF_NOT_NULL(soattl, soattl_v);                       \
4808
0
    SET_IF_NOT_NULL(serial, serial_v);                       \
4809
0
    SET_IF_NOT_NULL(refresh, refresh_v);                     \
4810
0
    SET_IF_NOT_NULL(retry, retry_v);                         \
4811
0
    SET_IF_NOT_NULL(expire, expire_v);                       \
4812
0
    SET_IF_NOT_NULL(minimum, minimum_v);                     \
4813
0
  }
4814
4815
#define CLR_SOA_VALUES()                          \
4816
0
  {                                         \
4817
0
    SET_SOA_VALUES(0, 0, 0, 0, 0, 0); \
4818
0
  }
4819
4820
static isc_result_t
4821
zone_load_soa_rr(dns_db_t *db, dns_dbnode_t *node, dns_dbversion_t *version,
4822
     unsigned int *soacount, uint32_t *soattl, uint32_t *serial,
4823
     uint32_t *refresh, uint32_t *retry, uint32_t *expire,
4824
0
     uint32_t *minimum) {
4825
0
  isc_result_t result;
4826
0
  unsigned int count = 0;
4827
0
  dns_rdataset_t rdataset;
4828
4829
0
  dns_rdataset_init(&rdataset);
4830
0
  result = dns_db_findrdataset(db, node, version, dns_rdatatype_soa,
4831
0
             dns_rdatatype_none, 0, &rdataset, NULL);
4832
0
  if (result == ISC_R_NOTFOUND) {
4833
0
    INSIST(!dns_rdataset_isassociated(&rdataset));
4834
0
    result = ISC_R_SUCCESS;
4835
0
    goto invalidate_rdataset;
4836
0
  }
4837
0
  if (result != ISC_R_SUCCESS) {
4838
0
    INSIST(!dns_rdataset_isassociated(&rdataset));
4839
0
    goto invalidate_rdataset;
4840
0
  }
4841
4842
0
  DNS_RDATASET_FOREACH(&rdataset) {
4843
0
    dns_rdata_t rdata = DNS_RDATA_INIT;
4844
0
    dns_rdataset_current(&rdataset, &rdata);
4845
4846
0
    count++;
4847
0
    if (count == 1) {
4848
0
      dns_rdata_soa_t soa;
4849
0
      result = dns_rdata_tostruct(&rdata, &soa);
4850
0
      SET_SOA_VALUES(rdataset.ttl, soa.serial, soa.refresh,
4851
0
               soa.retry, soa.expire, soa.minimum);
4852
0
      RUNTIME_CHECK(result == ISC_R_SUCCESS);
4853
0
    }
4854
0
  }
4855
0
  dns_rdataset_disassociate(&rdataset);
4856
4857
0
  result = ISC_R_SUCCESS;
4858
4859
0
invalidate_rdataset:
4860
0
  SET_IF_NOT_NULL(soacount, count);
4861
0
  if (count == 0) {
4862
0
    CLR_SOA_VALUES();
4863
0
  }
4864
4865
0
  dns_rdataset_invalidate(&rdataset);
4866
4867
0
  return result;
4868
0
}
4869
4870
/*
4871
 * zone must be locked.
4872
 */
4873
static isc_result_t
4874
zone_get_from_db(dns_zone_t *zone, dns_db_t *db, unsigned int *nscount,
4875
     unsigned int *soacount, uint32_t *soattl, uint32_t *serial,
4876
     uint32_t *refresh, uint32_t *retry, uint32_t *expire,
4877
0
     uint32_t *minimum, unsigned int *errors) {
4878
0
  isc_result_t result;
4879
0
  isc_result_t answer = ISC_R_SUCCESS;
4880
0
  dns_dbversion_t *version = NULL;
4881
0
  dns_dbnode_t *node;
4882
4883
0
  REQUIRE(db != NULL);
4884
0
  REQUIRE(zone != NULL);
4885
4886
0
  dns_db_currentversion(db, &version);
4887
4888
0
  SET_IF_NOT_NULL(nscount, 0);
4889
0
  SET_IF_NOT_NULL(soacount, 0);
4890
0
  SET_IF_NOT_NULL(errors, 0);
4891
0
  CLR_SOA_VALUES();
4892
4893
0
  node = NULL;
4894
0
  result = dns_db_findnode(db, &zone->origin, false, &node);
4895
0
  if (result != ISC_R_SUCCESS) {
4896
0
    answer = result;
4897
0
    goto closeversion;
4898
0
  }
4899
4900
0
  if (nscount != NULL || errors != NULL) {
4901
0
    result = zone_count_ns_rr(zone, db, node, version, nscount,
4902
0
            errors, true);
4903
0
    if (result != ISC_R_SUCCESS) {
4904
0
      answer = result;
4905
0
    }
4906
0
  }
4907
4908
0
  if (soacount != NULL || soattl != NULL || serial != NULL ||
4909
0
      refresh != NULL || retry != NULL || expire != NULL ||
4910
0
      minimum != NULL)
4911
0
  {
4912
0
    result = zone_load_soa_rr(db, node, version, soacount, soattl,
4913
0
            serial, refresh, retry, expire,
4914
0
            minimum);
4915
0
    if (result != ISC_R_SUCCESS) {
4916
0
      answer = result;
4917
0
    }
4918
0
  }
4919
4920
0
  dns_db_detachnode(&node);
4921
0
closeversion:
4922
0
  dns_db_closeversion(db, &version, false);
4923
4924
0
  return answer;
4925
0
}
4926
4927
static void
4928
0
zone_destroy(dns_zone_t *zone) {
4929
  /*
4930
   * Stop things being restarted after we cancel them below.
4931
   */
4932
0
  DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_EXITING);
4933
0
  dns_zone_log(zone, ISC_LOG_DEBUG(1), "final reference detached");
4934
4935
0
  if (zone->loop == NULL) {
4936
    /*
4937
     * This zone is unmanaged; we're probably running in
4938
     * named-checkzone or a unit test. There's no loop, so we
4939
     * need to free it immediately.
4940
     */
4941
0
    zone_shutdown(zone);
4942
0
  } else {
4943
    /*
4944
     * This zone has a loop; it can clean
4945
     * itself up asynchronously.
4946
     */
4947
0
    isc_async_run(zone->loop, zone_shutdown, zone);
4948
0
  }
4949
0
}
4950
4951
#if DNS_ZONE_TRACE
4952
ISC_REFCOUNT_TRACE_IMPL(dns_zone, zone_destroy);
4953
#else
4954
0
ISC_REFCOUNT_IMPL(dns_zone, zone_destroy);
Unexecuted instantiation: dns_zone_ref
Unexecuted instantiation: dns_zone_unref
Unexecuted instantiation: dns_zone_detach
4955
0
#endif
4956
0
4957
0
static void
4958
0
zone_iattach(dns_zone_t *source, dns_zone_t **target) {
4959
0
  REQUIRE(DNS_ZONE_VALID(source));
4960
0
  REQUIRE(LOCKED_ZONE(source));
4961
0
  REQUIRE(target != NULL && *target == NULL);
4962
0
  INSIST(isc_refcount_increment0(&source->irefs) +
4963
0
           isc_refcount_current(&source->references) >
4964
0
         0);
4965
0
  *target = source;
4966
0
}
4967
4968
void
4969
0
dns__zone_iattach_locked(dns_zone_t *source, dns_zone_t **target) {
4970
0
  zone_iattach(source, target);
4971
0
}
4972
4973
void
4974
0
dns_zone_iattach(dns_zone_t *source, dns_zone_t **target) {
4975
0
  REQUIRE(DNS_ZONE_VALID(source));
4976
4977
0
  LOCK_ZONE(source);
4978
0
  zone_iattach(source, target);
4979
0
  UNLOCK_ZONE(source);
4980
0
}
4981
4982
static void
4983
0
zone_idetach(dns_zone_t **zonep) {
4984
0
  dns_zone_t *zone;
4985
4986
  /*
4987
   * 'zone' locked by caller.
4988
   */
4989
0
  REQUIRE(zonep != NULL && DNS_ZONE_VALID(*zonep));
4990
0
  REQUIRE(LOCKED_ZONE(*zonep));
4991
4992
0
  zone = *zonep;
4993
0
  *zonep = NULL;
4994
4995
0
  INSIST(isc_refcount_decrement(&zone->irefs) - 1 +
4996
0
           isc_refcount_current(&zone->references) >
4997
0
         0);
4998
0
}
4999
5000
void
5001
0
dns__zone_idetach_locked(dns_zone_t **zonep) {
5002
0
  zone_idetach(zonep);
5003
0
}
5004
5005
void
5006
0
dns_zone_idetach(dns_zone_t **zonep) {
5007
0
  dns_zone_t *zone;
5008
5009
0
  REQUIRE(zonep != NULL && DNS_ZONE_VALID(*zonep));
5010
5011
0
  zone = *zonep;
5012
0
  *zonep = NULL;
5013
5014
0
  if (isc_refcount_decrement(&zone->irefs) == 1) {
5015
0
    bool free_needed;
5016
0
    LOCK_ZONE(zone);
5017
0
    free_needed = dns__zone_free_check(zone);
5018
0
    UNLOCK_ZONE(zone);
5019
0
    if (free_needed) {
5020
0
      dns__zone_free(zone);
5021
0
    }
5022
0
  }
5023
0
}
5024
5025
isc_refcount_t *
5026
0
dns__zone_irefs(dns_zone_t *zone) {
5027
0
  REQUIRE(DNS_ZONE_VALID(zone));
5028
5029
0
  return &zone->irefs;
5030
0
}
5031
5032
static void
5033
0
dns_zone_setskr(dns_zone_t *zone, dns_skr_t *skr) {
5034
0
  REQUIRE(DNS_ZONE_VALID(zone));
5035
5036
0
  LOCK_ZONE(zone);
5037
0
  zone->skrbundle = NULL;
5038
0
  if (zone->skr != NULL) {
5039
0
    dns_skr_detach(&zone->skr);
5040
0
  }
5041
0
  if (skr != NULL) {
5042
0
    dns_skr_attach(skr, &zone->skr);
5043
0
  }
5044
0
  UNLOCK_ZONE(zone);
5045
0
}
5046
5047
dns_skrbundle_t *
5048
0
dns_zone_getskrbundle(dns_zone_t *zone) {
5049
0
  dns_skrbundle_t *bundle;
5050
5051
0
  REQUIRE(DNS_ZONE_VALID(zone));
5052
5053
0
  LOCK_ZONE(zone);
5054
0
  if (dns__zone_inline_raw(zone) && zone->secure != NULL) {
5055
0
    bundle = zone->secure->skrbundle;
5056
0
  } else {
5057
0
    bundle = zone->skrbundle;
5058
0
  }
5059
0
  UNLOCK_ZONE(zone);
5060
5061
0
  return bundle;
5062
0
}
5063
5064
void
5065
0
dns_zone_setoption(dns_zone_t *zone, dns_zoneopt_t option, bool value) {
5066
0
  REQUIRE(DNS_ZONE_VALID(zone));
5067
5068
0
  if (value) {
5069
0
    DNS_ZONE_SETOPTION(zone, option);
5070
0
  } else {
5071
0
    DNS_ZONE_CLROPTION(zone, option);
5072
0
  }
5073
0
}
5074
5075
dns_zoneopt_t
5076
0
dns_zone_getoptions(dns_zone_t *zone) {
5077
0
  REQUIRE(DNS_ZONE_VALID(zone));
5078
5079
0
  return atomic_load_relaxed(&zone->options);
5080
0
}
5081
5082
static bool
5083
0
was_dumping(dns_zone_t *zone) {
5084
0
  REQUIRE(LOCKED_ZONE(zone));
5085
5086
0
  if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_DUMPING)) {
5087
0
    return true;
5088
0
  }
5089
5090
0
  DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_DUMPING);
5091
0
  DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_NEEDDUMP);
5092
0
  isc_time_settoepoch(&zone->dumptime);
5093
0
  return false;
5094
0
}
5095
5096
/*
5097
 * Key files are named after the key tag, but distinct keys may share a key
5098
 * tag, e.g. an offline KSK and a ZSK.  Treat a key file holding a different
5099
 * key than 'pubkey' as missing.
5100
 */
5101
static isc_result_t
5102
keyfromdir(dst_key_t *pubkey, const char *directory, isc_mem_t *mctx,
5103
0
     dst_key_t **key) {
5104
0
  isc_result_t result;
5105
5106
0
  result = dst_key_fromfile(
5107
0
    dst_key_name(pubkey), dst_key_id(pubkey), dst_key_alg(pubkey),
5108
0
    DST_TYPE_PUBLIC | DST_TYPE_PRIVATE | DST_TYPE_STATE, directory,
5109
0
    mctx, key);
5110
0
  if (result == ISC_R_SUCCESS && !dst_key_pubcompare(pubkey, *key, true))
5111
0
  {
5112
0
    dst_key_free(key);
5113
0
    result = ISC_R_FILENOTFOUND;
5114
0
  }
5115
5116
0
  return result;
5117
0
}
5118
5119
static isc_result_t
5120
keyfromfile(dns_zone_t *zone, dst_key_t *pubkey, isc_mem_t *mctx,
5121
0
      dst_key_t **key) {
5122
0
  const char *directory = zone->keydirectory;
5123
0
  dns_kasp_t *kasp = zone->kasp;
5124
0
  dst_key_t *foundkey = NULL;
5125
0
  isc_result_t result = ISC_R_NOTFOUND;
5126
5127
0
  if (kasp == NULL || (strcmp(dns_kasp_getname(kasp), "none") == 0) ||
5128
0
      (strcmp(dns_kasp_getname(kasp), "insecure") == 0))
5129
0
  {
5130
0
    result = keyfromdir(pubkey, directory, mctx, &foundkey);
5131
0
  } else {
5132
0
    ISC_LIST_FOREACH(dns_kasp_keys(kasp), kkey, link) {
5133
0
      dns_keystore_t *ks = dns_kasp_key_keystore(kkey);
5134
0
      directory = dns_keystore_directory(ks,
5135
0
                 zone->keydirectory);
5136
5137
0
      result = keyfromdir(pubkey, directory, mctx, &foundkey);
5138
0
      if (result == ISC_R_SUCCESS) {
5139
0
        break;
5140
0
      }
5141
0
    }
5142
0
  }
5143
5144
0
  *key = foundkey;
5145
0
  return result;
5146
0
}
5147
5148
static isc_result_t
5149
findzonekeys(dns_zone_t *zone, dns_db_t *db, dns_dbversion_t *ver,
5150
       dns_dbnode_t *node, const dns_name_t *name, isc_stdtime_t now,
5151
       isc_mem_t *mctx, unsigned int maxkeys, dst_key_t **keys,
5152
0
       unsigned int *nkeys) {
5153
0
  dns_rdataset_t rdataset;
5154
0
  dns_rdata_t rdata = DNS_RDATA_INIT;
5155
0
  isc_result_t result;
5156
0
  dst_key_t *pubkey = NULL;
5157
0
  unsigned int count = 0;
5158
5159
0
  *nkeys = 0;
5160
0
  memset(keys, 0, sizeof(*keys) * maxkeys);
5161
0
  dns_rdataset_init(&rdataset);
5162
0
  CHECK(dns_db_findrdataset(db, node, ver, dns_rdatatype_dnskey, 0, 0,
5163
0
          &rdataset, NULL));
5164
0
  CHECK(dns_rdataset_first(&rdataset));
5165
0
  while (result == ISC_R_SUCCESS && count < maxkeys) {
5166
0
    pubkey = NULL;
5167
0
    dns_rdataset_current(&rdataset, &rdata);
5168
5169
0
    result = dns_dnssec_keyfromrdata(name, &rdata, mctx, &pubkey);
5170
0
    if (result != ISC_R_SUCCESS) {
5171
0
      goto next;
5172
0
    }
5173
0
    dst_key_setttl(pubkey, rdataset.ttl);
5174
5175
0
    if (!ZONEKEY(pubkey)) {
5176
0
      goto next;
5177
0
    }
5178
    /* Corrupted .key file? */
5179
0
    if (!dns_name_equal(name, dst_key_name(pubkey))) {
5180
0
      goto next;
5181
0
    }
5182
0
    keys[count] = NULL;
5183
0
    result = keyfromfile(zone, pubkey, mctx, &keys[count]);
5184
5185
    /*
5186
     * If the key was revoked and the private file
5187
     * doesn't exist, maybe it was revoked internally
5188
     * by named.  Try loading the unrevoked version.
5189
     */
5190
0
    if (result == ISC_R_FILENOTFOUND) {
5191
0
      uint32_t flags;
5192
0
      flags = dst_key_flags(pubkey);
5193
0
      if ((flags & DNS_KEYFLAG_REVOKE) != 0) {
5194
0
        dst_key_setflags(pubkey,
5195
0
             flags & ~DNS_KEYFLAG_REVOKE);
5196
0
        result = keyfromfile(zone, pubkey, mctx,
5197
0
                 &keys[count]);
5198
0
        if (result == ISC_R_SUCCESS &&
5199
0
            dst_key_pubcompare(pubkey, keys[count],
5200
0
                   false))
5201
0
        {
5202
0
          dst_key_setflags(keys[count], flags);
5203
0
        }
5204
0
        dst_key_setflags(pubkey, flags);
5205
0
      }
5206
0
    }
5207
5208
0
    if (result != ISC_R_SUCCESS) {
5209
0
      char filename[DNS_NAME_FORMATSIZE + DST_ALG_FORMATSIZE +
5210
0
              sizeof("key file for //65535")];
5211
0
      isc_result_t result2;
5212
0
      isc_buffer_t buf;
5213
5214
0
      isc_buffer_init(&buf, filename, sizeof(filename));
5215
0
      result2 = dst_key_getfilename(
5216
0
        dst_key_name(pubkey), dst_key_id(pubkey),
5217
0
        dst_key_alg(pubkey),
5218
0
        DST_TYPE_PUBLIC | DST_TYPE_PRIVATE |
5219
0
          DST_TYPE_STATE,
5220
0
        NULL, mctx, &buf);
5221
0
      if (result2 != ISC_R_SUCCESS) {
5222
0
        char namebuf[DNS_NAME_FORMATSIZE];
5223
0
        char algbuf[DST_ALG_FORMATSIZE];
5224
5225
0
        dns_name_format(dst_key_name(pubkey), namebuf,
5226
0
            sizeof(namebuf));
5227
0
        dst_algorithm_format(dst_key_alg(pubkey),
5228
0
                 algbuf, sizeof(algbuf));
5229
0
        snprintf(filename, sizeof(filename) - 1,
5230
0
           "key file for %s/%s/%hu", namebuf,
5231
0
           algbuf, dst_key_id(pubkey));
5232
0
      }
5233
5234
0
      isc_log_write(DNS_LOGCATEGORY_GENERAL,
5235
0
              DNS_LOGMODULE_DNSSEC, ISC_LOG_WARNING,
5236
0
              "dns_zone_findkeys: error reading %s: %s",
5237
0
              filename, isc_result_totext(result));
5238
0
    }
5239
5240
0
    if (result == ISC_R_FILENOTFOUND || result == ISC_R_NOPERM) {
5241
0
      keys[count] = pubkey;
5242
0
      pubkey = NULL;
5243
0
      count++;
5244
0
      goto next;
5245
0
    }
5246
5247
0
    CHECK(result);
5248
5249
    /*
5250
     * If a key is marked inactive, skip it
5251
     */
5252
0
    if (!dns_dnssec_keyactive(keys[count], now)) {
5253
0
      dst_key_setinactive(pubkey, true);
5254
0
      dst_key_free(&keys[count]);
5255
0
      keys[count] = pubkey;
5256
0
      pubkey = NULL;
5257
0
      count++;
5258
0
      goto next;
5259
0
    }
5260
5261
    /*
5262
     * Whatever the key's default TTL may have
5263
     * been, the rdataset TTL takes priority.
5264
     */
5265
0
    dst_key_setttl(keys[count], rdataset.ttl);
5266
0
    count++;
5267
0
  next:
5268
0
    if (pubkey != NULL) {
5269
0
      dst_key_free(&pubkey);
5270
0
    }
5271
0
    dns_rdata_reset(&rdata);
5272
0
    result = dns_rdataset_next(&rdataset);
5273
0
  }
5274
0
  if (result != ISC_R_NOMORE) {
5275
0
    CHECK(result);
5276
0
  }
5277
0
  if (count == 0) {
5278
0
    result = ISC_R_NOTFOUND;
5279
0
  } else {
5280
0
    result = ISC_R_SUCCESS;
5281
0
  }
5282
5283
0
cleanup:
5284
0
  dns_rdataset_cleanup(&rdataset);
5285
0
  if (pubkey != NULL) {
5286
0
    dst_key_free(&pubkey);
5287
0
  }
5288
0
  if (result != ISC_R_SUCCESS) {
5289
0
    while (count > 0) {
5290
0
      dst_key_free(&keys[--count]);
5291
0
    }
5292
0
  }
5293
0
  *nkeys = count;
5294
0
  return result;
5295
0
}
5296
5297
/*%
5298
 * Find up to 'maxkeys' DNSSEC keys used for signing version 'ver' of database
5299
 * 'db' for zone 'zone' in its key directory, then load these keys into 'keys'.
5300
 * Only load the public part of a given key if it is not active at timestamp
5301
 * 'now'.  Store the number of keys found in 'nkeys'.
5302
 */
5303
isc_result_t
5304
dns_zone_findkeys(dns_zone_t *zone, dns_db_t *db, dns_dbversion_t *ver,
5305
      isc_stdtime_t now, isc_mem_t *mctx, unsigned int maxkeys,
5306
0
      dst_key_t **keys, unsigned int *nkeys) {
5307
0
  isc_result_t result;
5308
0
  dns_dbnode_t *node = NULL;
5309
5310
0
  REQUIRE(DNS_ZONE_VALID(zone));
5311
0
  REQUIRE(mctx != NULL);
5312
0
  REQUIRE(nkeys != NULL);
5313
0
  REQUIRE(keys != NULL);
5314
5315
0
  CHECK(dns_db_findnode(db, dns_db_origin(db), false, &node));
5316
5317
0
  dns_zone_lock_keyfiles(zone);
5318
5319
0
  result = findzonekeys(zone, db, ver, node, dns_db_origin(db), now, mctx,
5320
0
            maxkeys, keys, nkeys);
5321
5322
0
  dns_zone_unlock_keyfiles(zone);
5323
5324
0
  if (result == ISC_R_NOTFOUND) {
5325
0
    result = ISC_R_SUCCESS;
5326
0
  }
5327
5328
0
cleanup:
5329
5330
0
  if (node != NULL) {
5331
0
    dns_db_detachnode(&node);
5332
0
  }
5333
0
  return result;
5334
0
}
5335
5336
void
5337
0
dns_zone_prepare_shutdown(dns_zone_t *zone) {
5338
0
  REQUIRE(DNS_ZONE_VALID(zone));
5339
5340
0
  LOCK_ZONE(zone);
5341
0
  DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_EXITING);
5342
0
  UNLOCK_ZONE(zone);
5343
0
}
5344
5345
/*%
5346
 * Find DNSSEC keys used for signing zone with dnssec-policy. Load these keys
5347
 * into 'keys'. Requires KASP to be locked.
5348
 */
5349
isc_result_t
5350
dns_zone_getdnsseckeys(dns_zone_t *zone, dns_db_t *db, dns_dbversion_t *ver,
5351
0
           isc_stdtime_t now, dns_dnsseckeylist_t *keys) {
5352
0
  isc_result_t result;
5353
0
  const char *dir = dns_zone_getkeydirectory(zone);
5354
0
  dns_dbnode_t *node = NULL;
5355
0
  dns_dnsseckeylist_t dnskeys;
5356
0
  dns_name_t *origin = dns_zone_getorigin(zone);
5357
0
  dns_kasp_t *kasp = zone->kasp;
5358
0
  dns_rdataset_t keyset;
5359
5360
0
  REQUIRE(DNS_ZONE_VALID(zone));
5361
0
  REQUIRE(kasp != NULL);
5362
5363
0
  ISC_LIST_INIT(dnskeys);
5364
5365
0
  dns_rdataset_init(&keyset);
5366
5367
0
  CHECK(dns_db_findnode(db, origin, false, &node));
5368
5369
  /* Get keys from private key files. */
5370
0
  dns_zone_lock_keyfiles(zone);
5371
0
  result = dns_dnssec_findmatchingkeys(
5372
0
    origin, kasp, dir, dns_zone_getkeystores(zone), now, false,
5373
0
    dns_zone_getmctx(zone), keys);
5374
0
  dns_zone_unlock_keyfiles(zone);
5375
5376
0
  if (result != ISC_R_NOTFOUND) {
5377
0
    CHECK(result);
5378
0
  }
5379
5380
  /* Get public keys (dnskeys). */
5381
0
  dns_rdataset_init(&keyset);
5382
0
  result = dns_db_findrdataset(db, node, ver, dns_rdatatype_dnskey,
5383
0
             dns_rdatatype_none, 0, &keyset, NULL);
5384
0
  if (result == ISC_R_SUCCESS) {
5385
0
    CHECK(dns_dnssec_keylistfromrdataset(
5386
0
      origin, kasp, dir, dns_zone_getmctx(zone), &keyset,
5387
0
      NULL, NULL, false, false, &dnskeys));
5388
0
  } else if (result != ISC_R_NOTFOUND) {
5389
0
    CHECK(result);
5390
0
  }
5391
5392
  /* Add new 'dnskeys' to 'keys'. */
5393
0
  ISC_LIST_FOREACH(dnskeys, k1, link) {
5394
0
    bool match = false;
5395
5396
0
    ISC_LIST_FOREACH(*keys, k2, link) {
5397
0
      if (dst_key_compare(k1->key, k2->key)) {
5398
0
        match = true;
5399
0
        break;
5400
0
      }
5401
0
    }
5402
5403
    /* No match found, add the new key. */
5404
0
    if (!match) {
5405
0
      ISC_LIST_UNLINK(dnskeys, k1, link);
5406
0
      ISC_LIST_APPEND(*keys, k1, link);
5407
0
    }
5408
0
  }
5409
5410
0
cleanup:
5411
0
  dns_rdataset_cleanup(&keyset);
5412
0
  if (node != NULL) {
5413
0
    dns_db_detachnode(&node);
5414
0
  }
5415
0
  ISC_LIST_FOREACH(dnskeys, key, link) {
5416
0
    ISC_LIST_UNLINK(dnskeys, key, link);
5417
0
    dns_dnsseckey_destroy(dns_zone_getmctx(zone), &key);
5418
0
  }
5419
0
  return result;
5420
0
}
5421
5422
static isc_result_t
5423
offline(dns_db_t *db, dns_dbversion_t *ver, dns__zonediff_t *zonediff,
5424
0
  dns_name_t *name, dns_ttl_t ttl, dns_rdata_t *rdata) {
5425
0
  isc_result_t result;
5426
5427
0
  if ((rdata->flags & DNS_RDATA_OFFLINE) != 0) {
5428
0
    return ISC_R_SUCCESS;
5429
0
  }
5430
0
  RETERR(update_one_rr(db, ver, zonediff->diff, DNS_DIFFOP_DELRESIGN,
5431
0
           name, ttl, rdata));
5432
0
  rdata->flags |= DNS_RDATA_OFFLINE;
5433
0
  result = update_one_rr(db, ver, zonediff->diff, DNS_DIFFOP_ADDRESIGN,
5434
0
             name, ttl, rdata);
5435
0
  zonediff->offline = true;
5436
0
  return result;
5437
0
}
5438
5439
static void
5440
set_key_expiry_warning(dns_zone_t *zone, isc_stdtime_t when,
5441
0
           isc_stdtime_t now) {
5442
0
  unsigned int delta;
5443
0
  char timebuf[80];
5444
5445
0
  LOCK_ZONE(zone);
5446
0
  zone->key_expiry = when;
5447
0
  if (when <= now) {
5448
0
    dns_zone_log(zone, ISC_LOG_ERROR,
5449
0
           "DNSKEY RRSIG(s) have expired");
5450
0
    isc_time_settoepoch(&zone->keywarntime);
5451
0
  } else if (when < now + 7 * 24 * 3600) {
5452
0
    isc_time_t t;
5453
0
    isc_time_set(&t, when, 0);
5454
0
    isc_time_formattimestamp(&t, timebuf, 80);
5455
0
    dns_zone_log(zone, ISC_LOG_WARNING,
5456
0
           "DNSKEY RRSIG(s) will expire within 7 days: %s",
5457
0
           timebuf);
5458
0
    delta = when - now;
5459
0
    delta--;      /* loop prevention */
5460
0
    delta /= 24 * 3600; /* to whole days */
5461
0
    delta *= 24 * 3600; /* to seconds */
5462
0
    isc_time_set(&zone->keywarntime, when - delta, 0);
5463
0
  } else {
5464
0
    isc_time_set(&zone->keywarntime, when - 7 * 24 * 3600, 0);
5465
0
    isc_time_formattimestamp(&zone->keywarntime, timebuf, 80);
5466
0
    dns_zone_log(zone, ISC_LOG_NOTICE, "setting keywarntime to %s",
5467
0
           timebuf);
5468
0
  }
5469
0
  UNLOCK_ZONE(zone);
5470
0
}
5471
5472
/*
5473
 * Helper function to del_sigs(). We don't want to delete RRSIGs that
5474
 * have no new key.
5475
 */
5476
static bool
5477
delsig_ok(dns_rdata_rrsig_t *rrsig_ptr, dst_key_t **keys, unsigned int nkeys,
5478
0
    bool kasp, bool *warn) {
5479
0
  unsigned int i = 0;
5480
0
  isc_result_t ret;
5481
0
  bool have_ksk = false, have_zsk = false;
5482
0
  bool have_pksk = false, have_pzsk = false;
5483
0
  dst_algorithm_t algorithm;
5484
5485
0
  algorithm = dst_algorithm_fromdata(
5486
0
    rrsig_ptr->algorithm, rrsig_ptr->signature, rrsig_ptr->siglen);
5487
5488
0
  for (i = 0; i < nkeys; i++) {
5489
0
    bool ksk, zsk;
5490
5491
0
    if (have_pksk && have_ksk && have_pzsk && have_zsk) {
5492
0
      break;
5493
0
    }
5494
5495
0
    if (algorithm != dst_key_alg(keys[i])) {
5496
0
      continue;
5497
0
    }
5498
5499
0
    ret = dst_key_getbool(keys[i], DST_BOOL_KSK, &ksk);
5500
0
    if (ret != ISC_R_SUCCESS) {
5501
0
      ksk = KSK(keys[i]);
5502
0
    }
5503
0
    ret = dst_key_getbool(keys[i], DST_BOOL_ZSK, &zsk);
5504
0
    if (ret != ISC_R_SUCCESS) {
5505
0
      zsk = !KSK(keys[i]);
5506
0
    }
5507
5508
0
    if (ksk) {
5509
0
      have_ksk = true;
5510
0
      if (dst_key_isprivate(keys[i])) {
5511
0
        have_pksk = true;
5512
0
      }
5513
0
    }
5514
0
    if (zsk) {
5515
0
      have_zsk = true;
5516
0
      if (dst_key_isprivate(keys[i])) {
5517
0
        have_pzsk = true;
5518
0
      }
5519
0
    }
5520
0
  }
5521
5522
0
  if (have_zsk && have_ksk && !have_pzsk) {
5523
0
    *warn = true;
5524
0
  }
5525
5526
0
  if (have_pksk && have_pzsk) {
5527
0
    return true;
5528
0
  }
5529
5530
  /*
5531
   * Deleting the SOA RRSIG is always okay.
5532
   */
5533
0
  if (rrsig_ptr->covered == dns_rdatatype_soa) {
5534
0
    return true;
5535
0
  }
5536
5537
  /*
5538
   * It's okay to delete a signature if there is an active key with the
5539
   * same algorithm to replace it, unless that violates the DNSSEC
5540
   * policy.
5541
   */
5542
0
  if (have_pksk || have_pzsk) {
5543
0
    if (kasp && have_pzsk) {
5544
0
      return true;
5545
0
    }
5546
0
    return !kasp;
5547
0
  }
5548
5549
  /*
5550
   * Failing that, it is *not* okay to delete a signature
5551
   * if the associated public key is still in the DNSKEY RRset
5552
   */
5553
0
  for (i = 0; i < nkeys; i++) {
5554
0
    if ((algorithm == dst_key_alg(keys[i])) &&
5555
0
        (rrsig_ptr->keyid == dst_key_id(keys[i])))
5556
0
    {
5557
0
      return false;
5558
0
    }
5559
0
  }
5560
5561
  /*
5562
   * But if the key is gone, then go ahead.
5563
   */
5564
0
  return true;
5565
0
}
5566
5567
/*
5568
 * Delete expired RRsigs and any RRsigs we are about to re-sign.
5569
 * See also update.c:del_keysigs().
5570
 */
5571
static isc_result_t
5572
del_sigs(dns_zone_t *zone, dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
5573
   dns_rdatatype_t type, dns__zonediff_t *zonediff, dst_key_t **keys,
5574
0
   unsigned int nkeys, isc_stdtime_t now, bool incremental) {
5575
0
  isc_result_t result;
5576
0
  dns_dbnode_t *node = NULL;
5577
0
  dns_rdataset_t rdataset;
5578
0
  unsigned int i;
5579
0
  dns_rdata_rrsig_t rrsig;
5580
0
  dns_kasp_t *kasp = zone->kasp;
5581
0
  bool found;
5582
0
  bool offlineksk = false;
5583
0
  int64_t timewarn = 0, timemaybe = 0;
5584
5585
0
  dns_rdataset_init(&rdataset);
5586
5587
0
  if (kasp != NULL) {
5588
0
    offlineksk = dns_kasp_offlineksk(kasp);
5589
0
  }
5590
5591
0
  if (type == dns_rdatatype_nsec3) {
5592
0
    result = dns_db_findnsec3node(db, name, false, &node);
5593
0
  } else {
5594
0
    result = dns_db_findnode(db, name, false, &node);
5595
0
  }
5596
0
  if (result == ISC_R_NOTFOUND) {
5597
0
    return ISC_R_SUCCESS;
5598
0
  }
5599
0
  CHECK(result);
5600
5601
0
  result = dns_db_findrdataset(db, node, ver, dns_rdatatype_rrsig, type,
5602
0
             (isc_stdtime_t)0, &rdataset, NULL);
5603
0
  dns_db_detachnode(&node);
5604
5605
0
  if (result == ISC_R_NOTFOUND) {
5606
0
    INSIST(!dns_rdataset_isassociated(&rdataset));
5607
0
    return ISC_R_SUCCESS;
5608
0
  }
5609
0
  if (result != ISC_R_SUCCESS) {
5610
0
    INSIST(!dns_rdataset_isassociated(&rdataset));
5611
0
    goto cleanup;
5612
0
  }
5613
5614
0
  DNS_RDATASET_FOREACH(&rdataset) {
5615
0
    dns_rdata_t rdata = DNS_RDATA_INIT;
5616
0
    dst_algorithm_t algorithm;
5617
5618
0
    dns_rdataset_current(&rdataset, &rdata);
5619
0
    result = dns_rdata_tostruct(&rdata, &rrsig);
5620
0
    RUNTIME_CHECK(result == ISC_R_SUCCESS);
5621
0
    algorithm = dst_algorithm_fromdata(
5622
0
      rrsig.algorithm, rrsig.signature, rrsig.siglen);
5623
5624
0
    if (!dns_rdatatype_iskeymaterial(type)) {
5625
0
      bool warn = false, deleted = false;
5626
0
      if (delsig_ok(&rrsig, keys, nkeys, kasp != NULL, &warn))
5627
0
      {
5628
0
        result = update_one_rr(db, ver, zonediff->diff,
5629
0
                   DNS_DIFFOP_DELRESIGN,
5630
0
                   name, rdataset.ttl,
5631
0
                   &rdata);
5632
0
        if (result != ISC_R_SUCCESS) {
5633
0
          break;
5634
0
        }
5635
0
        deleted = true;
5636
0
      }
5637
0
      if (warn && !deleted) {
5638
        /*
5639
         * At this point, we've got an RRSIG,
5640
         * which is signed by an inactive key.
5641
         * An administrator needs to provide a new
5642
         * key/alg, but until that time, we want to
5643
         * keep the old RRSIG.  Marking the key as
5644
         * offline will prevent us spinning waiting
5645
         * for the private part.
5646
         */
5647
0
        if (incremental) {
5648
0
          result = offline(db, ver, zonediff,
5649
0
               name, rdataset.ttl,
5650
0
               &rdata);
5651
0
          if (result != ISC_R_SUCCESS) {
5652
0
            break;
5653
0
          }
5654
0
        }
5655
5656
        /*
5657
         * Log the key id and algorithm of
5658
         * the inactive key with no replacement
5659
         */
5660
0
        if (zone->log_key_expired_timer <= now) {
5661
0
          char origin[DNS_NAME_FORMATSIZE];
5662
0
          char algbuf[DST_ALG_FORMATSIZE];
5663
0
          dns_name_format(&zone->origin, origin,
5664
0
              sizeof(origin));
5665
0
          dst_algorithm_format(algorithm, algbuf,
5666
0
                   sizeof(algbuf));
5667
0
          dns_zone_log(zone, ISC_LOG_WARNING,
5668
0
                 "Key %s/%s/%hu "
5669
0
                 "missing or inactive "
5670
0
                 "and has no replacement: "
5671
0
                 "retaining signatures.",
5672
0
                 origin, algbuf,
5673
0
                 rrsig.keyid);
5674
0
          zone->log_key_expired_timer = now +
5675
0
                      3600;
5676
0
        }
5677
0
      }
5678
0
      continue;
5679
0
    }
5680
5681
    /*
5682
     * KSK RRSIGs requires special processing.
5683
     */
5684
0
    found = false;
5685
0
    for (i = 0; i < nkeys; i++) {
5686
0
      if (algorithm == dst_key_alg(keys[i]) &&
5687
0
          rrsig.keyid == dst_key_id(keys[i]))
5688
0
      {
5689
0
        found = true;
5690
        /*
5691
         * Mark offline DNSKEY.
5692
         * We want the earliest offline expire time
5693
         * iff there is a new offline signature.
5694
         */
5695
0
        if (!dst_key_inactive(keys[i]) &&
5696
0
            !dst_key_isprivate(keys[i]) && !offlineksk)
5697
0
        {
5698
0
          int64_t timeexpire = dns_time64_from32(
5699
0
            rrsig.timeexpire);
5700
0
          if (timewarn != 0 &&
5701
0
              timewarn > timeexpire)
5702
0
          {
5703
0
            timewarn = timeexpire;
5704
0
          }
5705
0
          if (rdata.flags & DNS_RDATA_OFFLINE) {
5706
0
            if (timemaybe == 0 ||
5707
0
                timemaybe > timeexpire)
5708
0
            {
5709
0
              timemaybe = timeexpire;
5710
0
            }
5711
0
            break;
5712
0
          }
5713
0
          if (timewarn == 0) {
5714
0
            timewarn = timemaybe;
5715
0
          }
5716
0
          if (timewarn == 0 ||
5717
0
              timewarn > timeexpire)
5718
0
          {
5719
0
            timewarn = timeexpire;
5720
0
          }
5721
0
          result = offline(db, ver, zonediff,
5722
0
               name, rdataset.ttl,
5723
0
               &rdata);
5724
0
          break;
5725
0
        }
5726
0
        result = update_one_rr(db, ver, zonediff->diff,
5727
0
                   DNS_DIFFOP_DELRESIGN,
5728
0
                   name, rdataset.ttl,
5729
0
                   &rdata);
5730
0
        break;
5731
0
      }
5732
0
    }
5733
5734
    /*
5735
     * If there is not a matching DNSKEY then
5736
     * delete the RRSIG.
5737
     */
5738
0
    if (!found) {
5739
0
      result = update_one_rr(db, ver, zonediff->diff,
5740
0
                 DNS_DIFFOP_DELRESIGN, name,
5741
0
                 rdataset.ttl, &rdata);
5742
0
    }
5743
0
    if (result != ISC_R_SUCCESS) {
5744
0
      break;
5745
0
    }
5746
0
  }
5747
5748
0
  dns_rdataset_disassociate(&rdataset);
5749
0
  if (timewarn > 0) {
5750
0
    isc_stdtime_t stdwarn = (isc_stdtime_t)timewarn;
5751
0
    if (timewarn == stdwarn) {
5752
0
      set_key_expiry_warning(zone, (isc_stdtime_t)timewarn,
5753
0
                 now);
5754
0
    } else {
5755
0
      dns_zone_log(zone, ISC_LOG_ERROR,
5756
0
             "key expiry warning time out of range");
5757
0
    }
5758
0
  }
5759
0
cleanup:
5760
0
  if (node != NULL) {
5761
0
    dns_db_detachnode(&node);
5762
0
  }
5763
0
  return result;
5764
0
}
5765
5766
static isc_result_t
5767
add_sigs(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name, dns_zone_t *zone,
5768
   dns_rdatatype_t type, dns_diff_t *diff, dst_key_t **keys, size_t nkeys,
5769
   isc_mem_t *mctx, isc_stdtime_t now, isc_stdtime_t inception,
5770
0
   isc_stdtime_t expire) {
5771
0
  isc_result_t result;
5772
0
  dns_dbnode_t *node = NULL;
5773
0
  dns_stats_t *dnssecsignstats;
5774
0
  dns_rdataset_t rdataset;
5775
0
  dns_rdata_t sig_rdata = DNS_RDATA_INIT;
5776
0
  unsigned char data[DNS_RDATA_MAXLENGTH];
5777
0
  isc_buffer_t buffer;
5778
0
  bool use_kasp = false;
5779
0
  bool offlineksk = false;
5780
5781
0
  if (zone->kasp != NULL) {
5782
0
    use_kasp = true;
5783
0
    offlineksk = dns_kasp_offlineksk(zone->kasp);
5784
0
  }
5785
5786
0
  dns_rdataset_init(&rdataset);
5787
0
  isc_buffer_init(&buffer, data, sizeof(data));
5788
5789
0
  if (type == dns_rdatatype_nsec3) {
5790
0
    result = dns_db_findnsec3node(db, name, false, &node);
5791
0
  } else {
5792
0
    result = dns_db_findnode(db, name, false, &node);
5793
0
  }
5794
0
  if (result == ISC_R_NOTFOUND) {
5795
0
    return ISC_R_SUCCESS;
5796
0
  }
5797
0
  CHECK(result);
5798
5799
0
  result = dns_db_findrdataset(db, node, ver, type, 0, (isc_stdtime_t)0,
5800
0
             &rdataset, NULL);
5801
0
  dns_db_detachnode(&node);
5802
0
  if (result == ISC_R_NOTFOUND) {
5803
0
    INSIST(!dns_rdataset_isassociated(&rdataset));
5804
0
    return ISC_R_SUCCESS;
5805
0
  }
5806
0
  if (result != ISC_R_SUCCESS) {
5807
0
    INSIST(!dns_rdataset_isassociated(&rdataset));
5808
0
    goto cleanup;
5809
0
  }
5810
5811
0
  if (type == dns_rdatatype_deleg) {
5812
    /* Warn if we don't have at least one ADT key */
5813
0
    bool adt = false;
5814
0
    for (size_t i = 0; i < nkeys; i++) {
5815
0
      if (ADT(keys[i])) {
5816
0
        adt = true;
5817
0
        break;
5818
0
      }
5819
0
    }
5820
0
    if (!adt) {
5821
0
      dns_zone_log(zone, ISC_LOG_WARNING,
5822
0
             "WARNING: signing DELEG but no DNSKEY "
5823
0
             "with the ADT flag is present");
5824
0
    }
5825
0
  }
5826
5827
0
  for (size_t i = 0; i < nkeys; i++) {
5828
    /* Don't add signatures for offline or inactive keys */
5829
0
    if (!dst_key_isprivate(keys[i]) && !offlineksk) {
5830
0
      continue;
5831
0
    }
5832
0
    if (dst_key_inactive(keys[i]) && !offlineksk) {
5833
0
      continue;
5834
0
    }
5835
5836
0
    if (use_kasp) {
5837
      /*
5838
       * A dnssec-policy is found. Check what RRsets this
5839
       * key should sign.
5840
       */
5841
0
      isc_result_t kresult;
5842
0
      isc_stdtime_t when;
5843
0
      bool ksk = false;
5844
0
      bool zsk = false;
5845
0
      bool have_zsk = false;
5846
5847
0
      kresult = dst_key_getbool(keys[i], DST_BOOL_KSK, &ksk);
5848
0
      if (kresult != ISC_R_SUCCESS) {
5849
0
        if (KSK(keys[i])) {
5850
0
          ksk = true;
5851
0
        }
5852
0
      }
5853
0
      kresult = dst_key_getbool(keys[i], DST_BOOL_ZSK, &zsk);
5854
0
      if (kresult != ISC_R_SUCCESS) {
5855
0
        if (!KSK(keys[i])) {
5856
0
          zsk = true;
5857
0
        }
5858
0
      }
5859
5860
      /*
5861
       * Don't consider inactive keys or offline keys.
5862
       */
5863
0
      if (!dst_key_isprivate(keys[i]) && offlineksk && zsk) {
5864
0
        continue;
5865
0
      }
5866
0
      if (dst_key_inactive(keys[i]) && offlineksk && zsk) {
5867
0
        continue;
5868
0
      }
5869
5870
0
      if (offlineksk) {
5871
0
        have_zsk = true;
5872
0
      } else {
5873
0
        (void)dst_key_have_ksk_and_zsk(keys, nkeys, i,
5874
0
                     true, ksk, zsk,
5875
0
                     NULL, &have_zsk);
5876
0
      }
5877
5878
0
      if (dns_rdatatype_iskeymaterial(type)) {
5879
        /*
5880
         * DNSKEY RRset is signed with KSK.
5881
         * CDS and CDNSKEY RRsets too (RFC 7344, 4.1).
5882
         */
5883
0
        if (!ksk) {
5884
0
          continue;
5885
0
        }
5886
0
      } else if (!zsk) {
5887
        /*
5888
         * Other RRsets are signed with ZSK.
5889
         */
5890
0
        if (type != dns_rdatatype_soa &&
5891
0
            type != zone->privatetype)
5892
0
        {
5893
0
          continue;
5894
0
        }
5895
0
        if (have_zsk) {
5896
0
          continue;
5897
0
        }
5898
0
      } else if (!dst_key_is_signing(keys[i], DST_BOOL_ZSK,
5899
0
                   now, &when))
5900
0
      {
5901
        /*
5902
         * This key is not active for zone-signing.
5903
         */
5904
0
        continue;
5905
0
      }
5906
0
    } else if (!REVOKE(keys[i])) {
5907
      /*
5908
       * Don't consider inactive keys, however the KSK may be
5909
       * temporary offline, so do consider keys which private
5910
       * key files are unavailable.
5911
       */
5912
0
      bool both = dst_key_have_ksk_and_zsk(
5913
0
        keys, nkeys, i, false, KSK(keys[i]),
5914
0
        !KSK(keys[i]), NULL, NULL);
5915
0
      if (both) {
5916
        /*
5917
         * CDS and CDNSKEY are signed with KSK (RFC
5918
         * 7344, 4.1).
5919
         */
5920
0
        if (dns_rdatatype_iskeymaterial(type)) {
5921
0
          if (!KSK(keys[i])) {
5922
0
            continue;
5923
0
          }
5924
0
        } else if (KSK(keys[i])) {
5925
0
          continue;
5926
0
        }
5927
0
      }
5928
0
    }
5929
5930
    /*
5931
     * If this key is revoked, it may only sign the DNSKEY RRset.
5932
     */
5933
0
    if (REVOKE(keys[i]) && type != dns_rdatatype_dnskey) {
5934
0
      continue;
5935
0
    }
5936
5937
    /* Calculate the signature, creating a RRSIG RDATA. */
5938
0
    isc_buffer_clear(&buffer);
5939
5940
0
    if (offlineksk && dns_rdatatype_iskeymaterial(type)) {
5941
      /* Look up the signature in the SKR bundle */
5942
0
      dns_skrbundle_t *bundle = dns_zone_getskrbundle(zone);
5943
0
      if (bundle == NULL) {
5944
0
        CLEANUP(DNS_R_NOSKRBUNDLE);
5945
0
      }
5946
0
      CHECK(dns_skrbundle_getsig(bundle, keys[i], type,
5947
0
               &sig_rdata));
5948
0
    } else {
5949
0
      CHECK(dns_dnssec_sign(name, &rdataset, keys[i],
5950
0
                &inception, &expire, mctx,
5951
0
                &buffer, &sig_rdata));
5952
0
    }
5953
5954
    /* Update the database and journal with the RRSIG. */
5955
    /* XXX inefficient - will cause dataset merging */
5956
0
    CHECK(update_one_rr(db, ver, diff, DNS_DIFFOP_ADDRESIGN, name,
5957
0
            rdataset.ttl, &sig_rdata));
5958
0
    dns_rdata_reset(&sig_rdata);
5959
0
    isc_buffer_init(&buffer, data, sizeof(data));
5960
5961
    /* Update DNSSEC sign statistics. */
5962
0
    dnssecsignstats = dns_zone_getdnssecsignstats(zone);
5963
0
    if (dnssecsignstats != NULL) {
5964
      /* Generated a new signature. */
5965
0
      dns_dnssecsignstats_increment(dnssecsignstats,
5966
0
                  ID(keys[i]),
5967
0
                  (uint8_t)ALG(keys[i]),
5968
0
                  dns_dnssecsignstats_sign);
5969
      /* This is a refresh. */
5970
0
      dns_dnssecsignstats_increment(
5971
0
        dnssecsignstats, ID(keys[i]),
5972
0
        (uint8_t)ALG(keys[i]),
5973
0
        dns_dnssecsignstats_refresh);
5974
0
    }
5975
0
  }
5976
5977
0
cleanup:
5978
0
  dns_rdataset_cleanup(&rdataset);
5979
0
  if (node != NULL) {
5980
0
    dns_db_detachnode(&node);
5981
0
  }
5982
0
  return result;
5983
0
}
5984
5985
static void
5986
calculate_rrsig_validity(dns_zone_t *zone, isc_stdtime_t now,
5987
       isc_stdtime_t *inception, isc_stdtime_t *soaexpire,
5988
0
       isc_stdtime_t *expire, isc_stdtime_t *fullexpire) {
5989
0
  REQUIRE(inception != NULL);
5990
0
  REQUIRE(soaexpire != NULL);
5991
  /* expire and fullexpire are optional */
5992
5993
0
  isc_stdtime_t jitter = DEFAULT_JITTER;
5994
0
  isc_stdtime_t sigvalidity = dns_zone_getsigvalidityinterval(zone);
5995
0
  isc_stdtime_t shortjitter = 0, fulljitter = 0;
5996
5997
0
  if (zone->kasp != NULL) {
5998
0
    jitter = dns_kasp_sigjitter(zone->kasp);
5999
0
    sigvalidity = dns_kasp_sigvalidity(zone->kasp);
6000
0
    INSIST(jitter <= sigvalidity);
6001
0
  }
6002
6003
0
  if (jitter > sigvalidity) {
6004
0
    jitter = sigvalidity;
6005
0
  }
6006
6007
0
  *inception = now - 3600; /* Allow for clock skew. */
6008
0
  *soaexpire = now + sigvalidity;
6009
6010
  /*
6011
   * Spread out signatures over time if they happen to be
6012
   * clumped.  We don't do this for each add_sigs() call as
6013
   * we still want some clustering to occur.  In normal operations
6014
   * the records should be re-signed as they fall due and they should
6015
   * already be spread out.  However if the server is off for a
6016
   * period we need to ensure that the clusters don't become
6017
   * synchronised by using the full jitter range.
6018
   */
6019
0
  if (sigvalidity >= 3600U) {
6020
0
    if (sigvalidity > 7200U) {
6021
0
      shortjitter = isc_random_uniform(3600);
6022
0
      fulljitter = isc_random_uniform(jitter);
6023
0
    } else {
6024
0
      shortjitter = fulljitter = isc_random_uniform(1200);
6025
0
    }
6026
0
  }
6027
6028
0
  SET_IF_NOT_NULL(expire, *soaexpire - shortjitter - 1);
6029
0
  SET_IF_NOT_NULL(fullexpire, *soaexpire - fulljitter - 1);
6030
0
}
6031
6032
static void
6033
0
zone_resigninc(dns_zone_t *zone) {
6034
0
  dns_db_t *db = NULL;
6035
0
  dns_dbversion_t *version = NULL;
6036
0
  dns_diff_t _sig_diff;
6037
0
  dns__zonediff_t zonediff;
6038
0
  dns_fixedname_t fixed;
6039
0
  dns_name_t *name;
6040
0
  dns_typepair_t typepair;
6041
0
  dst_key_t *zone_keys[DNS_MAXZONEKEYS];
6042
0
  isc_result_t result;
6043
0
  isc_stdtime_t now, inception, soaexpire, expire, fullexpire, stop;
6044
0
  unsigned int i;
6045
0
  unsigned int nkeys = 0;
6046
0
  isc_stdtime_t resign;
6047
6048
0
  ENTER;
6049
6050
0
  dns_diff_init(zone->mctx, &_sig_diff);
6051
0
  zonediff_init(&zonediff, &_sig_diff);
6052
6053
  /*
6054
   * Zone is frozen. Pause for 5 minutes.
6055
   */
6056
0
  if (zone->update_disabled) {
6057
0
    CLEANUP(ISC_R_FAILURE);
6058
0
  }
6059
6060
0
  ZONEDB_LOCK(&zone->dblock, isc_rwlocktype_read);
6061
0
  if (zone->db != NULL) {
6062
0
    dns_db_attach(zone->db, &db);
6063
0
  }
6064
0
  ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_read);
6065
0
  if (db == NULL) {
6066
0
    CLEANUP(ISC_R_FAILURE);
6067
0
  }
6068
6069
0
  result = dns_db_newversion(db, &version);
6070
0
  if (result != ISC_R_SUCCESS) {
6071
0
    dns_zone_log(zone, ISC_LOG_ERROR,
6072
0
           "zone_resigninc:dns_db_newversion -> %s",
6073
0
           isc_result_totext(result));
6074
0
    goto cleanup;
6075
0
  }
6076
6077
0
  now = isc_stdtime_now();
6078
6079
0
  result = dns_zone_findkeys(zone, db, version, now, zone->mctx,
6080
0
           DNS_MAXZONEKEYS, zone_keys, &nkeys);
6081
0
  if (result != ISC_R_SUCCESS) {
6082
0
    dns_zone_log(zone, ISC_LOG_ERROR,
6083
0
           "zone_resigninc:dns_zone_findkeys -> %s",
6084
0
           isc_result_totext(result));
6085
0
    goto cleanup;
6086
0
  }
6087
6088
0
  calculate_rrsig_validity(zone, now, &inception, &soaexpire, &expire,
6089
0
         &fullexpire);
6090
6091
0
  stop = now + 5;
6092
6093
0
  name = dns_fixedname_initname(&fixed);
6094
0
  result = dns_db_getsigningtime(db, &resign, name, &typepair);
6095
0
  if (result != ISC_R_SUCCESS && result != ISC_R_NOTFOUND) {
6096
0
    dns_zone_log(zone, ISC_LOG_ERROR,
6097
0
           "zone_resigninc:dns_db_getsigningtime -> %s",
6098
0
           isc_result_totext(result));
6099
0
  }
6100
6101
0
  i = 0;
6102
0
  while (result == ISC_R_SUCCESS) {
6103
0
    dns_rdatatype_t covers = DNS_TYPEPAIR_COVERS(typepair);
6104
6105
0
    resign -= dns_zone_getsigresigninginterval(zone);
6106
6107
    /*
6108
     * Stop if we hit the SOA as that means we have walked the
6109
     * entire zone.  The SOA record should always be the most
6110
     * recent signature.
6111
     */
6112
    /* XXXMPA increase number of RRsets signed pre call */
6113
0
    if ((covers == dns_rdatatype_soa &&
6114
0
         dns_name_equal(name, &zone->origin)) ||
6115
0
        i++ > zone->signatures || resign > stop)
6116
0
    {
6117
0
      break;
6118
0
    }
6119
6120
0
    result = del_sigs(zone, db, version, name, covers, &zonediff,
6121
0
          zone_keys, nkeys, now, true);
6122
0
    if (result != ISC_R_SUCCESS) {
6123
0
      dns_zone_log(zone, ISC_LOG_ERROR,
6124
0
             "zone_resigninc:del_sigs -> %s",
6125
0
             isc_result_totext(result));
6126
0
      break;
6127
0
    }
6128
6129
    /*
6130
     * If re-signing is over 5 minutes late use 'fullexpire'
6131
     * to redistribute the signature over the complete
6132
     * re-signing window, otherwise only add a small amount
6133
     * of jitter.
6134
     */
6135
0
    result = add_sigs(db, version, name, zone, covers,
6136
0
          zonediff.diff, zone_keys, nkeys, zone->mctx,
6137
0
          now, inception,
6138
0
          resign > (now - 300) ? expire : fullexpire);
6139
0
    if (result != ISC_R_SUCCESS) {
6140
0
      dns_zone_log(zone, ISC_LOG_ERROR,
6141
0
             "zone_resigninc:add_sigs -> %s",
6142
0
             isc_result_totext(result));
6143
0
      break;
6144
0
    }
6145
0
    result = dns_db_getsigningtime(db, &resign, name, &typepair);
6146
0
    if (nkeys == 0 && result == ISC_R_NOTFOUND) {
6147
0
      result = ISC_R_SUCCESS;
6148
0
      break;
6149
0
    }
6150
0
    if (result != ISC_R_SUCCESS) {
6151
0
      dns_zone_log(zone, ISC_LOG_ERROR,
6152
0
             "zone_resigninc:dns_db_getsigningtime -> "
6153
0
             "%s",
6154
0
             isc_result_totext(result));
6155
0
    }
6156
0
  }
6157
6158
0
  if (result != ISC_R_NOMORE) {
6159
0
    CHECK(result);
6160
0
  }
6161
6162
0
  result = del_sigs(zone, db, version, &zone->origin, dns_rdatatype_soa,
6163
0
        &zonediff, zone_keys, nkeys, now, true);
6164
0
  if (result != ISC_R_SUCCESS) {
6165
0
    dns_zone_log(zone, ISC_LOG_ERROR,
6166
0
           "zone_resigninc:del_sigs -> %s",
6167
0
           isc_result_totext(result));
6168
0
    goto cleanup;
6169
0
  }
6170
6171
  /*
6172
   * Did we change anything in the zone?
6173
   */
6174
0
  if (ISC_LIST_EMPTY(zonediff.diff->tuples)) {
6175
    /*
6176
     * Commit the changes if any key has been marked as offline.
6177
     */
6178
0
    if (zonediff.offline) {
6179
0
      dns_db_closeversion(db, &version, true);
6180
0
    }
6181
0
    goto cleanup;
6182
0
  }
6183
6184
  /* Increment SOA serial if we have made changes */
6185
0
  result = update_soa_serial(zone, db, version, zonediff.diff, zone->mctx,
6186
0
           zone->updatemethod);
6187
0
  if (result != ISC_R_SUCCESS) {
6188
0
    dns_zone_log(zone, ISC_LOG_ERROR,
6189
0
           "zone_resigninc:update_soa_serial -> %s",
6190
0
           isc_result_totext(result));
6191
0
    goto cleanup;
6192
0
  }
6193
6194
  /*
6195
   * Generate maximum life time signatures so that the above loop
6196
   * termination is sensible.
6197
   */
6198
0
  result = add_sigs(db, version, &zone->origin, zone, dns_rdatatype_soa,
6199
0
        zonediff.diff, zone_keys, nkeys, zone->mctx, now,
6200
0
        inception, soaexpire);
6201
0
  if (result != ISC_R_SUCCESS) {
6202
0
    dns_zone_log(zone, ISC_LOG_ERROR,
6203
0
           "zone_resigninc:add_sigs -> %s",
6204
0
           isc_result_totext(result));
6205
0
    goto cleanup;
6206
0
  }
6207
6208
  /* Write changes to journal file. */
6209
0
  CHECK(zone_journal(zone, zonediff.diff, NULL, "zone_resigninc"));
6210
6211
  /* Everything has succeeded. Commit the changes. */
6212
0
  dns_db_closeversion(db, &version, true);
6213
6214
0
cleanup:
6215
0
  dns_diff_clear(&_sig_diff);
6216
0
  for (i = 0; i < nkeys; i++) {
6217
0
    dst_key_free(&zone_keys[i]);
6218
0
  }
6219
0
  if (version != NULL) {
6220
0
    dns_db_closeversion(db, &version, false);
6221
0
    dns_db_detach(&db);
6222
0
  } else if (db != NULL) {
6223
0
    dns_db_detach(&db);
6224
0
  }
6225
6226
0
  LOCK_ZONE(zone);
6227
0
  if (result == ISC_R_SUCCESS) {
6228
0
    dns__zone_set_resigntime(zone);
6229
0
    zone_needdump(zone, DNS_DUMP_DELAY);
6230
0
    DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_NEEDNOTIFY);
6231
0
  } else {
6232
    /*
6233
     * Something failed.  Retry in 5 minutes.
6234
     */
6235
0
    isc_interval_t ival;
6236
0
    isc_interval_set(&ival, 300, 0);
6237
0
    isc_time_nowplusinterval(&zone->resigntime, &ival);
6238
0
  }
6239
0
  UNLOCK_ZONE(zone);
6240
6241
0
  INSIST(version == NULL);
6242
0
}
6243
6244
static isc_result_t
6245
next_active(dns_db_t *db, dns_dbversion_t *version, dns_name_t *oldname,
6246
0
      dns_name_t *newname, bool bottom) {
6247
0
  isc_result_t result;
6248
0
  dns_dbiterator_t *dbit = NULL;
6249
0
  dns_rdatasetiter_t *rdsit = NULL;
6250
0
  dns_dbnode_t *node = NULL;
6251
6252
0
  CHECK(dns_db_createiterator(db, DNS_DB_NONSEC3, &dbit));
6253
0
  CHECK(dns_dbiterator_seek(dbit, oldname));
6254
0
  do {
6255
0
    result = dns_dbiterator_next(dbit);
6256
0
    if (result == ISC_R_NOMORE) {
6257
0
      CHECK(dns_dbiterator_first(dbit));
6258
0
    }
6259
0
    CHECK(dns_dbiterator_current(dbit, &node, newname));
6260
0
    if (bottom && dns_name_issubdomain(newname, oldname) &&
6261
0
        !dns_name_equal(newname, oldname))
6262
0
    {
6263
0
      dns_db_detachnode(&node);
6264
0
      continue;
6265
0
    }
6266
    /*
6267
     * Is this node empty?
6268
     */
6269
0
    CHECK(dns_db_allrdatasets(db, node, version, 0, 0, &rdsit));
6270
0
    result = dns_rdatasetiter_first(rdsit);
6271
0
    dns_db_detachnode(&node);
6272
0
    dns_rdatasetiter_destroy(&rdsit);
6273
0
    if (result != ISC_R_NOMORE) {
6274
0
      break;
6275
0
    }
6276
0
  } while (1);
6277
0
cleanup:
6278
0
  if (node != NULL) {
6279
0
    dns_db_detachnode(&node);
6280
0
  }
6281
0
  if (dbit != NULL) {
6282
0
    dns_dbiterator_destroy(&dbit);
6283
0
  }
6284
0
  return result;
6285
0
}
6286
6287
static bool
6288
signed_with_good_key(dns_zone_t *zone, dns_db_t *db, dns_dbnode_t *node,
6289
         dns_dbversion_t *version, dns_rdatatype_t type,
6290
0
         dst_key_t *key, bool fullsign) {
6291
0
  isc_result_t result;
6292
0
  dns_rdataset_t rdataset;
6293
0
  dns_rdata_rrsig_t rrsig;
6294
0
  int count = 0;
6295
0
  dns_kasp_t *kasp = zone->kasp;
6296
6297
0
  dns_rdataset_init(&rdataset);
6298
0
  result = dns_db_findrdataset(db, node, version, dns_rdatatype_rrsig,
6299
0
             type, 0, &rdataset, NULL);
6300
0
  if (result != ISC_R_SUCCESS) {
6301
0
    INSIST(!dns_rdataset_isassociated(&rdataset));
6302
0
    return false;
6303
0
  }
6304
0
  DNS_RDATASET_FOREACH(&rdataset) {
6305
0
    dns_rdata_t rdata = DNS_RDATA_INIT;
6306
0
    dns_rdataset_current(&rdataset, &rdata);
6307
0
    result = dns_rdata_tostruct(&rdata, &rrsig);
6308
0
    INSIST(result == ISC_R_SUCCESS);
6309
0
    dst_algorithm_t algorithm;
6310
0
    algorithm = dst_algorithm_fromdata(
6311
0
      rrsig.algorithm, rrsig.signature, rrsig.siglen);
6312
0
    if (algorithm == dst_key_alg(key) &&
6313
0
        rrsig.keyid == dst_key_id(key))
6314
0
    {
6315
0
      dns_rdataset_disassociate(&rdataset);
6316
0
      return true;
6317
0
    }
6318
0
    if (algorithm == dst_key_alg(key)) {
6319
0
      count++;
6320
0
    }
6321
0
  }
6322
6323
0
  if (zone->kasp != NULL && !fullsign) {
6324
0
    int zsk_count = 0;
6325
0
    bool approved;
6326
6327
0
    KASP_LOCK(kasp);
6328
0
    ISC_LIST_FOREACH(dns_kasp_keys(kasp), kkey, link) {
6329
0
      if (dns_kasp_key_algorithm(kkey) != dst_key_alg(key)) {
6330
0
        continue;
6331
0
      }
6332
0
      if (dns_kasp_key_zsk(kkey)) {
6333
0
        zsk_count++;
6334
0
      }
6335
0
    }
6336
0
    KASP_UNLOCK(kasp);
6337
6338
0
    if (dns_rdatatype_iskeymaterial(type)) {
6339
      /*
6340
       * CDS and CDNSKEY are signed with KSK like DNSKEY.
6341
       * (RFC 7344, section 4.1 specifies that they must
6342
       * be signed with a key in the current DS RRset,
6343
       * which would only include KSK's.)
6344
       */
6345
0
      approved = false;
6346
0
    } else {
6347
0
      approved = (zsk_count == count);
6348
0
    }
6349
6350
0
    dns_rdataset_disassociate(&rdataset);
6351
0
    return approved;
6352
0
  }
6353
6354
0
  dns_rdataset_disassociate(&rdataset);
6355
0
  return false;
6356
0
}
6357
6358
static isc_result_t
6359
add_nsec(dns_db_t *db, dns_dbversion_t *version, dns_name_t *name,
6360
0
   dns_dbnode_t *node, dns_ttl_t ttl, bool bottom, dns_diff_t *diff) {
6361
0
  dns_fixedname_t fixed;
6362
0
  dns_name_t *next;
6363
0
  dns_rdata_t rdata = DNS_RDATA_INIT;
6364
0
  isc_result_t result;
6365
0
  unsigned char nsecbuffer[DNS_NSEC_BUFFERSIZE];
6366
6367
0
  next = dns_fixedname_initname(&fixed);
6368
6369
0
  CHECK(next_active(db, version, name, next, bottom));
6370
0
  CHECK(dns_nsec_buildrdata(db, version, node, next, nsecbuffer, &rdata));
6371
0
  CHECK(update_one_rr(db, version, diff, DNS_DIFFOP_ADD, name, ttl,
6372
0
          &rdata));
6373
0
cleanup:
6374
0
  return result;
6375
0
}
6376
6377
static isc_result_t
6378
check_if_bottom_of_zone(dns_db_t *db, dns_dbnode_t *node,
6379
0
      dns_dbversion_t *version, bool *is_bottom_of_zone) {
6380
0
  isc_result_t result;
6381
0
  dns_rdatasetiter_t *iterator = NULL;
6382
0
  bool seen_soa = false, seen_ns = false;
6383
0
  bool seen_dname = false, seen_deleg = false;
6384
6385
0
  REQUIRE(is_bottom_of_zone != NULL);
6386
6387
0
  result = dns_db_allrdatasets(db, node, version, 0, 0, &iterator);
6388
0
  if (result != ISC_R_SUCCESS) {
6389
0
    if (result == ISC_R_NOTFOUND) {
6390
0
      result = ISC_R_SUCCESS;
6391
0
    }
6392
0
    return result;
6393
0
  }
6394
6395
0
  DNS_RDATASETITER_FOREACH(iterator) {
6396
0
    dns_rdataset_t rdataset = DNS_RDATASET_INIT;
6397
0
    dns_rdatasetiter_current(iterator, &rdataset);
6398
0
    switch (rdataset.type) {
6399
0
    case dns_rdatatype_soa:
6400
0
      seen_soa = true;
6401
0
      break;
6402
0
    case dns_rdatatype_ns:
6403
0
      seen_ns = true;
6404
0
      break;
6405
0
    case dns_rdatatype_deleg:
6406
0
      seen_deleg = true;
6407
0
      break;
6408
0
    case dns_rdatatype_dname:
6409
0
      seen_dname = true;
6410
0
      break;
6411
0
    }
6412
0
    dns_rdataset_disassociate(&rdataset);
6413
0
  }
6414
6415
0
  if ((seen_ns && !seen_soa) || seen_dname || seen_deleg) {
6416
0
    *is_bottom_of_zone = true;
6417
0
  }
6418
6419
0
  dns_rdatasetiter_destroy(&iterator);
6420
0
  return ISC_R_SUCCESS;
6421
0
}
6422
6423
typedef struct seen {
6424
  bool rr;
6425
  bool soa;
6426
  bool ns;
6427
  bool nsec;
6428
  bool nsec3;
6429
  bool ds;
6430
  bool dname;
6431
  bool deleg;
6432
} seen_t;
6433
6434
static isc_result_t
6435
allrdatasets(dns_db_t *db, dns_dbnode_t *node, dns_dbversion_t *version,
6436
0
       dns_rdatasetiter_t **iterp, seen_t *seen) {
6437
0
  dns_rdataset_t rdataset = DNS_RDATASET_INIT;
6438
6439
0
  *seen = (seen_t){};
6440
6441
0
  RETERR(dns_db_allrdatasets(db, node, version, 0, 0, iterp));
6442
6443
0
  DNS_RDATASETITER_FOREACH(*iterp) {
6444
0
    dns_rdatasetiter_current(*iterp, &rdataset);
6445
6446
0
    if (rdataset.type == dns_rdatatype_rrsig) {
6447
0
      dns_rdataset_disassociate(&rdataset);
6448
0
      continue;
6449
0
    }
6450
6451
0
    (*seen).rr = true;
6452
6453
0
    if (rdataset.type == dns_rdatatype_soa) {
6454
0
      (*seen).soa = true;
6455
0
    } else if (rdataset.type == dns_rdatatype_ns) {
6456
0
      (*seen).ns = true;
6457
0
    } else if (rdataset.type == dns_rdatatype_ds) {
6458
0
      (*seen).ds = true;
6459
0
    } else if (rdataset.type == dns_rdatatype_dname) {
6460
0
      (*seen).dname = true;
6461
0
    } else if (rdataset.type == dns_rdatatype_nsec) {
6462
0
      (*seen).nsec = true;
6463
0
    } else if (rdataset.type == dns_rdatatype_nsec3) {
6464
0
      (*seen).nsec3 = true;
6465
0
    } else if (rdataset.type == dns_rdatatype_deleg) {
6466
0
      (*seen).deleg = true;
6467
0
    }
6468
6469
0
    dns_rdataset_disassociate(&rdataset);
6470
0
  }
6471
6472
0
  return ISC_R_SUCCESS;
6473
0
}
6474
6475
static isc_result_t
6476
sign_a_node(dns_db_t *db, dns_zone_t *zone, dns_name_t *name,
6477
      dns_dbnode_t *node, dns_dbversion_t *version, bool build_nsec3,
6478
      bool build_nsec, dst_key_t *key, isc_stdtime_t now,
6479
      isc_stdtime_t inception, isc_stdtime_t expire, dns_ttl_t nsecttl,
6480
      bool both, bool is_ksk, bool is_zsk, bool fullsign,
6481
      bool is_bottom_of_zone, bool have_adt, dns_diff_t *diff,
6482
0
      int32_t *signatures, isc_mem_t *mctx) {
6483
0
  isc_result_t result;
6484
0
  dns_rdatasetiter_t *iterator = NULL;
6485
0
  dns_rdataset_t rdataset = DNS_RDATASET_INIT;
6486
0
  dns_rdata_t rdata = DNS_RDATA_INIT;
6487
0
  dns_stats_t *dnssecsignstats;
6488
0
  bool offlineksk = false;
6489
0
  isc_buffer_t buffer;
6490
0
  unsigned char data[DNS_RDATA_MAXLENGTH];
6491
0
  seen_t seen;
6492
6493
0
  if (zone->kasp != NULL) {
6494
0
    offlineksk = dns_kasp_offlineksk(zone->kasp);
6495
0
  }
6496
6497
0
  result = allrdatasets(db, node, version, &iterator, &seen);
6498
0
  if (result != ISC_R_SUCCESS) {
6499
0
    if (result == ISC_R_NOTFOUND) {
6500
0
      result = ISC_R_SUCCESS;
6501
0
    }
6502
0
    return result;
6503
0
  }
6504
6505
0
  isc_buffer_init(&buffer, data, sizeof(data));
6506
6507
  /*
6508
   * Going from insecure to NSEC3.
6509
   * Don't generate NSEC3 records for NSEC3 records.
6510
   */
6511
0
  if (build_nsec3 && !seen.nsec3 && seen.rr) {
6512
0
    bool unsecure = !seen.ds && seen.ns && !seen.soa;
6513
0
    CHECK(dns_nsec3_addnsec3s(db, version, name, nsecttl, unsecure,
6514
0
            diff));
6515
0
    (*signatures)--;
6516
0
  }
6517
  /*
6518
   * Going from insecure to NSEC.
6519
   * Don't generate NSEC records for NSEC3 records.
6520
   */
6521
0
  if (build_nsec && !seen.nsec3 && !seen.nsec && seen.rr) {
6522
    /*
6523
     * Build a NSEC record except at the origin.
6524
     */
6525
0
    if (!dns_name_equal(name, dns_db_origin(db))) {
6526
0
      CHECK(add_nsec(db, version, name, node, nsecttl,
6527
0
               is_bottom_of_zone, diff));
6528
      /* Count a NSEC generation as a signature generation. */
6529
0
      (*signatures)--;
6530
0
    }
6531
0
  }
6532
6533
0
  DNS_RDATASETITER_FOREACH(iterator) {
6534
0
    isc_stdtime_t when;
6535
6536
0
    dns_rdataset_cleanup(&rdataset);
6537
6538
0
    dns_rdatasetiter_current(iterator, &rdataset);
6539
0
    if (rdataset.type == dns_rdatatype_soa ||
6540
0
        rdataset.type == dns_rdatatype_rrsig)
6541
0
    {
6542
0
      continue;
6543
0
    }
6544
0
    if (dns_rdatatype_iskeymaterial(rdataset.type)) {
6545
      /*
6546
       * CDS and CDNSKEY are signed with KSK like DNSKEY.
6547
       * (RFC 7344, section 4.1 specifies that they must
6548
       * be signed with a key in the current DS RRset,
6549
       * which would only include KSK's.)
6550
       */
6551
0
      if (!is_ksk && both) {
6552
0
        continue;
6553
0
      }
6554
0
    } else if (!is_zsk && both) {
6555
0
      continue;
6556
0
    } else if (is_zsk &&
6557
0
         !dst_key_is_signing(key, DST_BOOL_ZSK, now, &when))
6558
0
    {
6559
      /* Only applies to dnssec-policy. */
6560
0
      if (zone->kasp != NULL) {
6561
0
        continue;
6562
0
      }
6563
0
    }
6564
6565
0
    if (seen.ns && !seen.soa && rdataset.type != dns_rdatatype_ds &&
6566
0
        rdataset.type != dns_rdatatype_deleg &&
6567
0
        rdataset.type != dns_rdatatype_nsec)
6568
0
    {
6569
0
      continue;
6570
0
    }
6571
0
    if (signed_with_good_key(zone, db, node, version, rdataset.type,
6572
0
           key, fullsign))
6573
0
    {
6574
0
      continue;
6575
0
    }
6576
6577
0
    if (rdataset.type == dns_rdatatype_deleg && !have_adt) {
6578
0
      dns_zone_log(zone, ISC_LOG_WARNING,
6579
0
             "WARNING: signing DELEG but no DNSKEY "
6580
0
             "with the ADT flag is present");
6581
0
    }
6582
6583
    /* Calculate the signature, creating a RRSIG RDATA. */
6584
0
    isc_buffer_clear(&buffer);
6585
0
    if (offlineksk && dns_rdatatype_iskeymaterial(rdataset.type)) {
6586
      /* Look up the signature in the SKR bundle */
6587
0
      dns_skrbundle_t *bundle = dns_zone_getskrbundle(zone);
6588
0
      if (bundle == NULL) {
6589
0
        CLEANUP(DNS_R_NOSKRBUNDLE);
6590
0
      }
6591
0
      CHECK(dns_skrbundle_getsig(bundle, key, rdataset.type,
6592
0
               &rdata));
6593
0
    } else {
6594
0
      CHECK(dns_dnssec_sign(name, &rdataset, key, &inception,
6595
0
                &expire, mctx, &buffer, &rdata));
6596
0
    }
6597
6598
    /* Update the database and journal with the RRSIG. */
6599
    /* XXX inefficient - will cause dataset merging */
6600
0
    CHECK(update_one_rr(db, version, diff, DNS_DIFFOP_ADDRESIGN,
6601
0
            name, rdataset.ttl, &rdata));
6602
0
    dns_rdata_reset(&rdata);
6603
6604
    /* Update DNSSEC sign statistics. */
6605
0
    dnssecsignstats = dns_zone_getdnssecsignstats(zone);
6606
0
    if (dnssecsignstats != NULL) {
6607
      /* Generated a new signature. */
6608
0
      dns_dnssecsignstats_increment(dnssecsignstats, ID(key),
6609
0
                  ALG(key),
6610
0
                  dns_dnssecsignstats_sign);
6611
      /* This is a refresh. */
6612
0
      dns_dnssecsignstats_increment(
6613
0
        dnssecsignstats, ID(key), ALG(key),
6614
0
        dns_dnssecsignstats_refresh);
6615
0
    }
6616
6617
0
    (*signatures)--;
6618
0
  }
6619
6620
0
cleanup:
6621
0
  dns_rdataset_cleanup(&rdataset);
6622
0
  if (iterator != NULL) {
6623
0
    dns_rdatasetiter_destroy(&iterator);
6624
0
  }
6625
0
  return result;
6626
0
}
6627
6628
/*
6629
 * If 'update_only' is set then don't create a NSEC RRset if it doesn't exist.
6630
 */
6631
static isc_result_t
6632
updatesecure(dns_db_t *db, dns_dbversion_t *version, dns_name_t *name,
6633
0
       dns_ttl_t nsecttl, bool update_only, dns_diff_t *diff) {
6634
0
  isc_result_t result;
6635
0
  dns_rdataset_t rdataset;
6636
0
  dns_dbnode_t *node = NULL;
6637
6638
0
  CHECK(dns_db_getoriginnode(db, &node));
6639
0
  if (update_only) {
6640
0
    dns_rdataset_init(&rdataset);
6641
0
    result = dns_db_findrdataset(
6642
0
      db, node, version, dns_rdatatype_nsec,
6643
0
      dns_rdatatype_none, 0, &rdataset, NULL);
6644
0
    dns_rdataset_cleanup(&rdataset);
6645
0
    if (result == ISC_R_NOTFOUND) {
6646
0
      goto success;
6647
0
    }
6648
0
    CHECK(result);
6649
0
  }
6650
0
  CHECK(delete_nsec(db, version, node, name, diff));
6651
0
  CHECK(add_nsec(db, version, name, node, nsecttl, false, diff));
6652
0
success:
6653
0
  result = ISC_R_SUCCESS;
6654
0
cleanup:
6655
0
  if (node != NULL) {
6656
0
    dns_db_detachnode(&node);
6657
0
  }
6658
0
  return result;
6659
0
}
6660
6661
static isc_result_t
6662
updatesignwithkey(dns_zone_t *zone, dns_signing_t *signing,
6663
      dns_dbversion_t *version, bool build_nsec3, dns_ttl_t nsecttl,
6664
0
      dns_diff_t *diff) {
6665
0
  isc_result_t result;
6666
0
  dns_dbnode_t *node = NULL;
6667
0
  dns_rdataset_t rdataset;
6668
0
  bool seen_done = false;
6669
0
  bool have_rr = false;
6670
6671
0
  dns_rdataset_init(&rdataset);
6672
0
  CHECK(dns_db_getoriginnode(signing->db, &node));
6673
6674
0
  result = dns_db_findrdataset(signing->db, node, version,
6675
0
             zone->privatetype, dns_rdatatype_none, 0,
6676
0
             &rdataset, NULL);
6677
0
  if (result == ISC_R_NOTFOUND) {
6678
0
    INSIST(!dns_rdataset_isassociated(&rdataset));
6679
0
    result = ISC_R_SUCCESS;
6680
0
    goto cleanup;
6681
0
  }
6682
0
  if (result != ISC_R_SUCCESS) {
6683
0
    INSIST(!dns_rdataset_isassociated(&rdataset));
6684
0
    goto cleanup;
6685
0
  }
6686
6687
0
  DNS_RDATASET_FOREACH(&rdataset) {
6688
0
    dns_rdata_t rdata = DNS_RDATA_INIT;
6689
0
    unsigned char alg = dst_algorithm_tosecalg(signing->algorithm);
6690
6691
0
    dns_rdataset_current(&rdataset, &rdata);
6692
    /*
6693
     * If we don't match the algorithm or keyid skip the record.
6694
     */
6695
0
    if ((rdata.length != SIGNING_RECORD_SIZE &&
6696
0
         rdata.length != OLD_SIGNING_RECORD_SIZE) ||
6697
0
        rdata.data[0] == 0 || rdata.data[0] != alg ||
6698
0
        rdata.data[1] != ((signing->keyid >> 8) & 0xff) ||
6699
0
        rdata.data[2] != (signing->keyid & 0xff) ||
6700
0
        (rdata.length == SIGNING_RECORD_SIZE &&
6701
0
         (rdata.data[5] != (signing->algorithm >> 8 & 0xff) ||
6702
0
          rdata.data[6] != (signing->algorithm & 0xff))))
6703
0
    {
6704
0
      have_rr = true;
6705
0
      continue;
6706
0
    }
6707
    /*
6708
     * We have a match.  If we were signing (!signing->deleteit)
6709
     * and we already have a record indicating that we have
6710
     * finished signing (rdata.data[4] != 0) then keep it.
6711
     * Otherwise it needs to be deleted as we have removed all
6712
     * the signatures (signing->deleteit), so any record indicating
6713
     * completion is now out of date, or we have finished signing
6714
     * with the new record so we no longer need to remember that
6715
     * we need to sign the zone with the matching key across a
6716
     * nameserver re-start.
6717
     */
6718
0
    if (!signing->deleteit && rdata.data[4] != 0) {
6719
0
      seen_done = true;
6720
0
      have_rr = true;
6721
0
    } else {
6722
0
      CHECK(update_one_rr(signing->db, version, diff,
6723
0
              DNS_DIFFOP_DEL, &zone->origin,
6724
0
              rdataset.ttl, &rdata));
6725
0
    }
6726
0
  }
6727
6728
0
  if (!signing->deleteit && !seen_done) {
6729
    /*
6730
     * If we were signing then we need to indicate that we have
6731
     * finished signing the zone with this key.  If it is already
6732
     * there we don't need to add it a second time.
6733
     */
6734
0
    unsigned char data[SIGNING_RECORD_SIZE] = {
6735
0
      dst_algorithm_tosecalg(signing->algorithm),
6736
0
      (signing->keyid >> 8) & 0xff,
6737
0
      signing->keyid & 0xff,
6738
0
      0,
6739
0
      1,
6740
0
      (signing->algorithm >> 8) & 0xff,
6741
0
      signing->algorithm & 0xff,
6742
0
    };
6743
0
    dns_rdata_t rdata = (dns_rdata_t){
6744
0
      .length = signing->algorithm < 256
6745
0
            ? OLD_SIGNING_RECORD_SIZE
6746
0
            : sizeof(data),
6747
0
      .data = data,
6748
0
      .type = zone->privatetype,
6749
0
      .rdclass = dns_db_class(signing->db),
6750
0
      .link = ISC_LINK_INITIALIZER,
6751
0
    };
6752
    /*
6753
     * data[0] can't be 0 as that is used to signal that the
6754
     * record is being used to for NSEC/NSEC3 chains generation.
6755
     * Set it to 255 instead.
6756
     */
6757
0
    if (data[0] == 0) {
6758
0
      data[0] = 255;
6759
0
    }
6760
0
    CHECK(update_one_rr(signing->db, version, diff, DNS_DIFFOP_ADD,
6761
0
            &zone->origin, rdataset.ttl, &rdata));
6762
0
  } else if (!have_rr) {
6763
0
    dns_name_t *origin = dns_db_origin(signing->db);
6764
    /*
6765
     * Rebuild the NSEC/NSEC3 record for the origin as we no
6766
     * longer have any private records.
6767
     */
6768
0
    if (build_nsec3) {
6769
0
      CHECK(dns_nsec3_addnsec3s(signing->db, version, origin,
6770
0
              nsecttl, false, diff));
6771
0
    }
6772
0
    CHECK(updatesecure(signing->db, version, origin, nsecttl, true,
6773
0
           diff));
6774
0
  }
6775
6776
0
cleanup:
6777
0
  dns_rdataset_cleanup(&rdataset);
6778
0
  if (node != NULL) {
6779
0
    dns_db_detachnode(&node);
6780
0
  }
6781
0
  return result;
6782
0
}
6783
6784
/*
6785
 * Called from zone_nsec3chain() in order to update zone records indicating
6786
 * processing status of given NSEC3 chain:
6787
 *
6788
 *   - If the supplied dns_nsec3chain_t structure has been fully processed
6789
 *     (which is indicated by "active" being set to false):
6790
 *
6791
 *       - remove all NSEC3PARAM records matching the relevant NSEC3 chain,
6792
 *
6793
 *       - remove all private-type records containing NSEC3PARAM RDATA matching
6794
 *         the relevant NSEC3 chain.
6795
 *
6796
 *   - If the supplied dns_nsec3chain_t structure has not been fully processed
6797
 *     (which is indicated by "active" being set to true), only remove the
6798
 *     NSEC3PARAM record which matches the relevant NSEC3 chain and has the
6799
 *     "flags" field set to 0.
6800
 *
6801
 *   - If given NSEC3 chain is being added, add an NSEC3PARAM record contained
6802
 *     in the relevant private-type record, but with the "flags" field set to
6803
 *     0, indicating that this NSEC3 chain is now complete for this zone.
6804
 *
6805
 * Note that this function is called at different processing stages for NSEC3
6806
 * chain additions vs. removals and needs to handle all cases properly.
6807
 */
6808
static isc_result_t
6809
fixup_nsec3param(dns_db_t *db, dns_dbversion_t *ver, dns_nsec3chain_t *chain,
6810
0
     bool active, dns_rdatatype_t privatetype, dns_diff_t *diff) {
6811
0
  dns_dbnode_t *node = NULL;
6812
0
  dns_name_t *name = dns_db_origin(db);
6813
0
  dns_rdata_t rdata = DNS_RDATA_INIT;
6814
0
  dns_rdataset_t rdataset;
6815
0
  dns_rdata_nsec3param_t nsec3param;
6816
0
  dns_rdata_soa_t soa;
6817
0
  isc_result_t result;
6818
0
  isc_buffer_t buffer;
6819
0
  unsigned char parambuf[DNS_NSEC3PARAM_BUFFERSIZE];
6820
0
  dns_ttl_t ttl = 0;
6821
0
  bool nseconly = false, nsec3ok = false;
6822
6823
0
  dns_rdataset_init(&rdataset);
6824
6825
0
  result = dns_db_getoriginnode(db, &node);
6826
0
  RUNTIME_CHECK(result == ISC_R_SUCCESS);
6827
6828
  /* Default TTL is SOA MINIMUM */
6829
0
  result = dns_db_findrdataset(db, node, ver, dns_rdatatype_soa, 0, 0,
6830
0
             &rdataset, NULL);
6831
0
  if (result == ISC_R_SUCCESS) {
6832
0
    CHECK(dns_rdataset_first(&rdataset));
6833
0
    dns_rdataset_current(&rdataset, &rdata);
6834
0
    CHECK(dns_rdata_tostruct(&rdata, &soa));
6835
0
    ttl = soa.minimum;
6836
0
    dns_rdata_reset(&rdata);
6837
0
  }
6838
0
  dns_rdataset_cleanup(&rdataset);
6839
6840
0
  result = dns_db_findrdataset(db, node, ver, dns_rdatatype_nsec3param, 0,
6841
0
             0, &rdataset, NULL);
6842
0
  if (result == ISC_R_NOTFOUND) {
6843
0
    goto try_private;
6844
0
  }
6845
0
  if (result != ISC_R_SUCCESS) {
6846
0
    goto cleanup;
6847
0
  }
6848
6849
  /*
6850
   * Delete all NSEC3PARAM records which match that in nsec3chain.
6851
   */
6852
0
  DNS_RDATASET_FOREACH(&rdataset) {
6853
0
    dns_rdataset_current(&rdataset, &rdata);
6854
0
    CHECK(dns_rdata_tostruct(&rdata, &nsec3param));
6855
6856
0
    if (nsec3param.hash != chain->nsec3param.hash ||
6857
0
        (active && nsec3param.flags != 0) ||
6858
0
        nsec3param.iterations != chain->nsec3param.iterations ||
6859
0
        nsec3param.salt.length != chain->nsec3param.salt.length ||
6860
0
        memcmp(nsec3param.salt.base, chain->nsec3param.salt.base,
6861
0
         nsec3param.salt.length))
6862
0
    {
6863
      /*
6864
       * If the SOA minimum is different to the current TTL,
6865
       * delete the record.  We will re-add it with the new
6866
       * TTL below.
6867
       */
6868
0
      if (rdataset.ttl != ttl) {
6869
0
        CHECK(update_one_rr(db, ver, diff,
6870
0
                DNS_DIFFOP_DEL, name,
6871
0
                rdataset.ttl, &rdata));
6872
0
      }
6873
0
      dns_rdata_reset(&rdata);
6874
0
      continue;
6875
0
    }
6876
6877
0
    CHECK(update_one_rr(db, ver, diff, DNS_DIFFOP_DEL, name,
6878
0
            rdataset.ttl, &rdata));
6879
0
    dns_rdata_reset(&rdata);
6880
0
  }
6881
6882
  /*
6883
   * Restore any NSEC3PARAM records that we deleted to change the TTL.
6884
   */
6885
0
  if (rdataset.ttl != ttl) {
6886
0
    DNS_RDATASET_FOREACH(&rdataset) {
6887
0
      dns_rdataset_current(&rdataset, &rdata);
6888
0
      CHECK(dns_rdata_tostruct(&rdata, &nsec3param));
6889
6890
0
      if (nsec3param.hash != chain->nsec3param.hash ||
6891
0
          (active && nsec3param.flags != 0) ||
6892
0
          nsec3param.iterations !=
6893
0
            chain->nsec3param.iterations ||
6894
0
          nsec3param.salt.length !=
6895
0
            chain->nsec3param.salt.length ||
6896
0
          memcmp(nsec3param.salt.base,
6897
0
           chain->nsec3param.salt.base,
6898
0
           nsec3param.salt.length))
6899
0
      {
6900
0
        CHECK(update_one_rr(db, ver, diff,
6901
0
                DNS_DIFFOP_ADD, name, ttl,
6902
0
                &rdata));
6903
0
      }
6904
0
      dns_rdata_reset(&rdata);
6905
0
    }
6906
0
  }
6907
6908
0
  dns_rdataset_disassociate(&rdataset);
6909
6910
0
try_private:
6911
6912
0
  if (active) {
6913
0
    goto add;
6914
0
  }
6915
6916
0
  result = dns_nsec_nseconly(db, ver, diff, &nseconly);
6917
0
  nsec3ok = (result == ISC_R_SUCCESS && !nseconly);
6918
6919
  /*
6920
   * Delete all private records which match that in nsec3chain.
6921
   */
6922
0
  result = dns_db_findrdataset(db, node, ver, privatetype, 0, 0,
6923
0
             &rdataset, NULL);
6924
0
  if (result == ISC_R_NOTFOUND) {
6925
0
    goto add;
6926
0
  }
6927
0
  CHECK(result);
6928
6929
0
  DNS_RDATASET_FOREACH(&rdataset) {
6930
0
    dns_rdata_t private = DNS_RDATA_INIT;
6931
0
    unsigned char buf[DNS_NSEC3PARAM_BUFFERSIZE];
6932
6933
0
    dns_rdataset_current(&rdataset, &private);
6934
0
    if (!dns_nsec3param_fromprivate(&private, &rdata, buf,
6935
0
            sizeof(buf)))
6936
0
    {
6937
0
      continue;
6938
0
    }
6939
0
    CHECK(dns_rdata_tostruct(&rdata, &nsec3param));
6940
0
    dns_rdata_reset(&rdata);
6941
6942
0
    if ((!nsec3ok &&
6943
0
         (nsec3param.flags & DNS_NSEC3FLAG_INITIAL) != 0) ||
6944
0
        nsec3param.hash != chain->nsec3param.hash ||
6945
0
        nsec3param.iterations != chain->nsec3param.iterations ||
6946
0
        nsec3param.salt.length != chain->nsec3param.salt.length ||
6947
0
        memcmp(nsec3param.salt.base, chain->nsec3param.salt.base,
6948
0
         nsec3param.salt.length))
6949
0
    {
6950
0
      continue;
6951
0
    }
6952
6953
0
    CHECK(update_one_rr(db, ver, diff, DNS_DIFFOP_DEL, name,
6954
0
            rdataset.ttl, &private));
6955
0
  }
6956
6957
0
add:
6958
0
  if ((chain->nsec3param.flags & DNS_NSEC3FLAG_REMOVE) != 0) {
6959
0
    result = ISC_R_SUCCESS;
6960
0
    goto cleanup;
6961
0
  }
6962
6963
  /*
6964
   * Add a NSEC3PARAM record which matches that in nsec3chain but
6965
   * with all flags bits cleared.
6966
   *
6967
   * Note: we do not clear chain->nsec3param.flags as this change
6968
   * may be reversed.
6969
   */
6970
0
  isc_buffer_init(&buffer, &parambuf, sizeof(parambuf));
6971
0
  CHECK(dns_rdata_fromstruct(&rdata, dns_db_class(db),
6972
0
           dns_rdatatype_nsec3param, &chain->nsec3param,
6973
0
           &buffer));
6974
0
  rdata.data[1] = 0; /* Clear flag bits. */
6975
0
  CHECK(update_one_rr(db, ver, diff, DNS_DIFFOP_ADD, name, ttl, &rdata));
6976
6977
0
cleanup:
6978
0
  dns_db_detachnode(&node);
6979
0
  dns_rdataset_cleanup(&rdataset);
6980
0
  return result;
6981
0
}
6982
6983
static isc_result_t
6984
delete_nsec(dns_db_t *db, dns_dbversion_t *ver, dns_dbnode_t *node,
6985
0
      dns_name_t *name, dns_diff_t *diff) {
6986
0
  dns_rdataset_t rdataset;
6987
0
  isc_result_t result;
6988
6989
0
  dns_rdataset_init(&rdataset);
6990
6991
0
  result = dns_db_findrdataset(db, node, ver, dns_rdatatype_nsec, 0, 0,
6992
0
             &rdataset, NULL);
6993
0
  if (result == ISC_R_NOTFOUND) {
6994
0
    return ISC_R_SUCCESS;
6995
0
  }
6996
0
  if (result != ISC_R_SUCCESS) {
6997
0
    return result;
6998
0
  }
6999
7000
0
  DNS_RDATASET_FOREACH(&rdataset) {
7001
0
    dns_rdata_t rdata = DNS_RDATA_INIT;
7002
7003
0
    dns_rdataset_current(&rdataset, &rdata);
7004
0
    CHECK(update_one_rr(db, ver, diff, DNS_DIFFOP_DEL, name,
7005
0
            rdataset.ttl, &rdata));
7006
0
  }
7007
7008
0
cleanup:
7009
0
  dns_rdataset_disassociate(&rdataset);
7010
0
  return result;
7011
0
}
7012
7013
static isc_result_t
7014
deletematchingnsec3(dns_db_t *db, dns_dbversion_t *ver, dns_dbnode_t *node,
7015
        dns_name_t *name, const dns_rdata_nsec3param_t *param,
7016
0
        dns_diff_t *diff) {
7017
0
  dns_rdataset_t rdataset;
7018
0
  dns_rdata_nsec3_t nsec3;
7019
0
  isc_result_t result;
7020
7021
0
  dns_rdataset_init(&rdataset);
7022
0
  result = dns_db_findrdataset(db, node, ver, dns_rdatatype_nsec3, 0, 0,
7023
0
             &rdataset, NULL);
7024
0
  if (result == ISC_R_NOTFOUND) {
7025
0
    return ISC_R_SUCCESS;
7026
0
  }
7027
0
  if (result != ISC_R_SUCCESS) {
7028
0
    return result;
7029
0
  }
7030
7031
0
  DNS_RDATASET_FOREACH(&rdataset) {
7032
0
    dns_rdata_t rdata = DNS_RDATA_INIT;
7033
7034
0
    dns_rdataset_current(&rdataset, &rdata);
7035
0
    CHECK(dns_rdata_tostruct(&rdata, &nsec3));
7036
0
    if (nsec3.hash != param->hash ||
7037
0
        nsec3.iterations != param->iterations ||
7038
0
        nsec3.salt.length != param->salt.length ||
7039
0
        memcmp(nsec3.salt.base, param->salt.base,
7040
0
         nsec3.salt.length))
7041
0
    {
7042
0
      continue;
7043
0
    }
7044
0
    CHECK(update_one_rr(db, ver, diff, DNS_DIFFOP_DEL, name,
7045
0
            rdataset.ttl, &rdata));
7046
0
  }
7047
7048
0
cleanup:
7049
0
  dns_rdataset_disassociate(&rdataset);
7050
0
  return result;
7051
0
}
7052
7053
static isc_result_t
7054
need_nsec_chain(dns_db_t *db, dns_dbversion_t *ver,
7055
0
    const dns_rdata_nsec3param_t *param, bool *answer) {
7056
0
  dns_dbnode_t *node = NULL;
7057
0
  dns_rdata_nsec3param_t myparam;
7058
0
  dns_rdataset_t rdataset;
7059
0
  isc_result_t result;
7060
7061
0
  *answer = false;
7062
7063
0
  result = dns_db_getoriginnode(db, &node);
7064
0
  RUNTIME_CHECK(result == ISC_R_SUCCESS);
7065
7066
0
  dns_rdataset_init(&rdataset);
7067
7068
0
  result = dns_db_findrdataset(db, node, ver, dns_rdatatype_nsec, 0, 0,
7069
0
             &rdataset, NULL);
7070
0
  if (result == ISC_R_SUCCESS) {
7071
0
    dns_rdataset_disassociate(&rdataset);
7072
0
    dns_db_detachnode(&node);
7073
0
    return result;
7074
0
  }
7075
0
  if (result != ISC_R_NOTFOUND) {
7076
0
    dns_db_detachnode(&node);
7077
0
    return result;
7078
0
  }
7079
7080
0
  result = dns_db_findrdataset(db, node, ver, dns_rdatatype_nsec3param, 0,
7081
0
             0, &rdataset, NULL);
7082
0
  if (result == ISC_R_NOTFOUND) {
7083
0
    *answer = true;
7084
0
    dns_db_detachnode(&node);
7085
0
    return ISC_R_SUCCESS;
7086
0
  }
7087
0
  if (result != ISC_R_SUCCESS) {
7088
0
    dns_db_detachnode(&node);
7089
0
    return result;
7090
0
  }
7091
7092
0
  bool active = false;
7093
0
  DNS_RDATASET_FOREACH(&rdataset) {
7094
0
    dns_rdata_t rdata = DNS_RDATA_INIT;
7095
0
    dns_rdataset_current(&rdataset, &rdata);
7096
0
    CHECK(dns_rdata_tostruct(&rdata, &myparam));
7097
7098
    /*
7099
     * Ignore any NSEC3PARAM removals.
7100
     */
7101
0
    if (NSEC3REMOVE(myparam.flags)) {
7102
0
      continue;
7103
0
    }
7104
    /*
7105
     * Ignore the chain that we are in the process of deleting.
7106
     */
7107
0
    if (myparam.hash == param->hash &&
7108
0
        myparam.iterations == param->iterations &&
7109
0
        myparam.salt.length == param->salt.length &&
7110
0
        !memcmp(myparam.salt.base, param->salt.base,
7111
0
          myparam.salt.length))
7112
0
    {
7113
0
      continue;
7114
0
    }
7115
7116
    /*
7117
     * Found an active NSEC3 chain.
7118
     */
7119
0
    active = true;
7120
0
    break;
7121
0
  }
7122
7123
0
  *answer = !active;
7124
7125
0
cleanup:
7126
0
  dns_rdataset_cleanup(&rdataset);
7127
0
  dns_db_detachnode(&node);
7128
0
  return result;
7129
0
}
7130
7131
/*%
7132
 * Given a tuple which is part of a diff, return a pointer to the next tuple in
7133
 * that diff which has the same name and type (or NULL if no such tuple is
7134
 * found).
7135
 */
7136
static dns_difftuple_t *
7137
0
find_next_matching_tuple(dns_difftuple_t *cur) {
7138
0
  dns_difftuple_t *next = cur;
7139
7140
0
  while ((next = ISC_LIST_NEXT(next, link)) != NULL) {
7141
0
    if (cur->rdata.type == next->rdata.type &&
7142
0
        dns_name_equal(&cur->name, &next->name))
7143
0
    {
7144
0
      return next;
7145
0
    }
7146
0
  }
7147
7148
0
  return NULL;
7149
0
}
7150
7151
/*%
7152
 * Remove all tuples with the same name and type as 'cur' from 'src' and append
7153
 * them to 'dst'.
7154
 */
7155
static void
7156
0
move_matching_tuples(dns_difftuple_t *cur, dns_diff_t *src, dns_diff_t *dst) {
7157
0
  do {
7158
0
    dns_difftuple_t *next = find_next_matching_tuple(cur);
7159
0
    dns_diff_unlink(src, cur);
7160
0
    dns_diff_appendminimal(dst, &cur);
7161
0
    cur = next;
7162
0
  } while (cur != NULL);
7163
0
}
7164
7165
/*%
7166
 * Add/remove DNSSEC signatures for the list of "raw" zone changes supplied in
7167
 * 'diff'.  Gradually remove tuples from 'diff' and append them to 'zonediff'
7168
 * along with tuples representing relevant signature changes.
7169
 */
7170
isc_result_t
7171
dns__zone_updatesigs(dns_diff_t *diff, dns_db_t *db, dns_dbversion_t *version,
7172
         dst_key_t *zone_keys[], unsigned int nkeys,
7173
         dns_zone_t *zone, isc_stdtime_t inception,
7174
         isc_stdtime_t expire, isc_stdtime_t keyexpire,
7175
0
         isc_stdtime_t now, dns__zonediff_t *zonediff) {
7176
0
  dns_difftuple_t *tuple;
7177
0
  isc_result_t result;
7178
7179
0
  while ((tuple = ISC_LIST_HEAD(diff->tuples)) != NULL) {
7180
0
    isc_stdtime_t exp = expire;
7181
7182
0
    if (keyexpire != 0 &&
7183
0
        dns_rdatatype_iskeymaterial(tuple->rdata.type))
7184
0
    {
7185
0
      exp = keyexpire;
7186
0
    }
7187
7188
0
    result = del_sigs(zone, db, version, &tuple->name,
7189
0
          tuple->rdata.type, zonediff, zone_keys, nkeys,
7190
0
          now, false);
7191
0
    if (result != ISC_R_SUCCESS) {
7192
0
      dns_zone_log(zone, ISC_LOG_ERROR,
7193
0
             "dns__zone_updatesigs:del_sigs -> %s",
7194
0
             isc_result_totext(result));
7195
0
      return result;
7196
0
    }
7197
0
    result = add_sigs(db, version, &tuple->name, zone,
7198
0
          tuple->rdata.type, zonediff->diff, zone_keys,
7199
0
          nkeys, zone->mctx, now, inception, exp);
7200
0
    if (result != ISC_R_SUCCESS) {
7201
0
      dns_zone_log(zone, ISC_LOG_ERROR,
7202
0
             "dns__zone_updatesigs:add_sigs -> %s",
7203
0
             isc_result_totext(result));
7204
0
      return result;
7205
0
    }
7206
7207
    /*
7208
     * Signature changes for all RRs with name tuple->name and type
7209
     * tuple->rdata.type were appended to zonediff->diff.  Now we
7210
     * remove all the "raw" changes with the same name and type
7211
     * from diff (so that they are not processed by this loop
7212
     * again) and append them to zonediff so that they get applied.
7213
     */
7214
0
    move_matching_tuples(tuple, diff, zonediff->diff);
7215
0
  }
7216
0
  return ISC_R_SUCCESS;
7217
0
}
7218
7219
/*
7220
 * Incrementally build and sign a new NSEC3 chain using the parameters
7221
 * requested.
7222
 */
7223
static void
7224
0
zone_nsec3chain(dns_zone_t *zone) {
7225
0
  dns_db_t *db = NULL;
7226
0
  dns_dbnode_t *node = NULL;
7227
0
  dns_dbversion_t *version = NULL;
7228
0
  dns_diff_t _sig_diff;
7229
0
  dns_diff_t nsec_diff;
7230
0
  dns_diff_t nsec3_diff;
7231
0
  dns_diff_t param_diff;
7232
0
  dns__zonediff_t zonediff;
7233
0
  dns_fixedname_t fixed;
7234
0
  dns_fixedname_t nextfixed;
7235
0
  dns_name_t *name = NULL, *nextname = NULL;
7236
0
  dns_nsec3chain_t *nsec3chain = NULL;
7237
0
  dns_nsec3chainlist_t cleanup;
7238
0
  dst_key_t *zone_keys[DNS_MAXZONEKEYS];
7239
0
  int32_t signatures;
7240
0
  bool delegation;
7241
0
  bool first;
7242
0
  isc_result_t result;
7243
0
  isc_stdtime_t now, inception, soaexpire, expire;
7244
0
  unsigned int i;
7245
0
  unsigned int nkeys = 0;
7246
0
  uint32_t nodes;
7247
0
  bool unsecure = false;
7248
0
  seen_t seen;
7249
0
  dns_rdatasetiter_t *iterator = NULL;
7250
0
  bool buildnsecchain;
7251
0
  bool updatensec = false;
7252
0
  dns_rdatatype_t privatetype = zone->privatetype;
7253
7254
0
  ENTER;
7255
7256
0
  name = dns_fixedname_initname(&fixed);
7257
0
  nextname = dns_fixedname_initname(&nextfixed);
7258
0
  dns_diff_init(zone->mctx, &param_diff);
7259
0
  dns_diff_init(zone->mctx, &nsec3_diff);
7260
0
  dns_diff_init(zone->mctx, &nsec_diff);
7261
0
  dns_diff_init(zone->mctx, &_sig_diff);
7262
0
  zonediff_init(&zonediff, &_sig_diff);
7263
0
  ISC_LIST_INIT(cleanup);
7264
7265
  /*
7266
   * Updates are disabled.  Pause for 5 minutes.
7267
   */
7268
0
  if (zone->update_disabled) {
7269
0
    CLEANUP(ISC_R_FAILURE);
7270
0
  }
7271
7272
0
  ZONEDB_LOCK(&zone->dblock, isc_rwlocktype_read);
7273
  /*
7274
   * This function is called when zone timer fires, after the latter gets
7275
   * set by zone_addnsec3chain().  If the action triggering the call to
7276
   * zone_addnsec3chain() is closely followed by a zone deletion request,
7277
   * it might turn out that the timer thread will not be woken up until
7278
   * after the zone is deleted by rmzone(), which calls dns_db_detach()
7279
   * for zone->db, causing the latter to become NULL.  Return immediately
7280
   * if that happens.
7281
   */
7282
0
  if (zone->db != NULL) {
7283
0
    dns_db_attach(zone->db, &db);
7284
0
  }
7285
0
  ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_read);
7286
0
  if (db == NULL) {
7287
0
    return;
7288
0
  }
7289
7290
0
  result = dns_db_newversion(db, &version);
7291
0
  if (result != ISC_R_SUCCESS) {
7292
0
    dnssec_log(zone, ISC_LOG_ERROR,
7293
0
         "zone_nsec3chain:dns_db_newversion -> %s",
7294
0
         isc_result_totext(result));
7295
0
    goto cleanup;
7296
0
  }
7297
7298
0
  now = isc_stdtime_now();
7299
7300
0
  result = dns_zone_findkeys(zone, db, version, now, zone->mctx,
7301
0
           DNS_MAXZONEKEYS, zone_keys, &nkeys);
7302
0
  if (result != ISC_R_SUCCESS) {
7303
0
    dnssec_log(zone, ISC_LOG_ERROR,
7304
0
         "zone_nsec3chain:dns_zone_findkeys -> %s",
7305
0
         isc_result_totext(result));
7306
0
    goto cleanup;
7307
0
  }
7308
7309
0
  calculate_rrsig_validity(zone, now, &inception, &soaexpire, NULL,
7310
0
         &expire);
7311
7312
  /*
7313
   * We keep pulling nodes off each iterator in turn until
7314
   * we have no more nodes to pull off or we reach the limits
7315
   * for this quantum.
7316
   */
7317
0
  nodes = zone->nodes;
7318
0
  signatures = zone->signatures;
7319
0
  LOCK_ZONE(zone);
7320
0
  nsec3chain = ISC_LIST_HEAD(zone->nsec3chain);
7321
0
  UNLOCK_ZONE(zone);
7322
0
  first = true;
7323
7324
0
  if (nsec3chain != NULL) {
7325
0
    nsec3chain->save_delete_nsec = nsec3chain->delete_nsec;
7326
0
  }
7327
  /*
7328
   * Generate new NSEC3 chains first.
7329
   *
7330
   * The following while loop iterates over nodes in the zone database,
7331
   * updating the NSEC3 chain by calling dns_nsec3_addnsec3() for each of
7332
   * them.  Once all nodes are processed, the "delete_nsec" field is
7333
   * consulted to check whether we are supposed to remove NSEC records
7334
   * from the zone database; if so, the database iterator is reset to
7335
   * point to the first node and the loop traverses all of them again,
7336
   * this time removing NSEC records.  If we hit a node which is obscured
7337
   * by a delegation or a DNAME, nodes are skipped over until we find one
7338
   * that is not obscured by the same obscuring name and then normal
7339
   * processing is resumed.
7340
   *
7341
   * The above is repeated until all requested NSEC3 chain changes are
7342
   * applied or when we reach the limits for this quantum, whichever
7343
   * happens first.
7344
   *
7345
   * Note that the "signatures" variable is only used here to limit the
7346
   * amount of work performed.  Actual DNSSEC signatures are only
7347
   * generated by dns__zone_updatesigs() calls later in this function.
7348
   */
7349
0
  while (nsec3chain != NULL && nodes-- > 0 && signatures > 0) {
7350
0
    dns_dbiterator_pause(nsec3chain->dbiterator);
7351
7352
0
    LOCK_ZONE(zone);
7353
0
    dns_nsec3chain_t *nextnsec3chain = ISC_LIST_NEXT(nsec3chain,
7354
0
                 link);
7355
7356
0
    ZONEDB_LOCK(&zone->dblock, isc_rwlocktype_read);
7357
0
    if (nsec3chain->done || nsec3chain->db != zone->db) {
7358
0
      ISC_LIST_UNLINK(zone->nsec3chain, nsec3chain, link);
7359
0
      ISC_LIST_APPEND(cleanup, nsec3chain, link);
7360
0
    }
7361
0
    ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_read);
7362
0
    UNLOCK_ZONE(zone);
7363
0
    if (ISC_LIST_TAIL(cleanup) == nsec3chain) {
7364
0
      goto next_addchain;
7365
0
    }
7366
7367
    /*
7368
     * Possible future db.
7369
     */
7370
0
    if (nsec3chain->db != db) {
7371
0
      goto next_addchain;
7372
0
    }
7373
7374
0
    if (NSEC3REMOVE(nsec3chain->nsec3param.flags)) {
7375
0
      goto next_addchain;
7376
0
    }
7377
7378
0
    dns_dbiterator_current(nsec3chain->dbiterator, &node, name);
7379
7380
0
    if (nsec3chain->delete_nsec) {
7381
0
      delegation = false;
7382
0
      dns_dbiterator_pause(nsec3chain->dbiterator);
7383
0
      CHECK(delete_nsec(db, version, node, name, &nsec_diff));
7384
0
      goto next_addnode;
7385
0
    }
7386
    /*
7387
     * On the first pass we need to check if the current node
7388
     * has not been obscured.
7389
     */
7390
0
    delegation = false;
7391
0
    unsecure = false;
7392
0
    if (first) {
7393
0
      dns_fixedname_t ffound;
7394
0
      dns_name_t *found;
7395
0
      found = dns_fixedname_initname(&ffound);
7396
0
      result = dns_db_find(
7397
0
        db, name, version, dns_rdatatype_soa,
7398
0
        DNS_DBFIND_NOWILD, 0, found, NULL, NULL);
7399
0
      if ((result == DNS_R_DELEGATION ||
7400
0
           result == DNS_R_DNAME) &&
7401
0
          !dns_name_equal(name, found))
7402
0
      {
7403
        /*
7404
         * Remember the obscuring name so that
7405
         * we skip all obscured names.
7406
         */
7407
0
        dns_name_copy(found, name);
7408
0
        delegation = true;
7409
0
        goto next_addnode;
7410
0
      }
7411
0
    }
7412
7413
    /*
7414
     * Check to see if this is a bottom of zone node.
7415
     */
7416
0
    result = allrdatasets(db, node, version, &iterator, &seen);
7417
0
    if (result == ISC_R_NOTFOUND) {
7418
      /* Empty node? */
7419
0
      goto next_addnode;
7420
0
    }
7421
0
    CHECK(result);
7422
7423
0
    INSIST(!seen.nsec3);
7424
7425
0
    dns_rdatasetiter_destroy(&iterator);
7426
    /*
7427
     * Is there a NSEC chain than needs to be cleaned up?
7428
     */
7429
0
    if (seen.nsec) {
7430
0
      nsec3chain->seen_nsec = true;
7431
0
    }
7432
7433
0
    if (seen.ns && !seen.soa && !seen.ds) {
7434
0
      unsecure = true;
7435
0
    }
7436
0
    if ((seen.ns && !seen.soa) || seen.dname) {
7437
0
      delegation = true;
7438
0
    }
7439
7440
    /*
7441
     * Process one node.
7442
     */
7443
0
    dns_dbiterator_pause(nsec3chain->dbiterator);
7444
0
    result = dns_nsec3_addnsec3(
7445
0
      db, version, name, &nsec3chain->nsec3param,
7446
0
      zone_nsecttl(zone), unsecure, &nsec3_diff);
7447
0
    if (result != ISC_R_SUCCESS) {
7448
0
      dnssec_log(zone, ISC_LOG_ERROR,
7449
0
           "zone_nsec3chain:"
7450
0
           "dns_nsec3_addnsec3 -> %s",
7451
0
           isc_result_totext(result));
7452
0
      goto cleanup;
7453
0
    }
7454
7455
    /*
7456
     * Treat each call to dns_nsec3_addnsec3() as if it's cost is
7457
     * two signatures.  Additionally there will, in general, be
7458
     * two signature generated below.
7459
     *
7460
     * If we are only changing the optout flag the cost is half
7461
     * that of the cost of generating a completely new chain.
7462
     */
7463
0
    signatures -= 4;
7464
7465
    /*
7466
     * Go onto next node.
7467
     */
7468
0
  next_addnode:
7469
0
    first = false;
7470
0
    dns_db_detachnode(&node);
7471
0
    do {
7472
0
      result = dns_dbiterator_next(nsec3chain->dbiterator);
7473
7474
0
      if (result == ISC_R_NOMORE && nsec3chain->delete_nsec) {
7475
0
        dns_dbiterator_pause(nsec3chain->dbiterator);
7476
0
        CHECK(fixup_nsec3param(db, version, nsec3chain,
7477
0
                   false, privatetype,
7478
0
                   &param_diff));
7479
0
        LOCK_ZONE(zone);
7480
0
        ISC_LIST_UNLINK(zone->nsec3chain, nsec3chain,
7481
0
            link);
7482
0
        UNLOCK_ZONE(zone);
7483
0
        ISC_LIST_APPEND(cleanup, nsec3chain, link);
7484
0
        goto next_addchain;
7485
0
      }
7486
0
      if (result == ISC_R_NOMORE) {
7487
0
        dns_dbiterator_pause(nsec3chain->dbiterator);
7488
0
        if (nsec3chain->seen_nsec) {
7489
0
          CHECK(fixup_nsec3param(
7490
0
            db, version, nsec3chain, true,
7491
0
            privatetype, &param_diff));
7492
0
          nsec3chain->delete_nsec = true;
7493
0
          goto same_addchain;
7494
0
        }
7495
0
        CHECK(fixup_nsec3param(db, version, nsec3chain,
7496
0
                   false, privatetype,
7497
0
                   &param_diff));
7498
0
        LOCK_ZONE(zone);
7499
0
        ISC_LIST_UNLINK(zone->nsec3chain, nsec3chain,
7500
0
            link);
7501
0
        UNLOCK_ZONE(zone);
7502
0
        ISC_LIST_APPEND(cleanup, nsec3chain, link);
7503
0
        goto next_addchain;
7504
0
      } else if (result != ISC_R_SUCCESS) {
7505
0
        dnssec_log(zone, ISC_LOG_ERROR,
7506
0
             "zone_nsec3chain:"
7507
0
             "dns_dbiterator_next -> %s",
7508
0
             isc_result_totext(result));
7509
0
        goto cleanup;
7510
0
      } else if (delegation) {
7511
0
        dns_dbiterator_current(nsec3chain->dbiterator,
7512
0
                   &node, nextname);
7513
0
        dns_db_detachnode(&node);
7514
0
        if (!dns_name_issubdomain(nextname, name)) {
7515
0
          break;
7516
0
        }
7517
0
      } else {
7518
0
        break;
7519
0
      }
7520
0
    } while (1);
7521
0
    continue;
7522
7523
0
  same_addchain:
7524
0
    CHECK(dns_dbiterator_first(nsec3chain->dbiterator));
7525
0
    first = true;
7526
0
    continue;
7527
7528
0
  next_addchain:
7529
0
    dns_dbiterator_pause(nsec3chain->dbiterator);
7530
0
    nsec3chain = nextnsec3chain;
7531
0
    first = true;
7532
0
    if (nsec3chain != NULL) {
7533
0
      nsec3chain->save_delete_nsec = nsec3chain->delete_nsec;
7534
0
    }
7535
0
  }
7536
7537
0
  if (nsec3chain != NULL) {
7538
0
    goto skip_removals;
7539
0
  }
7540
7541
  /*
7542
   * Process removals.
7543
   *
7544
   * This is a counterpart of the above while loop which takes care of
7545
   * removing an NSEC3 chain.  It starts with determining whether the
7546
   * zone needs to switch from NSEC3 to NSEC; if so, it first builds an
7547
   * NSEC chain by iterating over all nodes in the zone database and only
7548
   * then goes on to remove NSEC3 records be iterating over all nodes
7549
   * again and calling deletematchingnsec3() for each of them; otherwise,
7550
   * it starts removing NSEC3 records immediately.  Rules for processing
7551
   * obscured nodes and interrupting work are the same as for the while
7552
   * loop above.
7553
   */
7554
0
  LOCK_ZONE(zone);
7555
0
  nsec3chain = ISC_LIST_HEAD(zone->nsec3chain);
7556
0
  UNLOCK_ZONE(zone);
7557
0
  first = true;
7558
0
  buildnsecchain = false;
7559
0
  while (nsec3chain != NULL && nodes-- > 0 && signatures > 0) {
7560
0
    dns_dbiterator_pause(nsec3chain->dbiterator);
7561
7562
0
    LOCK_ZONE(zone);
7563
0
    dns_nsec3chain_t *nextnsec3chain = ISC_LIST_NEXT(nsec3chain,
7564
0
                 link);
7565
0
    UNLOCK_ZONE(zone);
7566
7567
0
    if (nsec3chain->db != db) {
7568
0
      goto next_removechain;
7569
0
    }
7570
7571
0
    if (!NSEC3REMOVE(nsec3chain->nsec3param.flags)) {
7572
0
      goto next_removechain;
7573
0
    }
7574
7575
    /*
7576
     * Work out if we need to build a NSEC chain as a consequence
7577
     * of removing this NSEC3 chain.
7578
     */
7579
0
    if (first && !updatensec &&
7580
0
        (nsec3chain->nsec3param.flags & DNS_NSEC3FLAG_NONSEC) == 0)
7581
0
    {
7582
0
      result = need_nsec_chain(db, version,
7583
0
             &nsec3chain->nsec3param,
7584
0
             &buildnsecchain);
7585
0
      if (result != ISC_R_SUCCESS) {
7586
0
        dnssec_log(zone, ISC_LOG_ERROR,
7587
0
             "zone_nsec3chain:"
7588
0
             "need_nsec_chain -> %s",
7589
0
             isc_result_totext(result));
7590
0
        goto cleanup;
7591
0
      }
7592
0
    }
7593
7594
0
    if (first) {
7595
0
      dnssec_log(zone, ISC_LOG_DEBUG(3),
7596
0
           "zone_nsec3chain:buildnsecchain = %u",
7597
0
           buildnsecchain);
7598
0
    }
7599
7600
0
    dns_dbiterator_current(nsec3chain->dbiterator, &node, name);
7601
0
    dns_dbiterator_pause(nsec3chain->dbiterator);
7602
0
    delegation = false;
7603
7604
0
    if (!buildnsecchain) {
7605
      /*
7606
       * Delete the NSEC3PARAM record matching this chain.
7607
       */
7608
0
      if (first) {
7609
0
        result = fixup_nsec3param(
7610
0
          db, version, nsec3chain, true,
7611
0
          privatetype, &param_diff);
7612
0
        if (result != ISC_R_SUCCESS) {
7613
0
          dnssec_log(zone, ISC_LOG_ERROR,
7614
0
               "zone_nsec3chain:"
7615
0
               "fixup_nsec3param -> %s",
7616
0
               isc_result_totext(result));
7617
0
          goto cleanup;
7618
0
        }
7619
0
      }
7620
7621
      /*
7622
       * Delete the NSEC3 records.
7623
       */
7624
0
      result = deletematchingnsec3(db, version, node, name,
7625
0
                 &nsec3chain->nsec3param,
7626
0
                 &nsec3_diff);
7627
0
      if (result != ISC_R_SUCCESS) {
7628
0
        dnssec_log(zone, ISC_LOG_ERROR,
7629
0
             "zone_nsec3chain:"
7630
0
             "deletematchingnsec3 -> %s",
7631
0
             isc_result_totext(result));
7632
0
        goto cleanup;
7633
0
      }
7634
0
      goto next_removenode;
7635
0
    }
7636
7637
0
    if (first) {
7638
0
      dns_fixedname_t ffound;
7639
0
      dns_name_t *found;
7640
0
      found = dns_fixedname_initname(&ffound);
7641
0
      result = dns_db_find(
7642
0
        db, name, version, dns_rdatatype_soa,
7643
0
        DNS_DBFIND_NOWILD, 0, found, NULL, NULL);
7644
0
      if ((result == DNS_R_DELEGATION ||
7645
0
           result == DNS_R_DNAME) &&
7646
0
          !dns_name_equal(name, found))
7647
0
      {
7648
        /*
7649
         * Remember the obscuring name so that
7650
         * we skip all obscured names.
7651
         */
7652
0
        dns_name_copy(found, name);
7653
0
        delegation = true;
7654
0
        goto next_removenode;
7655
0
      }
7656
0
    }
7657
7658
    /*
7659
     * Check to see if this is a bottom of zone node.
7660
     */
7661
0
    result = allrdatasets(db, node, version, &iterator, &seen);
7662
0
    if (result == ISC_R_NOTFOUND) {
7663
      /* Empty node? */
7664
0
      goto next_removenode;
7665
0
    }
7666
0
    CHECK(result);
7667
7668
0
    dns_rdatasetiter_destroy(&iterator);
7669
7670
0
    if (!seen.rr || seen.nsec3 || seen.nsec) {
7671
0
      goto next_removenode;
7672
0
    }
7673
0
    if ((seen.ns && !seen.soa) || seen.dname) {
7674
0
      delegation = true;
7675
0
    }
7676
7677
    /*
7678
     * Add a NSEC record except at the origin.
7679
     */
7680
0
    if (!dns_name_equal(name, dns_db_origin(db))) {
7681
0
      dns_dbiterator_pause(nsec3chain->dbiterator);
7682
0
      CHECK(add_nsec(db, version, name, node,
7683
0
               zone_nsecttl(zone), delegation,
7684
0
               &nsec_diff));
7685
0
      signatures--;
7686
0
    }
7687
7688
0
  next_removenode:
7689
0
    first = false;
7690
0
    dns_db_detachnode(&node);
7691
0
    do {
7692
0
      result = dns_dbiterator_next(nsec3chain->dbiterator);
7693
0
      if (result == ISC_R_NOMORE && buildnsecchain) {
7694
        /*
7695
         * The NSEC chain should now be built.
7696
         * We can now remove the NSEC3 chain.
7697
         */
7698
0
        updatensec = true;
7699
0
        goto same_removechain;
7700
0
      }
7701
0
      if (result == ISC_R_NOMORE) {
7702
0
        dns_dbiterator_pause(nsec3chain->dbiterator);
7703
0
        LOCK_ZONE(zone);
7704
0
        ISC_LIST_UNLINK(zone->nsec3chain, nsec3chain,
7705
0
            link);
7706
0
        UNLOCK_ZONE(zone);
7707
0
        ISC_LIST_APPEND(cleanup, nsec3chain, link);
7708
0
        result = fixup_nsec3param(
7709
0
          db, version, nsec3chain, false,
7710
0
          privatetype, &param_diff);
7711
0
        if (result != ISC_R_SUCCESS) {
7712
0
          dnssec_log(zone, ISC_LOG_ERROR,
7713
0
               "zone_nsec3chain:"
7714
0
               "fixup_nsec3param -> %s",
7715
0
               isc_result_totext(result));
7716
0
          goto cleanup;
7717
0
        }
7718
0
        goto next_removechain;
7719
0
      } else if (result != ISC_R_SUCCESS) {
7720
0
        dnssec_log(zone, ISC_LOG_ERROR,
7721
0
             "zone_nsec3chain:"
7722
0
             "dns_dbiterator_next -> %s",
7723
0
             isc_result_totext(result));
7724
0
        goto cleanup;
7725
0
      } else if (delegation) {
7726
0
        dns_dbiterator_current(nsec3chain->dbiterator,
7727
0
                   &node, nextname);
7728
0
        dns_db_detachnode(&node);
7729
0
        if (!dns_name_issubdomain(nextname, name)) {
7730
0
          break;
7731
0
        }
7732
0
      } else {
7733
0
        break;
7734
0
      }
7735
0
    } while (1);
7736
0
    continue;
7737
7738
0
  same_removechain:
7739
0
    CHECK(dns_dbiterator_first(nsec3chain->dbiterator));
7740
0
    buildnsecchain = false;
7741
0
    first = true;
7742
0
    continue;
7743
7744
0
  next_removechain:
7745
0
    dns_dbiterator_pause(nsec3chain->dbiterator);
7746
0
    nsec3chain = nextnsec3chain;
7747
0
    first = true;
7748
0
  }
7749
7750
0
skip_removals:
7751
  /*
7752
   * We may need to update the NSEC/NSEC3 records for the zone apex.
7753
   */
7754
0
  if (!ISC_LIST_EMPTY(param_diff.tuples)) {
7755
0
    bool rebuild_nsec = false, rebuild_nsec3 = false;
7756
0
    result = dns_db_getoriginnode(db, &node);
7757
0
    RUNTIME_CHECK(result == ISC_R_SUCCESS);
7758
0
    result = dns_db_allrdatasets(db, node, version, 0, 0,
7759
0
               &iterator);
7760
0
    if (result != ISC_R_SUCCESS) {
7761
0
      dnssec_log(zone, ISC_LOG_ERROR,
7762
0
           "zone_nsec3chain:dns_db_allrdatasets -> %s",
7763
0
           isc_result_totext(result));
7764
0
      goto cleanup;
7765
0
    }
7766
0
    DNS_RDATASETITER_FOREACH(iterator) {
7767
0
      dns_rdataset_t rdataset = DNS_RDATASET_INIT;
7768
0
      dns_rdatasetiter_current(iterator, &rdataset);
7769
0
      if (rdataset.type == dns_rdatatype_nsec) {
7770
0
        rebuild_nsec = true;
7771
0
      } else if (rdataset.type == dns_rdatatype_nsec3param) {
7772
0
        rebuild_nsec3 = true;
7773
0
      }
7774
0
      dns_rdataset_disassociate(&rdataset);
7775
0
    }
7776
0
    dns_rdatasetiter_destroy(&iterator);
7777
0
    dns_db_detachnode(&node);
7778
7779
0
    if (rebuild_nsec) {
7780
0
      if (nsec3chain != NULL) {
7781
0
        dns_dbiterator_pause(nsec3chain->dbiterator);
7782
0
      }
7783
7784
0
      result = updatesecure(db, version, &zone->origin,
7785
0
                zone_nsecttl(zone), true,
7786
0
                &nsec_diff);
7787
0
      if (result != ISC_R_SUCCESS) {
7788
0
        dnssec_log(zone, ISC_LOG_ERROR,
7789
0
             "zone_nsec3chain:updatesecure -> %s",
7790
0
             isc_result_totext(result));
7791
0
        goto cleanup;
7792
0
      }
7793
0
    }
7794
7795
0
    if (rebuild_nsec3) {
7796
0
      if (nsec3chain != NULL) {
7797
0
        dns_dbiterator_pause(nsec3chain->dbiterator);
7798
0
      }
7799
7800
0
      result = dns_nsec3_addnsec3s(
7801
0
        db, version, dns_db_origin(db),
7802
0
        zone_nsecttl(zone), false, &nsec3_diff);
7803
0
      if (result != ISC_R_SUCCESS) {
7804
0
        dnssec_log(zone, ISC_LOG_ERROR,
7805
0
             "zone_nsec3chain:"
7806
0
             "dns_nsec3_addnsec3s -> %s",
7807
0
             isc_result_totext(result));
7808
0
        goto cleanup;
7809
0
      }
7810
0
    }
7811
0
  }
7812
7813
  /*
7814
   * Add / update signatures for the NSEC3 records.
7815
   */
7816
0
  if (nsec3chain != NULL) {
7817
0
    dns_dbiterator_pause(nsec3chain->dbiterator);
7818
0
  }
7819
0
  result = dns__zone_updatesigs(&nsec3_diff, db, version, zone_keys,
7820
0
              nkeys, zone, inception, expire, 0, now,
7821
0
              &zonediff);
7822
0
  if (result != ISC_R_SUCCESS) {
7823
0
    dnssec_log(zone, ISC_LOG_ERROR,
7824
0
         "zone_nsec3chain:dns__zone_updatesigs -> %s",
7825
0
         isc_result_totext(result));
7826
0
    goto cleanup;
7827
0
  }
7828
7829
  /*
7830
   * We have changed the NSEC3PARAM or private RRsets
7831
   * above so we need to update the signatures.
7832
   */
7833
0
  result = dns__zone_updatesigs(&param_diff, db, version, zone_keys,
7834
0
              nkeys, zone, inception, expire, 0, now,
7835
0
              &zonediff);
7836
0
  if (result != ISC_R_SUCCESS) {
7837
0
    dnssec_log(zone, ISC_LOG_ERROR,
7838
0
         "zone_nsec3chain:dns__zone_updatesigs -> %s",
7839
0
         isc_result_totext(result));
7840
0
    goto cleanup;
7841
0
  }
7842
7843
0
  if (updatensec) {
7844
0
    result = updatesecure(db, version, &zone->origin,
7845
0
              zone_nsecttl(zone), false, &nsec_diff);
7846
0
    if (result != ISC_R_SUCCESS) {
7847
0
      dnssec_log(zone, ISC_LOG_ERROR,
7848
0
           "zone_nsec3chain:updatesecure -> %s",
7849
0
           isc_result_totext(result));
7850
0
      goto cleanup;
7851
0
    }
7852
0
  }
7853
7854
0
  result = dns__zone_updatesigs(&nsec_diff, db, version, zone_keys, nkeys,
7855
0
              zone, inception, expire, 0, now,
7856
0
              &zonediff);
7857
0
  if (result != ISC_R_SUCCESS) {
7858
0
    dnssec_log(zone, ISC_LOG_ERROR,
7859
0
         "zone_nsec3chain:dns__zone_updatesigs -> %s",
7860
0
         isc_result_totext(result));
7861
0
    goto cleanup;
7862
0
  }
7863
7864
  /*
7865
   * If we made no effective changes to the zone then we can just
7866
   * cleanup otherwise we need to increment the serial.
7867
   */
7868
0
  if (ISC_LIST_EMPTY(zonediff.diff->tuples)) {
7869
    /*
7870
     * No need to call dns_db_closeversion() here as it is
7871
     * called with commit = true below.
7872
     */
7873
0
    goto closeversion;
7874
0
  }
7875
7876
0
  result = del_sigs(zone, db, version, &zone->origin, dns_rdatatype_soa,
7877
0
        &zonediff, zone_keys, nkeys, now, false);
7878
0
  if (result != ISC_R_SUCCESS) {
7879
0
    dnssec_log(zone, ISC_LOG_ERROR,
7880
0
         "zone_nsec3chain:del_sigs -> %s",
7881
0
         isc_result_totext(result));
7882
0
    goto cleanup;
7883
0
  }
7884
7885
0
  result = update_soa_serial(zone, db, version, zonediff.diff, zone->mctx,
7886
0
           zone->updatemethod);
7887
0
  if (result != ISC_R_SUCCESS) {
7888
0
    dnssec_log(zone, ISC_LOG_ERROR,
7889
0
         "zone_nsec3chain:update_soa_serial -> %s",
7890
0
         isc_result_totext(result));
7891
0
    goto cleanup;
7892
0
  }
7893
7894
0
  result = add_sigs(db, version, &zone->origin, zone, dns_rdatatype_soa,
7895
0
        zonediff.diff, zone_keys, nkeys, zone->mctx, now,
7896
0
        inception, soaexpire);
7897
0
  if (result != ISC_R_SUCCESS) {
7898
0
    dnssec_log(zone, ISC_LOG_ERROR,
7899
0
         "zone_nsec3chain:add_sigs -> %s",
7900
0
         isc_result_totext(result));
7901
0
    goto cleanup;
7902
0
  }
7903
7904
  /* Write changes to journal file. */
7905
0
  CHECK(zone_journal(zone, zonediff.diff, NULL, "zone_nsec3chain"));
7906
7907
0
  LOCK_ZONE(zone);
7908
0
  zone_needdump(zone, DNS_DUMP_DELAY);
7909
0
  DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_NEEDNOTIFY);
7910
0
  UNLOCK_ZONE(zone);
7911
7912
0
closeversion:
7913
  /*
7914
   * Pause all iterators so that dns_db_closeversion() can succeed.
7915
   */
7916
0
  LOCK_ZONE(zone);
7917
0
  ISC_LIST_FOREACH(zone->nsec3chain, chain, link) {
7918
0
    dns_dbiterator_pause(chain->dbiterator);
7919
0
  }
7920
0
  UNLOCK_ZONE(zone);
7921
7922
  /*
7923
   * Everything has succeeded. Commit the changes.
7924
   * Unconditionally commit as zonediff.offline not checked above.
7925
   */
7926
0
  dns_db_closeversion(db, &version, true);
7927
7928
  /*
7929
   * Everything succeeded so we can clean these up now.
7930
   */
7931
0
  ISC_LIST_FOREACH(cleanup, chain, link) {
7932
0
    ISC_LIST_UNLINK(cleanup, chain, link);
7933
0
    dns_db_detach(&chain->db);
7934
0
    dns_dbiterator_destroy(&chain->dbiterator);
7935
0
    isc_mem_put(zone->mctx, chain, sizeof *chain);
7936
0
  }
7937
7938
0
  LOCK_ZONE(zone);
7939
0
  dns__zone_set_resigntime(zone);
7940
0
  UNLOCK_ZONE(zone);
7941
7942
0
cleanup:
7943
0
  if (result != ISC_R_SUCCESS) {
7944
0
    dnssec_log(zone, ISC_LOG_ERROR, "zone_nsec3chain: %s",
7945
0
         isc_result_totext(result));
7946
0
  }
7947
7948
  /*
7949
   * On error roll back the current nsec3chain.
7950
   */
7951
0
  if (result != ISC_R_SUCCESS && nsec3chain != NULL) {
7952
0
    if (nsec3chain->done) {
7953
0
      dns_db_detach(&nsec3chain->db);
7954
0
      dns_dbiterator_destroy(&nsec3chain->dbiterator);
7955
0
      isc_mem_put(zone->mctx, nsec3chain, sizeof *nsec3chain);
7956
0
    } else {
7957
0
      result = dns_dbiterator_first(nsec3chain->dbiterator);
7958
0
      RUNTIME_CHECK(result == ISC_R_SUCCESS);
7959
0
      dns_dbiterator_pause(nsec3chain->dbiterator);
7960
0
      nsec3chain->delete_nsec = nsec3chain->save_delete_nsec;
7961
0
    }
7962
0
  }
7963
7964
  /*
7965
   * Rollback the cleanup list.
7966
   */
7967
0
  ISC_LIST_FOREACH_REV(cleanup, chain, link) {
7968
0
    ISC_LIST_UNLINK(cleanup, chain, link);
7969
0
    if (chain->done) {
7970
0
      dns_db_detach(&chain->db);
7971
0
      dns_dbiterator_destroy(&chain->dbiterator);
7972
0
      isc_mem_put(zone->mctx, chain, sizeof *chain);
7973
0
    } else {
7974
0
      LOCK_ZONE(zone);
7975
0
      ISC_LIST_PREPEND(zone->nsec3chain, chain, link);
7976
0
      UNLOCK_ZONE(zone);
7977
0
      result = dns_dbiterator_first(chain->dbiterator);
7978
0
      RUNTIME_CHECK(result == ISC_R_SUCCESS);
7979
0
      dns_dbiterator_pause(chain->dbiterator);
7980
0
      chain->delete_nsec = chain->save_delete_nsec;
7981
0
    }
7982
0
  }
7983
7984
0
  LOCK_ZONE(zone);
7985
0
  ISC_LIST_FOREACH(zone->nsec3chain, chain, link) {
7986
0
    dns_dbiterator_pause(chain->dbiterator);
7987
0
  }
7988
0
  UNLOCK_ZONE(zone);
7989
7990
0
  dns_diff_clear(&param_diff);
7991
0
  dns_diff_clear(&nsec3_diff);
7992
0
  dns_diff_clear(&nsec_diff);
7993
0
  dns_diff_clear(&_sig_diff);
7994
7995
0
  if (iterator != NULL) {
7996
0
    dns_rdatasetiter_destroy(&iterator);
7997
0
  }
7998
7999
0
  for (i = 0; i < nkeys; i++) {
8000
0
    dst_key_free(&zone_keys[i]);
8001
0
  }
8002
8003
0
  if (node != NULL) {
8004
0
    dns_db_detachnode(&node);
8005
0
  }
8006
0
  if (version != NULL) {
8007
0
    dns_db_closeversion(db, &version, false);
8008
0
    dns_db_detach(&db);
8009
0
  } else if (db != NULL) {
8010
0
    dns_db_detach(&db);
8011
0
  }
8012
8013
0
  LOCK_ZONE(zone);
8014
0
  if (ISC_LIST_HEAD(zone->nsec3chain) != NULL) {
8015
0
    isc_interval_t interval;
8016
0
    if (zone->update_disabled || result != ISC_R_SUCCESS) {
8017
0
      isc_interval_set(&interval, 60, 0); /* 1 minute */
8018
0
    } else {
8019
0
      isc_interval_set(&interval, 0, 10000000); /* 10 ms */
8020
0
    }
8021
0
    isc_time_nowplusinterval(&zone->nsec3chaintime, &interval);
8022
0
  } else {
8023
0
    isc_time_settoepoch(&zone->nsec3chaintime);
8024
0
  }
8025
0
  UNLOCK_ZONE(zone);
8026
8027
0
  INSIST(version == NULL);
8028
0
}
8029
8030
/*%
8031
 * Delete all RRSIG records with the given algorithm and keyid.
8032
 * Remove the NSEC record and RRSIGs if nkeys is zero.
8033
 * If all remaining RRsets are signed with the given algorithm
8034
 * set *has_algp to true.
8035
 */
8036
static isc_result_t
8037
del_sig(dns_db_t *db, dns_dbversion_t *version, dns_name_t *name,
8038
  dns_dbnode_t *node, unsigned int nkeys, dst_algorithm_t algorithm,
8039
0
  uint16_t keyid, bool *has_algp, dns_diff_t *diff) {
8040
0
  dns_rdata_rrsig_t rrsig;
8041
0
  dns_rdataset_t rdataset;
8042
0
  dns_rdatasetiter_t *iterator = NULL;
8043
0
  isc_result_t result;
8044
0
  bool alg_missed = false;
8045
0
  bool alg_found = false;
8046
8047
0
  char namebuf[DNS_NAME_FORMATSIZE];
8048
0
  dns_name_format(name, namebuf, sizeof(namebuf));
8049
8050
0
  result = dns_db_allrdatasets(db, node, version, 0, 0, &iterator);
8051
0
  if (result != ISC_R_SUCCESS) {
8052
0
    if (result == ISC_R_NOTFOUND) {
8053
0
      result = ISC_R_SUCCESS;
8054
0
    }
8055
0
    return result;
8056
0
  }
8057
8058
0
  dns_rdataset_init(&rdataset);
8059
0
  DNS_RDATASETITER_FOREACH(iterator) {
8060
0
    bool has_alg = false;
8061
0
    dns_rdatasetiter_current(iterator, &rdataset);
8062
0
    if (nkeys == 0 && rdataset.type == dns_rdatatype_nsec) {
8063
0
      DNS_RDATASET_FOREACH(&rdataset) {
8064
0
        dns_rdata_t rdata = DNS_RDATA_INIT;
8065
0
        dns_rdataset_current(&rdataset, &rdata);
8066
0
        CHECK(update_one_rr(db, version, diff,
8067
0
                DNS_DIFFOP_DEL, name,
8068
0
                rdataset.ttl, &rdata));
8069
0
      }
8070
0
      dns_rdataset_disassociate(&rdataset);
8071
0
      continue;
8072
0
    }
8073
0
    if (rdataset.type != dns_rdatatype_rrsig) {
8074
0
      dns_rdataset_disassociate(&rdataset);
8075
0
      continue;
8076
0
    }
8077
0
    DNS_RDATASET_FOREACH(&rdataset) {
8078
0
      dns_rdata_t rdata = DNS_RDATA_INIT;
8079
0
      dst_algorithm_t sigalg;
8080
8081
0
      dns_rdataset_current(&rdataset, &rdata);
8082
0
      CHECK(dns_rdata_tostruct(&rdata, &rrsig));
8083
8084
0
      sigalg = dst_algorithm_fromdata(
8085
0
        rrsig.algorithm, rrsig.signature, rrsig.siglen);
8086
0
      if (nkeys != 0 &&
8087
0
          (sigalg != algorithm || rrsig.keyid != keyid))
8088
0
      {
8089
0
        if (sigalg == algorithm) {
8090
0
          has_alg = true;
8091
0
        }
8092
0
        continue;
8093
0
      }
8094
0
      CHECK(update_one_rr(db, version, diff,
8095
0
              DNS_DIFFOP_DELRESIGN, name,
8096
0
              rdataset.ttl, &rdata));
8097
0
    }
8098
0
    dns_rdataset_disassociate(&rdataset);
8099
8100
    /*
8101
     * After deleting, if there's still a signature for
8102
     * 'algorithm', set alg_found; if not, set alg_missed.
8103
     */
8104
0
    if (has_alg) {
8105
0
      alg_found = true;
8106
0
    } else {
8107
0
      alg_missed = true;
8108
0
    }
8109
0
  }
8110
8111
  /*
8112
   * Set `has_algp` if the algorithm was found in every RRset:
8113
   * i.e., found in at least one, and not missing from any.
8114
   */
8115
0
  *has_algp = (alg_found && !alg_missed);
8116
0
cleanup:
8117
0
  dns_rdataset_cleanup(&rdataset);
8118
0
  dns_rdatasetiter_destroy(&iterator);
8119
0
  return result;
8120
0
}
8121
8122
/*
8123
 * Prevent the zone entering a inconsistent state where
8124
 * NSEC only DNSKEYs are present with NSEC3 chains.
8125
 */
8126
bool
8127
dns_zone_check_dnskey_nsec3(dns_zone_t *zone, dns_db_t *db,
8128
          dns_dbversion_t *ver, dns_diff_t *diff,
8129
0
          dst_key_t **keys, unsigned int numkeys) {
8130
0
  uint8_t alg;
8131
0
  dns_rdatatype_t privatetype;
8132
0
  bool nseconly = false, nsec3 = false;
8133
0
  isc_result_t result;
8134
8135
0
  REQUIRE(DNS_ZONE_VALID(zone));
8136
0
  REQUIRE(db != NULL);
8137
8138
0
  privatetype = dns_zone_getprivatetype(zone);
8139
8140
  /* Scan the tuples for an NSEC-only DNSKEY */
8141
0
  if (diff != NULL) {
8142
0
    ISC_LIST_FOREACH(diff->tuples, tuple, link) {
8143
0
      if (nseconly && nsec3) {
8144
0
        break;
8145
0
      }
8146
8147
0
      if (tuple->op != DNS_DIFFOP_ADD) {
8148
0
        continue;
8149
0
      }
8150
8151
0
      if (tuple->rdata.type == dns_rdatatype_nsec3param) {
8152
0
        nsec3 = true;
8153
0
      }
8154
8155
0
      if (tuple->rdata.type != dns_rdatatype_dnskey) {
8156
0
        continue;
8157
0
      }
8158
8159
0
      alg = tuple->rdata.data[3];
8160
0
      if (alg == DNS_KEYALG_RSAMD5 || alg == DNS_KEYALG_DSA ||
8161
0
          alg == DNS_KEYALG_RSASHA1)
8162
0
      {
8163
0
        nseconly = true;
8164
0
      }
8165
0
    }
8166
0
  }
8167
  /* Scan the zone keys for an NSEC-only DNSKEY */
8168
0
  if (keys != NULL && !nseconly) {
8169
0
    for (unsigned int i = 0; i < numkeys; i++) {
8170
0
      alg = dst_key_alg(keys[i]);
8171
0
      if (alg == DNS_KEYALG_RSAMD5 || alg == DNS_KEYALG_DSA ||
8172
0
          alg == DNS_KEYALG_RSASHA1)
8173
0
      {
8174
0
        nseconly = true;
8175
0
        break;
8176
0
      }
8177
0
    }
8178
0
  }
8179
8180
  /* Check DB for NSEC-only DNSKEY */
8181
0
  if (!nseconly) {
8182
0
    result = dns_nsec_nseconly(db, ver, diff, &nseconly);
8183
    /*
8184
     * Adding an NSEC3PARAM record can proceed without a
8185
     * DNSKEY (it will trigger a delayed change), so we can
8186
     * ignore ISC_R_NOTFOUND here.
8187
     */
8188
0
    if (result == ISC_R_NOTFOUND) {
8189
0
      result = ISC_R_SUCCESS;
8190
0
    }
8191
0
    CHECK(result);
8192
0
  }
8193
8194
  /* Check existing DB for NSEC3 */
8195
0
  if (!nsec3) {
8196
0
    CHECK(dns_nsec3_activex(db, ver, false, privatetype, &nsec3));
8197
0
  }
8198
8199
  /* Check kasp for NSEC3PARAM settings */
8200
0
  if (!nsec3) {
8201
0
    dns_kasp_t *kasp = zone->kasp;
8202
0
    if (kasp != NULL) {
8203
0
      nsec3 = dns_kasp_nsec3(kasp);
8204
0
    }
8205
0
  }
8206
8207
  /* Refuse to allow NSEC3 with NSEC-only keys */
8208
0
  if (nseconly && nsec3) {
8209
0
    goto cleanup;
8210
0
  }
8211
8212
0
  return true;
8213
8214
0
cleanup:
8215
0
  return false;
8216
0
}
8217
8218
/*
8219
 * Incrementally sign the zone using the keys requested.
8220
 * Builds the NSEC chain if required.
8221
 */
8222
static void
8223
0
zone_sign(dns_zone_t *zone) {
8224
0
  dns_db_t *db = NULL;
8225
0
  dns_dbnode_t *node = NULL;
8226
0
  dns_dbversion_t *version = NULL;
8227
0
  dns_diff_t _sig_diff;
8228
0
  dns_diff_t post_diff;
8229
0
  dns__zonediff_t zonediff;
8230
0
  dns_fixedname_t fixed;
8231
0
  dns_fixedname_t nextfixed;
8232
0
  dns_kasp_t *kasp = NULL;
8233
0
  dns_name_t *name = NULL, *nextname = NULL;
8234
0
  dns_rdataset_t rdataset;
8235
0
  dns_signing_t *signing = NULL;
8236
0
  dns_signinglist_t cleanup;
8237
0
  dst_key_t *zone_keys[DNS_MAXZONEKEYS];
8238
0
  int32_t signatures;
8239
0
  bool is_ksk, is_zsk;
8240
0
  bool with_ksk, with_zsk;
8241
0
  bool commit = false;
8242
0
  bool is_bottom_of_zone;
8243
0
  bool build_nsec = false;
8244
0
  bool build_nsec3 = false;
8245
0
  bool use_kasp = false;
8246
0
  bool first;
8247
0
  isc_result_t result;
8248
0
  isc_stdtime_t now, inception, soaexpire, expire;
8249
0
  unsigned int i, j;
8250
0
  unsigned int nkeys = 0;
8251
0
  uint32_t nodes;
8252
8253
0
  ENTER;
8254
8255
0
  dns_rdataset_init(&rdataset);
8256
0
  name = dns_fixedname_initname(&fixed);
8257
0
  nextname = dns_fixedname_initname(&nextfixed);
8258
0
  dns_diff_init(zone->mctx, &_sig_diff);
8259
0
  dns_diff_init(zone->mctx, &post_diff);
8260
0
  zonediff_init(&zonediff, &_sig_diff);
8261
0
  ISC_LIST_INIT(cleanup);
8262
8263
  /*
8264
   * Updates are disabled.  Pause for 1 minute.
8265
   */
8266
0
  if (zone->update_disabled) {
8267
0
    result = ISC_R_FAILURE;
8268
0
    goto done;
8269
0
  }
8270
8271
0
  ZONEDB_LOCK(&zone->dblock, isc_rwlocktype_read);
8272
0
  if (zone->db != NULL) {
8273
0
    dns_db_attach(zone->db, &db);
8274
0
  }
8275
0
  ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_read);
8276
0
  if (db == NULL) {
8277
0
    result = ISC_R_FAILURE;
8278
0
    goto done;
8279
0
  }
8280
8281
0
  result = dns_db_newversion(db, &version);
8282
0
  if (result != ISC_R_SUCCESS) {
8283
0
    dnssec_log(zone, ISC_LOG_ERROR,
8284
0
         "zone_sign:dns_db_newversion -> %s",
8285
0
         isc_result_totext(result));
8286
0
    goto done;
8287
0
  }
8288
8289
0
  now = isc_stdtime_now();
8290
8291
0
  result = dns_zone_findkeys(zone, db, version, now, zone->mctx,
8292
0
           DNS_MAXZONEKEYS, zone_keys, &nkeys);
8293
0
  if (result != ISC_R_SUCCESS) {
8294
0
    dnssec_log(zone, ISC_LOG_ERROR,
8295
0
         "zone_sign:dns_zone_findkeys -> %s",
8296
0
         isc_result_totext(result));
8297
0
    goto done;
8298
0
  }
8299
8300
0
  kasp = zone->kasp;
8301
8302
0
  calculate_rrsig_validity(zone, now, &inception, &soaexpire, NULL,
8303
0
         &expire);
8304
8305
  /*
8306
   * We keep pulling nodes off each iterator in turn until
8307
   * we have no more nodes to pull off or we reach the limits
8308
   * for this quantum.
8309
   */
8310
0
  nodes = zone->nodes;
8311
0
  signatures = zone->signatures;
8312
0
  signing = ISC_LIST_HEAD(zone->signing);
8313
0
  first = true;
8314
8315
0
  if (kasp != NULL) {
8316
0
    use_kasp = true;
8317
0
  }
8318
0
  dnssec_log(zone, ISC_LOG_DEBUG(3), "zone_sign:use kasp -> %s",
8319
0
       use_kasp ? "yes" : "no");
8320
8321
  /* Determine which type of chain to build */
8322
0
  CHECK(dns_private_chains(db, version, zone->privatetype, &build_nsec,
8323
0
         &build_nsec3));
8324
0
  if (!build_nsec && !build_nsec3) {
8325
0
    if (use_kasp) {
8326
0
      build_nsec3 = dns_kasp_nsec3(kasp);
8327
0
      if (!dns_zone_check_dnskey_nsec3(
8328
0
            zone, db, version, NULL,
8329
0
            (dst_key_t **)&zone_keys, nkeys))
8330
0
      {
8331
0
        dnssec_log(zone, ISC_LOG_INFO,
8332
0
             "wait building NSEC3 chain until "
8333
0
             "NSEC only DNSKEYs are removed");
8334
0
        build_nsec3 = false;
8335
0
      }
8336
0
      build_nsec = !build_nsec3;
8337
0
    } else {
8338
      /* If neither chain is found, default to NSEC */
8339
0
      build_nsec = true;
8340
0
    }
8341
0
  }
8342
8343
0
  while (signing != NULL && nodes-- > 0 && signatures > 0) {
8344
0
    dns_signing_t *nextsigning = ISC_LIST_NEXT(signing, link);
8345
0
    bool has_alg = false;
8346
0
    bool have_adt = false;
8347
8348
0
    dns_dbiterator_pause(signing->dbiterator);
8349
8350
0
    ZONEDB_LOCK(&zone->dblock, isc_rwlocktype_read);
8351
0
    if (signing->done || signing->db != zone->db) {
8352
      /*
8353
       * The zone has been reloaded.  We will have to
8354
       * created new signings as part of the reload
8355
       * process so we can destroy this one.
8356
       */
8357
0
      ISC_LIST_UNLINK(zone->signing, signing, link);
8358
0
      ISC_LIST_APPEND(cleanup, signing, link);
8359
0
      ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_read);
8360
0
      goto next_signing;
8361
0
    }
8362
0
    ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_read);
8363
8364
0
    if (signing->db != db) {
8365
0
      goto next_signing;
8366
0
    }
8367
8368
0
    is_bottom_of_zone = false;
8369
8370
0
    if (first && signing->deleteit) {
8371
      /*
8372
       * Remove the key we are deleting from consideration.
8373
       */
8374
0
      for (i = 0, j = 0; i < nkeys; i++) {
8375
        /*
8376
         * Find the key we want to remove.
8377
         */
8378
0
        if (ALG(zone_keys[i]) == signing->algorithm &&
8379
0
            dst_key_id(zone_keys[i]) == signing->keyid)
8380
0
        {
8381
0
          dst_key_free(&zone_keys[i]);
8382
0
          continue;
8383
0
        }
8384
0
        zone_keys[j] = zone_keys[i];
8385
0
        j++;
8386
0
      }
8387
0
      for (i = j; i < nkeys; i++) {
8388
0
        zone_keys[i] = NULL;
8389
0
      }
8390
0
      nkeys = j;
8391
0
    }
8392
8393
0
    dns_dbiterator_current(signing->dbiterator, &node, name);
8394
8395
0
    if (signing->deleteit) {
8396
0
      dns_dbiterator_pause(signing->dbiterator);
8397
0
      CHECK(del_sig(db, version, name, node, nkeys,
8398
0
              signing->algorithm, signing->keyid,
8399
0
              &has_alg, zonediff.diff));
8400
0
    }
8401
8402
    /*
8403
     * On the first pass we need to check if the current node
8404
     * has not been obscured.
8405
     */
8406
0
    if (first) {
8407
0
      dns_fixedname_t ffound;
8408
0
      dns_name_t *found;
8409
0
      found = dns_fixedname_initname(&ffound);
8410
0
      result = dns_db_find(
8411
0
        db, name, version, dns_rdatatype_soa,
8412
0
        DNS_DBFIND_NOWILD, 0, found, NULL, NULL);
8413
0
      if ((result == DNS_R_DELEGATION ||
8414
0
           result == DNS_R_DNAME) &&
8415
0
          !dns_name_equal(name, found))
8416
0
      {
8417
        /*
8418
         * Remember the obscuring name so that
8419
         * we skip all obscured names.
8420
         */
8421
0
        dns_name_copy(found, name);
8422
0
        is_bottom_of_zone = true;
8423
0
        goto next_node;
8424
0
      }
8425
0
    }
8426
8427
    /* Check whether we still have any ADT keys */
8428
0
    for (i = 0; i < nkeys; i++) {
8429
0
      if (ADT(zone_keys[i])) {
8430
0
        have_adt = true;
8431
0
        break;
8432
0
      }
8433
0
    }
8434
8435
    /*
8436
     * Process one node.
8437
     */
8438
0
    with_ksk = false;
8439
0
    with_zsk = false;
8440
0
    dns_dbiterator_pause(signing->dbiterator);
8441
8442
0
    CHECK(check_if_bottom_of_zone(db, node, version,
8443
0
                &is_bottom_of_zone));
8444
8445
0
    for (i = 0; !has_alg && i < nkeys; i++) {
8446
0
      bool both = false;
8447
      /*
8448
       * Find the keys we want to sign with.
8449
       */
8450
0
      if (!dst_key_isprivate(zone_keys[i])) {
8451
0
        continue;
8452
0
      }
8453
0
      if (dst_key_inactive(zone_keys[i])) {
8454
0
        continue;
8455
0
      }
8456
8457
      /*
8458
       * When adding look for the specific key.
8459
       */
8460
0
      if (!signing->deleteit &&
8461
0
          (ALG(zone_keys[i]) != signing->algorithm ||
8462
0
           dst_key_id(zone_keys[i]) != signing->keyid))
8463
0
      {
8464
0
        continue;
8465
0
      }
8466
8467
      /*
8468
       * When deleting make sure we are properly signed
8469
       * with the algorithm that was being removed.
8470
       */
8471
0
      if (signing->deleteit &&
8472
0
          ALG(zone_keys[i]) != signing->algorithm)
8473
0
      {
8474
0
        continue;
8475
0
      }
8476
8477
      /*
8478
       * We do KSK processing.
8479
       */
8480
0
      if (use_kasp) {
8481
        /*
8482
         * A dnssec-policy is found. Check what
8483
         * RRsets this key can sign.
8484
         */
8485
0
        isc_result_t kresult;
8486
0
        is_ksk = false;
8487
0
        kresult = dst_key_getbool(
8488
0
          zone_keys[i], DST_BOOL_KSK, &is_ksk);
8489
0
        if (kresult != ISC_R_SUCCESS) {
8490
0
          if (KSK(zone_keys[i])) {
8491
0
            is_ksk = true;
8492
0
          }
8493
0
        }
8494
8495
0
        is_zsk = false;
8496
0
        kresult = dst_key_getbool(
8497
0
          zone_keys[i], DST_BOOL_ZSK, &is_zsk);
8498
0
        if (kresult != ISC_R_SUCCESS) {
8499
0
          if (!KSK(zone_keys[i])) {
8500
0
            is_zsk = true;
8501
0
          }
8502
0
        }
8503
0
        both = true;
8504
0
      } else {
8505
0
        is_ksk = KSK(zone_keys[i]);
8506
0
        is_zsk = !is_ksk;
8507
8508
        /*
8509
         * Don't consider inactive keys, however the key
8510
         * may be temporary offline, so do consider KSKs
8511
         * which private key files are unavailable.
8512
         */
8513
0
        both = dst_key_have_ksk_and_zsk(
8514
0
          zone_keys, nkeys, i, false, is_ksk,
8515
0
          is_zsk, NULL, NULL);
8516
0
        if (both || REVOKE(zone_keys[i])) {
8517
0
          is_ksk = KSK(zone_keys[i]);
8518
0
          is_zsk = !KSK(zone_keys[i]);
8519
0
        } else {
8520
0
          is_ksk = false;
8521
0
          is_zsk = false;
8522
0
        }
8523
0
      }
8524
8525
      /*
8526
       * If deleting signatures, we need to ensure that
8527
       * the RRset is still signed at least once by a
8528
       * KSK and a ZSK.
8529
       */
8530
0
      if (signing->deleteit && is_zsk && with_zsk) {
8531
0
        continue;
8532
0
      }
8533
8534
0
      if (signing->deleteit && is_ksk && with_ksk) {
8535
0
        continue;
8536
0
      }
8537
8538
0
      CHECK(sign_a_node(
8539
0
        db, zone, name, node, version, build_nsec3,
8540
0
        build_nsec, zone_keys[i], now, inception,
8541
0
        expire, zone_nsecttl(zone), both, is_ksk,
8542
0
        is_zsk, signing->fullsign, is_bottom_of_zone,
8543
0
        have_adt, zonediff.diff, &signatures,
8544
0
        zone->mctx));
8545
      /*
8546
       * If we are adding we are done.  Look for other keys
8547
       * of the same algorithm if deleting.
8548
       */
8549
0
      if (!signing->deleteit) {
8550
0
        break;
8551
0
      }
8552
0
      if (is_zsk) {
8553
0
        with_zsk = true;
8554
0
      }
8555
0
      if (is_ksk) {
8556
0
        with_ksk = true;
8557
0
      }
8558
0
    }
8559
8560
    /*
8561
     * Go onto next node.
8562
     */
8563
0
  next_node:
8564
0
    first = false;
8565
0
    dns_db_detachnode(&node);
8566
0
    do {
8567
0
      result = dns_dbiterator_next(signing->dbiterator);
8568
0
      if (result == ISC_R_NOMORE) {
8569
0
        ISC_LIST_UNLINK(zone->signing, signing, link);
8570
0
        ISC_LIST_APPEND(cleanup, signing, link);
8571
0
        dns_dbiterator_pause(signing->dbiterator);
8572
0
        if (nkeys != 0 && build_nsec) {
8573
          /*
8574
           * We have finished regenerating the
8575
           * zone with a zone signing key.
8576
           * The NSEC chain is now complete and
8577
           * there is a full set of signatures
8578
           * for the zone.  We can now clear the
8579
           * OPT bit from the NSEC record.
8580
           */
8581
0
          result = updatesecure(
8582
0
            db, version, &zone->origin,
8583
0
            zone_nsecttl(zone), false,
8584
0
            &post_diff);
8585
0
          if (result != ISC_R_SUCCESS) {
8586
0
            dnssec_log(zone, ISC_LOG_ERROR,
8587
0
                 "updatesecure -> %s",
8588
0
                 isc_result_totext(
8589
0
                   result));
8590
0
            goto done;
8591
0
          }
8592
0
        }
8593
0
        result = updatesignwithkey(
8594
0
          zone, signing, version, build_nsec3,
8595
0
          zone_nsecttl(zone), &post_diff);
8596
0
        if (result != ISC_R_SUCCESS) {
8597
0
          dnssec_log(zone, ISC_LOG_ERROR,
8598
0
               "updatesignwithkey -> %s",
8599
0
               isc_result_totext(result));
8600
0
          goto done;
8601
0
        }
8602
0
        build_nsec = false;
8603
0
        goto next_signing;
8604
0
      } else if (result != ISC_R_SUCCESS) {
8605
0
        dnssec_log(zone, ISC_LOG_ERROR,
8606
0
             "zone_sign:"
8607
0
             "dns_dbiterator_next -> %s",
8608
0
             isc_result_totext(result));
8609
0
        goto done;
8610
0
      } else if (is_bottom_of_zone) {
8611
0
        dns_dbiterator_current(signing->dbiterator,
8612
0
                   &node, nextname);
8613
0
        dns_db_detachnode(&node);
8614
0
        if (!dns_name_issubdomain(nextname, name)) {
8615
0
          break;
8616
0
        }
8617
0
      } else {
8618
0
        break;
8619
0
      }
8620
0
    } while (1);
8621
0
    continue;
8622
8623
0
  next_signing:
8624
0
    dns_dbiterator_pause(signing->dbiterator);
8625
0
    signing = nextsigning;
8626
0
    first = true;
8627
0
  }
8628
8629
0
  if (ISC_LIST_HEAD(post_diff.tuples) != NULL) {
8630
0
    result = dns__zone_updatesigs(&post_diff, db, version,
8631
0
                zone_keys, nkeys, zone, inception,
8632
0
                expire, 0, now, &zonediff);
8633
0
    if (result != ISC_R_SUCCESS) {
8634
0
      dnssec_log(zone, ISC_LOG_ERROR,
8635
0
           "zone_sign:dns__zone_updatesigs -> %s",
8636
0
           isc_result_totext(result));
8637
0
      goto done;
8638
0
    }
8639
0
  }
8640
8641
  /*
8642
   * Have we changed anything?
8643
   */
8644
0
  if (ISC_LIST_EMPTY(zonediff.diff->tuples)) {
8645
0
    if (zonediff.offline) {
8646
0
      commit = true;
8647
0
    }
8648
0
    result = ISC_R_SUCCESS;
8649
0
    goto pauseall;
8650
0
  }
8651
8652
0
  commit = true;
8653
8654
0
  result = del_sigs(zone, db, version, &zone->origin, dns_rdatatype_soa,
8655
0
        &zonediff, zone_keys, nkeys, now, false);
8656
0
  if (result != ISC_R_SUCCESS) {
8657
0
    dnssec_log(zone, ISC_LOG_ERROR, "zone_sign:del_sigs -> %s",
8658
0
         isc_result_totext(result));
8659
0
    goto done;
8660
0
  }
8661
8662
0
  result = update_soa_serial(zone, db, version, zonediff.diff, zone->mctx,
8663
0
           zone->updatemethod);
8664
0
  if (result != ISC_R_SUCCESS) {
8665
0
    dnssec_log(zone, ISC_LOG_ERROR,
8666
0
         "zone_sign:update_soa_serial -> %s",
8667
0
         isc_result_totext(result));
8668
0
    goto done;
8669
0
  }
8670
8671
  /*
8672
   * Generate maximum life time signatures so that the above loop
8673
   * termination is sensible.
8674
   */
8675
0
  result = add_sigs(db, version, &zone->origin, zone, dns_rdatatype_soa,
8676
0
        zonediff.diff, zone_keys, nkeys, zone->mctx, now,
8677
0
        inception, soaexpire);
8678
0
  if (result != ISC_R_SUCCESS) {
8679
0
    dnssec_log(zone, ISC_LOG_ERROR, "zone_sign:add_sigs -> %s",
8680
0
         isc_result_totext(result));
8681
0
    goto done;
8682
0
  }
8683
8684
  /*
8685
   * Write changes to journal file.
8686
   */
8687
0
  CHECK(zone_journal(zone, zonediff.diff, NULL, "zone_sign"));
8688
8689
0
pauseall:
8690
  /*
8691
   * Pause all iterators so that dns_db_closeversion() can succeed.
8692
   */
8693
0
  ISC_LIST_FOREACH(zone->signing, s, link) {
8694
0
    dns_dbiterator_pause(s->dbiterator);
8695
0
  }
8696
8697
0
  ISC_LIST_FOREACH(cleanup, s, link) {
8698
0
    dns_dbiterator_pause(s->dbiterator);
8699
0
  }
8700
8701
  /*
8702
   * Everything has succeeded. Commit the changes.
8703
   */
8704
0
  dns_db_closeversion(db, &version, commit);
8705
8706
  /*
8707
   * Everything succeeded so we can clean these up now.
8708
   */
8709
0
  ISC_LIST_FOREACH(cleanup, s, link) {
8710
0
    ISC_LIST_UNLINK(cleanup, s, link);
8711
0
    dns_db_detach(&s->db);
8712
0
    dns_dbiterator_destroy(&s->dbiterator);
8713
0
    isc_mem_put(zone->mctx, s, sizeof *s);
8714
0
  }
8715
8716
0
  LOCK_ZONE(zone);
8717
0
  dns__zone_set_resigntime(zone);
8718
0
  if (commit) {
8719
0
    DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_NEEDNOTIFY);
8720
0
    zone_needdump(zone, DNS_DUMP_DELAY);
8721
0
  }
8722
0
  UNLOCK_ZONE(zone);
8723
8724
0
cleanup:
8725
0
  if (result != ISC_R_SUCCESS) {
8726
0
    dnssec_log(zone, ISC_LOG_ERROR, "zone_sign: failed: %s",
8727
0
         isc_result_totext(result));
8728
0
  }
8729
8730
0
done:
8731
  /*
8732
   * Pause all dbiterators.
8733
   */
8734
0
  ISC_LIST_FOREACH(zone->signing, s, link) {
8735
0
    dns_dbiterator_pause(s->dbiterator);
8736
0
  }
8737
8738
  /*
8739
   * Rollback the cleanup list.
8740
   */
8741
0
  ISC_LIST_FOREACH(cleanup, s, link) {
8742
0
    ISC_LIST_UNLINK(cleanup, s, link);
8743
0
    ISC_LIST_PREPEND(zone->signing, s, link);
8744
0
    dns_dbiterator_first(s->dbiterator);
8745
0
    dns_dbiterator_pause(s->dbiterator);
8746
0
  }
8747
8748
0
  dns_diff_clear(&_sig_diff);
8749
0
  dns_diff_clear(&post_diff);
8750
8751
0
  for (i = 0; i < nkeys; i++) {
8752
0
    dst_key_free(&zone_keys[i]);
8753
0
  }
8754
8755
0
  if (node != NULL) {
8756
0
    dns_db_detachnode(&node);
8757
0
  }
8758
8759
0
  if (version != NULL) {
8760
0
    dns_db_closeversion(db, &version, false);
8761
0
    dns_db_detach(&db);
8762
0
  } else if (db != NULL) {
8763
0
    dns_db_detach(&db);
8764
0
  }
8765
8766
0
  LOCK_ZONE(zone);
8767
0
  if (ISC_LIST_HEAD(zone->signing) != NULL) {
8768
0
    isc_interval_t interval;
8769
0
    if (zone->update_disabled || result != ISC_R_SUCCESS) {
8770
0
      isc_interval_set(&interval, 60, 0); /* 1 minute */
8771
0
    } else {
8772
0
      isc_interval_set(&interval, 0, 10000000); /* 10 ms */
8773
0
    }
8774
0
    isc_time_nowplusinterval(&zone->signingtime, &interval);
8775
0
  } else {
8776
0
    isc_time_settoepoch(&zone->signingtime);
8777
0
  }
8778
0
  UNLOCK_ZONE(zone);
8779
8780
0
  INSIST(version == NULL);
8781
0
}
8782
8783
static isc_result_t
8784
normalize_key(dns_rdata_t *rr, dns_rdata_t *target, unsigned char *data,
8785
0
        int size) {
8786
0
  dns_rdata_dnskey_t dnskey;
8787
0
  dns_rdata_keydata_t keydata;
8788
0
  isc_buffer_t buf;
8789
0
  isc_result_t result = ISC_R_SUCCESS;
8790
8791
0
  dns_rdata_reset(target);
8792
0
  isc_buffer_init(&buf, data, size);
8793
8794
0
  switch (rr->type) {
8795
0
  case dns_rdatatype_dnskey:
8796
0
    result = dns_rdata_tostruct(rr, &dnskey);
8797
0
    RUNTIME_CHECK(result == ISC_R_SUCCESS);
8798
0
    dnskey.flags &= ~DNS_KEYFLAG_REVOKE;
8799
0
    result = dns_rdata_fromstruct(target, rr->rdclass,
8800
0
                dns_rdatatype_dnskey, &dnskey,
8801
0
                &buf);
8802
0
    break;
8803
0
  case dns_rdatatype_keydata:
8804
0
    result = dns_rdata_tostruct(rr, &keydata);
8805
0
    if (result == ISC_R_UNEXPECTEDEND) {
8806
0
      return result;
8807
0
    }
8808
0
    RUNTIME_CHECK(result == ISC_R_SUCCESS);
8809
0
    dns_keydata_todnskey(&keydata, &dnskey);
8810
0
    result = dns_rdata_fromstruct(target, rr->rdclass,
8811
0
                dns_rdatatype_dnskey, &dnskey,
8812
0
                &buf);
8813
0
    break;
8814
0
  default:
8815
0
    UNREACHABLE();
8816
0
  }
8817
8818
0
  return result;
8819
0
}
8820
8821
/*
8822
 * 'rdset' contains either a DNSKEY rdataset from the zone apex, or
8823
 * a KEYDATA rdataset from the key zone.
8824
 *
8825
 * 'rr' contains either a DNSKEY record, or a KEYDATA record
8826
 *
8827
 * After normalizing keys to the same format (DNSKEY, with revoke bit
8828
 * cleared), return true if a key that matches 'rr' is found in
8829
 * 'rdset', or false if not.
8830
 */
8831
8832
static bool
8833
0
matchkey(dns_rdataset_t *rdset, dns_rdata_t *rr) {
8834
0
  unsigned char data1[4096];
8835
0
  dns_rdata_t rdata1 = DNS_RDATA_INIT;
8836
0
  isc_result_t result;
8837
8838
0
  result = normalize_key(rr, &rdata1, data1, sizeof(data1));
8839
0
  if (result != ISC_R_SUCCESS) {
8840
0
    return false;
8841
0
  }
8842
8843
0
  DNS_RDATASET_FOREACH(rdset) {
8844
0
    unsigned char data2[4096];
8845
0
    dns_rdata_t rdata = DNS_RDATA_INIT;
8846
0
    dns_rdata_t rdata2 = DNS_RDATA_INIT;
8847
8848
0
    dns_rdataset_current(rdset, &rdata);
8849
0
    result = normalize_key(&rdata, &rdata2, data2, sizeof(data2));
8850
0
    if (result != ISC_R_SUCCESS) {
8851
0
      continue;
8852
0
    }
8853
0
    if (dns_rdata_compare(&rdata1, &rdata2) == 0) {
8854
0
      return true;
8855
0
    }
8856
0
  }
8857
8858
0
  return false;
8859
0
}
8860
8861
/*
8862
 * Calculate the refresh interval for a keydata zone, per
8863
 * RFC5011: MAX(1 hr,
8864
 *    MIN(15 days,
8865
 *        1/2 * OrigTTL,
8866
 *        1/2 * RRSigExpirationInterval))
8867
 * or for retries: MAX(1 hr,
8868
 *           MIN(1 day,
8869
 *         1/10 * OrigTTL,
8870
 *         1/10 * RRSigExpirationInterval))
8871
 */
8872
static isc_stdtime_t
8873
0
refresh_time(dns_zonefetch_t *fetch, bool retry) {
8874
0
  isc_result_t result;
8875
0
  uint32_t t;
8876
0
  dns_rdataset_t *sigset;
8877
0
  dns_rdata_t sigrr = DNS_RDATA_INIT;
8878
0
  dns_rdata_rrsig_t sig;
8879
0
  isc_stdtime_t now;
8880
8881
0
  REQUIRE(fetch->fetchtype == ZONEFETCHTYPE_KEY);
8882
8883
0
  now = isc_stdtime_now();
8884
8885
0
  if (dns_rdataset_isassociated(&fetch->sigset)) {
8886
0
    sigset = &fetch->sigset;
8887
0
  } else {
8888
0
    return now + dns_zone_mkey_hour;
8889
0
  }
8890
8891
0
  result = dns_rdataset_first(sigset);
8892
0
  if (result != ISC_R_SUCCESS) {
8893
0
    return now + dns_zone_mkey_hour;
8894
0
  }
8895
8896
0
  dns_rdataset_current(sigset, &sigrr);
8897
0
  result = dns_rdata_tostruct(&sigrr, &sig);
8898
0
  RUNTIME_CHECK(result == ISC_R_SUCCESS);
8899
8900
0
  if (!retry) {
8901
0
    t = sig.originalttl / 2;
8902
8903
0
    if (isc_serial_gt(sig.timeexpire, now)) {
8904
0
      uint32_t exp = (sig.timeexpire - now) / 2;
8905
0
      if (t > exp) {
8906
0
        t = exp;
8907
0
      }
8908
0
    }
8909
8910
0
    if (t > (15 * dns_zone_mkey_day)) {
8911
0
      t = (15 * dns_zone_mkey_day);
8912
0
    }
8913
8914
0
    if (t < dns_zone_mkey_hour) {
8915
0
      t = dns_zone_mkey_hour;
8916
0
    }
8917
0
  } else {
8918
0
    t = sig.originalttl / 10;
8919
8920
0
    if (isc_serial_gt(sig.timeexpire, now)) {
8921
0
      uint32_t exp = (sig.timeexpire - now) / 10;
8922
0
      if (t > exp) {
8923
0
        t = exp;
8924
0
      }
8925
0
    }
8926
8927
0
    if (t > dns_zone_mkey_day) {
8928
0
      t = dns_zone_mkey_day;
8929
0
    }
8930
8931
0
    if (t < dns_zone_mkey_hour) {
8932
0
      t = dns_zone_mkey_hour;
8933
0
    }
8934
0
  }
8935
8936
0
  return now + t;
8937
0
}
8938
8939
/*
8940
 * This routine is called when no changes are needed in a KEYDATA
8941
 * record except to simply update the refresh timer.  Caller should
8942
 * hold zone lock.
8943
 */
8944
static isc_result_t
8945
0
minimal_update(dns_zonefetch_t *fetch, dns_dbversion_t *ver, dns_diff_t *diff) {
8946
0
  dns_keyfetch_t *kfetch;
8947
0
  isc_result_t result;
8948
0
  isc_buffer_t keyb;
8949
0
  unsigned char key_buf[4096];
8950
0
  dns_rdata_keydata_t keydata;
8951
0
  dns_name_t *name;
8952
0
  dns_zone_t *zone;
8953
0
  isc_stdtime_t now;
8954
8955
0
  REQUIRE(fetch->fetchtype == ZONEFETCHTYPE_KEY);
8956
8957
0
  now = isc_stdtime_now();
8958
0
  zone = fetch->zone;
8959
0
  name = dns_name(&fetch->name);
8960
0
  kfetch = &fetch->fetchdata.keyfetch;
8961
8962
0
  DNS_RDATASET_FOREACH(&kfetch->keydataset) {
8963
0
    dns_rdata_t rdata = DNS_RDATA_INIT;
8964
0
    dns_rdataset_current(&kfetch->keydataset, &rdata);
8965
8966
    /* Delete old version */
8967
0
    CHECK(update_one_rr(kfetch->db, ver, diff, DNS_DIFFOP_DEL, name,
8968
0
            0, &rdata));
8969
8970
    /* Update refresh timer */
8971
0
    result = dns_rdata_tostruct(&rdata, &keydata);
8972
0
    if (result == ISC_R_UNEXPECTEDEND) {
8973
0
      continue;
8974
0
    }
8975
0
    CHECK(result);
8976
8977
0
    keydata.refresh = refresh_time(fetch, true);
8978
0
    set_refreshkeytimer(zone, &keydata, now, false);
8979
8980
0
    dns_rdata_reset(&rdata);
8981
0
    isc_buffer_init(&keyb, key_buf, sizeof(key_buf));
8982
0
    CHECK(dns_rdata_fromstruct(&rdata, zone->rdclass,
8983
0
             dns_rdatatype_keydata, &keydata,
8984
0
             &keyb));
8985
8986
    /* Insert updated version */
8987
0
    CHECK(update_one_rr(kfetch->db, ver, diff, DNS_DIFFOP_ADD, name,
8988
0
            0, &rdata));
8989
0
  }
8990
0
  result = ISC_R_SUCCESS;
8991
0
cleanup:
8992
0
  return result;
8993
0
}
8994
8995
/*
8996
 * Verify that DNSKEY set is signed by the key specified in 'keydata'.
8997
 */
8998
static bool
8999
0
revocable(dns_zonefetch_t *fetch, dns_rdata_keydata_t *keydata) {
9000
0
  isc_result_t result;
9001
0
  dns_name_t *keyname;
9002
0
  isc_mem_t *mctx;
9003
0
  dns_rdata_t rr = DNS_RDATA_INIT;
9004
0
  dns_rdata_rrsig_t sig;
9005
0
  dns_rdata_dnskey_t dnskey;
9006
0
  dst_key_t *dstkey = NULL;
9007
0
  unsigned char key_buf[4096];
9008
0
  isc_buffer_t keyb;
9009
0
  bool answer = false;
9010
0
  dst_algorithm_t algorithm;
9011
9012
0
  REQUIRE(fetch != NULL && keydata != NULL);
9013
0
  REQUIRE(fetch->fetchtype == ZONEFETCHTYPE_KEY);
9014
0
  REQUIRE(dns_rdataset_isassociated(&fetch->sigset));
9015
9016
0
  keyname = dns_name(&fetch->name);
9017
0
  mctx = fetch->zone->view->mctx;
9018
9019
  /* Generate a key from keydata */
9020
0
  isc_buffer_init(&keyb, key_buf, sizeof(key_buf));
9021
0
  dns_keydata_todnskey(keydata, &dnskey);
9022
9023
0
  result = dns_rdata_fromstruct(&rr, keydata->common.rdclass,
9024
0
              dns_rdatatype_dnskey, &dnskey, &keyb);
9025
0
  if (result != ISC_R_SUCCESS) {
9026
0
    return false;
9027
0
  }
9028
9029
0
  result = dns_dnssec_keyfromrdata(keyname, &rr, mctx, &dstkey);
9030
0
  if (result != ISC_R_SUCCESS) {
9031
0
    return false;
9032
0
  }
9033
9034
  /* See if that key generated any of the signatures */
9035
0
  DNS_RDATASET_FOREACH(&fetch->sigset) {
9036
0
    dns_rdata_t sigrr = DNS_RDATA_INIT;
9037
9038
0
    dns_rdataset_current(&fetch->sigset, &sigrr);
9039
0
    result = dns_rdata_tostruct(&sigrr, &sig);
9040
0
    RUNTIME_CHECK(result == ISC_R_SUCCESS);
9041
9042
0
    algorithm = dst_algorithm_fromdata(sig.algorithm, sig.signature,
9043
0
               sig.siglen);
9044
0
    if (dst_key_alg(dstkey) == algorithm &&
9045
0
        dst_key_rid(dstkey) == sig.keyid)
9046
0
    {
9047
0
      result = dns_dnssec_verify(keyname, &fetch->rrset,
9048
0
               dstkey, false, mctx, &sigrr,
9049
0
               NULL, NULL);
9050
9051
0
      dnssec_log(fetch->zone, ISC_LOG_DEBUG(3),
9052
0
           "Confirm revoked DNSKEY is self-signed: %s",
9053
0
           isc_result_totext(result));
9054
9055
0
      if (result == ISC_R_SUCCESS) {
9056
0
        answer = true;
9057
0
        break;
9058
0
      }
9059
0
    }
9060
0
  }
9061
9062
0
  dst_key_free(&dstkey);
9063
0
  return answer;
9064
0
}
9065
9066
/*
9067
 * Fetch DNSKEY records at the trust anchor name.
9068
 */
9069
static isc_result_t
9070
0
keyfetch_start(dns_zonefetch_t *fetch) {
9071
0
  REQUIRE(fetch->fetchtype == ZONEFETCHTYPE_KEY);
9072
9073
0
  fetch->qname = dns_name(&fetch->name);
9074
0
  fetch->qtype = dns_rdatatype_dnskey;
9075
9076
0
  return ISC_R_SUCCESS;
9077
0
}
9078
9079
static void
9080
0
keyfetch_continue(dns_zonefetch_t *fetch) {
9081
0
  REQUIRE(fetch->fetchtype == ZONEFETCHTYPE_KEY);
9082
  /* No continue path for keyfetch exists. */
9083
0
  REQUIRE(0);
9084
0
}
9085
9086
static void
9087
0
keyfetch_cancel(dns_zonefetch_t *fetch) {
9088
0
  dns_keyfetch_t *kfetch;
9089
0
  dns_zone_t *zone;
9090
9091
0
  REQUIRE(fetch->fetchtype == ZONEFETCHTYPE_KEY);
9092
0
  REQUIRE(DNS_ZONE_VALID(fetch->zone));
9093
0
  REQUIRE(LOCKED_ZONE(fetch->zone));
9094
9095
0
  kfetch = &fetch->fetchdata.keyfetch;
9096
0
  zone = fetch->zone;
9097
9098
  /*
9099
   * Error during a key fetch; cancel and retry in an hour.
9100
   */
9101
0
  zone->fetchcount[ZONEFETCHTYPE_KEY]--;
9102
9103
0
  dns_db_detach(&kfetch->db);
9104
0
  dns_rdataset_disassociate(&kfetch->keydataset);
9105
9106
0
  if (!DNS_ZONE_FLAG(zone, DNS_ZONEFLG_EXITING)) {
9107
    /* Don't really retry if we are exiting */
9108
0
    isc_time_t timenow, timethen;
9109
0
    char timebuf[80];
9110
9111
0
    timenow = isc_time_now();
9112
0
    DNS_ZONE_TIME_ADD(&timenow, dns_zone_mkey_hour, &timethen);
9113
0
    zone->refreshkeytime = timethen;
9114
0
    dns__zone_settimer(zone, timenow);
9115
9116
0
    isc_time_formattimestamp(&zone->refreshkeytime, timebuf, 80);
9117
0
    dnssec_log(zone, ISC_LOG_DEBUG(1), "retry key refresh: %s",
9118
0
         timebuf);
9119
0
  }
9120
0
}
9121
9122
static void
9123
0
keyfetch_cleanup(dns_zonefetch_t *fetch) {
9124
0
  dns_keyfetch_t *kfetch = NULL;
9125
9126
0
  REQUIRE(fetch->fetchtype == ZONEFETCHTYPE_KEY);
9127
9128
0
  kfetch = &fetch->fetchdata.keyfetch;
9129
9130
0
  dns_db_detach(&kfetch->db);
9131
9132
0
  dns_rdataset_cleanup(&kfetch->keydataset);
9133
0
}
9134
9135
/*
9136
 * A DNSKEY set has been fetched from the zone apex of a zone whose trust
9137
 * anchors are being managed; scan the keyset, and update the key zone and the
9138
 * local trust anchors according to RFC5011.
9139
 */
9140
static isc_result_t
9141
0
keyfetch_done(dns_zonefetch_t *fetch, isc_result_t eresult) {
9142
0
  isc_result_t result;
9143
0
  dns_keyfetch_t *kfetch = NULL;
9144
0
  dns_zone_t *zone = NULL;
9145
0
  isc_mem_t *mctx = NULL;
9146
0
  dns_keytable_t *secroots = NULL;
9147
0
  dns_dbversion_t *ver = NULL;
9148
0
  dns_diff_t diff;
9149
0
  bool alldone = false;
9150
0
  bool commit = false;
9151
0
  dns_name_t *keyname = NULL;
9152
0
  dns_rdata_t keydatarr = DNS_RDATA_INIT;
9153
0
  dns_rdata_rrsig_t sig;
9154
0
  dns_rdata_dnskey_t dnskey;
9155
0
  dns_rdata_keydata_t keydata;
9156
0
  bool initializing;
9157
0
  char namebuf[DNS_NAME_FORMATSIZE];
9158
0
  unsigned char key_buf[4096];
9159
0
  isc_buffer_t keyb;
9160
0
  dst_key_t *dstkey = NULL;
9161
0
  isc_stdtime_t now;
9162
0
  int pending = 0;
9163
0
  bool secure = false, initial = false;
9164
0
  dns_keynode_t *keynode = NULL;
9165
0
  dns_rdataset_t *dnskeys = NULL, *dnskeysigs = NULL;
9166
0
  dns_rdataset_t *keydataset = NULL, dsset;
9167
0
  bool skipped[256] = { false };
9168
9169
0
  REQUIRE(fetch != NULL);
9170
0
  REQUIRE(fetch->fetchtype == ZONEFETCHTYPE_KEY);
9171
0
  REQUIRE(DNS_ZONE_VALID(fetch->zone));
9172
0
  REQUIRE(LOCKED_ZONE(fetch->zone));
9173
9174
0
  kfetch = &fetch->fetchdata.keyfetch;
9175
0
  zone = fetch->zone;
9176
0
  mctx = fetch->mctx;
9177
0
  keyname = dns_name(&fetch->name);
9178
0
  dnskeys = &fetch->rrset;
9179
0
  dnskeysigs = &fetch->sigset;
9180
9181
0
  keydataset = &kfetch->keydataset;
9182
9183
0
  now = isc_stdtime_now();
9184
0
  dns_name_format(keyname, namebuf, sizeof(namebuf));
9185
9186
0
  result = dns_view_getsecroots(zone->view, &secroots);
9187
0
  INSIST(result == ISC_R_SUCCESS);
9188
9189
0
  dns_diff_init(mctx, &diff);
9190
9191
0
  CHECK(dns_db_newversion(kfetch->db, &ver));
9192
9193
0
  zone->fetchcount[ZONEFETCHTYPE_KEY]--;
9194
0
  alldone = (zone->fetchcount[ZONEFETCHTYPE_KEY] == 0);
9195
9196
0
  if (alldone) {
9197
0
    DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_REFRESHING);
9198
0
  }
9199
9200
0
  dnssec_log(zone, ISC_LOG_DEBUG(3),
9201
0
       "Returned from key fetch in keyfetch_done() for '%s': %s",
9202
0
       namebuf, isc_result_totext(eresult));
9203
9204
0
  result = dns_zonefetch_verify(fetch, eresult, dns_trust_none);
9205
0
  if (result != ISC_R_SUCCESS) {
9206
0
    CHECK(minimal_update(fetch, ver, &diff));
9207
0
    goto done;
9208
0
  }
9209
9210
  /*
9211
   * Clear any cached trust level, as we need to run validation
9212
   * over again; trusted keys might have changed.
9213
   */
9214
0
  dnskeys->trust = dnskeysigs->trust = dns_trust_none;
9215
9216
  /* Look up the trust anchor */
9217
0
  result = dns_keytable_find(secroots, keyname, &keynode);
9218
0
  if (result != ISC_R_SUCCESS) {
9219
0
    goto anchors_done;
9220
0
  }
9221
9222
  /*
9223
   * If the keynode has a DS trust anchor, use it for verification.
9224
   */
9225
0
  dns_rdataset_init(&dsset);
9226
0
  if (dns_keynode_dsset(keynode, &dsset)) {
9227
0
    DNS_RDATASET_FOREACH(dnskeysigs) {
9228
0
      isc_result_t tresult = ISC_R_NOTFOUND;
9229
0
      dns_rdata_t keyrdata = DNS_RDATA_INIT;
9230
0
      dns_rdata_t sigrr = DNS_RDATA_INIT;
9231
9232
0
      dns_rdataset_current(dnskeysigs, &sigrr);
9233
0
      dns_rdata_tostruct(&sigrr, &sig);
9234
9235
0
      DNS_RDATASET_FOREACH(&dsset) {
9236
0
        dns_rdata_t dsrdata = DNS_RDATA_INIT;
9237
0
        dns_rdata_ds_t ds;
9238
9239
0
        dns_rdata_reset(&dsrdata);
9240
0
        dns_rdataset_current(&dsset, &dsrdata);
9241
0
        dns_rdata_tostruct(&dsrdata, &ds);
9242
9243
0
        if (ds.key_tag != sig.keyid ||
9244
0
            ds.algorithm != sig.algorithm)
9245
0
        {
9246
0
          continue;
9247
0
        }
9248
9249
0
        tresult = dns_dnssec_matchdskey(
9250
0
          keyname, &dsrdata, dnskeys, &keyrdata);
9251
0
        if (tresult == ISC_R_SUCCESS) {
9252
0
          break;
9253
0
        }
9254
0
      }
9255
9256
0
      if (tresult == ISC_R_NOTFOUND) {
9257
0
        continue;
9258
0
      }
9259
9260
0
      result = dns_dnssec_keyfromrdata(keyname, &keyrdata,
9261
0
               mctx, &dstkey);
9262
0
      if (result != ISC_R_SUCCESS) {
9263
0
        continue;
9264
0
      }
9265
9266
0
      result = dns_dnssec_verify(keyname, dnskeys, dstkey,
9267
0
               false, mctx, &sigrr, NULL,
9268
0
               NULL);
9269
0
      dst_key_free(&dstkey);
9270
9271
0
      dnssec_log(zone, ISC_LOG_DEBUG(3),
9272
0
           "Verifying DNSKEY set for zone "
9273
0
           "'%s' using DS %hu/%d: %s",
9274
0
           namebuf, sig.keyid, sig.algorithm,
9275
0
           isc_result_totext(result));
9276
9277
0
      if (result == ISC_R_SUCCESS) {
9278
0
        dnskeys->trust = dns_trust_secure;
9279
0
        dnskeysigs->trust = dns_trust_secure;
9280
0
        initial = dns_keynode_initial(keynode);
9281
0
        dns_keynode_trust(keynode);
9282
0
        secure = true;
9283
0
        break;
9284
0
      }
9285
0
    }
9286
0
    dns_rdataset_disassociate(&dsset);
9287
0
  }
9288
9289
0
anchors_done:
9290
0
  if (keynode != NULL) {
9291
0
    dns_keynode_detach(&keynode);
9292
0
  }
9293
9294
  /*
9295
   * If we were not able to verify the answer using the current
9296
   * trusted keys then all we can do is look at any revoked keys.
9297
   */
9298
0
  if (!secure) {
9299
0
    dnssec_log(zone, ISC_LOG_INFO,
9300
0
         "DNSKEY set for zone '%s' could not be verified "
9301
0
         "with current keys",
9302
0
         namebuf);
9303
0
  }
9304
9305
  /*
9306
   * First scan keydataset to find keys that are not in dnskeyset
9307
   *   - Missing keys which are not scheduled for removal,
9308
   *     log a warning
9309
   *   - Missing keys which are scheduled for removal and
9310
   *     the remove hold-down timer has completed should
9311
   *     be removed from the key zone
9312
   *   - Missing keys whose acceptance timers have not yet
9313
   *     completed, log a warning and reset the acceptance
9314
   *     timer to 30 days in the future
9315
   *   - All keys not being removed have their refresh timers
9316
   *     updated
9317
   */
9318
0
  initializing = true;
9319
0
  DNS_RDATASET_FOREACH(keydataset) {
9320
0
    dns_keytag_t keytag;
9321
9322
0
    dns_rdata_reset(&keydatarr);
9323
0
    dns_rdataset_current(keydataset, &keydatarr);
9324
0
    result = dns_rdata_tostruct(&keydatarr, &keydata);
9325
0
    RUNTIME_CHECK(result == ISC_R_SUCCESS);
9326
9327
0
    dns_keydata_todnskey(&keydata, &dnskey);
9328
0
    result = compute_tag(&dnskey, &keytag);
9329
0
    if (result != ISC_R_SUCCESS) {
9330
      /*
9331
       * Skip if we cannot compute the key tag.
9332
       * This may happen if the algorithm is unsupported
9333
       */
9334
0
      dns_zone_log(zone, ISC_LOG_ERROR,
9335
0
             "Cannot compute tag for key in zone %s: "
9336
0
             "%s (skipping)",
9337
0
             namebuf, isc_result_totext(result));
9338
0
      continue;
9339
0
    }
9340
0
    RUNTIME_CHECK(result == ISC_R_SUCCESS);
9341
9342
    /*
9343
     * If any keydata record has a nonzero add holddown, then
9344
     * there was a pre-existing trust anchor for this domain;
9345
     * that means we are *not* initializing it and shouldn't
9346
     * automatically trust all the keys we find at the zone apex.
9347
     */
9348
0
    initializing = initializing && (keydata.addhd == 0);
9349
9350
0
    if (!matchkey(dnskeys, &keydatarr)) {
9351
0
      bool deletekey = false;
9352
9353
0
      if (!secure) {
9354
0
        if (keydata.removehd != 0 &&
9355
0
            keydata.removehd <= now)
9356
0
        {
9357
0
          deletekey = true;
9358
0
        }
9359
0
      } else if (keydata.addhd == 0) {
9360
0
        deletekey = true;
9361
0
      } else if (keydata.addhd > now) {
9362
0
        dnssec_log(zone, ISC_LOG_INFO,
9363
0
             "Pending key %hu for zone %s "
9364
0
             "unexpectedly missing from DNSKEY "
9365
0
             "RRset: restarting 30-day "
9366
0
             "acceptance timer",
9367
0
             keytag, namebuf);
9368
0
        if (keydata.addhd < now + dns_zone_mkey_month) {
9369
0
          keydata.addhd = now +
9370
0
              dns_zone_mkey_month;
9371
0
        }
9372
0
        keydata.refresh = refresh_time(fetch, false);
9373
0
      } else if (keydata.removehd == 0) {
9374
0
        dnssec_log(zone, ISC_LOG_INFO,
9375
0
             "Active key %hu for zone %s "
9376
0
             "unexpectedly missing from DNSKEY "
9377
0
             "RRset",
9378
0
             keytag, namebuf);
9379
0
        keydata.refresh = now + dns_zone_mkey_hour;
9380
0
      } else if (keydata.removehd <= now) {
9381
0
        deletekey = true;
9382
0
        dnssec_log(
9383
0
          zone, ISC_LOG_INFO,
9384
0
          "Revoked key %hu for zone %s no longer "
9385
0
          "present in DNSKEY RRset: deleting "
9386
0
          "from managed keys database",
9387
0
          keytag, namebuf);
9388
0
      } else {
9389
0
        keydata.refresh = refresh_time(fetch, false);
9390
0
      }
9391
9392
0
      if (secure || deletekey) {
9393
        /* Delete old version */
9394
0
        CHECK(update_one_rr(kfetch->db, ver, &diff,
9395
0
                DNS_DIFFOP_DEL, keyname, 0,
9396
0
                &keydatarr));
9397
0
      }
9398
9399
0
      if (!secure || deletekey) {
9400
0
        continue;
9401
0
      }
9402
9403
0
      dns_rdata_reset(&keydatarr);
9404
0
      isc_buffer_init(&keyb, key_buf, sizeof(key_buf));
9405
0
      result = dns_rdata_fromstruct(&keydatarr, zone->rdclass,
9406
0
                  dns_rdatatype_keydata,
9407
0
                  &keydata, &keyb);
9408
0
      if (result != ISC_R_SUCCESS) {
9409
0
        dnssec_log(zone, ISC_LOG_WARNING,
9410
0
             "dns_rdata_fromstruct failed: "
9411
0
             "KEYDATA %hu: %s",
9412
0
             keytag, isc_result_totext(result));
9413
0
        continue;
9414
0
      }
9415
9416
      /* Insert updated version */
9417
0
      CHECK(update_one_rr(kfetch->db, ver, &diff,
9418
0
              DNS_DIFFOP_ADD, keyname, 0,
9419
0
              &keydatarr));
9420
9421
0
      set_refreshkeytimer(zone, &keydata, now, false);
9422
0
    }
9423
0
  }
9424
9425
  /*
9426
   * Next scan dnskeyset:
9427
   *   - If new keys are found (i.e., lacking a match in keydataset)
9428
   *     add them to the key zone and set the acceptance timer
9429
   *     to 30 days in the future (or to immediately if we've
9430
   *     determined that we're initializing the zone for the
9431
   *     first time)
9432
   *   - Previously-known keys that have been revoked
9433
   *     must be scheduled for removal from the key zone (or,
9434
   *     if they hadn't been accepted as trust anchors yet
9435
   *     anyway, removed at once)
9436
   *   - Previously-known unrevoked keys whose acceptance timers
9437
   *     have completed are promoted to trust anchors
9438
   *   - All keys not being removed have their refresh
9439
   *     timers updated
9440
   */
9441
0
  DNS_RDATASET_FOREACH(dnskeys) {
9442
0
    dns_rdata_t dnskeyrr = DNS_RDATA_INIT;
9443
0
    bool revoked = false;
9444
0
    bool newkey = false;
9445
0
    bool updatekey = false;
9446
0
    bool deletekey = false;
9447
0
    bool trustkey = false;
9448
0
    dns_keytag_t keytag;
9449
9450
0
    dns_rdataset_current(dnskeys, &dnskeyrr);
9451
0
    result = dns_rdata_tostruct(&dnskeyrr, &dnskey);
9452
0
    RUNTIME_CHECK(result == ISC_R_SUCCESS);
9453
9454
    /* Skip ZSK's */
9455
0
    if ((dnskey.flags & DNS_KEYFLAG_KSK) == 0) {
9456
0
      continue;
9457
0
    }
9458
9459
0
    result = compute_tag(&dnskey, &keytag);
9460
0
    if (result != ISC_R_SUCCESS) {
9461
      /*
9462
       * Skip if we cannot compute the key tag.
9463
       * This may happen if the algorithm is unsupported
9464
       */
9465
0
      dns_zone_log(zone, ISC_LOG_ERROR,
9466
0
             "Cannot compute tag for key in zone %s: "
9467
0
             "%s (skipping)",
9468
0
             namebuf, isc_result_totext(result));
9469
0
      continue;
9470
0
    }
9471
0
    RUNTIME_CHECK(result == ISC_R_SUCCESS);
9472
9473
0
    if (!dns_resolver_algorithm_supported(
9474
0
          zone->view->resolver, keyname, dnskey.algorithm,
9475
0
          dnskey.data, dnskey.datalen))
9476
0
    {
9477
0
      if (!skipped[dnskey.algorithm]) {
9478
0
        dns_zone_log(zone, ISC_LOG_INFO,
9479
0
               "Managed keys for '%s' skipping "
9480
0
               "unsupported algorithm %u",
9481
0
               namebuf, dnskey.algorithm);
9482
0
      }
9483
0
      skipped[dnskey.algorithm] = true;
9484
0
      continue;
9485
0
    }
9486
9487
0
    revoked = ((dnskey.flags & DNS_KEYFLAG_REVOKE) != 0);
9488
9489
0
    if (matchkey(keydataset, &dnskeyrr)) {
9490
0
      dns_rdata_reset(&keydatarr);
9491
0
      dns_rdataset_current(keydataset, &keydatarr);
9492
0
      result = dns_rdata_tostruct(&keydatarr, &keydata);
9493
0
      RUNTIME_CHECK(result == ISC_R_SUCCESS);
9494
9495
0
      if (revoked && revocable(fetch, &keydata)) {
9496
0
        if (keydata.addhd > now) {
9497
          /*
9498
           * Key wasn't trusted yet, and now
9499
           * it's been revoked?  Just remove it
9500
           */
9501
0
          deletekey = true;
9502
0
          dnssec_log(zone, ISC_LOG_INFO,
9503
0
               "Pending key %hu for "
9504
0
               "zone %s is now revoked: "
9505
0
               "deleting from the "
9506
0
               "managed keys database",
9507
0
               keytag, namebuf);
9508
0
        } else if (keydata.removehd == 0) {
9509
          /*
9510
           * Remove key from secroots.
9511
           */
9512
0
          dns_view_untrust(zone->view, keyname,
9513
0
               &dnskey);
9514
9515
          /* If initializing, delete now */
9516
0
          if (keydata.addhd == 0) {
9517
0
            deletekey = true;
9518
0
          } else {
9519
0
            keydata.removehd =
9520
0
              now +
9521
0
              dns_zone_mkey_month;
9522
0
            keydata.flags |=
9523
0
              DNS_KEYFLAG_REVOKE;
9524
0
          }
9525
9526
0
          dnssec_log(zone, ISC_LOG_INFO,
9527
0
               "Trusted key %hu for "
9528
0
               "zone %s is now revoked",
9529
0
               keytag, namebuf);
9530
0
        } else if (keydata.removehd < now) {
9531
          /* Scheduled for removal */
9532
0
          deletekey = true;
9533
9534
0
          dnssec_log(zone, ISC_LOG_INFO,
9535
0
               "Revoked key %hu for "
9536
0
               "zone %s removal timer "
9537
0
               "complete: deleting from "
9538
0
               "the managed keys database",
9539
0
               keytag, namebuf);
9540
0
        }
9541
0
      } else if (revoked && keydata.removehd == 0) {
9542
0
        dnssec_log(zone, ISC_LOG_WARNING,
9543
0
             "Active key %hu for zone "
9544
0
             "%s is revoked but "
9545
0
             "did not self-sign; "
9546
0
             "ignoring",
9547
0
             keytag, namebuf);
9548
0
        continue;
9549
0
      } else if (secure) {
9550
0
        if (keydata.removehd != 0) {
9551
          /*
9552
           * Key isn't revoked--but it
9553
           * seems it used to be.
9554
           * Remove it now and add it
9555
           * back as if it were a fresh key,
9556
           * with a 30-day acceptance timer.
9557
           */
9558
0
          deletekey = true;
9559
0
          newkey = true;
9560
0
          keydata.removehd = 0;
9561
0
          keydata.addhd = now +
9562
0
              dns_zone_mkey_month;
9563
9564
0
          dnssec_log(zone, ISC_LOG_INFO,
9565
0
               "Revoked key %hu for "
9566
0
               "zone %s has returned: "
9567
0
               "starting 30-day "
9568
0
               "acceptance timer",
9569
0
               keytag, namebuf);
9570
0
        } else if (keydata.addhd > now) {
9571
0
          pending++;
9572
0
        } else if (keydata.addhd == 0) {
9573
0
          keydata.addhd = now;
9574
0
        }
9575
9576
0
        if (keydata.addhd <= now) {
9577
0
          trustkey = true;
9578
0
          dnssec_log(zone, ISC_LOG_INFO,
9579
0
               "Key %hu for zone %s "
9580
0
               "is now trusted (%s)",
9581
0
               keytag, namebuf,
9582
0
               initial ? "initializing key "
9583
0
                   "verified"
9584
0
                 : "acceptance timer "
9585
0
                   "complete");
9586
0
        }
9587
0
      } else if (keydata.addhd > now) {
9588
        /*
9589
         * Not secure, and key is pending:
9590
         * reset the acceptance timer
9591
         */
9592
0
        pending++;
9593
0
        keydata.addhd = now + dns_zone_mkey_month;
9594
0
        dnssec_log(zone, ISC_LOG_INFO,
9595
0
             "Pending key %hu "
9596
0
             "for zone %s was "
9597
0
             "not validated: restarting "
9598
0
             "30-day acceptance timer",
9599
0
             keytag, namebuf);
9600
0
      }
9601
9602
0
      if (!deletekey && !newkey) {
9603
0
        updatekey = true;
9604
0
      }
9605
0
    } else if (secure) {
9606
      /*
9607
       * Key wasn't in the key zone but it's
9608
       * revoked now anyway, so just skip it
9609
       */
9610
0
      if (revoked) {
9611
0
        continue;
9612
0
      }
9613
9614
      /* Key wasn't in the key zone: add it */
9615
0
      newkey = true;
9616
9617
0
      if (initializing) {
9618
0
        dnssec_log(zone, ISC_LOG_WARNING,
9619
0
             "Initializing automatic trust "
9620
0
             "anchor management for zone '%s'; "
9621
0
             "DNSKEY ID %hu is now trusted, "
9622
0
             "waiving the normal 30-day "
9623
0
             "waiting period.",
9624
0
             namebuf, keytag);
9625
0
        trustkey = true;
9626
0
      } else {
9627
0
        dnssec_log(zone, ISC_LOG_INFO,
9628
0
             "New key %hu observed "
9629
0
             "for zone '%s': "
9630
0
             "starting 30-day "
9631
0
             "acceptance timer",
9632
0
             keytag, namebuf);
9633
0
      }
9634
0
    } else {
9635
      /*
9636
       * No previously known key, and the key is not
9637
       * secure, so skip it.
9638
       */
9639
0
      continue;
9640
0
    }
9641
9642
    /* Delete old version */
9643
0
    if (deletekey || !newkey) {
9644
0
      CHECK(update_one_rr(kfetch->db, ver, &diff,
9645
0
              DNS_DIFFOP_DEL, keyname, 0,
9646
0
              &keydatarr));
9647
0
    }
9648
9649
0
    if (updatekey) {
9650
      /* Set refresh timer */
9651
0
      keydata.refresh = refresh_time(fetch, false);
9652
0
      dns_rdata_reset(&keydatarr);
9653
0
      isc_buffer_init(&keyb, key_buf, sizeof(key_buf));
9654
0
      result = dns_rdata_fromstruct(&keydatarr, zone->rdclass,
9655
0
                  dns_rdatatype_keydata,
9656
0
                  &keydata, &keyb);
9657
0
      if (result != ISC_R_SUCCESS) {
9658
0
        dnssec_log(zone, ISC_LOG_WARNING,
9659
0
             "dns_rdata_fromstruct failed: "
9660
0
             "KEYDATA %hu: %s",
9661
0
             keytag, isc_result_totext(result));
9662
0
        continue;
9663
0
      }
9664
9665
      /* Insert updated version */
9666
0
      CHECK(update_one_rr(kfetch->db, ver, &diff,
9667
0
              DNS_DIFFOP_ADD, keyname, 0,
9668
0
              &keydatarr));
9669
0
    } else if (newkey) {
9670
      /* Convert DNSKEY to KEYDATA */
9671
0
      result = dns_rdata_tostruct(&dnskeyrr, &dnskey);
9672
0
      RUNTIME_CHECK(result == ISC_R_SUCCESS);
9673
0
      dns_keydata_fromdnskey(&keydata, &dnskey, 0, 0, 0);
9674
0
      keydata.addhd = initializing
9675
0
            ? now
9676
0
            : now + dns_zone_mkey_month;
9677
0
      keydata.refresh = refresh_time(fetch, false);
9678
0
      dns_rdata_reset(&keydatarr);
9679
0
      isc_buffer_init(&keyb, key_buf, sizeof(key_buf));
9680
0
      CHECK(dns_rdata_fromstruct(&keydatarr, zone->rdclass,
9681
0
               dns_rdatatype_keydata,
9682
0
               &keydata, &keyb));
9683
9684
      /* Insert into key zone */
9685
0
      CHECK(update_one_rr(kfetch->db, ver, &diff,
9686
0
              DNS_DIFFOP_ADD, keyname, 0,
9687
0
              &keydatarr));
9688
0
    }
9689
9690
0
    if (trustkey) {
9691
      /* Trust this key. */
9692
0
      result = dns_rdata_tostruct(&dnskeyrr, &dnskey);
9693
0
      RUNTIME_CHECK(result == ISC_R_SUCCESS);
9694
0
      trust_key(zone, keyname, &dnskey, false);
9695
0
    }
9696
9697
0
    if (secure && !deletekey) {
9698
0
      INSIST(newkey || updatekey);
9699
0
      set_refreshkeytimer(zone, &keydata, now, false);
9700
0
    }
9701
0
  }
9702
9703
  /*
9704
   * RFC5011 says, "A trust point that has all of its trust anchors
9705
   * revoked is considered deleted and is treated as if the trust
9706
   * point was never configured."  But if someone revoked their
9707
   * active key before the standby was trusted, that would mean the
9708
   * zone would suddenly be nonsecured.  We avoid this by checking to
9709
   * see if there's pending keydata.  If so, we put a null key in
9710
   * the security roots; then all queries to the zone will fail.
9711
   */
9712
0
  if (pending != 0) {
9713
0
    fail_secure(zone, keyname);
9714
0
  }
9715
9716
0
done:
9717
0
  if (!ISC_LIST_EMPTY(diff.tuples)) {
9718
    /* Write changes to journal file. */
9719
0
    CHECK(update_soa_serial(zone, kfetch->db, ver, &diff, mctx,
9720
0
          zone->updatemethod));
9721
0
    CHECK(zone_journal(zone, &diff, NULL, "keyfetch_done"));
9722
0
    commit = true;
9723
9724
0
    DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_LOADED);
9725
0
    zone_needdump(zone, 30);
9726
0
  } else if (result == ISC_R_NOMORE) {
9727
    /*
9728
     * If "updatekey" was true for all keys found in the DNSKEY
9729
     * response and the previous update of those keys happened
9730
     * during the same second (only possible if a key refresh was
9731
     * externally triggered), it may happen that all relevant
9732
     * update_one_rr() calls will return ISC_R_SUCCESS, but
9733
     * diff.tuples will remain empty.  Reset result to
9734
     * ISC_R_SUCCESS to prevent a bogus warning from being logged.
9735
     */
9736
0
    result = ISC_R_SUCCESS;
9737
0
  }
9738
9739
0
cleanup:
9740
0
  if (result != ISC_R_SUCCESS) {
9741
0
    dnssec_log(zone, ISC_LOG_ERROR,
9742
0
         "error during trust anchor processing (%s): "
9743
0
         "DNSSEC validation may be at risk",
9744
0
         isc_result_totext(result));
9745
0
  }
9746
9747
0
  dns_diff_clear(&diff);
9748
9749
0
  if (ver != NULL) {
9750
0
    dns_db_closeversion(kfetch->db, &ver, commit);
9751
0
  }
9752
9753
0
  if (secroots != NULL) {
9754
0
    dns_keytable_detach(&secroots);
9755
0
  }
9756
9757
0
  INSIST(ver == NULL);
9758
9759
0
  return result;
9760
0
}
9761
9762
/*
9763
 * Refresh the data in the key zone.  Initiate a fetch to look up
9764
 * DNSKEY records at the trust anchor name.
9765
 */
9766
static void
9767
0
zone_refreshkeys(dns_zone_t *zone) {
9768
0
  isc_result_t result;
9769
0
  dns_rriterator_t rrit;
9770
0
  dns_db_t *db = NULL;
9771
0
  dns_dbversion_t *ver = NULL;
9772
0
  dns_diff_t diff;
9773
0
  dns_rdata_keydata_t kd;
9774
0
  isc_stdtime_t now = isc_stdtime_now();
9775
0
  bool commit = false;
9776
0
  bool fetching = false;
9777
0
  bool timerset = false;
9778
9779
0
  ENTER;
9780
0
  REQUIRE(zone->db != NULL);
9781
9782
0
  LOCK_ZONE(zone);
9783
0
  if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_EXITING)) {
9784
0
    isc_time_settoepoch(&zone->refreshkeytime);
9785
0
    UNLOCK_ZONE(zone);
9786
0
    return;
9787
0
  }
9788
9789
0
  ZONEDB_LOCK(&zone->dblock, isc_rwlocktype_read);
9790
0
  dns_db_attach(zone->db, &db);
9791
0
  ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_read);
9792
9793
0
  dns_diff_init(zone->mctx, &diff);
9794
9795
0
  CHECK(dns_db_newversion(db, &ver));
9796
9797
0
  DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_REFRESHING);
9798
9799
0
  dns_rriterator_init(&rrit, db, ver, 0);
9800
0
  for (result = dns_rriterator_first(&rrit); result == ISC_R_SUCCESS;
9801
0
       result = dns_rriterator_nextrrset(&rrit))
9802
0
  {
9803
0
    isc_stdtime_t timer = 0xffffffff;
9804
0
    dns_name_t *name = NULL;
9805
0
    dns_rdataset_t *kdset = NULL;
9806
0
    uint32_t ttl;
9807
9808
0
    dns_rriterator_current(&rrit, &name, &ttl, &kdset, NULL);
9809
0
    if (kdset == NULL || kdset->type != dns_rdatatype_keydata ||
9810
0
        !dns_rdataset_isassociated(kdset))
9811
0
    {
9812
0
      continue;
9813
0
    }
9814
9815
    /*
9816
     * Scan the stored keys looking for ones that need
9817
     * removal or refreshing
9818
     */
9819
0
    DNS_RDATASET_FOREACH(kdset) {
9820
0
      dns_rdata_t rdata = DNS_RDATA_INIT;
9821
0
      dns_rdataset_current(kdset, &rdata);
9822
0
      result = dns_rdata_tostruct(&rdata, &kd);
9823
0
      RUNTIME_CHECK(result == ISC_R_SUCCESS);
9824
9825
      /* Removal timer expired? */
9826
0
      if (kd.removehd != 0 && kd.removehd < now) {
9827
0
        dns_rriterator_pause(&rrit);
9828
0
        CHECK(update_one_rr(db, ver, &diff,
9829
0
                DNS_DIFFOP_DEL, name, ttl,
9830
0
                &rdata));
9831
0
        continue;
9832
0
      }
9833
9834
      /* Acceptance timer expired? */
9835
0
      if (kd.addhd <= now) {
9836
0
        timer = kd.addhd;
9837
0
      }
9838
9839
      /* Or do we just need to refresh the keyset? */
9840
0
      if (timer > kd.refresh) {
9841
0
        timer = kd.refresh;
9842
0
      }
9843
9844
0
      dns_rriterator_pause(&rrit);
9845
0
      set_refreshkeytimer(zone, &kd, now, false);
9846
0
      timerset = true;
9847
0
    }
9848
9849
0
    if (timer > now) {
9850
0
      continue;
9851
0
    }
9852
9853
0
    dns_rriterator_pause(&rrit);
9854
9855
#ifdef ENABLE_AFL
9856
    if (!dns_fuzzing_resolver) {
9857
#endif /* ifdef ENABLE_AFL */
9858
0
      dns_zonefetch_t *fetch = NULL;
9859
0
      dns_keyfetch_t *kfetch = NULL;
9860
9861
      /*
9862
       * This is a special query for RFC5011 maintenance
9863
       * of a trust anchor. We will be validating it
9864
       * in keyfetch_done() against a previously-known
9865
       * trust anchor; we do not want the normal
9866
       * validation process to occur.  We set
9867
       * DNS_FETCHOPT_NOVALIDATE to suppress validation
9868
       * in the resolver, and DNS_FETCHOPT_UNSHARED so
9869
       * this fetch isn't combined with another one that
9870
       * might be validating.
9871
       *
9872
       * We must also use DNS_FETCHOPT_NOCACHED, because
9873
       * if it was not set and the cache still held a
9874
       * non-expired, validated version of the DNSKEY,
9875
       * then we'd receive the old, cached version
9876
       * instead of the new response - the old version
9877
       * would have a higher trust level.
9878
       */
9879
0
      fetch = isc_mem_get(zone->mctx,
9880
0
              sizeof(dns_zonefetch_t));
9881
0
      *fetch = (dns_zonefetch_t){
9882
0
        .zone = zone,
9883
0
        .options = DNS_FETCHOPT_NOVALIDATE |
9884
0
             DNS_FETCHOPT_UNSHARED |
9885
0
             DNS_FETCHOPT_NOCACHED,
9886
0
        .fetchtype = ZONEFETCHTYPE_KEY,
9887
0
        .fetchmethods =
9888
0
          (dns_zonefetch_methods_t){
9889
0
            .start_fetch = keyfetch_start,
9890
0
            .continue_fetch =
9891
0
              keyfetch_continue,
9892
0
            .cancel_fetch = keyfetch_cancel,
9893
0
            .cleanup_fetch =
9894
0
              keyfetch_cleanup,
9895
0
            .done_fetch = keyfetch_done,
9896
0
          },
9897
0
      };
9898
0
      isc_mem_attach(zone->mctx, &fetch->mctx);
9899
9900
0
      zone->fetchcount[ZONEFETCHTYPE_KEY]++;
9901
9902
0
      kfetch = &fetch->fetchdata.keyfetch;
9903
0
      dns_rdataset_init(&kfetch->keydataset);
9904
0
      dns_rdataset_clone(kdset, &kfetch->keydataset);
9905
0
      dns_db_attach(db, &kfetch->db);
9906
9907
0
      dns_zonefetch_schedule(fetch, name);
9908
9909
0
      if (isc_log_wouldlog(ISC_LOG_DEBUG(3))) {
9910
0
        char namebuf[DNS_NAME_FORMATSIZE];
9911
0
        dns_name_format(name, namebuf, sizeof(namebuf));
9912
0
        dnssec_log(zone, ISC_LOG_DEBUG(3),
9913
0
             "Creating key fetch in "
9914
0
             "zone_refreshkeys() for '%s'",
9915
0
             namebuf);
9916
0
      }
9917
0
      fetching = true;
9918
#ifdef ENABLE_AFL
9919
    }
9920
#endif /* ifdef ENABLE_AFL */
9921
0
  }
9922
0
  if (!ISC_LIST_EMPTY(diff.tuples)) {
9923
0
    CHECK(update_soa_serial(zone, db, ver, &diff, zone->mctx,
9924
0
          zone->updatemethod));
9925
0
    CHECK(zone_journal(zone, &diff, NULL, "zone_refreshkeys"));
9926
0
    commit = true;
9927
0
    DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_LOADED);
9928
0
    zone_needdump(zone, 30);
9929
0
  }
9930
9931
0
cleanup:
9932
0
  if (!timerset) {
9933
0
    isc_time_settoepoch(&zone->refreshkeytime);
9934
0
  }
9935
9936
0
  if (!fetching) {
9937
0
    DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_REFRESHING);
9938
0
  }
9939
9940
0
  dns_diff_clear(&diff);
9941
0
  if (ver != NULL) {
9942
0
    dns_rriterator_destroy(&rrit);
9943
0
    dns_db_closeversion(db, &ver, commit);
9944
0
  }
9945
0
  dns_db_detach(&db);
9946
9947
0
  UNLOCK_ZONE(zone);
9948
9949
0
  INSIST(ver == NULL);
9950
0
}
9951
9952
typedef enum inline_sync_action {
9953
  inline_sync_none = 0,
9954
  inline_sync_bootstrap,
9955
  inline_sync_incremental_start,
9956
  inline_sync_incremental_continue,
9957
} inline_sync_action_t;
9958
9959
/*
9960
 * Inline-signing secure zones pull raw-zone changes during maintenance.
9961
 * Raw-zone updates queue immediate secure maintenance.
9962
 */
9963
static inline_sync_action_t
9964
0
zone_inline_sync_action(dns_zone_t *zone) {
9965
0
  REQUIRE(LOCKED_ZONE(zone));
9966
9967
0
  if (!dns__zone_inline_secure(zone)) {
9968
0
    return inline_sync_none;
9969
0
  }
9970
9971
0
  if (zone->inline_sync_phase == inline_sync_full) {
9972
0
    zone->inline_sync_phase = inline_sync_idle;
9973
    /*
9974
     * A full rebuild replaces any parked incremental sync state;
9975
     * zone_maintenance() cancels zone->iss before bootstrapping.
9976
     */
9977
0
    return inline_sync_bootstrap;
9978
0
  }
9979
9980
0
  if (zone->iss != NULL) {
9981
0
    return inline_sync_incremental_continue;
9982
0
  }
9983
9984
0
  if (zone->inline_sync_phase == inline_sync_incremental) {
9985
    /*
9986
     * An incremental sync is a one-shot raw-to-secure request.
9987
     * Parked incremental syncs are continued before this request is
9988
     * consumed, so raw updates that arrive during signing are not
9989
     * collapsed into continuation wakes.
9990
     */
9991
0
    zone->inline_sync_phase = inline_sync_idle;
9992
0
    if (zone->db == NULL) {
9993
0
      return inline_sync_bootstrap;
9994
0
    }
9995
0
    return inline_sync_incremental_start;
9996
0
  }
9997
9998
0
  INSIST(zone->inline_sync_phase == inline_sync_idle);
9999
0
  return inline_sync_none;
10000
0
}
10001
10002
static bool
10003
0
zone_inline_sync_pending(dns_zone_t *zone) {
10004
0
  REQUIRE(LOCKED_ZONE(zone));
10005
10006
0
  return dns__zone_inline_secure(zone) &&
10007
0
         (zone->iss != NULL ||
10008
0
    zone->inline_sync_phase == inline_sync_incremental ||
10009
0
    zone->inline_sync_phase == inline_sync_full);
10010
0
}
10011
10012
static void
10013
0
zone_maintenance(dns_zone_t *zone) {
10014
0
  isc_time_t now;
10015
0
  isc_result_t result;
10016
0
  bool load_pending, exiting, dumping, viewok = false, notify;
10017
0
  bool refreshkeys, rekey;
10018
0
  bool sign = false, resign = false, chain = false, warn_expire = false;
10019
0
  inline_sync_action_t inline_sync = inline_sync_none;
10020
10021
0
  REQUIRE(DNS_ZONE_VALID(zone));
10022
0
  ENTER;
10023
10024
  /*
10025
   * Are we pending load/reload, exiting, or unconfigured
10026
   * (e.g. because of a syntax failure in the config file)?
10027
   * If so, don't attempt maintenance.
10028
   */
10029
0
  LOCK_ZONE(zone);
10030
0
  load_pending = DNS_ZONE_FLAG(zone, DNS_ZONEFLG_LOADPENDING);
10031
0
  exiting = DNS_ZONE_FLAG(zone, DNS_ZONEFLG_EXITING);
10032
0
  if (!load_pending && !exiting && zone->view != NULL) {
10033
0
    dns_adb_t *adb = NULL;
10034
0
    dns_view_getadb(zone->view, &adb);
10035
0
    if (adb != NULL) {
10036
0
      dns_adb_detach(&adb);
10037
0
      viewok = true;
10038
0
    }
10039
0
  }
10040
0
  UNLOCK_ZONE(zone);
10041
10042
0
  if (load_pending || exiting || !viewok) {
10043
0
    return;
10044
0
  }
10045
10046
0
  now = isc_time_now();
10047
10048
  /*
10049
   * Expire check.
10050
   */
10051
0
  switch (zone->type) {
10052
0
  case dns_zone_redirect:
10053
0
    if (dns_remote_addresses(&zone->primaries) == NULL) {
10054
0
      break;
10055
0
    }
10056
0
    FALLTHROUGH;
10057
0
  case dns_zone_secondary:
10058
0
  case dns_zone_mirror:
10059
0
  case dns_zone_stub:
10060
0
    LOCK_ZONE(zone);
10061
0
    if (isc_time_compare(&now, &zone->expiretime) >= 0 &&
10062
0
        DNS_ZONE_FLAG(zone, DNS_ZONEFLG_LOADED))
10063
0
    {
10064
0
      zone_expire(zone);
10065
0
      zone->refreshtime = now;
10066
0
    }
10067
0
    UNLOCK_ZONE(zone);
10068
0
    break;
10069
0
  default:
10070
0
    break;
10071
0
  }
10072
10073
  /*
10074
   * Up to date check.
10075
   */
10076
0
  switch (zone->type) {
10077
0
  case dns_zone_redirect:
10078
0
    if (dns_remote_addresses(&zone->primaries) == NULL) {
10079
0
      break;
10080
0
    }
10081
0
    FALLTHROUGH;
10082
0
  case dns_zone_secondary:
10083
0
  case dns_zone_mirror:
10084
0
  case dns_zone_stub:
10085
0
    LOCK_ZONE(zone);
10086
0
    if (isc_time_compare(&now, &zone->refreshtime) >= 0) {
10087
0
      zone_refresh(zone);
10088
0
    }
10089
0
    UNLOCK_ZONE(zone);
10090
0
    break;
10091
0
  default:
10092
0
    break;
10093
0
  }
10094
10095
  /*
10096
   * Secondaries send notifies before backing up to disk,
10097
   * primaries after.
10098
   */
10099
0
  LOCK_ZONE(zone);
10100
0
  if (zone->notifysoa.notifydefer != 0 &&
10101
0
      !DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NOTIFYNODEFER) &&
10102
0
      !DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NOTIFYDEFERRED))
10103
0
  {
10104
0
    if (isc_time_compare(&now, &zone->notifytime) > 0) {
10105
0
      zone->notifytime = now;
10106
0
    }
10107
0
    DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_NOTIFYDEFERRED);
10108
0
    DNS_ZONE_TIME_ADD(&zone->notifytime,
10109
0
          zone->notifysoa.notifydefer,
10110
0
          &zone->notifytime);
10111
0
  }
10112
0
  notify = (zone->type == dns_zone_secondary ||
10113
0
      zone->type == dns_zone_mirror) &&
10114
0
     (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NEEDNOTIFY) ||
10115
0
      DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NEEDSTARTUPNOTIFY)) &&
10116
0
     isc_time_compare(&now, &zone->notifytime) >= 0;
10117
0
  UNLOCK_ZONE(zone);
10118
10119
0
  if (notify) {
10120
0
    zone_notify(zone, &now);
10121
0
  }
10122
10123
  /*
10124
   * Do we need to consolidate the backing store?
10125
   */
10126
0
  switch (zone->type) {
10127
0
  case dns_zone_primary:
10128
0
  case dns_zone_secondary:
10129
0
  case dns_zone_mirror:
10130
0
  case dns_zone_key:
10131
0
  case dns_zone_redirect:
10132
0
  case dns_zone_stub:
10133
0
    LOCK_ZONE(zone);
10134
0
    if (zone->masterfile != NULL &&
10135
0
        isc_time_compare(&now, &zone->dumptime) >= 0 &&
10136
0
        DNS_ZONE_FLAG(zone, DNS_ZONEFLG_LOADED) &&
10137
0
        DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NEEDDUMP))
10138
0
    {
10139
0
      dumping = was_dumping(zone);
10140
0
    } else {
10141
0
      dumping = true;
10142
0
    }
10143
0
    UNLOCK_ZONE(zone);
10144
0
    if (!dumping) {
10145
0
      result = zone_dump(zone, true); /* loop locked */
10146
0
      if (result != ISC_R_SUCCESS) {
10147
0
        dns_zone_log(zone, ISC_LOG_WARNING,
10148
0
               "dump failed: %s",
10149
0
               isc_result_totext(result));
10150
0
      }
10151
0
    }
10152
0
    break;
10153
0
  default:
10154
0
    break;
10155
0
  }
10156
10157
  /*
10158
   * Primary/redirect zones send notifies now, if needed
10159
   */
10160
0
  switch (zone->type) {
10161
0
  case dns_zone_primary:
10162
0
  case dns_zone_redirect:
10163
0
    LOCK_ZONE(zone);
10164
0
    notify = (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NEEDNOTIFY) ||
10165
0
        DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NEEDSTARTUPNOTIFY)) &&
10166
0
       isc_time_compare(&now, &zone->notifytime) >= 0;
10167
0
    UNLOCK_ZONE(zone);
10168
0
    if (notify) {
10169
0
      zone_notify(zone, &now);
10170
0
    }
10171
0
  default:
10172
0
    break;
10173
0
  }
10174
10175
0
  LOCK_ZONE(zone);
10176
0
  inline_sync = zone_inline_sync_action(zone);
10177
0
  UNLOCK_ZONE(zone);
10178
10179
0
  switch (inline_sync) {
10180
0
  case inline_sync_bootstrap:
10181
0
    zone_clear_inline_sync(zone);
10182
0
    inline_secure_bootstrap(zone);
10183
0
    break;
10184
0
  case inline_sync_incremental_start:
10185
0
    inline_sync_run(zone);
10186
0
    break;
10187
0
  case inline_sync_incremental_continue:
10188
0
    inline_sync_resume(zone);
10189
0
    break;
10190
0
  case inline_sync_none:
10191
0
    break;
10192
0
  }
10193
10194
  /*
10195
   * Apply one queued DB mutation before snapshotting DNSSEC maintenance
10196
   * timers, so chain/sign work observes the resulting zone state.
10197
   */
10198
0
  zone_process_maintenance_request(zone);
10199
10200
0
  LOCK_ZONE(zone);
10201
0
  if (zone_inline_sync_pending(zone)) {
10202
0
    dns__zone_settimer(zone, now);
10203
0
    UNLOCK_ZONE(zone);
10204
0
    return;
10205
0
  }
10206
0
  UNLOCK_ZONE(zone);
10207
10208
0
  switch (zone->type) {
10209
0
  case dns_zone_primary:
10210
0
  case dns_zone_redirect:
10211
0
  case dns_zone_secondary:
10212
0
    LOCK_ZONE(zone);
10213
0
    sign = time_greater_equal(now, zone->signingtime);
10214
0
    resign = time_greater_equal(now, zone->resigntime);
10215
0
    chain = time_greater_equal(now, zone->nsec3chaintime);
10216
0
    warn_expire = time_greater_equal(now, zone->keywarntime);
10217
0
    UNLOCK_ZONE(zone);
10218
0
    break;
10219
10220
0
  default:
10221
0
    break;
10222
0
  }
10223
10224
  /*
10225
   * Do we need to refresh keys?
10226
   */
10227
0
  switch (zone->type) {
10228
0
  case dns_zone_key:
10229
0
    LOCK_ZONE(zone);
10230
0
    refreshkeys = isc_time_compare(&now, &zone->refreshkeytime) >=
10231
0
              0 &&
10232
0
            DNS_ZONE_FLAG(zone, DNS_ZONEFLG_LOADED) &&
10233
0
            !DNS_ZONE_FLAG(zone, DNS_ZONEFLG_REFRESHING);
10234
0
    UNLOCK_ZONE(zone);
10235
0
    if (refreshkeys) {
10236
0
      zone_refreshkeys(zone);
10237
0
    }
10238
0
    break;
10239
0
  case dns_zone_primary:
10240
0
    LOCK_ZONE(zone);
10241
0
    rekey = time_greater_equal(now, zone->refreshkeytime);
10242
0
    UNLOCK_ZONE(zone);
10243
0
    if (rekey) {
10244
0
      zone_rekey(zone);
10245
0
    }
10246
0
  default:
10247
0
    break;
10248
0
  }
10249
10250
0
  switch (zone->type) {
10251
0
  case dns_zone_primary:
10252
0
  case dns_zone_redirect:
10253
0
  case dns_zone_secondary:
10254
    /*
10255
     * Do the DNSSEC work that was due before key maintenance.
10256
     */
10257
0
    if (chain) {
10258
0
      zone_nsec3chain(zone);
10259
0
    } else if (sign) {
10260
0
      zone_sign(zone);
10261
0
    } else if (resign) {
10262
0
      zone_resigninc(zone);
10263
0
    }
10264
10265
    /*
10266
     * Do we need to issue a key expiry warning?
10267
     */
10268
0
    if (warn_expire) {
10269
0
      set_key_expiry_warning(zone, zone->key_expiry,
10270
0
                 isc_time_seconds(&now));
10271
0
    }
10272
0
    break;
10273
10274
0
  default:
10275
0
    break;
10276
0
  }
10277
0
  LOCK_ZONE(zone);
10278
0
  dns__zone_settimer(zone, now);
10279
0
  UNLOCK_ZONE(zone);
10280
0
}
10281
10282
void
10283
0
dns_zone_markdirty(dns_zone_t *zone) {
10284
0
  dns_zone_t *secure = NULL;
10285
10286
  /*
10287
   * Obtaining a lock on zone->secure could result in a deadlock due to
10288
   * a LOR, so spin if both locks cannot be obtained.
10289
   */
10290
0
again:
10291
0
  LOCK_ZONE(zone);
10292
0
  if (zone->type == dns_zone_primary) {
10293
0
    if (dns__zone_inline_raw(zone)) {
10294
0
      isc_result_t result;
10295
10296
0
      secure = zone->secure;
10297
0
      INSIST(secure != zone);
10298
0
      TRYLOCK_ZONE(result, secure);
10299
0
      if (result != ISC_R_SUCCESS) {
10300
0
        UNLOCK_ZONE(zone);
10301
0
        secure = NULL;
10302
0
        isc_thread_yield();
10303
0
        goto again;
10304
0
      }
10305
10306
0
      zone_schedule_inline_sync(secure,
10307
0
              inline_sync_incremental);
10308
0
    }
10309
10310
    /* XXXMPA make separate call back */
10311
0
    dns__zone_set_resigntime(zone);
10312
0
    if (zone->loop != NULL) {
10313
0
      dns__zone_settimer(zone, isc_time_now());
10314
0
    }
10315
0
  }
10316
0
  if (secure != NULL) {
10317
0
    UNLOCK_ZONE(secure);
10318
0
  }
10319
0
  zone_needdump(zone, DNS_DUMP_DELAY);
10320
0
  UNLOCK_ZONE(zone);
10321
0
}
10322
10323
static void
10324
0
zone_expire(dns_zone_t *zone) {
10325
0
  dns_db_t *db = NULL;
10326
10327
  /*
10328
   * 'zone' locked by caller.
10329
   */
10330
10331
0
  REQUIRE(LOCKED_ZONE(zone));
10332
10333
0
  DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_EXPIRED);
10334
0
  zone->refresh = DNS_ZONE_DEFAULTREFRESH;
10335
0
  zone->retry = DNS_ZONE_DEFAULTRETRY;
10336
0
  DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_HAVETIMERS);
10337
10338
0
  dns_zone_log(zone, ISC_LOG_WARNING, "expired");
10339
10340
  /*
10341
   * An RPZ zone has expired; before unloading it, we must
10342
   * first remove it from the RPZ summary database. The
10343
   * easiest way to do this is "update" it with an empty
10344
   * database so that the update callback synchronizes
10345
   * the diff automatically.
10346
   */
10347
0
  if (zone->rpzs != NULL && zone->rpz_num != DNS_RPZ_INVALID_NUM) {
10348
0
    isc_result_t result;
10349
0
    dns_rpz_zone_t *rpz = zone->rpzs->zones[zone->rpz_num];
10350
10351
0
    CHECK(dns_db_create(zone->mctx, ZONEDB_DEFAULT, &zone->origin,
10352
0
            dns_dbtype_zone, zone->rdclass, 0, NULL,
10353
0
            &db));
10354
0
    CHECK(dns_rpz_dbupdate_callback(db, rpz));
10355
0
    dns_zone_log(zone, ISC_LOG_WARNING,
10356
0
           "response-policy zone expired; "
10357
0
           "policies unloaded");
10358
0
  }
10359
10360
0
cleanup:
10361
0
  if (db != NULL) {
10362
0
    dns_db_detach(&db);
10363
0
  }
10364
10365
0
  zone_unload(zone);
10366
0
}
10367
10368
static void
10369
0
zone_refresh(dns_zone_t *zone) {
10370
0
  isc_interval_t i;
10371
0
  uint32_t oldflags;
10372
0
  isc_result_t result;
10373
10374
0
  REQUIRE(DNS_ZONE_VALID(zone));
10375
0
  REQUIRE(LOCKED_ZONE(zone));
10376
10377
0
  if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_EXITING)) {
10378
0
    return;
10379
0
  }
10380
10381
  /*
10382
   * Set DNS_ZONEFLG_REFRESH so that there is only one refresh operation
10383
   * in progress at a time.
10384
   */
10385
10386
0
  oldflags = atomic_load(&zone->flags);
10387
0
  if (dns_remote_addresses(&zone->primaries) == NULL) {
10388
0
    DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_NOPRIMARIES);
10389
0
    if ((oldflags & DNS_ZONEFLG_NOPRIMARIES) == 0) {
10390
0
      dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN,
10391
0
              ISC_LOG_ERROR,
10392
0
              "cannot refresh: no primaries");
10393
0
    }
10394
0
    return;
10395
0
  }
10396
0
  DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_REFRESH);
10397
0
  DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_NOEDNS);
10398
0
  if ((oldflags & (DNS_ZONEFLG_REFRESH | DNS_ZONEFLG_LOADING)) != 0) {
10399
0
    return;
10400
0
  }
10401
10402
  /*
10403
   * Set the next refresh time as if refresh check has failed.
10404
   * Setting this to the retry time will do that.  XXXMLG
10405
   * If we are successful it will be reset using zone->refresh.
10406
   */
10407
0
  isc_interval_set(&i, zone->retry - isc_random_uniform(zone->retry / 4),
10408
0
       0);
10409
0
  result = isc_time_nowplusinterval(&zone->refreshtime, &i);
10410
0
  if (result != ISC_R_SUCCESS) {
10411
0
    dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN, ISC_LOG_WARNING,
10412
0
            "isc_time_nowplusinterval() failed: %s",
10413
0
            isc_result_totext(result));
10414
0
  }
10415
10416
  /*
10417
   * When lacking user-specified timer values from the SOA,
10418
   * do exponential backoff of the retry time up to a
10419
   * maximum of six hours.
10420
   */
10421
0
  if (!DNS_ZONE_FLAG(zone, DNS_ZONEFLG_HAVETIMERS)) {
10422
0
    zone->retry = ISC_MIN(zone->retry * 2, 6 * 3600);
10423
0
  }
10424
10425
0
  dns_remote_reset(&zone->primaries, true);
10426
10427
  /* initiate soa query */
10428
0
  queue_soa_query(zone);
10429
0
}
10430
10431
static void
10432
0
zone_refresh_async(void *arg) {
10433
0
  dns_zone_t *zone = arg;
10434
10435
0
  LOCK_ZONE(zone);
10436
0
  zone_refresh(zone);
10437
0
  UNLOCK_ZONE(zone);
10438
10439
0
  dns_zone_detach(&zone);
10440
0
}
10441
10442
void
10443
0
dns_zone_refresh(dns_zone_t *zone) {
10444
0
  REQUIRE(DNS_ZONE_VALID(zone));
10445
10446
0
  dns_zone_ref(zone);
10447
0
  isc_async_run(zone->loop, zone_refresh_async, zone);
10448
0
}
10449
10450
static isc_result_t
10451
zone_journal_rollforward(dns_zone_t *zone, dns_db_t *db, bool *needdump,
10452
0
       bool *fixjournal) {
10453
0
  dns_journal_t *journal = NULL;
10454
0
  unsigned int options;
10455
0
  isc_result_t result;
10456
10457
0
  if (zone->type == dns_zone_primary &&
10458
0
      (dns__zone_inline_secure(zone) ||
10459
0
       (zone->update_acl != NULL || zone->ssutable != NULL)))
10460
0
  {
10461
0
    options = DNS_JOURNALOPT_RESIGN;
10462
0
  } else {
10463
0
    options = 0;
10464
0
  }
10465
10466
0
  result = dns_journal_open(zone->mctx, zone->journal, DNS_JOURNAL_READ,
10467
0
          &journal);
10468
0
  if (result == ISC_R_NOTFOUND) {
10469
0
    dns_zone_logc(zone, DNS_LOGCATEGORY_ZONELOAD, ISC_LOG_DEBUG(3),
10470
0
            "no journal file, but that's OK ");
10471
0
    return ISC_R_SUCCESS;
10472
0
  } else if (result != ISC_R_SUCCESS) {
10473
0
    dns_zone_logc(zone, DNS_LOGCATEGORY_ZONELOAD, ISC_LOG_ERROR,
10474
0
            "journal open failed: %s",
10475
0
            isc_result_totext(result));
10476
0
    return result;
10477
0
  }
10478
10479
0
  if (dns_journal_empty(journal)) {
10480
0
    dns_zone_logc(zone, DNS_LOGCATEGORY_ZONELOAD, ISC_LOG_DEBUG(1),
10481
0
            "journal empty");
10482
0
    dns_journal_destroy(&journal);
10483
0
    return ISC_R_SUCCESS;
10484
0
  }
10485
10486
0
  result = dns_journal_rollforward(journal, db, options);
10487
0
  switch (result) {
10488
0
  case ISC_R_SUCCESS:
10489
0
    *needdump = true;
10490
0
    FALLTHROUGH;
10491
0
  case DNS_R_UPTODATE:
10492
0
    if (dns_journal_recovered(journal)) {
10493
0
      *fixjournal = true;
10494
0
      dns_zone_logc(
10495
0
        zone, DNS_LOGCATEGORY_ZONELOAD,
10496
0
        ISC_LOG_DEBUG(1),
10497
0
        "journal rollforward completed successfully "
10498
0
        "using old journal format: %s",
10499
0
        isc_result_totext(result));
10500
0
    } else {
10501
0
      dns_zone_logc(zone, DNS_LOGCATEGORY_ZONELOAD,
10502
0
              ISC_LOG_DEBUG(1),
10503
0
              "journal rollforward completed "
10504
0
              "successfully: %s",
10505
0
              isc_result_totext(result));
10506
0
    }
10507
10508
0
    dns_journal_destroy(&journal);
10509
0
    return ISC_R_SUCCESS;
10510
0
  case ISC_R_NOTFOUND:
10511
0
  case ISC_R_RANGE:
10512
0
    dns_zone_logc(zone, DNS_LOGCATEGORY_ZONELOAD, ISC_LOG_ERROR,
10513
0
            "journal rollforward failed: journal out of sync "
10514
0
            "with zone");
10515
0
    dns_journal_destroy(&journal);
10516
0
    return result;
10517
0
  default:
10518
0
    dns_zone_logc(zone, DNS_LOGCATEGORY_ZONELOAD, ISC_LOG_ERROR,
10519
0
            "journal rollforward failed: %s",
10520
0
            isc_result_totext(result));
10521
0
    dns_journal_destroy(&journal);
10522
0
    return result;
10523
0
  }
10524
0
}
10525
10526
static void
10527
0
zone_journal_compact(dns_zone_t *zone, dns_db_t *db, uint32_t serial) {
10528
0
  isc_result_t result;
10529
0
  int32_t journalsize;
10530
0
  dns_dbversion_t *ver = NULL;
10531
0
  uint64_t dbsize;
10532
0
  uint32_t options = 0;
10533
10534
0
  INSIST(LOCKED_ZONE(zone));
10535
0
  if (dns__zone_inline_raw(zone)) {
10536
0
    INSIST(LOCKED_ZONE(zone->secure));
10537
0
  }
10538
10539
0
  journalsize = zone->journalsize;
10540
0
  if (journalsize == -1) {
10541
0
    journalsize = DNS_JOURNAL_SIZE_MAX;
10542
0
    dns_db_currentversion(db, &ver);
10543
0
    result = dns_db_getsize(db, ver, NULL, &dbsize);
10544
0
    dns_db_closeversion(db, &ver, false);
10545
0
    if (result != ISC_R_SUCCESS) {
10546
0
      dns_zone_log(zone, ISC_LOG_ERROR,
10547
0
             "zone_journal_compact: "
10548
0
             "could not get zone size: %s",
10549
0
             isc_result_totext(result));
10550
0
    } else if (dbsize < DNS_JOURNAL_SIZE_MAX / 2) {
10551
0
      journalsize = (int32_t)dbsize * 2;
10552
0
    }
10553
0
  }
10554
0
  if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_FIXJOURNAL)) {
10555
0
    options |= DNS_JOURNAL_COMPACTALL;
10556
0
    DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_FIXJOURNAL);
10557
0
    zone_debuglog(zone, __func__, 1, "repair full journal");
10558
0
  } else {
10559
0
    zone_debuglog(zone, __func__, 1, "target journal size %d",
10560
0
            journalsize);
10561
0
  }
10562
0
  result = dns_journal_compact(zone->mctx, zone->journal, serial, options,
10563
0
             journalsize);
10564
0
  switch (result) {
10565
0
  case ISC_R_SUCCESS:
10566
0
  case ISC_R_NOSPACE:
10567
0
  case ISC_R_NOTFOUND:
10568
0
    dns_zone_log(zone, ISC_LOG_DEBUG(3), "dns_journal_compact: %s",
10569
0
           isc_result_totext(result));
10570
0
    break;
10571
0
  default:
10572
0
    dns_zone_log(zone, ISC_LOG_ERROR,
10573
0
           "dns_journal_compact failed: %s",
10574
0
           isc_result_totext(result));
10575
0
    break;
10576
0
  }
10577
0
}
10578
10579
isc_result_t
10580
0
dns_zone_flush(dns_zone_t *zone) {
10581
0
  isc_result_t result = ISC_R_SUCCESS;
10582
0
  bool dumping;
10583
10584
0
  REQUIRE(DNS_ZONE_VALID(zone));
10585
10586
0
  LOCK_ZONE(zone);
10587
0
  DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_FLUSH);
10588
0
  if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NEEDDUMP) &&
10589
0
      zone->masterfile != NULL)
10590
0
  {
10591
0
    DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_NEEDCOMPACT);
10592
0
    result = ISC_R_ALREADYRUNNING;
10593
0
    dumping = was_dumping(zone);
10594
0
  } else {
10595
0
    dumping = true;
10596
0
  }
10597
0
  UNLOCK_ZONE(zone);
10598
0
  if (!dumping) {
10599
0
    result = zone_dump(zone, true);
10600
0
  }
10601
0
  return result;
10602
0
}
10603
10604
static void
10605
0
zone_needdump(dns_zone_t *zone, unsigned int delay) {
10606
0
  isc_time_t dumptime;
10607
0
  isc_time_t now;
10608
10609
  /*
10610
   * 'zone' locked by caller
10611
   */
10612
10613
0
  REQUIRE(DNS_ZONE_VALID(zone));
10614
0
  REQUIRE(LOCKED_ZONE(zone));
10615
0
  ENTER;
10616
10617
  /*
10618
   * Do we have a place to dump to and are we loaded?
10619
   */
10620
0
  if (zone->masterfile == NULL ||
10621
0
      DNS_ZONE_FLAG(zone, DNS_ZONEFLG_LOADED) == 0)
10622
0
  {
10623
0
    return;
10624
0
  }
10625
10626
0
  now = isc_time_now();
10627
  /* add some noise */
10628
0
  DNS_ZONE_JITTER_ADD(&now, delay, &dumptime);
10629
10630
0
  DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_NEEDDUMP);
10631
0
  if (isc_time_isepoch(&zone->dumptime) ||
10632
0
      isc_time_compare(&zone->dumptime, &dumptime) > 0)
10633
0
  {
10634
0
    zone->dumptime = dumptime;
10635
0
  }
10636
0
  if (zone->loop != NULL) {
10637
0
    dns__zone_settimer(zone, now);
10638
0
  }
10639
0
}
10640
10641
static void
10642
0
dump_done(void *arg, isc_result_t result) {
10643
0
  dns_zone_t *zone = arg;
10644
0
  dns_zone_t *secure = NULL;
10645
0
  bool again = false;
10646
0
  bool compact = false;
10647
0
  uint32_t serial;
10648
0
  isc_result_t tresult = ISC_R_UNSET;
10649
10650
0
  REQUIRE(DNS_ZONE_VALID(zone));
10651
10652
0
  ENTER;
10653
10654
  /*
10655
   * Adjust modification time of zone file to preserve expire timing.
10656
   */
10657
0
  if ((zone->type == dns_zone_secondary ||
10658
0
       zone->type == dns_zone_mirror ||
10659
0
       zone->type == dns_zone_redirect) &&
10660
0
      result == ISC_R_SUCCESS)
10661
0
  {
10662
0
    LOCK_ZONE(zone);
10663
0
    isc_time_t when;
10664
0
    isc_interval_t i;
10665
0
    isc_interval_set(&i, zone->expire, 0);
10666
0
    result = isc_time_subtract(&zone->expiretime, &i, &when);
10667
0
    if (result == ISC_R_SUCCESS) {
10668
0
      (void)isc_file_settime(zone->masterfile, &when);
10669
0
    } else {
10670
0
      result = ISC_R_SUCCESS;
10671
0
    }
10672
0
    UNLOCK_ZONE(zone);
10673
0
  }
10674
10675
0
  if (result == ISC_R_SUCCESS && zone->journal != NULL) {
10676
0
    tresult = dns_dumpctx_serial(zone->dumpctx, &serial);
10677
0
  }
10678
10679
0
  if (tresult == ISC_R_SUCCESS) {
10680
    /*
10681
     * Handle lock order inversion.
10682
     */
10683
0
  again:
10684
0
    LOCK_ZONE(zone);
10685
0
    if (dns__zone_inline_raw(zone)) {
10686
0
      secure = zone->secure;
10687
0
      INSIST(secure != zone);
10688
0
      TRYLOCK_ZONE(result, secure);
10689
0
      if (result != ISC_R_SUCCESS) {
10690
0
        UNLOCK_ZONE(zone);
10691
0
        secure = NULL;
10692
0
        isc_thread_yield();
10693
0
        goto again;
10694
0
      }
10695
0
    }
10696
10697
    /*
10698
     * If there is a secure version of this zone
10699
     * use its serial if it is less than ours.
10700
     */
10701
0
    if (secure != NULL) {
10702
0
      uint32_t sserial;
10703
0
      isc_result_t mresult;
10704
10705
0
      ZONEDB_LOCK(&secure->dblock, isc_rwlocktype_read);
10706
0
      if (secure->db != NULL) {
10707
0
        mresult = dns_db_getsoaserial(zone->secure->db,
10708
0
                    NULL, &sserial);
10709
0
        if (mresult == ISC_R_SUCCESS &&
10710
0
            isc_serial_lt(sserial, serial))
10711
0
        {
10712
0
          serial = sserial;
10713
0
        }
10714
0
      }
10715
0
      ZONEDB_UNLOCK(&secure->dblock, isc_rwlocktype_read);
10716
0
    }
10717
0
    if (zone->xfr == NULL) {
10718
0
      dns_db_t *zdb = NULL;
10719
0
      if (dns_zone_getdb(zone, &zdb) == ISC_R_SUCCESS) {
10720
0
        zone_journal_compact(zone, zdb, serial);
10721
0
        dns_db_detach(&zdb);
10722
0
      }
10723
0
    } else {
10724
0
      compact = true;
10725
0
      zone->compact_serial = serial;
10726
0
    }
10727
0
    if (secure != NULL) {
10728
0
      UNLOCK_ZONE(secure);
10729
0
    }
10730
0
    UNLOCK_ZONE(zone);
10731
0
  }
10732
10733
0
  LOCK_ZONE(zone);
10734
0
  DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_DUMPING);
10735
0
  if (compact) {
10736
0
    DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_NEEDCOMPACT);
10737
0
  }
10738
0
  if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_SHUTDOWN)) {
10739
    /*
10740
     * If DNS_ZONEFLG_SHUTDOWN is set, all external references to
10741
     * the zone are gone, which means it is in the process of being
10742
     * cleaned up, so do not reschedule dumping.
10743
     *
10744
     * Detach from the raw version of the zone in case this
10745
     * operation has been deferred in zone_shutdown().
10746
     */
10747
0
    if (zone->raw != NULL) {
10748
0
      dns_zone_detach(&zone->raw);
10749
0
    }
10750
0
    if (result == ISC_R_SUCCESS) {
10751
0
      DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_FLUSH);
10752
0
    }
10753
0
  } else if (result != ISC_R_SUCCESS && result != ISC_R_CANCELED) {
10754
    /*
10755
     * Try again in a short while.
10756
     */
10757
0
    zone_needdump(zone, DNS_DUMP_DELAY);
10758
0
  } else if (result == ISC_R_SUCCESS &&
10759
0
       DNS_ZONE_FLAG(zone, DNS_ZONEFLG_FLUSH) &&
10760
0
       DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NEEDDUMP) &&
10761
0
       DNS_ZONE_FLAG(zone, DNS_ZONEFLG_LOADED))
10762
0
  {
10763
0
    DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_NEEDDUMP);
10764
0
    DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_DUMPING);
10765
0
    isc_time_settoepoch(&zone->dumptime);
10766
0
    again = true;
10767
0
  } else if (result == ISC_R_SUCCESS) {
10768
0
    DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_FLUSH);
10769
0
  }
10770
10771
0
  if (zone->dumpctx != NULL) {
10772
0
    dns_dumpctx_detach(&zone->dumpctx);
10773
0
  }
10774
0
  UNLOCK_ZONE(zone);
10775
0
  if (again) {
10776
0
    (void)zone_dump(zone, false);
10777
0
  }
10778
0
  dns_zone_idetach(&zone);
10779
0
}
10780
10781
static isc_result_t
10782
0
zone_dump(dns_zone_t *zone, bool compact) {
10783
0
  isc_result_t result;
10784
0
  dns_dbversion_t *version = NULL;
10785
0
  bool again = false;
10786
0
  dns_db_t *db = NULL;
10787
0
  char *masterfile = NULL;
10788
0
  dns_masterformat_t masterformat = dns_masterformat_none;
10789
0
  const dns_master_style_t *masterstyle = NULL;
10790
0
  dns_masterrawheader_t rawdata;
10791
0
  bool inline_secure;
10792
10793
  /*
10794
   * 'compact' MUST only be set if we are loop locked.
10795
   */
10796
10797
0
  REQUIRE(DNS_ZONE_VALID(zone));
10798
0
  ENTER;
10799
10800
0
redo:
10801
0
  ZONEDB_LOCK(&zone->dblock, isc_rwlocktype_read);
10802
0
  if (zone->db != NULL) {
10803
0
    dns_db_attach(zone->db, &db);
10804
0
  }
10805
0
  ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_read);
10806
0
  LOCK_ZONE(zone);
10807
0
  if (zone->masterfile != NULL) {
10808
0
    masterfile = isc_mem_strdup(zone->mctx, zone->masterfile);
10809
0
    masterformat = zone->masterformat;
10810
0
  }
10811
0
  if (zone->type == dns_zone_key) {
10812
0
    masterstyle = &dns_master_style_keyzone;
10813
0
  } else if (zone->masterstyle != NULL) {
10814
0
    masterstyle = zone->masterstyle;
10815
0
  } else {
10816
0
    masterstyle = &dns_master_style_default;
10817
0
  }
10818
0
  UNLOCK_ZONE(zone);
10819
0
  if (db == NULL) {
10820
0
    result = DNS_R_NOTLOADED;
10821
0
    goto fail;
10822
0
  }
10823
0
  if (masterfile == NULL) {
10824
0
    result = DNS_R_NOMASTERFILE;
10825
0
    goto fail;
10826
0
  }
10827
10828
0
  dns_db_currentversion(db, &version);
10829
10830
0
  dns_master_initrawheader(&rawdata);
10831
10832
0
  LOCK_ZONE(zone);
10833
0
  inline_secure = dns__zone_inline_secure(zone);
10834
0
  UNLOCK_ZONE(zone);
10835
10836
0
  if (inline_secure) {
10837
0
    get_raw_serial(zone->raw, &rawdata);
10838
0
  }
10839
10840
0
  if (compact && zone->type != dns_zone_stub) {
10841
0
    LOCK_ZONE(zone);
10842
0
    zone_iattach(zone, &(dns_zone_t *){ NULL });
10843
10844
0
    INSIST(zone != zone->raw);
10845
10846
0
    result = dns_master_dumpasync(
10847
0
      zone->mctx, db, version, masterstyle, masterfile,
10848
0
      zone->loop, dump_done, zone, &zone->dumpctx,
10849
0
      masterformat, &rawdata);
10850
10851
0
    UNLOCK_ZONE(zone);
10852
0
    if (result != ISC_R_SUCCESS) {
10853
0
      dns_zone_idetach(&(dns_zone_t *){ zone });
10854
0
      goto fail;
10855
0
    }
10856
0
    result = DNS_R_CONTINUE;
10857
0
  } else {
10858
0
    result = dns_master_dump(zone->mctx, db, version, masterstyle,
10859
0
           masterfile, masterformat, &rawdata);
10860
0
    if ((zone->type == dns_zone_secondary ||
10861
0
         zone->type == dns_zone_mirror ||
10862
0
         zone->type == dns_zone_redirect) &&
10863
0
        result == ISC_R_SUCCESS)
10864
0
    {
10865
0
      isc_time_t when;
10866
0
      isc_interval_t i;
10867
0
      isc_interval_set(&i, zone->expire, 0);
10868
0
      result = isc_time_subtract(&zone->expiretime, &i,
10869
0
               &when);
10870
0
      if (result == ISC_R_SUCCESS) {
10871
0
        (void)isc_file_settime(zone->masterfile, &when);
10872
0
      } else {
10873
0
        result = ISC_R_SUCCESS;
10874
0
      }
10875
0
    }
10876
0
  }
10877
0
fail:
10878
0
  if (version != NULL) {
10879
0
    dns_db_closeversion(db, &version, false);
10880
0
  }
10881
0
  if (db != NULL) {
10882
0
    dns_db_detach(&db);
10883
0
  }
10884
0
  if (masterfile != NULL) {
10885
0
    isc_mem_free(zone->mctx, masterfile);
10886
0
  }
10887
10888
0
  if (result == DNS_R_CONTINUE) {
10889
    /*
10890
     * Asyncronous write is in progress.  Zone flags will get
10891
     * updated on completion.  Cleanup is complete.  We are done.
10892
     */
10893
0
    return ISC_R_SUCCESS;
10894
0
  }
10895
10896
0
  again = false;
10897
0
  LOCK_ZONE(zone);
10898
0
  DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_DUMPING);
10899
0
  if (result != ISC_R_SUCCESS) {
10900
    /*
10901
     * Try again in a short while.
10902
     */
10903
0
    zone_needdump(zone, DNS_DUMP_DELAY);
10904
0
  } else if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_FLUSH) &&
10905
0
       DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NEEDDUMP) &&
10906
0
       DNS_ZONE_FLAG(zone, DNS_ZONEFLG_LOADED))
10907
0
  {
10908
0
    DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_NEEDDUMP);
10909
0
    DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_DUMPING);
10910
0
    isc_time_settoepoch(&zone->dumptime);
10911
0
    again = true;
10912
0
  } else {
10913
0
    DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_FLUSH);
10914
0
  }
10915
0
  UNLOCK_ZONE(zone);
10916
0
  if (again) {
10917
0
    goto redo;
10918
0
  }
10919
10920
0
  return result;
10921
0
}
10922
10923
static isc_result_t
10924
dumptostream(dns_zone_t *zone, FILE *fd, const dns_master_style_t *style,
10925
0
       dns_masterformat_t format, const uint32_t rawversion) {
10926
0
  isc_result_t result;
10927
0
  dns_dbversion_t *version = NULL;
10928
0
  dns_db_t *db = NULL;
10929
0
  dns_masterrawheader_t rawdata;
10930
0
  bool inline_secure;
10931
10932
0
  REQUIRE(DNS_ZONE_VALID(zone));
10933
10934
0
  ZONEDB_LOCK(&zone->dblock, isc_rwlocktype_read);
10935
0
  if (zone->db != NULL) {
10936
0
    dns_db_attach(zone->db, &db);
10937
0
  }
10938
0
  ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_read);
10939
0
  if (db == NULL) {
10940
0
    return DNS_R_NOTLOADED;
10941
0
  }
10942
10943
0
  LOCK_ZONE(zone);
10944
0
  inline_secure = dns__zone_inline_secure(zone);
10945
0
  UNLOCK_ZONE(zone);
10946
10947
0
  dns_db_currentversion(db, &version);
10948
0
  dns_master_initrawheader(&rawdata);
10949
0
  if (rawversion == 0) {
10950
0
    rawdata.flags |= DNS_MASTERRAW_COMPAT;
10951
0
  } else if (inline_secure) {
10952
0
    get_raw_serial(zone->raw, &rawdata);
10953
0
  } else if (zone->sourceserialset) {
10954
0
    rawdata.flags = DNS_MASTERRAW_SOURCESERIALSET;
10955
0
    rawdata.sourceserial = zone->sourceserial;
10956
0
  }
10957
0
  result = dns_master_dumptostream(zone->mctx, db, version, style, format,
10958
0
           &rawdata, fd);
10959
0
  dns_db_closeversion(db, &version, false);
10960
0
  dns_db_detach(&db);
10961
0
  return result;
10962
0
}
10963
10964
isc_result_t
10965
dns_zone_dumptostream(dns_zone_t *zone, FILE *fd, dns_masterformat_t format,
10966
          const dns_master_style_t *style,
10967
0
          const uint32_t rawversion) {
10968
0
  return dumptostream(zone, fd, style, format, rawversion);
10969
0
}
10970
10971
void
10972
0
dns_zone_unload(dns_zone_t *zone) {
10973
0
  REQUIRE(DNS_ZONE_VALID(zone));
10974
10975
0
  LOCK_ZONE(zone);
10976
0
  zone_unload(zone);
10977
0
  UNLOCK_ZONE(zone);
10978
0
}
10979
10980
static void
10981
0
checkds_cancel(dns_zone_t *zone) {
10982
  /*
10983
   * 'zone' locked by caller.
10984
   */
10985
10986
0
  REQUIRE(LOCKED_ZONE(zone));
10987
10988
0
  ISC_LIST_FOREACH(zone->checkds_requests, checkds, link) {
10989
0
    if (checkds->find != NULL) {
10990
0
      dns_adb_cancelfind(checkds->find);
10991
0
    }
10992
0
    if (checkds->request != NULL) {
10993
0
      dns_request_cancel(checkds->request);
10994
0
    }
10995
0
  }
10996
0
}
10997
10998
void
10999
0
dns__zone_forward_cancel(dns_zone_t *zone) {
11000
  /*
11001
   * 'zone' locked by caller.
11002
   */
11003
11004
0
  REQUIRE(LOCKED_ZONE(zone));
11005
11006
0
  ISC_LIST_FOREACH(zone->forwards, forward, link) {
11007
0
    if (forward->request != NULL) {
11008
0
      dns_request_cancel(forward->request);
11009
0
    }
11010
0
  }
11011
0
}
11012
11013
static void
11014
0
zone_unload(dns_zone_t *zone) {
11015
  /*
11016
   * 'zone' locked by caller.
11017
   */
11018
11019
0
  REQUIRE(LOCKED_ZONE(zone));
11020
11021
0
  if (!DNS_ZONE_FLAG(zone, DNS_ZONEFLG_FLUSH) ||
11022
0
      !DNS_ZONE_FLAG(zone, DNS_ZONEFLG_DUMPING))
11023
0
  {
11024
0
    if (zone->dumpctx != NULL) {
11025
0
      dns_dumpctx_cancel(zone->dumpctx);
11026
0
    }
11027
0
  }
11028
0
  ZONEDB_LOCK(&zone->dblock, isc_rwlocktype_write);
11029
0
  zone_detachdb(zone);
11030
0
  ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_write);
11031
0
  DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_LOADED);
11032
0
  DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_NEEDDUMP);
11033
11034
0
  if (zone->type == dns_zone_mirror) {
11035
0
    dns_zone_log(zone, ISC_LOG_INFO,
11036
0
           "mirror zone is no longer in use; "
11037
0
           "reverting to normal recursion");
11038
0
  }
11039
0
}
11040
11041
void
11042
0
dns_zone_notify(dns_zone_t *zone, bool nodefer) {
11043
0
  REQUIRE(DNS_ZONE_VALID(zone));
11044
11045
0
  LOCK_ZONE(zone);
11046
0
  DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_NEEDNOTIFY);
11047
0
  if (nodefer) {
11048
0
    if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NOTIFYDEFERRED)) {
11049
      /*
11050
       * We have previously deferred the notify, but we have a
11051
       * new request not to defer it. Reverse the deferring
11052
       * operation.
11053
       */
11054
0
      DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_NOTIFYDEFERRED);
11055
0
      DNS_ZONE_TIME_SUBTRACT(&zone->notifytime,
11056
0
                 zone->notifysoa.notifydefer,
11057
0
                 &zone->notifytime);
11058
0
    }
11059
0
    DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_NOTIFYNODEFER);
11060
0
  }
11061
0
  dns__zone_settimer(zone, isc_time_now());
11062
0
  UNLOCK_ZONE(zone);
11063
0
}
11064
11065
static void
11066
0
zone_notify(dns_zone_t *zone, isc_time_t *now) {
11067
0
  dns_dbnode_t *node = NULL;
11068
0
  dns_db_t *zonedb = NULL;
11069
0
  dns_dbversion_t *version = NULL;
11070
0
  dns_name_t *origin = NULL;
11071
0
  dns_name_t primary;
11072
0
  dns_rdata_ns_t ns;
11073
0
  dns_rdata_soa_t soa;
11074
0
  dns_rdata_t soardata = DNS_RDATA_INIT;
11075
0
  uint32_t serial;
11076
0
  dns_rdataset_t nsrdset;
11077
0
  dns_rdataset_t soardset;
11078
0
  isc_result_t result;
11079
0
  isc_sockaddr_t src;
11080
0
  isc_sockaddr_t dst;
11081
0
  bool isqueued;
11082
0
  dns_notifytype_t notifytype;
11083
0
  unsigned int flags = 0;
11084
0
  bool loggednotify = false;
11085
0
  bool startup;
11086
11087
0
  REQUIRE(DNS_ZONE_VALID(zone));
11088
11089
0
  LOCK_ZONE(zone);
11090
0
  startup = !DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NEEDNOTIFY);
11091
0
  DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_NEEDNOTIFY |
11092
0
               DNS_ZONEFLG_NEEDSTARTUPNOTIFY |
11093
0
               DNS_ZONEFLG_NOTIFYNODEFER |
11094
0
               DNS_ZONEFLG_NOTIFYDEFERRED);
11095
0
  notifytype = zone->notifysoa.notifytype;
11096
0
  DNS_ZONE_TIME_ADD(now, zone->notifysoa.notifydelay, &zone->notifytime);
11097
0
  UNLOCK_ZONE(zone);
11098
11099
0
  if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_EXITING) ||
11100
0
      !DNS_ZONE_FLAG(zone, DNS_ZONEFLG_LOADED))
11101
0
  {
11102
0
    return;
11103
0
  }
11104
11105
0
  if (notifytype == dns_notifytype_no) {
11106
0
    return;
11107
0
  }
11108
11109
0
  if (notifytype == dns_notifytype_masteronly &&
11110
0
      zone->type != dns_zone_primary)
11111
0
  {
11112
0
    return;
11113
0
  }
11114
11115
0
  origin = &zone->origin;
11116
11117
  /*
11118
   * Record that this was a notify due to starting up.
11119
   */
11120
0
  if (startup) {
11121
0
    flags |= DNS_NOTIFY_STARTUP;
11122
0
  }
11123
11124
  /*
11125
   * Get SOA RRset.
11126
   */
11127
0
  ZONEDB_LOCK(&zone->dblock, isc_rwlocktype_read);
11128
0
  if (zone->db != NULL) {
11129
0
    dns_db_attach(zone->db, &zonedb);
11130
0
  }
11131
0
  ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_read);
11132
0
  if (zonedb == NULL) {
11133
0
    return;
11134
0
  }
11135
0
  dns_db_currentversion(zonedb, &version);
11136
0
  result = dns_db_findnode(zonedb, origin, false, &node);
11137
0
  if (result != ISC_R_SUCCESS) {
11138
0
    goto cleanup1;
11139
0
  }
11140
11141
0
  dns_rdataset_init(&soardset);
11142
0
  result = dns_db_findrdataset(zonedb, node, version, dns_rdatatype_soa,
11143
0
             dns_rdatatype_none, 0, &soardset, NULL);
11144
0
  if (result != ISC_R_SUCCESS) {
11145
0
    goto cleanup2;
11146
0
  }
11147
11148
  /*
11149
   * Find serial and primary server's name.
11150
   */
11151
0
  dns_name_init(&primary);
11152
0
  result = dns_rdataset_first(&soardset);
11153
0
  if (result != ISC_R_SUCCESS) {
11154
0
    goto cleanup3;
11155
0
  }
11156
0
  dns_rdataset_current(&soardset, &soardata);
11157
0
  result = dns_rdata_tostruct(&soardata, &soa);
11158
0
  RUNTIME_CHECK(result == ISC_R_SUCCESS);
11159
0
  dns_name_dup(&soa.origin, zone->mctx, &primary);
11160
0
  serial = soa.serial;
11161
0
  dns_rdataset_disassociate(&soardset);
11162
11163
  /*
11164
   * Enqueue notify requests for 'also-notify' servers.
11165
   */
11166
0
  LOCK_ZONE(zone);
11167
11168
0
  dns_remote_reset(&zone->alsonotify, false);
11169
0
  while (!dns_remote_done(&zone->alsonotify)) {
11170
0
    dns_tsigkey_t *key = NULL;
11171
0
    dns_transport_t *transport = NULL;
11172
0
    dns_notify_t *notify = NULL;
11173
0
    dns_view_t *view = dns_zone_getview(zone);
11174
11175
0
    dst = dns_remote_curraddr(&zone->alsonotify);
11176
0
    if (isc_sockaddr_disabled(&dst)) {
11177
0
      goto next;
11178
0
    }
11179
11180
0
    if (dns_remote_keyname(&zone->alsonotify) != NULL) {
11181
0
      dns_name_t *keyname =
11182
0
        dns_remote_keyname(&zone->alsonotify);
11183
0
      (void)dns_view_gettsig(view, keyname, &key);
11184
0
    }
11185
11186
0
    if (dns_remote_tlsname(&zone->alsonotify) != NULL) {
11187
0
      dns_name_t *tlsname =
11188
0
        dns_remote_tlsname(&zone->alsonotify);
11189
0
      result = dns_view_gettransport(view, DNS_TRANSPORT_TLS,
11190
0
                   tlsname, &transport);
11191
11192
0
      if (result == ISC_R_SUCCESS) {
11193
0
        dns_zone_logc(
11194
0
          zone, DNS_LOGCATEGORY_NOTIFY,
11195
0
          ISC_LOG_INFO,
11196
0
          "got TLS configuration for a notify");
11197
0
      } else {
11198
0
        dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN,
11199
0
                ISC_LOG_ERROR,
11200
0
                "could not get TLS configuration "
11201
0
                "for zone transfer: %s",
11202
0
                isc_result_totext(result));
11203
0
        if (key != NULL) {
11204
0
          dns_tsigkey_detach(&key);
11205
0
        }
11206
0
        goto next;
11207
0
      }
11208
11209
0
      flags |= DNS_NOTIFY_TCP;
11210
0
    }
11211
11212
0
    src = dns_remote_sourceaddr(&zone->alsonotify);
11213
0
    INSIST(isc_sockaddr_pf(&src) == isc_sockaddr_pf(&dst));
11214
11215
0
    if (dns_notify_isqueued(&zone->notifysoa, dns_rdatatype_soa,
11216
0
          zone->view->dstport, flags, NULL, &dst,
11217
0
          key, transport))
11218
0
    {
11219
0
      if (key != NULL) {
11220
0
        dns_tsigkey_detach(&key);
11221
0
      }
11222
0
      if (transport != NULL) {
11223
0
        dns_transport_detach(&transport);
11224
0
      }
11225
0
      goto next;
11226
0
    }
11227
11228
0
    dns_notify_create(zone->mctx, dns_rdatatype_soa,
11229
0
          zone->view->dstport, flags, &notify);
11230
0
    zone_iattach(zone, &notify->zone);
11231
0
    notify->src = src;
11232
0
    notify->dst = dst;
11233
11234
0
    INSIST(notify->key == NULL);
11235
11236
0
    if (key != NULL) {
11237
0
      notify->key = key;
11238
0
      key = NULL;
11239
0
    }
11240
11241
0
    INSIST(notify->transport == NULL);
11242
0
    if (transport != NULL) {
11243
0
      notify->transport = transport;
11244
0
      transport = NULL;
11245
0
    }
11246
11247
0
    ISC_LIST_APPEND(zone->notifysoa.notifies, notify, link);
11248
0
    result = dns_notify_queue(notify, startup);
11249
0
    if (result != ISC_R_SUCCESS) {
11250
0
      dns_notify_destroy(notify, true);
11251
0
    }
11252
0
    if (!loggednotify) {
11253
0
      dns_zone_logc(zone, DNS_LOGCATEGORY_NOTIFY,
11254
0
              ISC_LOG_INFO,
11255
0
              "sending notifies (serial %u)", serial);
11256
0
      loggednotify = true;
11257
0
    }
11258
0
  next:
11259
0
    flags &= ~DNS_NOTIFY_TCP;
11260
0
    dns_remote_next(&zone->alsonotify, false);
11261
0
  }
11262
0
  UNLOCK_ZONE(zone);
11263
11264
0
  if (notifytype == dns_notifytype_explicit) {
11265
0
    goto cleanup3;
11266
0
  }
11267
11268
  /*
11269
   * Process NS RRset to generate notifies.
11270
   */
11271
11272
0
  dns_rdataset_init(&nsrdset);
11273
0
  result = dns_db_findrdataset(zonedb, node, version, dns_rdatatype_ns,
11274
0
             dns_rdatatype_none, 0, &nsrdset, NULL);
11275
0
  if (result != ISC_R_SUCCESS) {
11276
0
    goto cleanup3;
11277
0
  }
11278
11279
0
  DNS_RDATASET_FOREACH(&nsrdset) {
11280
0
    dns_rdata_t rdata = DNS_RDATA_INIT;
11281
0
    dns_rdataset_current(&nsrdset, &rdata);
11282
11283
0
    dns_notify_t *notify = NULL;
11284
11285
0
    result = dns_rdata_tostruct(&rdata, &ns);
11286
0
    RUNTIME_CHECK(result == ISC_R_SUCCESS);
11287
11288
    /*
11289
     * Don't notify the primary server unless explicitly
11290
     * configured to do so.
11291
     */
11292
0
    if (!DNS_ZONE_OPTION(zone, DNS_ZONEOPT_NOTIFYTOSOA) &&
11293
0
        dns_name_compare(&primary, &ns.name) == 0)
11294
0
    {
11295
0
      continue;
11296
0
    }
11297
11298
0
    if (!loggednotify) {
11299
0
      dns_zone_logc(zone, DNS_LOGCATEGORY_NOTIFY,
11300
0
              ISC_LOG_INFO,
11301
0
              "sending notifies (serial %u)", serial);
11302
0
      loggednotify = true;
11303
0
    }
11304
11305
0
    LOCK_ZONE(zone);
11306
0
    isqueued = dns_notify_isqueued(
11307
0
      &zone->notifysoa, dns_rdatatype_soa,
11308
0
      zone->view->dstport, flags, &ns.name, NULL, NULL, NULL);
11309
0
    UNLOCK_ZONE(zone);
11310
0
    if (isqueued) {
11311
0
      continue;
11312
0
    }
11313
0
    dns_notify_create(zone->mctx, dns_rdatatype_soa,
11314
0
          zone->view->dstport, flags, &notify);
11315
0
    dns_zone_iattach(zone, &notify->zone);
11316
0
    dns_name_dup(&ns.name, zone->mctx, &notify->ns);
11317
0
    LOCK_ZONE(zone);
11318
0
    ISC_LIST_APPEND(zone->notifysoa.notifies, notify, link);
11319
0
    UNLOCK_ZONE(zone);
11320
0
    dns_notify_find_address(notify);
11321
0
  }
11322
0
  dns_rdataset_disassociate(&nsrdset);
11323
11324
0
cleanup3:
11325
0
  if (dns_name_dynamic(&primary)) {
11326
0
    dns_name_free(&primary, zone->mctx);
11327
0
  }
11328
0
cleanup2:
11329
0
  dns_db_detachnode(&node);
11330
0
cleanup1:
11331
0
  dns_db_closeversion(zonedb, &version, false);
11332
0
  dns_db_detach(&zonedb);
11333
0
}
11334
11335
/***
11336
 *** Private
11337
 ***/
11338
static void
11339
create_query(dns_zone_t *zone, dns_rdatatype_t rdtype, dns_name_t *name,
11340
0
       dns_message_t **messagep) {
11341
0
  dns_message_t *message = NULL;
11342
0
  dns_linkedname_t *qname = NULL;
11343
0
  dns_rdataset_t *qrdataset = NULL;
11344
11345
0
  dns_message_create(zone->mctx, NULL, NULL, DNS_MESSAGE_INTENTRENDER,
11346
0
         &message);
11347
11348
0
  message->opcode = dns_opcode_query;
11349
0
  message->rdclass = zone->rdclass;
11350
11351
0
  dns_message_gettempname(message, &qname);
11352
11353
0
  dns_message_gettemprdataset(message, &qrdataset);
11354
11355
  /*
11356
   * Make question.
11357
   */
11358
0
  dns_name_clone(name, dns_name(qname));
11359
0
  dns_rdataset_makequestion(qrdataset, zone->rdclass, rdtype);
11360
0
  ISC_LIST_APPEND(qname->list, qrdataset, link);
11361
0
  dns_message_addname(message, qname, DNS_SECTION_QUESTION);
11362
11363
0
  *messagep = message;
11364
0
}
11365
11366
static isc_result_t
11367
add_opt(dns_message_t *message, uint16_t udpsize, bool reqnsid,
11368
0
  bool reqexpire) {
11369
0
  dns_message_ednsinit(message, 0, udpsize, 0, 0);
11370
11371
  /* Set EDNS options if applicable. */
11372
0
  if (reqnsid) {
11373
0
    dns_ednsopt_t option = { .code = DNS_OPT_NSID };
11374
0
    RETERR(dns_message_ednsaddopt(message, &option));
11375
0
  }
11376
0
  if (reqexpire) {
11377
0
    dns_ednsopt_t option = { .code = DNS_OPT_EXPIRE };
11378
0
    RETERR(dns_message_ednsaddopt(message, &option));
11379
0
  }
11380
11381
0
  return dns_message_setopt(message);
11382
0
}
11383
11384
/*
11385
 * Called when stub zone update is finished.
11386
 * Update zone refresh, retry, expire values accordingly with
11387
 * SOA received from primary, sync database to file, restart
11388
 * zone management timer.
11389
 */
11390
static void
11391
0
stub_finish_zone_update(dns_stub_t *stub, isc_time_t now) {
11392
0
  uint32_t refresh, retry, expire;
11393
0
  isc_result_t result;
11394
0
  isc_interval_t i;
11395
0
  unsigned int soacount;
11396
0
  dns_zone_t *zone = stub->zone;
11397
11398
  /*
11399
   * Tidy up.
11400
   */
11401
0
  dns_db_closeversion(stub->db, &stub->version, true);
11402
0
  ZONEDB_LOCK(&zone->dblock, isc_rwlocktype_write);
11403
0
  if (zone->db == NULL) {
11404
0
    zone_attachdb(zone, stub->db);
11405
0
  }
11406
0
  result = zone_get_from_db(zone, zone->db, NULL, &soacount, NULL, NULL,
11407
0
          &refresh, &retry, &expire, NULL, NULL);
11408
0
  if (result == ISC_R_SUCCESS && soacount > 0U) {
11409
0
    zone->refresh = RANGE(refresh, zone->minrefresh,
11410
0
              zone->maxrefresh);
11411
0
    zone->retry = RANGE(retry, zone->minretry, zone->maxretry);
11412
0
    zone->expire = RANGE(expire, zone->refresh + zone->retry,
11413
0
             DNS_MAX_EXPIRE);
11414
0
    DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_HAVETIMERS);
11415
0
  }
11416
0
  ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_write);
11417
0
  dns_db_detach(&stub->db);
11418
11419
0
  DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_REFRESH);
11420
0
  DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_LOADED);
11421
0
  DNS_ZONE_JITTER_ADD(&now, zone->refresh, &zone->refreshtime);
11422
0
  isc_interval_set(&i, zone->expire, 0);
11423
0
  DNS_ZONE_TIME_ADD(&now, zone->expire, &zone->expiretime);
11424
11425
0
  if (zone->masterfile != NULL) {
11426
0
    zone_needdump(zone, 0);
11427
0
  }
11428
11429
0
  dns__zone_settimer(zone, now);
11430
0
}
11431
11432
/*
11433
 * Process answers for A and AAAA queries when
11434
 * resolving nameserver addresses for which glue
11435
 * was missing in a previous answer for a NS query.
11436
 */
11437
static void
11438
0
stub_glue_response(void *arg) {
11439
0
  dns_request_t *request = (dns_request_t *)arg;
11440
0
  struct stub_glue_request *sgr = dns_request_getarg(request);
11441
0
  struct stub_cb_args *cb_args = sgr->args;
11442
0
  dns_stub_t *stub = cb_args->stub;
11443
0
  dns_message_t *msg = NULL;
11444
0
  dns_zone_t *zone = NULL;
11445
0
  char primary[ISC_SOCKADDR_FORMATSIZE];
11446
0
  char source[ISC_SOCKADDR_FORMATSIZE];
11447
0
  uint32_t addr_count, cnamecnt;
11448
0
  isc_result_t result;
11449
0
  isc_sockaddr_t curraddr, sourceaddr;
11450
0
  dns_rdataset_t *addr_rdataset = NULL;
11451
0
  dns_dbnode_t *node = NULL;
11452
11453
0
  INSIST(DNS_STUB_VALID(stub));
11454
11455
0
  zone = stub->zone;
11456
11457
0
  ENTER;
11458
11459
0
  LOCK_ZONE(zone);
11460
11461
0
  if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_EXITING)) {
11462
0
    zone_debuglog(zone, __func__, 1, "exiting");
11463
0
    goto cleanup;
11464
0
  }
11465
11466
0
  sourceaddr = zone_addr_tosockaddr(&zone->sourceaddr);
11467
0
  curraddr = dns_remote_curraddr(&zone->primaries);
11468
0
  isc_sockaddr_format(&curraddr, primary, sizeof(primary));
11469
0
  isc_sockaddr_format(&sourceaddr, source, sizeof(source));
11470
11471
0
  if (dns_request_getresult(request) != ISC_R_SUCCESS) {
11472
0
    dns_unreachcache_add(zone->view->unreachcache, &curraddr,
11473
0
             &sourceaddr);
11474
0
    dns_zone_log(zone, ISC_LOG_INFO,
11475
0
           "could not refresh stub from primary %s"
11476
0
           " (source %s): %s",
11477
0
           primary, source,
11478
0
           isc_result_totext(dns_request_getresult(request)));
11479
0
    goto cleanup;
11480
0
  }
11481
11482
0
  dns_message_create(zone->mctx, NULL, NULL, DNS_MESSAGE_INTENTPARSE,
11483
0
         &msg);
11484
0
  result = dns_request_getresponse(request, msg, 0);
11485
0
  if (result != ISC_R_SUCCESS) {
11486
0
    dns_zone_log(zone, ISC_LOG_INFO,
11487
0
           "refreshing stub: unable to parse response (%s)",
11488
0
           isc_result_totext(result));
11489
0
    goto cleanup;
11490
0
  }
11491
11492
  /*
11493
   * Unexpected opcode.
11494
   */
11495
0
  if (msg->opcode != dns_opcode_query) {
11496
0
    char opcode[128];
11497
0
    isc_buffer_t rb;
11498
11499
0
    isc_buffer_init(&rb, opcode, sizeof(opcode));
11500
0
    (void)dns_opcode_totext(msg->opcode, &rb);
11501
11502
0
    dns_zone_log(zone, ISC_LOG_INFO,
11503
0
           "refreshing stub: "
11504
0
           "unexpected opcode (%.*s) from %s (source %s)",
11505
0
           (int)rb.used, opcode, primary, source);
11506
0
    goto cleanup;
11507
0
  }
11508
11509
  /*
11510
   * Unexpected rcode.
11511
   */
11512
0
  if (msg->rcode != dns_rcode_noerror) {
11513
0
    char rcode[128];
11514
0
    isc_buffer_t rb;
11515
11516
0
    isc_buffer_init(&rb, rcode, sizeof(rcode));
11517
0
    (void)dns_rcode_totext(msg->rcode, &rb);
11518
11519
0
    dns_zone_log(zone, ISC_LOG_INFO,
11520
0
           "refreshing stub: "
11521
0
           "unexpected rcode (%.*s) from %s (source %s)",
11522
0
           (int)rb.used, rcode, primary, source);
11523
0
    goto cleanup;
11524
0
  }
11525
11526
  /*
11527
   * We need complete messages.
11528
   */
11529
0
  if ((msg->flags & DNS_MESSAGEFLAG_TC) != 0) {
11530
0
    if (dns_request_usedtcp(request)) {
11531
0
      dns_zone_log(zone, ISC_LOG_INFO,
11532
0
             "refreshing stub: truncated TCP "
11533
0
             "response from primary %s (source %s)",
11534
0
             primary, source);
11535
0
    }
11536
0
    goto cleanup;
11537
0
  }
11538
11539
  /*
11540
   * If non-auth log.
11541
   */
11542
0
  if ((msg->flags & DNS_MESSAGEFLAG_AA) == 0) {
11543
0
    dns_zone_log(zone, ISC_LOG_INFO,
11544
0
           "refreshing stub: "
11545
0
           "non-authoritative answer from "
11546
0
           "primary %s (source %s)",
11547
0
           primary, source);
11548
0
    goto cleanup;
11549
0
  }
11550
11551
  /*
11552
   * Sanity checks.
11553
   */
11554
0
  cnamecnt = message_count(msg, DNS_SECTION_ANSWER, dns_rdatatype_cname);
11555
0
  addr_count = message_count(msg, DNS_SECTION_ANSWER,
11556
0
           sgr->ipv4 ? dns_rdatatype_a
11557
0
               : dns_rdatatype_aaaa);
11558
11559
0
  if (cnamecnt != 0) {
11560
0
    dns_zone_log(zone, ISC_LOG_INFO,
11561
0
           "refreshing stub: unexpected CNAME response "
11562
0
           "from primary %s (source %s)",
11563
0
           primary, source);
11564
0
    goto cleanup;
11565
0
  }
11566
11567
0
  if (addr_count == 0) {
11568
0
    dns_zone_log(zone, ISC_LOG_INFO,
11569
0
           "refreshing stub: no %s records in response "
11570
0
           "from primary %s (source %s)",
11571
0
           sgr->ipv4 ? "A" : "AAAA", primary, source);
11572
0
    goto cleanup;
11573
0
  }
11574
  /*
11575
   * Extract A or AAAA RRset from message.
11576
   */
11577
0
  result = dns_message_findname(msg, DNS_SECTION_ANSWER, &sgr->name,
11578
0
              sgr->ipv4 ? dns_rdatatype_a
11579
0
            : dns_rdatatype_aaaa,
11580
0
              dns_rdatatype_none, NULL, &addr_rdataset);
11581
0
  if (result != ISC_R_SUCCESS) {
11582
0
    if (result != DNS_R_NXDOMAIN && result != DNS_R_NXRRSET) {
11583
0
      char namebuf[DNS_NAME_FORMATSIZE];
11584
0
      dns_name_format(&sgr->name, namebuf, sizeof(namebuf));
11585
0
      dns_zone_log(
11586
0
        zone, ISC_LOG_INFO,
11587
0
        "refreshing stub: dns_message_findname(%s/%s) "
11588
0
        "failed (%s)",
11589
0
        namebuf, sgr->ipv4 ? "A" : "AAAA",
11590
0
        isc_result_totext(result));
11591
0
    }
11592
0
    goto cleanup;
11593
0
  }
11594
11595
0
  result = dns_db_findnode(stub->db, &sgr->name, true, &node);
11596
0
  if (result != ISC_R_SUCCESS) {
11597
0
    dns_zone_log(zone, ISC_LOG_INFO,
11598
0
           "refreshing stub: "
11599
0
           "dns_db_findnode() failed: %s",
11600
0
           isc_result_totext(result));
11601
0
    goto cleanup;
11602
0
  }
11603
11604
0
  result = dns_db_addrdataset(stub->db, node, stub->version, 0,
11605
0
            addr_rdataset, 0, NULL);
11606
0
  if (result != ISC_R_SUCCESS) {
11607
0
    dns_zone_log(zone, ISC_LOG_INFO,
11608
0
           "refreshing stub: "
11609
0
           "dns_db_addrdataset() failed: %s",
11610
0
           isc_result_totext(result));
11611
0
  }
11612
0
  dns_db_detachnode(&node);
11613
11614
0
cleanup:
11615
0
  if (msg != NULL) {
11616
0
    dns_message_detach(&msg);
11617
0
  }
11618
11619
0
  dns_name_free(&sgr->name, zone->mctx);
11620
0
  dns_request_destroy(&sgr->request);
11621
0
  isc_mem_put(zone->mctx, sgr, sizeof(*sgr));
11622
11623
  /* If last request, release all related resources */
11624
0
  if (atomic_fetch_sub_release(&stub->pending_requests, 1) == 1) {
11625
0
    isc_mem_put(zone->mctx, cb_args, sizeof(*cb_args));
11626
0
    stub_finish_zone_update(stub, isc_time_now());
11627
0
    UNLOCK_ZONE(zone);
11628
0
    stub->magic = 0;
11629
0
    dns_zone_idetach(&stub->zone);
11630
0
    INSIST(stub->db == NULL);
11631
0
    INSIST(stub->version == NULL);
11632
0
    isc_mem_put(stub->mctx, stub, sizeof(*stub));
11633
0
  } else {
11634
0
    UNLOCK_ZONE(zone);
11635
0
  }
11636
0
}
11637
11638
/*
11639
 * Create and send an A or AAAA query to the primary
11640
 * server of the stub zone given.
11641
 */
11642
static isc_result_t
11643
stub_request_nameserver_address(struct stub_cb_args *args, bool ipv4,
11644
0
        const dns_name_t *name) {
11645
0
  dns_message_t *message = NULL;
11646
0
  dns_zone_t *zone;
11647
0
  isc_result_t result;
11648
0
  struct stub_glue_request *sgr;
11649
0
  isc_sockaddr_t curraddr, sourceaddr;
11650
11651
0
  zone = args->stub->zone;
11652
0
  sgr = isc_mem_get(zone->mctx, sizeof(*sgr));
11653
0
  *sgr = (struct stub_glue_request){
11654
0
    .args = args,
11655
0
    .name = (dns_name_t)DNS_NAME_INITEMPTY,
11656
0
    .ipv4 = ipv4,
11657
0
  };
11658
11659
0
  dns_name_dup(name, zone->mctx, &sgr->name);
11660
11661
0
  create_query(zone, ipv4 ? dns_rdatatype_a : dns_rdatatype_aaaa,
11662
0
         &sgr->name, &message);
11663
11664
0
  if (!DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NOEDNS)) {
11665
0
    result = add_opt(message, args->udpsize, args->reqnsid, false);
11666
0
    if (result != ISC_R_SUCCESS) {
11667
0
      zone_debuglog(zone, __func__, 1,
11668
0
              "unable to add opt record: %s",
11669
0
              isc_result_totext(result));
11670
0
      goto fail;
11671
0
    }
11672
0
  }
11673
11674
0
  atomic_fetch_add_release(&args->stub->pending_requests, 1);
11675
11676
0
  sourceaddr = zone_addr_tosockaddr(&zone->sourceaddr);
11677
0
  curraddr = dns_remote_curraddr(&zone->primaries);
11678
0
  result = dns_request_create(
11679
0
    zone->view->requestmgr, message, &sourceaddr, &curraddr, NULL,
11680
0
    NULL, DNS_REQUESTOPT_TCP, args->tsig_key, args->connect_timeout,
11681
0
    args->timeout, UDP_REQUEST_TIMEOUT, UDP_REQUEST_RETRIES,
11682
0
    zone->loop, stub_glue_response, sgr, &sgr->request);
11683
11684
0
  if (result != ISC_R_SUCCESS) {
11685
0
    uint_fast32_t pr;
11686
0
    pr = atomic_fetch_sub_release(&args->stub->pending_requests, 1);
11687
0
    INSIST(pr > 1);
11688
0
    zone_debuglog(zone, __func__, 1,
11689
0
            "dns_request_create() failed: %s",
11690
0
            isc_result_totext(result));
11691
0
    goto fail;
11692
0
  }
11693
11694
0
  dns_message_detach(&message);
11695
11696
0
  return ISC_R_SUCCESS;
11697
11698
0
fail:
11699
0
  dns_name_free(&sgr->name, zone->mctx);
11700
0
  isc_mem_put(zone->mctx, sgr, sizeof(*sgr));
11701
11702
0
  if (message != NULL) {
11703
0
    dns_message_detach(&message);
11704
0
  }
11705
11706
0
  return result;
11707
0
}
11708
11709
static isc_result_t
11710
save_nsrrset(dns_message_t *message, dns_name_t *name,
11711
       struct stub_cb_args *cb_args, dns_db_t *db,
11712
0
       dns_dbversion_t *version) {
11713
0
  dns_rdataset_t *nsrdataset = NULL;
11714
0
  dns_rdataset_t *rdataset = NULL;
11715
0
  dns_dbnode_t *node = NULL;
11716
0
  dns_rdata_ns_t ns;
11717
0
  isc_result_t result;
11718
0
  bool has_glue = false;
11719
11720
  /*
11721
   * List of NS entries in answer, keep names that will be used
11722
   * to resolve missing A/AAAA glue for each entry.
11723
   */
11724
0
  dns_namelist_t ns_list;
11725
0
  ISC_LIST_INIT(ns_list);
11726
11727
  /*
11728
   * Extract NS RRset from message.
11729
   */
11730
0
  result = dns_message_findname(message, DNS_SECTION_ANSWER, name,
11731
0
              dns_rdatatype_ns, dns_rdatatype_none,
11732
0
              NULL, &nsrdataset);
11733
0
  if (result != ISC_R_SUCCESS) {
11734
0
    goto done;
11735
0
  }
11736
11737
  /*
11738
   * Add NS rdataset.
11739
   */
11740
0
  result = dns_db_findnode(db, name, true, &node);
11741
0
  if (result != ISC_R_SUCCESS) {
11742
0
    goto done;
11743
0
  }
11744
0
  result = dns_db_addrdataset(db, node, version, 0, nsrdataset, 0, NULL);
11745
0
  dns_db_detachnode(&node);
11746
0
  if (result != ISC_R_SUCCESS) {
11747
0
    goto done;
11748
0
  }
11749
  /*
11750
   * Add glue rdatasets.
11751
   */
11752
0
  DNS_RDATASET_FOREACH(nsrdataset) {
11753
0
    dns_rdata_t rdata = DNS_RDATA_INIT;
11754
0
    dns_rdataset_current(nsrdataset, &rdata);
11755
0
    result = dns_rdata_tostruct(&rdata, &ns);
11756
0
    RUNTIME_CHECK(result == ISC_R_SUCCESS);
11757
11758
0
    if (!dns_name_issubdomain(&ns.name, name)) {
11759
0
      continue;
11760
0
    }
11761
0
    rdataset = NULL;
11762
0
    result = dns_message_findname(message, DNS_SECTION_ADDITIONAL,
11763
0
                &ns.name, dns_rdatatype_aaaa,
11764
0
                dns_rdatatype_none, NULL,
11765
0
                &rdataset);
11766
0
    if (result == ISC_R_SUCCESS) {
11767
0
      has_glue = true;
11768
0
      result = dns_db_findnode(db, &ns.name, true, &node);
11769
0
      if (result != ISC_R_SUCCESS) {
11770
0
        goto done;
11771
0
      }
11772
0
      result = dns_db_addrdataset(db, node, version, 0,
11773
0
                rdataset, 0, NULL);
11774
0
      dns_db_detachnode(&node);
11775
0
      if (result != ISC_R_SUCCESS) {
11776
0
        goto done;
11777
0
      }
11778
0
    }
11779
11780
0
    rdataset = NULL;
11781
0
    result = dns_message_findname(
11782
0
      message, DNS_SECTION_ADDITIONAL, &ns.name,
11783
0
      dns_rdatatype_a, dns_rdatatype_none, NULL, &rdataset);
11784
0
    if (result == ISC_R_SUCCESS) {
11785
0
      has_glue = true;
11786
0
      result = dns_db_findnode(db, &ns.name, true, &node);
11787
0
      if (result != ISC_R_SUCCESS) {
11788
0
        goto done;
11789
0
      }
11790
0
      result = dns_db_addrdataset(db, node, version, 0,
11791
0
                rdataset, 0, NULL);
11792
0
      dns_db_detachnode(&node);
11793
0
      if (result != ISC_R_SUCCESS) {
11794
0
        goto done;
11795
0
      }
11796
0
    }
11797
11798
    /*
11799
     * If no glue is found so far, we add the name to the list to
11800
     * resolve the A/AAAA glue later. If any glue is found in any
11801
     * iteration step, this list will be discarded and only the glue
11802
     * provided in this message will be used.
11803
     */
11804
0
    if (!has_glue && dns_name_issubdomain(&ns.name, name)) {
11805
0
      dns_linkedname_t *tmp_name;
11806
0
      tmp_name = isc_mem_get(cb_args->stub->mctx,
11807
0
                 sizeof(*tmp_name));
11808
0
      dns_linkedname_init(tmp_name);
11809
0
      dns_name_dup(&ns.name, cb_args->stub->mctx,
11810
0
             dns_name(tmp_name));
11811
0
      ISC_LIST_APPEND(ns_list, tmp_name, link);
11812
0
    }
11813
0
  }
11814
11815
  /*
11816
   * If no glue records were found, we attempt to resolve A/AAAA
11817
   * for each NS entry found in the answer.
11818
   */
11819
0
  if (!has_glue) {
11820
0
    ISC_LIST_FOREACH(ns_list, ns_name, link) {
11821
      /*
11822
       * Resolve NS IPv4 address/A.
11823
       */
11824
0
      result = stub_request_nameserver_address(
11825
0
        cb_args, true, dns_name(ns_name));
11826
0
      if (result != ISC_R_SUCCESS) {
11827
0
        goto done;
11828
0
      }
11829
      /*
11830
       * Resolve NS IPv6 address/AAAA.
11831
       */
11832
0
      result = stub_request_nameserver_address(
11833
0
        cb_args, false, dns_name(ns_name));
11834
0
      if (result != ISC_R_SUCCESS) {
11835
0
        goto done;
11836
0
      }
11837
0
    }
11838
0
  }
11839
11840
0
  result = ISC_R_SUCCESS;
11841
11842
0
done:
11843
0
  ISC_LIST_FOREACH(ns_list, ns_name, link) {
11844
0
    ISC_LIST_UNLINK(ns_list, ns_name, link);
11845
0
    dns_name_free(dns_name(ns_name), cb_args->stub->mctx);
11846
0
    isc_mem_put(cb_args->stub->mctx, ns_name, sizeof(*ns_name));
11847
0
  }
11848
0
  return result;
11849
0
}
11850
11851
static void
11852
0
stub_callback(void *arg) {
11853
0
  dns_request_t *request = (dns_request_t *)arg;
11854
0
  struct stub_cb_args *cb_args = dns_request_getarg(request);
11855
0
  dns_stub_t *stub = cb_args->stub;
11856
0
  dns_message_t *msg = NULL;
11857
0
  dns_zone_t *zone = NULL;
11858
0
  char primary[ISC_SOCKADDR_FORMATSIZE];
11859
0
  char source[ISC_SOCKADDR_FORMATSIZE];
11860
0
  uint32_t nscnt, cnamecnt;
11861
0
  isc_result_t result;
11862
0
  isc_sockaddr_t curraddr, sourceaddr;
11863
0
  isc_time_t now;
11864
0
  bool exiting = false;
11865
11866
0
  INSIST(DNS_STUB_VALID(stub));
11867
11868
0
  zone = stub->zone;
11869
11870
0
  ENTER;
11871
11872
0
  now = isc_time_now();
11873
11874
0
  LOCK_ZONE(zone);
11875
11876
0
  if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_EXITING)) {
11877
0
    goto exiting;
11878
0
  }
11879
11880
0
  sourceaddr = zone_addr_tosockaddr(&zone->sourceaddr);
11881
0
  curraddr = dns_remote_curraddr(&zone->primaries);
11882
0
  isc_sockaddr_format(&curraddr, primary, sizeof(primary));
11883
0
  isc_sockaddr_format(&sourceaddr, source, sizeof(source));
11884
11885
0
  result = dns_request_getresult(request);
11886
0
  switch (result) {
11887
0
  case ISC_R_SUCCESS:
11888
0
    break;
11889
0
  case ISC_R_SHUTTINGDOWN:
11890
0
  case ISC_R_CANCELED:
11891
0
    goto exiting;
11892
0
  case ISC_R_TIMEDOUT:
11893
0
    if (!DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NOEDNS)) {
11894
0
      DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_NOEDNS);
11895
0
      dns_zone_log(zone, ISC_LOG_DEBUG(1),
11896
0
             "refreshing stub: timeout retrying "
11897
0
             "without EDNS primary %s (source %s)",
11898
0
             primary, source);
11899
0
      goto same_primary;
11900
0
    }
11901
0
    FALLTHROUGH;
11902
0
  default:
11903
0
    dns_unreachcache_add(zone->view->unreachcache, &curraddr,
11904
0
             &sourceaddr);
11905
0
    dns_zone_log(zone, ISC_LOG_INFO,
11906
0
           "could not refresh stub from primary "
11907
0
           "%s (source %s): %s",
11908
0
           primary, source, isc_result_totext(result));
11909
0
    goto next_primary;
11910
0
  }
11911
11912
0
  dns_message_create(zone->mctx, NULL, NULL, DNS_MESSAGE_INTENTPARSE,
11913
0
         &msg);
11914
11915
0
  result = dns_request_getresponse(request, msg, 0);
11916
0
  if (result != ISC_R_SUCCESS) {
11917
0
    goto next_primary;
11918
0
  }
11919
11920
  /*
11921
   * Unexpected opcode.
11922
   */
11923
0
  if (msg->opcode != dns_opcode_query) {
11924
0
    char opcode[128];
11925
0
    isc_buffer_t rb;
11926
11927
0
    isc_buffer_init(&rb, opcode, sizeof(opcode));
11928
0
    (void)dns_opcode_totext(msg->opcode, &rb);
11929
11930
0
    dns_zone_log(zone, ISC_LOG_INFO,
11931
0
           "refreshing stub: "
11932
0
           "unexpected opcode (%.*s) from %s (source %s)",
11933
0
           (int)rb.used, opcode, primary, source);
11934
0
    goto next_primary;
11935
0
  }
11936
11937
  /*
11938
   * Unexpected rcode.
11939
   */
11940
0
  if (msg->rcode != dns_rcode_noerror) {
11941
0
    char rcode[128];
11942
0
    isc_buffer_t rb;
11943
11944
0
    isc_buffer_init(&rb, rcode, sizeof(rcode));
11945
0
    (void)dns_rcode_totext(msg->rcode, &rb);
11946
11947
0
    if (!DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NOEDNS) &&
11948
0
        (msg->rcode == dns_rcode_servfail ||
11949
0
         msg->rcode == dns_rcode_notimp ||
11950
0
         (msg->rcode == dns_rcode_formerr && msg->opt == NULL)))
11951
0
    {
11952
0
      dns_zone_log(zone, ISC_LOG_DEBUG(1),
11953
0
             "refreshing stub: rcode (%.*s) retrying "
11954
0
             "without EDNS primary %s (source %s)",
11955
0
             (int)rb.used, rcode, primary, source);
11956
0
      DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_NOEDNS);
11957
0
      goto same_primary;
11958
0
    }
11959
11960
0
    dns_zone_log(zone, ISC_LOG_INFO,
11961
0
           "refreshing stub: "
11962
0
           "unexpected rcode (%.*s) from %s (source %s)",
11963
0
           (int)rb.used, rcode, primary, source);
11964
0
    goto next_primary;
11965
0
  }
11966
11967
  /*
11968
   * We need complete messages.
11969
   */
11970
0
  if ((msg->flags & DNS_MESSAGEFLAG_TC) != 0) {
11971
0
    if (dns_request_usedtcp(request)) {
11972
0
      dns_zone_log(zone, ISC_LOG_INFO,
11973
0
             "refreshing stub: truncated TCP "
11974
0
             "response from primary %s (source %s)",
11975
0
             primary, source);
11976
0
      goto next_primary;
11977
0
    }
11978
0
    DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_USEVC);
11979
0
    goto same_primary;
11980
0
  }
11981
11982
  /*
11983
   * If non-auth log and next primary.
11984
   */
11985
0
  if ((msg->flags & DNS_MESSAGEFLAG_AA) == 0) {
11986
0
    dns_zone_log(zone, ISC_LOG_INFO,
11987
0
           "refreshing stub: "
11988
0
           "non-authoritative answer from "
11989
0
           "primary %s (source %s)",
11990
0
           primary, source);
11991
0
    goto next_primary;
11992
0
  }
11993
11994
  /*
11995
   * Sanity checks.
11996
   */
11997
0
  cnamecnt = message_count(msg, DNS_SECTION_ANSWER, dns_rdatatype_cname);
11998
0
  nscnt = message_count(msg, DNS_SECTION_ANSWER, dns_rdatatype_ns);
11999
12000
0
  if (cnamecnt != 0) {
12001
0
    dns_zone_log(zone, ISC_LOG_INFO,
12002
0
           "refreshing stub: unexpected CNAME response "
12003
0
           "from primary %s (source %s)",
12004
0
           primary, source);
12005
0
    goto next_primary;
12006
0
  }
12007
12008
0
  if (nscnt == 0) {
12009
0
    dns_zone_log(zone, ISC_LOG_INFO,
12010
0
           "refreshing stub: no NS records in response "
12011
0
           "from primary %s (source %s)",
12012
0
           primary, source);
12013
0
    goto next_primary;
12014
0
  }
12015
12016
0
  atomic_fetch_add(&stub->pending_requests, 1);
12017
12018
  /*
12019
   * Save answer.
12020
   */
12021
0
  result = save_nsrrset(msg, &zone->origin, cb_args, stub->db,
12022
0
            stub->version);
12023
0
  if (result != ISC_R_SUCCESS) {
12024
0
    dns_zone_log(zone, ISC_LOG_INFO,
12025
0
           "refreshing stub: unable to save NS records "
12026
0
           "from primary %s (source %s)",
12027
0
           primary, source);
12028
0
    goto next_primary;
12029
0
  }
12030
12031
0
  dns_message_detach(&msg);
12032
0
  dns_request_destroy(&zone->request);
12033
12034
  /*
12035
   * Check to see if there are no outstanding requests and
12036
   * finish off if that is so.
12037
   */
12038
0
  if (atomic_fetch_sub(&stub->pending_requests, 1) == 1) {
12039
0
    isc_mem_put(zone->mctx, cb_args, sizeof(*cb_args));
12040
0
    stub_finish_zone_update(stub, now);
12041
0
    goto free_stub;
12042
0
  }
12043
12044
0
  UNLOCK_ZONE(zone);
12045
0
  return;
12046
12047
0
exiting:
12048
0
  zone_debuglog(zone, __func__, 1, "exiting");
12049
0
  exiting = true;
12050
12051
0
next_primary:
12052
0
  isc_mem_put(zone->mctx, cb_args, sizeof(*cb_args));
12053
0
  if (stub->version != NULL) {
12054
0
    dns_db_closeversion(stub->db, &stub->version, false);
12055
0
  }
12056
0
  if (stub->db != NULL) {
12057
0
    dns_db_detach(&stub->db);
12058
0
  }
12059
0
  if (msg != NULL) {
12060
0
    dns_message_detach(&msg);
12061
0
  }
12062
0
  dns_request_destroy(&zone->request);
12063
  /*
12064
   * Skip to next failed / untried primary.
12065
   */
12066
0
  dns_remote_next(&zone->primaries, true);
12067
0
  DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_NOEDNS);
12068
0
  if (exiting || dns_remote_done(&zone->primaries)) {
12069
0
    DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_REFRESH);
12070
0
    dns__zone_settimer(zone, now);
12071
0
    goto free_stub;
12072
0
  }
12073
0
  queue_soa_query(zone);
12074
0
  goto free_stub;
12075
12076
0
same_primary:
12077
0
  isc_mem_put(zone->mctx, cb_args, sizeof(*cb_args));
12078
0
  if (msg != NULL) {
12079
0
    dns_message_detach(&msg);
12080
0
  }
12081
0
  dns_request_destroy(&zone->request);
12082
0
  ns_query(zone, NULL, stub);
12083
0
  UNLOCK_ZONE(zone);
12084
0
  return;
12085
12086
0
free_stub:
12087
0
  UNLOCK_ZONE(zone);
12088
0
  stub->magic = 0;
12089
0
  dns_zone_idetach(&stub->zone);
12090
0
  INSIST(stub->db == NULL);
12091
0
  INSIST(stub->version == NULL);
12092
0
  isc_mem_put(stub->mctx, stub, sizeof(*stub));
12093
0
}
12094
12095
/*
12096
 * Get the EDNS EXPIRE option from the response and if it exists trim
12097
 * expire to be not more than it.
12098
 */
12099
static void
12100
0
get_edns_expire(dns_zone_t *zone, dns_message_t *message, uint32_t *expirep) {
12101
0
  isc_result_t result;
12102
0
  uint32_t expire;
12103
0
  dns_rdata_t rdata = DNS_RDATA_INIT;
12104
0
  isc_buffer_t optbuf;
12105
0
  uint16_t optcode;
12106
0
  uint16_t optlen;
12107
12108
0
  REQUIRE(expirep != NULL);
12109
0
  REQUIRE(message != NULL);
12110
12111
0
  if (message->opt == NULL) {
12112
0
    return;
12113
0
  }
12114
12115
0
  result = dns_rdataset_first(message->opt);
12116
0
  if (result == ISC_R_SUCCESS) {
12117
0
    dns_rdataset_current(message->opt, &rdata);
12118
0
    isc_buffer_init(&optbuf, rdata.data, rdata.length);
12119
0
    isc_buffer_add(&optbuf, rdata.length);
12120
0
    while (isc_buffer_remaininglength(&optbuf) >= 4) {
12121
0
      optcode = isc_buffer_getuint16(&optbuf);
12122
0
      optlen = isc_buffer_getuint16(&optbuf);
12123
      /*
12124
       * A EDNS EXPIRE response has a length of 4.
12125
       */
12126
0
      if (optcode != DNS_OPT_EXPIRE || optlen != 4) {
12127
0
        isc_buffer_forward(&optbuf, optlen);
12128
0
        continue;
12129
0
      }
12130
0
      expire = isc_buffer_getuint32(&optbuf);
12131
0
      dns_zone_log(zone, ISC_LOG_DEBUG(1),
12132
0
             "got EDNS EXPIRE of %u", expire);
12133
      /*
12134
       * Trim *expirep?
12135
       */
12136
0
      if (expire < *expirep) {
12137
0
        *expirep = expire;
12138
0
      }
12139
0
      break;
12140
0
    }
12141
0
  }
12142
0
}
12143
12144
/*
12145
 * Set the file modification time zone->expire seconds before expiretime.
12146
 */
12147
static void
12148
0
setmodtime(dns_zone_t *zone, isc_time_t *expiretime) {
12149
0
  isc_result_t result;
12150
0
  isc_time_t when;
12151
0
  isc_interval_t i;
12152
12153
0
  isc_interval_set(&i, zone->expire, 0);
12154
0
  result = isc_time_subtract(expiretime, &i, &when);
12155
0
  if (result != ISC_R_SUCCESS) {
12156
0
    return;
12157
0
  }
12158
12159
0
  result = ISC_R_FAILURE;
12160
0
  if (zone->journal != NULL) {
12161
0
    result = isc_file_settime(zone->journal, &when);
12162
0
  }
12163
0
  if (result == ISC_R_SUCCESS &&
12164
0
      !DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NEEDDUMP) &&
12165
0
      !DNS_ZONE_FLAG(zone, DNS_ZONEFLG_DUMPING))
12166
0
  {
12167
0
    result = isc_file_settime(zone->masterfile, &when);
12168
0
  } else if (result != ISC_R_SUCCESS) {
12169
0
    result = isc_file_settime(zone->masterfile, &when);
12170
0
  }
12171
12172
  /*
12173
   * Someone removed the file from underneath us!
12174
   */
12175
0
  if (result == ISC_R_FILENOTFOUND) {
12176
0
    zone_needdump(zone, DNS_DUMP_DELAY);
12177
0
  } else if (result != ISC_R_SUCCESS) {
12178
0
    dns_zone_log(zone, ISC_LOG_ERROR,
12179
0
           "refresh: could not set "
12180
0
           "file modification time of '%s': %s",
12181
0
           zone->masterfile, isc_result_totext(result));
12182
0
  }
12183
0
}
12184
12185
/*
12186
 * An SOA query has finished (successfully or not).
12187
 */
12188
static void
12189
0
refresh_callback(void *arg) {
12190
0
  dns_request_t *request = (dns_request_t *)arg;
12191
0
  dns_zone_t *zone = dns_request_getarg(request);
12192
0
  dns_message_t *msg = NULL;
12193
0
  uint32_t soacnt, cnamecnt, soacount, nscount;
12194
0
  isc_time_t now;
12195
0
  char primary[ISC_SOCKADDR_FORMATSIZE];
12196
0
  char source[ISC_SOCKADDR_FORMATSIZE];
12197
0
  dns_rdataset_t *rdataset = NULL;
12198
0
  dns_rdata_t rdata = DNS_RDATA_INIT;
12199
0
  dns_rdata_soa_t soa;
12200
0
  isc_result_t result;
12201
0
  const isc_result_t eresult = dns_request_getresult(request);
12202
0
  isc_sockaddr_t curraddr, sourceaddr;
12203
0
  uint32_t serial, oldserial = 0;
12204
0
  bool do_queue_xfrin = false;
12205
12206
0
  INSIST(DNS_ZONE_VALID(zone));
12207
12208
0
  ENTER;
12209
12210
0
  if (isc_log_wouldlog(ISC_LOG_DEBUG(3))) {
12211
0
    dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN, ISC_LOG_DEBUG(3),
12212
0
            "refresh: request result: %s",
12213
0
            isc_result_totext(eresult));
12214
0
  }
12215
12216
0
  now = isc_time_now();
12217
12218
0
  LOCK_ZONE(zone);
12219
12220
0
  if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_EXITING)) {
12221
0
    goto exiting;
12222
0
  }
12223
12224
  /*
12225
   * If timeout, log and try the next primary
12226
   */
12227
0
  sourceaddr = zone_addr_tosockaddr(&zone->sourceaddr);
12228
0
  curraddr = dns_remote_curraddr(&zone->primaries);
12229
0
  isc_sockaddr_format(&curraddr, primary, sizeof(primary));
12230
0
  isc_sockaddr_format(&sourceaddr, source, sizeof(source));
12231
12232
0
  switch (eresult) {
12233
0
  case ISC_R_SUCCESS:
12234
0
    break;
12235
0
  case ISC_R_SHUTTINGDOWN:
12236
0
  case ISC_R_CANCELED:
12237
0
    goto exiting;
12238
0
  case ISC_R_TIMEDOUT:
12239
0
    if (!DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NOEDNS)) {
12240
0
      DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_NOEDNS);
12241
0
      dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN,
12242
0
              ISC_LOG_DEBUG(1),
12243
0
              "refresh: timeout retrying without EDNS "
12244
0
              "primary %s (source %s)",
12245
0
              primary, source);
12246
0
      goto same_primary;
12247
0
    } else if (!dns_request_usedtcp(request)) {
12248
0
      dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN,
12249
0
              ISC_LOG_INFO,
12250
0
              "refresh: retry limit for "
12251
0
              "primary %s exceeded (source %s)",
12252
0
              primary, source);
12253
      /* Try with secondary with TCP. */
12254
0
      if ((zone->type == dns_zone_secondary ||
12255
0
           zone->type == dns_zone_mirror ||
12256
0
           zone->type == dns_zone_redirect) &&
12257
0
          DNS_ZONE_OPTION(zone, DNS_ZONEOPT_TRYTCPREFRESH))
12258
0
      {
12259
0
        if (dns_unreachcache_find(
12260
0
              zone->view->unreachcache, &curraddr,
12261
0
              &sourceaddr) != ISC_R_SUCCESS)
12262
0
        {
12263
0
          DNS_ZONE_SETFLAG(
12264
0
            zone,
12265
0
            DNS_ZONEFLG_SOABEFOREAXFR);
12266
0
          goto tcp_transfer;
12267
0
        }
12268
0
        dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN,
12269
0
                ISC_LOG_DEBUG(1),
12270
0
                "refresh: skipped tcp fallback "
12271
0
                "as primary %s (source %s) is "
12272
0
                "unreachable (cached)",
12273
0
                primary, source);
12274
0
      }
12275
0
      goto next_primary;
12276
0
    }
12277
0
    FALLTHROUGH;
12278
0
  default:
12279
0
    result = eresult;
12280
0
    dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN, ISC_LOG_INFO,
12281
0
            "refresh: failure trying primary "
12282
0
            "%s (source %s): %s",
12283
0
            primary, source, isc_result_totext(result));
12284
0
    goto next_primary;
12285
0
  }
12286
12287
0
  dns_message_create(zone->mctx, NULL, NULL, DNS_MESSAGE_INTENTPARSE,
12288
0
         &msg);
12289
0
  result = dns_request_getresponse(request, msg, 0);
12290
0
  if (result != ISC_R_SUCCESS) {
12291
0
    dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN, ISC_LOG_INFO,
12292
0
            "refresh: failure trying primary "
12293
0
            "%s (source %s): %s",
12294
0
            primary, source, isc_result_totext(result));
12295
0
    goto next_primary;
12296
0
  }
12297
12298
  /*
12299
   * Unexpected opcode.
12300
   */
12301
0
  if (msg->opcode != dns_opcode_query) {
12302
0
    char opcode[128];
12303
0
    isc_buffer_t rb;
12304
12305
0
    isc_buffer_init(&rb, opcode, sizeof(opcode));
12306
0
    (void)dns_opcode_totext(msg->opcode, &rb);
12307
12308
0
    dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN, ISC_LOG_INFO,
12309
0
            "refresh: "
12310
0
            "unexpected opcode (%.*s) from %s (source %s)",
12311
0
            (int)rb.used, opcode, primary, source);
12312
0
    goto next_primary;
12313
0
  }
12314
12315
  /*
12316
   * Unexpected rcode.
12317
   */
12318
0
  if (msg->rcode != dns_rcode_noerror) {
12319
0
    char rcode[128];
12320
0
    isc_buffer_t rb;
12321
12322
0
    isc_buffer_init(&rb, rcode, sizeof(rcode));
12323
0
    (void)dns_rcode_totext(msg->rcode, &rb);
12324
12325
0
    if (!DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NOEDNS) &&
12326
0
        (msg->rcode == dns_rcode_servfail ||
12327
0
         msg->rcode == dns_rcode_notimp ||
12328
0
         (msg->rcode == dns_rcode_formerr && msg->opt == NULL)))
12329
0
    {
12330
0
      dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN,
12331
0
              ISC_LOG_DEBUG(1),
12332
0
              "refresh: rcode (%.*s) retrying without "
12333
0
              "EDNS primary %s (source %s)",
12334
0
              (int)rb.used, rcode, primary, source);
12335
0
      DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_NOEDNS);
12336
0
      goto same_primary;
12337
0
    }
12338
0
    if (!DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NOEDNS) &&
12339
0
        msg->rcode == dns_rcode_badvers)
12340
0
    {
12341
0
      dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN,
12342
0
              ISC_LOG_DEBUG(1),
12343
0
              "refresh: rcode (%.*s) retrying without "
12344
0
              "EDNS EXPIRE OPTION primary %s "
12345
0
              "(source %s)",
12346
0
              (int)rb.used, rcode, primary, source);
12347
0
      DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_NOEDNS);
12348
0
      goto same_primary;
12349
0
    }
12350
0
    dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN, ISC_LOG_INFO,
12351
0
            "refresh: unexpected rcode (%.*s) from "
12352
0
            "primary %s (source %s)",
12353
0
            (int)rb.used, rcode, primary, source);
12354
    /*
12355
     * Perhaps AXFR/IXFR is allowed even if SOA queries aren't.
12356
     */
12357
0
    if (msg->rcode == dns_rcode_refused &&
12358
0
        (zone->type == dns_zone_secondary ||
12359
0
         zone->type == dns_zone_mirror ||
12360
0
         zone->type == dns_zone_redirect))
12361
0
    {
12362
0
      goto tcp_transfer;
12363
0
    }
12364
0
    goto next_primary;
12365
0
  }
12366
12367
  /*
12368
   * If truncated punt to zone transfer which will query again.
12369
   */
12370
0
  if ((msg->flags & DNS_MESSAGEFLAG_TC) != 0) {
12371
0
    if (zone->type == dns_zone_secondary ||
12372
0
        zone->type == dns_zone_mirror ||
12373
0
        zone->type == dns_zone_redirect)
12374
0
    {
12375
0
      dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN,
12376
0
              ISC_LOG_INFO,
12377
0
              "refresh: truncated UDP answer, "
12378
0
              "initiating TCP zone xfer "
12379
0
              "for primary %s (source %s)",
12380
0
              primary, source);
12381
0
      DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_SOABEFOREAXFR);
12382
0
      goto tcp_transfer;
12383
0
    } else {
12384
0
      INSIST(zone->type == dns_zone_stub);
12385
0
      if (dns_request_usedtcp(request)) {
12386
0
        dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN,
12387
0
                ISC_LOG_INFO,
12388
0
                "refresh: truncated TCP response "
12389
0
                "from primary %s (source %s)",
12390
0
                primary, source);
12391
0
        goto next_primary;
12392
0
      }
12393
0
      DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_USEVC);
12394
0
      goto same_primary;
12395
0
    }
12396
0
  }
12397
12398
  /*
12399
   * If non-auth, log and try the next primary
12400
   */
12401
0
  if ((msg->flags & DNS_MESSAGEFLAG_AA) == 0) {
12402
0
    dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN, ISC_LOG_INFO,
12403
0
            "refresh: non-authoritative answer from "
12404
0
            "primary %s (source %s)",
12405
0
            primary, source);
12406
0
    goto next_primary;
12407
0
  }
12408
12409
0
  cnamecnt = message_count(msg, DNS_SECTION_ANSWER, dns_rdatatype_cname);
12410
0
  soacnt = message_count(msg, DNS_SECTION_ANSWER, dns_rdatatype_soa);
12411
0
  nscount = message_count(msg, DNS_SECTION_AUTHORITY, dns_rdatatype_ns);
12412
0
  soacount = message_count(msg, DNS_SECTION_AUTHORITY, dns_rdatatype_soa);
12413
12414
  /*
12415
   * There should not be a CNAME record at top of zone.
12416
   */
12417
0
  if (cnamecnt != 0) {
12418
0
    dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN, ISC_LOG_INFO,
12419
0
            "refresh: CNAME at top of zone "
12420
0
            "in primary %s (source %s)",
12421
0
            primary, source);
12422
0
    goto next_primary;
12423
0
  }
12424
12425
  /*
12426
   * If referral, log and try the next primary;
12427
   */
12428
0
  if (soacnt == 0 && soacount == 0 && nscount != 0) {
12429
0
    dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN, ISC_LOG_INFO,
12430
0
            "refresh: referral response "
12431
0
            "from primary %s (source %s)",
12432
0
            primary, source);
12433
0
    goto next_primary;
12434
0
  }
12435
12436
  /*
12437
   * If nodata, log and try the next primary;
12438
   */
12439
0
  if (soacnt == 0 && (nscount == 0 || soacount != 0)) {
12440
0
    dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN, ISC_LOG_INFO,
12441
0
            "refresh: NODATA response "
12442
0
            "from primary %s (source %s)",
12443
0
            primary, source);
12444
0
    goto next_primary;
12445
0
  }
12446
12447
  /*
12448
   * Only one soa at top of zone.
12449
   */
12450
0
  if (soacnt != 1) {
12451
0
    dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN, ISC_LOG_INFO,
12452
0
            "refresh: answer SOA count (%d) != 1 "
12453
0
            "from primary %s (source %s)",
12454
0
            soacnt, primary, source);
12455
0
    goto next_primary;
12456
0
  }
12457
12458
  /*
12459
   * Extract serial
12460
   */
12461
0
  rdataset = NULL;
12462
0
  result = dns_message_findname(msg, DNS_SECTION_ANSWER, &zone->origin,
12463
0
              dns_rdatatype_soa, dns_rdatatype_none,
12464
0
              NULL, &rdataset);
12465
0
  if (result != ISC_R_SUCCESS) {
12466
0
    dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN, ISC_LOG_INFO,
12467
0
            "refresh: unable to get SOA record "
12468
0
            "from primary %s (source %s)",
12469
0
            primary, source);
12470
0
    goto next_primary;
12471
0
  }
12472
12473
0
  result = dns_rdataset_first(rdataset);
12474
0
  if (result != ISC_R_SUCCESS) {
12475
0
    dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN, ISC_LOG_INFO,
12476
0
            "refresh: dns_rdataset_first() failed");
12477
0
    goto next_primary;
12478
0
  }
12479
12480
0
  dns_rdataset_current(rdataset, &rdata);
12481
0
  result = dns_rdata_tostruct(&rdata, &soa);
12482
0
  RUNTIME_CHECK(result == ISC_R_SUCCESS);
12483
12484
0
  serial = soa.serial;
12485
0
  if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_LOADED)) {
12486
0
    unsigned int dbsoacount;
12487
0
    result = zone_get_from_db(zone, zone->db, NULL, &dbsoacount,
12488
0
            NULL, &oldserial, NULL, NULL, NULL,
12489
0
            NULL, NULL);
12490
0
    RUNTIME_CHECK(result == ISC_R_SUCCESS);
12491
0
    RUNTIME_CHECK(dbsoacount > 0U);
12492
0
    zone_debuglogc(zone, DNS_LOGCATEGORY_XFER_IN, __func__, 1,
12493
0
             "serial: new %u, old %u", serial, oldserial);
12494
0
  } else {
12495
0
    zone_debuglogc(zone, DNS_LOGCATEGORY_XFER_IN, __func__, 1,
12496
0
             "serial: new %u, old not loaded", serial);
12497
0
  }
12498
12499
0
  if (!DNS_ZONE_FLAG(zone, DNS_ZONEFLG_LOADED) ||
12500
0
      DNS_ZONE_FLAG(zone, DNS_ZONEFLG_FORCEXFER) ||
12501
0
      isc_serial_gt(serial, oldserial))
12502
0
  {
12503
0
    if (dns_unreachcache_find(zone->view->unreachcache, &curraddr,
12504
0
            &sourceaddr) == ISC_R_SUCCESS)
12505
0
    {
12506
0
      dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN,
12507
0
              ISC_LOG_INFO,
12508
0
              "refresh: skipping %s as primary %s "
12509
0
              "(source %s) is unreachable (cached)",
12510
0
              (zone->type == dns_zone_secondary ||
12511
0
               zone->type == dns_zone_mirror ||
12512
0
               zone->type == dns_zone_redirect)
12513
0
                ? "zone transfer"
12514
0
                : "NS query",
12515
0
              primary, source);
12516
0
      goto next_primary;
12517
0
    }
12518
0
  tcp_transfer:
12519
0
    dns_request_destroy(&zone->request);
12520
0
    if (zone->type == dns_zone_secondary ||
12521
0
        zone->type == dns_zone_mirror ||
12522
0
        zone->type == dns_zone_redirect)
12523
0
    {
12524
0
      do_queue_xfrin = true;
12525
0
    } else {
12526
0
      INSIST(zone->type == dns_zone_stub);
12527
0
      ns_query(zone, rdataset, NULL);
12528
0
    }
12529
0
    if (msg != NULL) {
12530
0
      dns_message_detach(&msg);
12531
0
    }
12532
0
  } else if (isc_serial_eq(soa.serial, oldserial)) {
12533
0
    isc_time_t expiretime;
12534
0
    uint32_t expire;
12535
12536
    /*
12537
     * Compute the new expire time based on this response.
12538
     */
12539
0
    expire = zone->expire;
12540
0
    get_edns_expire(zone, msg, &expire);
12541
0
    DNS_ZONE_TIME_ADD(&now, expire, &expiretime);
12542
12543
    /*
12544
     * Has the expire time improved?
12545
     */
12546
0
    if (isc_time_compare(&expiretime, &zone->expiretime) > 0) {
12547
0
      zone->expiretime = expiretime;
12548
0
      if (zone->masterfile != NULL) {
12549
0
        setmodtime(zone, &expiretime);
12550
0
      }
12551
0
    }
12552
12553
0
    DNS_ZONE_JITTER_ADD(&now, zone->refresh, &zone->refreshtime);
12554
0
    dns_remote_mark(&zone->primaries, true);
12555
0
    goto next_primary;
12556
0
  } else {
12557
0
    if (!DNS_ZONE_OPTION(zone, DNS_ZONEOPT_MULTIMASTER)) {
12558
0
      dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN,
12559
0
              ISC_LOG_INFO,
12560
0
              "serial number (%u) "
12561
0
              "received from primary %s < ours (%u)",
12562
0
              soa.serial, primary, oldserial);
12563
0
    } else {
12564
0
      zone_debuglogc(zone, DNS_LOGCATEGORY_XFER_IN, __func__,
12565
0
               1, "ahead");
12566
0
    }
12567
0
    dns_remote_mark(&zone->primaries, true);
12568
0
    goto next_primary;
12569
0
  }
12570
0
  if (msg != NULL) {
12571
0
    dns_message_detach(&msg);
12572
0
  }
12573
0
  goto detach;
12574
12575
0
next_primary:
12576
0
  if (msg != NULL) {
12577
0
    dns_message_detach(&msg);
12578
0
  }
12579
0
  dns_request_destroy(&zone->request);
12580
  /*
12581
   * Skip to next failed / untried primary.
12582
   */
12583
0
  dns_remote_next(&zone->primaries, true);
12584
0
  DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_NOEDNS);
12585
0
  if (dns_remote_done(&zone->primaries)) {
12586
0
    DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_REFRESH);
12587
0
    if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NEEDREFRESH)) {
12588
0
      DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_NEEDREFRESH);
12589
0
      zone->refreshtime = now;
12590
0
    }
12591
0
    dns__zone_settimer(zone, now);
12592
0
    goto detach;
12593
0
  }
12594
12595
0
  queue_soa_query(zone);
12596
0
  goto detach;
12597
12598
0
exiting:
12599
  /*
12600
   * We can get here not only during shutdown, but also when the refresh
12601
   * is canceled during reconfiguration. In that case, make sure to clear
12602
   * the DNS_ZONEFLG_REFRESH flag so that future zone refreshes don't get
12603
   * stuck, and make sure a new refresh attempt is made again soon after
12604
   * the reconfiguration is complete.
12605
   */
12606
0
  DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_REFRESH);
12607
0
  zone->refreshtime = now;
12608
0
  dns__zone_settimer(zone, now);
12609
12610
0
  dns_request_destroy(&zone->request);
12611
0
  goto detach;
12612
12613
0
same_primary:
12614
0
  if (msg != NULL) {
12615
0
    dns_message_detach(&msg);
12616
0
  }
12617
0
  dns_request_destroy(&zone->request);
12618
0
  queue_soa_query(zone);
12619
12620
0
detach:
12621
0
  if (do_queue_xfrin) {
12622
    /* Shows in the statistics channel the duration of the step. */
12623
0
    zone->xfrintime = isc_time_now();
12624
0
  }
12625
0
  UNLOCK_ZONE(zone);
12626
0
  if (do_queue_xfrin) {
12627
0
    queue_xfrin(zone);
12628
0
  }
12629
0
  dns_zone_idetach(&zone);
12630
0
  return;
12631
0
}
12632
12633
struct soaquery {
12634
  dns_zone_t *zone;
12635
  isc_rlevent_t *rlevent;
12636
};
12637
12638
static void
12639
0
queue_soa_query(dns_zone_t *zone) {
12640
0
  isc_result_t result;
12641
0
  struct soaquery *sq = NULL;
12642
12643
0
  ENTER;
12644
  /*
12645
   * Locked by caller
12646
   */
12647
0
  REQUIRE(LOCKED_ZONE(zone));
12648
12649
0
  if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_EXITING)) {
12650
0
    cancel_refresh(zone);
12651
0
    return;
12652
0
  }
12653
12654
0
  sq = isc_mem_get(zone->mctx, sizeof(*sq));
12655
0
  *sq = (struct soaquery){ .zone = NULL };
12656
12657
  /* Shows in the statistics channel the duration of the current step. */
12658
0
  zone->xfrintime = isc_time_now();
12659
12660
  /*
12661
   * Attach so that we won't clean up until the event is delivered.
12662
   */
12663
0
  zone_iattach(zone, &sq->zone);
12664
0
  result = isc_ratelimiter_enqueue(dns_g_zonemgr->refreshrl, zone->loop,
12665
0
           soa_query, sq, &sq->rlevent);
12666
0
  if (result != ISC_R_SUCCESS) {
12667
0
    zone_idetach(&sq->zone);
12668
0
    isc_mem_put(zone->mctx, sq, sizeof(*sq));
12669
0
    cancel_refresh(zone);
12670
0
  }
12671
0
}
12672
12673
static void
12674
0
soa_query(void *arg) {
12675
0
  struct soaquery *sq = (struct soaquery *)arg;
12676
0
  dns_zone_t *zone = sq->zone;
12677
0
  isc_result_t result = ISC_R_FAILURE;
12678
0
  dns_message_t *message = NULL;
12679
0
  isc_netaddr_t primaryip;
12680
0
  dns_tsigkey_t *key = NULL;
12681
0
  dns_transport_t *transport = NULL;
12682
0
  uint32_t options;
12683
0
  bool cancel = true;
12684
0
  bool have_xfrsource = false, reqnsid, reqexpire;
12685
0
  uint16_t udpsize = SEND_BUFFER_SIZE;
12686
0
  isc_sockaddr_t curraddr, sourceaddr, remotesource;
12687
0
  bool do_queue_xfrin = false;
12688
12689
0
  REQUIRE(DNS_ZONE_VALID(zone));
12690
12691
0
  ENTER;
12692
12693
0
  LOCK_ZONE(zone);
12694
0
  if (sq->rlevent->canceled || DNS_ZONE_FLAG(zone, DNS_ZONEFLG_EXITING) ||
12695
0
      zone->view->requestmgr == NULL)
12696
0
  {
12697
0
    if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_EXITING)) {
12698
0
      cancel = false;
12699
0
    }
12700
0
    goto cleanup;
12701
0
  }
12702
12703
0
again:
12704
0
  dns_zone_logc(
12705
0
    zone, DNS_LOGCATEGORY_XFER_IN, ISC_LOG_DEBUG(3),
12706
0
    "soa_query: remote server current address index %d count %d",
12707
0
    zone->primaries.curraddr, zone->primaries.addrcnt);
12708
0
  INSIST(dns_remote_count(&zone->primaries) > 0);
12709
0
  INSIST(!dns_remote_done(&zone->primaries));
12710
12711
0
  remotesource = dns_remote_sourceaddr(&zone->primaries);
12712
0
  sourceaddr = zone_addr_tosockaddr(&zone->sourceaddr);
12713
0
  curraddr = dns_remote_curraddr(&zone->primaries);
12714
0
  isc_netaddr_fromsockaddr(&primaryip, &curraddr);
12715
12716
0
  if (isc_sockaddr_disabled(&curraddr)) {
12717
0
    goto skip_primary;
12718
0
  }
12719
12720
  /*
12721
   * First, look for a tsig key in the primaries statement, then
12722
   * try for a server key.
12723
   */
12724
0
  if (dns_remote_keyname(&zone->primaries) != NULL) {
12725
0
    dns_view_t *view = dns_zone_getview(zone);
12726
0
    dns_name_t *keyname = dns_remote_keyname(&zone->primaries);
12727
0
    result = dns_view_gettsig(view, keyname, &key);
12728
0
    if (result != ISC_R_SUCCESS) {
12729
0
      char namebuf[DNS_NAME_FORMATSIZE];
12730
0
      dns_name_format(keyname, namebuf, sizeof(namebuf));
12731
0
      dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN,
12732
0
              ISC_LOG_ERROR, "unable to find key: %s",
12733
0
              namebuf);
12734
0
      goto skip_primary;
12735
0
    }
12736
0
  }
12737
0
  if (key == NULL) {
12738
0
    result = dns_view_getpeertsig(zone->view, &primaryip, &key);
12739
0
    if (result != ISC_R_SUCCESS && result != ISC_R_NOTFOUND) {
12740
0
      char addrbuf[ISC_NETADDR_FORMATSIZE];
12741
0
      isc_netaddr_format(&primaryip, addrbuf,
12742
0
             sizeof(addrbuf));
12743
0
      dns_zone_logc(
12744
0
        zone, DNS_LOGCATEGORY_XFER_IN, ISC_LOG_ERROR,
12745
0
        "unable to find TSIG key for %s", addrbuf);
12746
0
      goto skip_primary;
12747
0
    }
12748
0
  }
12749
12750
0
  if (dns_remote_tlsname(&zone->primaries) != NULL) {
12751
0
    dns_view_t *view = dns_zone_getview(zone);
12752
0
    dns_name_t *tlsname = dns_remote_tlsname(&zone->primaries);
12753
0
    result = dns_view_gettransport(view, DNS_TRANSPORT_TLS, tlsname,
12754
0
                 &transport);
12755
0
    if (result != ISC_R_SUCCESS) {
12756
0
      char namebuf[DNS_NAME_FORMATSIZE];
12757
0
      dns_name_format(tlsname, namebuf, sizeof(namebuf));
12758
0
      dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN,
12759
0
              ISC_LOG_ERROR,
12760
0
              "unable to find TLS configuration: %s",
12761
0
              namebuf);
12762
0
      goto skip_primary;
12763
0
    }
12764
0
  }
12765
12766
0
  options = DNS_ZONE_FLAG(zone, DNS_ZONEFLG_USEVC) ? DNS_REQUESTOPT_TCP
12767
0
               : 0;
12768
0
  reqnsid = zone->view->requestnsid;
12769
0
  reqexpire = zone->requestexpire;
12770
0
  if (zone->view->peers != NULL) {
12771
0
    dns_peer_t *peer = NULL;
12772
0
    bool edns, usetcp;
12773
0
    result = dns_peerlist_peerbyaddr(zone->view->peers, &primaryip,
12774
0
             &peer);
12775
0
    if (result == ISC_R_SUCCESS) {
12776
0
      result = dns_peer_getsupportedns(peer, &edns);
12777
0
      if (result == ISC_R_SUCCESS && !edns) {
12778
0
        DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_NOEDNS);
12779
0
      }
12780
0
      result = dns_peer_gettransfersource(peer, &sourceaddr);
12781
0
      if (result == ISC_R_SUCCESS) {
12782
0
        have_xfrsource = true;
12783
0
      }
12784
0
      udpsize = dns_view_getudpsize(zone->view);
12785
0
      (void)dns_peer_getudpsize(peer, &udpsize);
12786
0
      (void)dns_peer_getrequestnsid(peer, &reqnsid);
12787
0
      (void)dns_peer_getrequestexpire(peer, &reqexpire);
12788
0
      result = dns_peer_getforcetcp(peer, &usetcp);
12789
0
      if (result == ISC_R_SUCCESS && usetcp) {
12790
0
        options |= DNS_REQUESTOPT_TCP;
12791
0
      }
12792
0
    }
12793
0
  }
12794
12795
0
  switch (isc_sockaddr_pf(&curraddr)) {
12796
0
  case PF_INET:
12797
0
    if (!have_xfrsource) {
12798
0
      isc_sockaddr_t any;
12799
0
      isc_sockaddr_any(&any);
12800
12801
0
      sourceaddr = remotesource;
12802
0
      if (isc_sockaddr_equal(&sourceaddr, &any)) {
12803
0
        sourceaddr = zone_addr4_tosockaddr(
12804
0
          &zone->xfrsource4);
12805
0
      }
12806
0
    }
12807
0
    break;
12808
0
  case PF_INET6:
12809
0
    if (!have_xfrsource) {
12810
0
      isc_sockaddr_t any;
12811
0
      isc_sockaddr_any6(&any);
12812
12813
0
      sourceaddr = remotesource;
12814
0
      if (isc_sockaddr_equal(&sourceaddr, &any)) {
12815
0
        sourceaddr = zone_addr6_tosockaddr(
12816
0
          &zone->xfrsource6);
12817
0
      }
12818
0
    }
12819
0
    break;
12820
0
  default:
12821
0
    CLEANUP(ISC_R_NOTIMPLEMENTED);
12822
0
  }
12823
0
  zone->sourceaddr = zone_addr_fromsockaddr(&sourceaddr);
12824
12825
  /*
12826
   * FIXME(OS): This is a bit hackish, but it enforces the SOA query to go
12827
   * through the XFR channel instead of doing dns_request that doesn't
12828
   * have DoT support yet.
12829
   */
12830
0
  if (transport != NULL) {
12831
0
    DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_SOABEFOREAXFR);
12832
0
    do_queue_xfrin = true;
12833
0
    cancel = false;
12834
0
    result = ISC_R_SUCCESS;
12835
0
    goto cleanup;
12836
0
  }
12837
12838
0
  create_query(zone, dns_rdatatype_soa, &zone->origin, &message);
12839
12840
0
  if (!DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NOEDNS)) {
12841
0
    result = add_opt(message, udpsize, reqnsid, reqexpire);
12842
0
    if (result != ISC_R_SUCCESS) {
12843
0
      zone_debuglogc(zone, DNS_LOGCATEGORY_XFER_IN, __func__,
12844
0
               1, "unable to add opt record: %s",
12845
0
               isc_result_totext(result));
12846
0
    }
12847
0
  }
12848
12849
0
  zone_iattach(zone, &(dns_zone_t *){ NULL });
12850
0
  const unsigned int connect_timeout = isc_nm_getprimariestimeout() /
12851
0
               MS_PER_SEC;
12852
0
  result = dns_request_create(
12853
0
    zone->view->requestmgr, message, &sourceaddr, &curraddr, NULL,
12854
0
    NULL, options, key, connect_timeout, TCP_REQUEST_TIMEOUT,
12855
0
    UDP_REQUEST_TIMEOUT, UDP_REQUEST_RETRIES, zone->loop,
12856
0
    refresh_callback, zone, &zone->request);
12857
0
  if (result != ISC_R_SUCCESS) {
12858
0
    zone_idetach(&(dns_zone_t *){ zone });
12859
0
    zone_debuglogc(zone, DNS_LOGCATEGORY_XFER_IN, __func__, 1,
12860
0
             "dns_request_create() failed: %s",
12861
0
             isc_result_totext(result));
12862
0
    goto skip_primary;
12863
0
  } else {
12864
    /* Shows in the statistics channel the duration of the query. */
12865
0
    zone->xfrintime = isc_time_now();
12866
12867
0
    if (isc_sockaddr_pf(&curraddr) == PF_INET) {
12868
0
      dns__zone_stats_increment(
12869
0
        zone, dns_zonestatscounter_soaoutv4);
12870
0
    } else {
12871
0
      dns__zone_stats_increment(
12872
0
        zone, dns_zonestatscounter_soaoutv6);
12873
0
    }
12874
0
  }
12875
0
  cancel = false;
12876
0
cleanup:
12877
0
  if (transport != NULL) {
12878
0
    dns_transport_detach(&transport);
12879
0
  }
12880
0
  if (key != NULL) {
12881
0
    dns_tsigkey_detach(&key);
12882
0
  }
12883
0
  if (result != ISC_R_SUCCESS) {
12884
0
    DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_REFRESH);
12885
0
  }
12886
0
  if (message != NULL) {
12887
0
    dns_message_detach(&message);
12888
0
  }
12889
0
  if (cancel) {
12890
0
    cancel_refresh(zone);
12891
0
  }
12892
0
  if (do_queue_xfrin) {
12893
    /* Shows in the statistics channel the duration of the step. */
12894
0
    zone->xfrintime = isc_time_now();
12895
0
  }
12896
0
  UNLOCK_ZONE(zone);
12897
0
  if (do_queue_xfrin) {
12898
0
    queue_xfrin(zone);
12899
0
  }
12900
0
  isc_rlevent_free(&sq->rlevent);
12901
0
  isc_mem_put(zone->mctx, sq, sizeof(*sq));
12902
0
  dns_zone_idetach(&zone);
12903
0
  return;
12904
12905
0
skip_primary:
12906
0
  if (transport != NULL) {
12907
0
    dns_transport_detach(&transport);
12908
0
  }
12909
0
  if (key != NULL) {
12910
0
    dns_tsigkey_detach(&key);
12911
0
  }
12912
0
  if (message != NULL) {
12913
0
    dns_message_detach(&message);
12914
0
  }
12915
  /*
12916
   * Skip to next failed / untried primary.
12917
   */
12918
0
  dns_remote_next(&zone->primaries, true);
12919
0
  if (!dns_remote_done(&zone->primaries)) {
12920
0
    goto again;
12921
0
  }
12922
0
  dns_remote_reset(&zone->primaries, false);
12923
0
  goto cleanup;
12924
0
}
12925
12926
static void
12927
0
ns_query(dns_zone_t *zone, dns_rdataset_t *soardataset, dns_stub_t *stub) {
12928
0
  isc_result_t result;
12929
0
  dns_message_t *message = NULL;
12930
0
  isc_netaddr_t primaryip;
12931
0
  dns_tsigkey_t *key = NULL;
12932
0
  dns_dbnode_t *node = NULL;
12933
0
  bool have_xfrsource = false;
12934
0
  bool reqnsid;
12935
0
  uint16_t udpsize = SEND_BUFFER_SIZE;
12936
0
  isc_sockaddr_t curraddr, sourceaddr, remotesource;
12937
0
  struct stub_cb_args *cb_args = NULL;
12938
12939
0
  REQUIRE(DNS_ZONE_VALID(zone));
12940
0
  REQUIRE(LOCKED_ZONE(zone));
12941
0
  REQUIRE((soardataset != NULL && stub == NULL) ||
12942
0
    (soardataset == NULL && stub != NULL));
12943
0
  REQUIRE(stub == NULL || DNS_STUB_VALID(stub));
12944
12945
0
  ENTER;
12946
12947
0
  if (stub == NULL) {
12948
0
    stub = isc_mem_get(zone->mctx, sizeof(*stub));
12949
0
    stub->magic = STUB_MAGIC;
12950
0
    stub->mctx = zone->mctx;
12951
0
    stub->zone = NULL;
12952
0
    stub->db = NULL;
12953
0
    stub->version = NULL;
12954
0
    atomic_init(&stub->pending_requests, 0);
12955
12956
    /*
12957
     * Attach so that the zone won't disappear from under us.
12958
     */
12959
0
    zone_iattach(zone, &stub->zone);
12960
12961
    /*
12962
     * If a db exists we will update it, otherwise we create a
12963
     * new one and attach it to the zone once we have the NS
12964
     * RRset and glue.
12965
     */
12966
0
    ZONEDB_LOCK(&zone->dblock, isc_rwlocktype_read);
12967
0
    if (zone->db != NULL) {
12968
0
      dns_db_attach(zone->db, &stub->db);
12969
0
      ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_read);
12970
0
    } else {
12971
0
      ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_read);
12972
12973
0
      INSIST(zone->db_argc >= 1);
12974
0
      result = dns_db_create(zone->mctx, zone->db_argv[0],
12975
0
                 &zone->origin, dns_dbtype_stub,
12976
0
                 zone->rdclass, zone->db_argc - 1,
12977
0
                 zone->db_argv + 1, &stub->db);
12978
0
      if (result != ISC_R_SUCCESS) {
12979
0
        dns_zone_log(zone, ISC_LOG_ERROR,
12980
0
               "refreshing stub: "
12981
0
               "could not create "
12982
0
               "database: %s",
12983
0
               isc_result_totext(result));
12984
0
        goto cleanup;
12985
0
      }
12986
0
      dns_db_setmaxrrperset(stub->db, zone->maxrrperset);
12987
0
      dns_db_setmaxtypepername(stub->db,
12988
0
             zone->maxtypepername);
12989
0
    }
12990
12991
0
    result = dns_db_newversion(stub->db, &stub->version);
12992
0
    if (result != ISC_R_SUCCESS) {
12993
0
      dns_zone_log(zone, ISC_LOG_INFO,
12994
0
             "refreshing stub: "
12995
0
             "dns_db_newversion() failed: %s",
12996
0
             isc_result_totext(result));
12997
0
      goto cleanup;
12998
0
    }
12999
13000
    /*
13001
     * Update SOA record.
13002
     */
13003
0
    result = dns_db_findnode(stub->db, &zone->origin, true, &node);
13004
0
    if (result != ISC_R_SUCCESS) {
13005
0
      dns_zone_log(zone, ISC_LOG_INFO,
13006
0
             "refreshing stub: "
13007
0
             "dns_db_findnode() failed: %s",
13008
0
             isc_result_totext(result));
13009
0
      goto cleanup;
13010
0
    }
13011
13012
0
    result = dns_db_addrdataset(stub->db, node, stub->version, 0,
13013
0
              soardataset, 0, NULL);
13014
0
    dns_db_detachnode(&node);
13015
0
    if (result != ISC_R_SUCCESS) {
13016
0
      dns_zone_log(zone, ISC_LOG_INFO,
13017
0
             "refreshing stub: "
13018
0
             "dns_db_addrdataset() failed: %s",
13019
0
             isc_result_totext(result));
13020
0
      goto cleanup;
13021
0
    }
13022
0
  }
13023
13024
  /*
13025
   * XXX Optimisation: Create message when zone is setup and reuse.
13026
   */
13027
0
  create_query(zone, dns_rdatatype_ns, &zone->origin, &message);
13028
13029
0
  INSIST(dns_remote_count(&zone->primaries) > 0);
13030
0
  INSIST(!dns_remote_done(&zone->primaries));
13031
13032
0
  remotesource = dns_remote_sourceaddr(&zone->primaries);
13033
0
  sourceaddr = zone_addr_tosockaddr(&zone->sourceaddr);
13034
0
  curraddr = dns_remote_curraddr(&zone->primaries);
13035
0
  isc_netaddr_fromsockaddr(&primaryip, &curraddr);
13036
  /*
13037
   * First, look for a tsig key in the primaries statement, then
13038
   * try for a server key.
13039
   */
13040
0
  if (dns_remote_keyname(&zone->primaries) != NULL) {
13041
0
    dns_view_t *view = dns_zone_getview(zone);
13042
0
    dns_name_t *keyname = dns_remote_keyname(&zone->primaries);
13043
0
    result = dns_view_gettsig(view, keyname, &key);
13044
0
    if (result != ISC_R_SUCCESS) {
13045
0
      char namebuf[DNS_NAME_FORMATSIZE];
13046
0
      dns_name_format(keyname, namebuf, sizeof(namebuf));
13047
0
      dns_zone_log(zone, ISC_LOG_ERROR,
13048
0
             "unable to find key: %s", namebuf);
13049
0
    }
13050
0
  }
13051
0
  if (key == NULL) {
13052
0
    (void)dns_view_getpeertsig(zone->view, &primaryip, &key);
13053
0
  }
13054
13055
  /* FIXME(OS): Do we need the transport here too? Most probably yes */
13056
13057
0
  reqnsid = zone->view->requestnsid;
13058
0
  if (zone->view->peers != NULL) {
13059
0
    dns_peer_t *peer = NULL;
13060
0
    bool edns;
13061
0
    result = dns_peerlist_peerbyaddr(zone->view->peers, &primaryip,
13062
0
             &peer);
13063
0
    if (result == ISC_R_SUCCESS) {
13064
0
      result = dns_peer_getsupportedns(peer, &edns);
13065
0
      if (result == ISC_R_SUCCESS && !edns) {
13066
0
        DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_NOEDNS);
13067
0
      }
13068
0
      result = dns_peer_gettransfersource(peer, &sourceaddr);
13069
0
      if (result == ISC_R_SUCCESS) {
13070
0
        have_xfrsource = true;
13071
0
      }
13072
0
      udpsize = dns_view_getudpsize(zone->view);
13073
0
      (void)dns_peer_getudpsize(peer, &udpsize);
13074
0
      (void)dns_peer_getrequestnsid(peer, &reqnsid);
13075
0
    }
13076
0
  }
13077
0
  if (!DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NOEDNS)) {
13078
0
    result = add_opt(message, udpsize, reqnsid, false);
13079
0
    if (result != ISC_R_SUCCESS) {
13080
0
      zone_debuglog(zone, __func__, 1,
13081
0
              "unable to add opt record: %s",
13082
0
              isc_result_totext(result));
13083
0
    }
13084
0
  }
13085
13086
  /*
13087
   * Always use TCP so that we shouldn't truncate in additional section.
13088
   */
13089
0
  switch (isc_sockaddr_pf(&curraddr)) {
13090
0
  case PF_INET:
13091
0
    if (!have_xfrsource) {
13092
0
      isc_sockaddr_t any;
13093
0
      isc_sockaddr_any(&any);
13094
13095
0
      sourceaddr = remotesource;
13096
0
      if (isc_sockaddr_equal(&sourceaddr, &any)) {
13097
0
        sourceaddr = zone_addr4_tosockaddr(
13098
0
          &zone->xfrsource4);
13099
0
      }
13100
0
    }
13101
0
    break;
13102
0
  case PF_INET6:
13103
0
    if (!have_xfrsource) {
13104
0
      isc_sockaddr_t any;
13105
0
      isc_sockaddr_any6(&any);
13106
13107
0
      sourceaddr = remotesource;
13108
0
      if (isc_sockaddr_equal(&sourceaddr, &any)) {
13109
0
        sourceaddr = zone_addr6_tosockaddr(
13110
0
          &zone->xfrsource6);
13111
0
      }
13112
0
    }
13113
0
    break;
13114
0
  default:
13115
0
    result = ISC_R_NOTIMPLEMENTED;
13116
0
    POST(result);
13117
0
    goto cleanup;
13118
0
  }
13119
0
  zone->sourceaddr = zone_addr_fromsockaddr(&sourceaddr);
13120
13121
  /*
13122
   * Save request parameters so we can reuse them later on
13123
   * for resolving missing glue A/AAAA records.
13124
   */
13125
0
  cb_args = isc_mem_get(zone->mctx, sizeof(*cb_args));
13126
0
  cb_args->stub = stub;
13127
0
  cb_args->tsig_key = key;
13128
0
  cb_args->udpsize = udpsize;
13129
0
  cb_args->connect_timeout = isc_nm_getprimariestimeout() / MS_PER_SEC;
13130
0
  cb_args->timeout = TCP_REQUEST_TIMEOUT;
13131
0
  cb_args->reqnsid = reqnsid;
13132
13133
0
  result = dns_request_create(
13134
0
    zone->view->requestmgr, message, &sourceaddr, &curraddr, NULL,
13135
0
    NULL, DNS_REQUESTOPT_TCP, key, cb_args->connect_timeout,
13136
0
    cb_args->timeout, UDP_REQUEST_TIMEOUT, UDP_REQUEST_RETRIES,
13137
0
    zone->loop, stub_callback, cb_args, &zone->request);
13138
0
  if (result != ISC_R_SUCCESS) {
13139
0
    zone_debuglog(zone, __func__, 1,
13140
0
            "dns_request_create() failed: %s",
13141
0
            isc_result_totext(result));
13142
0
    goto cleanup;
13143
0
  }
13144
0
  dns_message_detach(&message);
13145
0
  goto unlock;
13146
13147
0
cleanup:
13148
0
  cancel_refresh(zone);
13149
0
  stub->magic = 0;
13150
0
  if (stub->version != NULL) {
13151
0
    dns_db_closeversion(stub->db, &stub->version, false);
13152
0
  }
13153
0
  if (stub->db != NULL) {
13154
0
    dns_db_detach(&stub->db);
13155
0
  }
13156
0
  if (stub->zone != NULL) {
13157
0
    zone_idetach(&stub->zone);
13158
0
  }
13159
0
  if (cb_args != NULL) {
13160
0
    isc_mem_put(zone->mctx, cb_args, sizeof(*cb_args));
13161
0
  }
13162
0
  isc_mem_put(stub->mctx, stub, sizeof(*stub));
13163
0
  if (message != NULL) {
13164
0
    dns_message_detach(&message);
13165
0
  }
13166
0
unlock:
13167
0
  if (key != NULL) {
13168
0
    dns_tsigkey_detach(&key);
13169
0
  }
13170
0
  return;
13171
0
}
13172
13173
/*
13174
 * Shut the zone down.
13175
 */
13176
static void
13177
0
zone_shutdown(void *arg) {
13178
0
  dns_zone_t *zone = (dns_zone_t *)arg;
13179
0
  bool free_needed, linked = false;
13180
0
  dns_zone_t *raw = NULL, *secure = NULL;
13181
0
  dns_view_t *view = NULL, *prev_view = NULL;
13182
13183
0
  REQUIRE(DNS_ZONE_VALID(zone));
13184
0
  INSIST(isc_refcount_current(&zone->references) == 0);
13185
13186
0
  zone_debuglog(zone, __func__, 3, "shutting down");
13187
13188
  /*
13189
   * If we were waiting for xfrin quota, step out of
13190
   * the queue.
13191
   * A zone without an event loop cannot be waiting for transfer quota.
13192
   */
13193
0
  if (zone->loop != NULL) {
13194
0
    RWLOCK(&dns_g_zonemgr->rwlock, isc_rwlocktype_write);
13195
0
    if (zone->statelist == &dns_g_zonemgr->waiting_for_xfrin) {
13196
0
      ISC_LIST_UNLINK(dns_g_zonemgr->waiting_for_xfrin, zone,
13197
0
          statelink);
13198
0
      linked = true;
13199
0
      zone->statelist = NULL;
13200
0
    }
13201
0
    if (zone->statelist == &dns_g_zonemgr->xfrin_in_progress) {
13202
0
      ISC_LIST_UNLINK(dns_g_zonemgr->xfrin_in_progress, zone,
13203
0
          statelink);
13204
0
      zone->statelist = NULL;
13205
0
      dns__zonemgr_resume_xfrs(dns_g_zonemgr, false);
13206
0
    }
13207
0
    RWUNLOCK(&dns_g_zonemgr->rwlock, isc_rwlocktype_write);
13208
0
  }
13209
13210
  /*
13211
   * In loop context, no locking required.  See dns__zone_xfrdone().
13212
   */
13213
0
  if (zone->xfr != NULL) {
13214
    /* The final detach will happen in dns__zone_xfrdone() */
13215
0
    dns_xfrin_shutdown(zone->xfr);
13216
0
  }
13217
13218
  /* Detach the zone configuration pointer */
13219
0
  dns_zone_setcfg(zone, NULL, NULL);
13220
13221
0
  zone_clear_inline_sync(zone);
13222
13223
0
  LOCK_ZONE(zone);
13224
0
  INSIST(zone != zone->raw);
13225
13226
  /*
13227
   * Detach the views early, we don't need them anymore.  However, we need
13228
   * to detach them outside of the zone lock to break the lock loop
13229
   * between view, adb and zone locks.
13230
   */
13231
0
  view = zone->view;
13232
0
  zone->view = NULL;
13233
0
  prev_view = zone->prev_view;
13234
0
  zone->prev_view = NULL;
13235
13236
0
  if (linked) {
13237
0
    isc_refcount_decrement(&zone->irefs);
13238
0
  }
13239
0
  if (zone->request != NULL) {
13240
0
    dns_request_cancel(zone->request);
13241
0
  }
13242
13243
0
  if (zone->loadctx != NULL) {
13244
0
    dns_loadctx_cancel(zone->loadctx);
13245
0
  }
13246
13247
0
  if (!DNS_ZONE_FLAG(zone, DNS_ZONEFLG_FLUSH) ||
13248
0
      !DNS_ZONE_FLAG(zone, DNS_ZONEFLG_DUMPING))
13249
0
  {
13250
0
    if (zone->dumpctx != NULL) {
13251
0
      dns_dumpctx_cancel(zone->dumpctx);
13252
0
    }
13253
0
  }
13254
13255
0
  checkds_cancel(zone);
13256
13257
0
  dns_notify_cancel(&zone->notifysoa);
13258
0
  dns_notify_cancel(&zone->notifycds);
13259
13260
0
  dns__zone_forward_cancel(zone);
13261
13262
0
  if (zone->timer != NULL) {
13263
0
    isc_refcount_decrement(&zone->irefs);
13264
0
    isc_timer_destroy(&zone->timer);
13265
0
  }
13266
13267
  /*
13268
   * We have now canceled everything set the flag to allow
13269
   * dns__zone_free_check() to succeed. We must not unlock between
13270
   * setting this flag and calling dns__zone_free_check().
13271
   */
13272
0
  DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_SHUTDOWN);
13273
0
  free_needed = dns__zone_free_check(zone);
13274
  /*
13275
   * If a dump is in progress for the secure zone, defer detaching from
13276
   * the raw zone as it may prevent the unsigned serial number from being
13277
   * stored in the raw-format dump of the secure zone.  In this scenario,
13278
   * dump_done() takes care of cleaning up the zone->raw reference.
13279
   */
13280
0
  if (dns__zone_inline_secure(zone) &&
13281
0
      !DNS_ZONE_FLAG(zone, DNS_ZONEFLG_DUMPING))
13282
0
  {
13283
0
    raw = zone->raw;
13284
0
    zone->raw = NULL;
13285
0
  }
13286
0
  if (dns__zone_inline_raw(zone)) {
13287
0
    secure = zone->secure;
13288
0
    zone->secure = NULL;
13289
0
  }
13290
0
  UNLOCK_ZONE(zone);
13291
13292
0
  if (view != NULL) {
13293
0
    dns_view_weakdetach(&view);
13294
0
  }
13295
0
  if (prev_view != NULL) {
13296
0
    dns_view_weakdetach(&prev_view);
13297
0
  }
13298
13299
0
  if (raw != NULL) {
13300
0
    dns_zone_detach(&raw);
13301
0
  }
13302
0
  if (secure != NULL) {
13303
0
    dns_zone_idetach(&secure);
13304
0
  }
13305
0
  if (free_needed) {
13306
0
    dns__zone_free(zone);
13307
0
  }
13308
0
}
13309
13310
static void
13311
0
zone_timer(void *arg) {
13312
0
  dns_zone_t *zone = (dns_zone_t *)arg;
13313
13314
0
  REQUIRE(DNS_ZONE_VALID(zone));
13315
13316
0
  zone_maintenance(zone);
13317
0
}
13318
13319
static void
13320
0
zone_timer_stop(dns_zone_t *zone) {
13321
0
  zone_debuglog(zone, __func__, 10, "stop zone timer");
13322
0
  if (zone->timer != NULL) {
13323
0
    isc_timer_stop(zone->timer);
13324
0
  }
13325
0
}
13326
13327
static void
13328
0
zone_timer_set(dns_zone_t *zone, isc_time_t *next, isc_time_t *now) {
13329
0
  isc_interval_t interval;
13330
13331
0
  if (isc_time_compare(next, now) <= 0) {
13332
0
    isc_interval_set(&interval, 0, 0);
13333
0
  } else {
13334
0
    isc_time_subtract(next, now, &interval);
13335
0
  }
13336
13337
0
  if (zone->loop == NULL) {
13338
0
    zone_debuglog(zone, __func__, 10, "zone is not managed");
13339
0
  } else if (zone->timer == NULL) {
13340
0
    isc_refcount_increment0(&zone->irefs);
13341
0
    isc_timer_create(zone->loop, zone_timer, zone, &zone->timer);
13342
0
  }
13343
0
  if (zone->timer != NULL) {
13344
0
    isc_timer_start(zone->timer, isc_timertype_once, &interval);
13345
0
  }
13346
0
}
13347
13348
static void
13349
0
zone__settimer(void *arg) {
13350
0
  zone_settimer_t *data = arg;
13351
0
  dns_zone_t *zone = data->zone;
13352
0
  isc_time_t now = data->now;
13353
0
  isc_time_t next;
13354
0
  bool free_needed = false;
13355
13356
0
  REQUIRE(DNS_ZONE_VALID(zone));
13357
0
  ENTER;
13358
13359
0
  LOCK_ZONE(zone);
13360
0
  if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_EXITING)) {
13361
0
    goto free;
13362
0
  }
13363
0
  isc_time_settoepoch(&next);
13364
13365
0
  switch (zone->type) {
13366
0
  case dns_zone_redirect:
13367
0
    if (dns_remote_addresses(&zone->primaries) != NULL) {
13368
0
      goto treat_as_secondary;
13369
0
    }
13370
0
    FALLTHROUGH;
13371
0
  case dns_zone_primary:
13372
0
    if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NEEDNOTIFY) ||
13373
0
        DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NEEDSTARTUPNOTIFY))
13374
0
    {
13375
0
      next = zone->notifytime;
13376
0
    }
13377
0
    if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NEEDDUMP) &&
13378
0
        !DNS_ZONE_FLAG(zone, DNS_ZONEFLG_DUMPING))
13379
0
    {
13380
0
      INSIST(!isc_time_isepoch(&zone->dumptime));
13381
0
      next = time_min(next, zone->dumptime);
13382
0
    }
13383
0
    if (zone->type == dns_zone_redirect) {
13384
0
      break;
13385
0
    }
13386
0
    if (!DNS_ZONE_FLAG(zone, DNS_ZONEFLG_REFRESHING)) {
13387
0
      next = time_min(next, zone->refreshkeytime);
13388
0
    }
13389
0
    next = time_min(next, zone->resigntime);
13390
0
    next = time_min(next, zone->keywarntime);
13391
0
    next = time_min(next, zone->signingtime);
13392
0
    if (zone_inline_sync_pending(zone)) {
13393
0
      next = time_min(next, now);
13394
0
    }
13395
0
    if (zone_maintenance_request_pending(zone)) {
13396
0
      next = time_min(next, now);
13397
0
    }
13398
0
    next = time_min(next, zone->nsec3chaintime);
13399
0
    break;
13400
13401
0
  case dns_zone_secondary:
13402
0
  case dns_zone_mirror:
13403
0
  treat_as_secondary:
13404
0
    if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NEEDNOTIFY) ||
13405
0
        DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NEEDSTARTUPNOTIFY))
13406
0
    {
13407
0
      next = zone->notifytime;
13408
0
    }
13409
0
    FALLTHROUGH;
13410
0
  case dns_zone_stub:
13411
0
    if (!DNS_ZONE_FLAG(zone, DNS_ZONEFLG_REFRESH) &&
13412
0
        !DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NOPRIMARIES) &&
13413
0
        !DNS_ZONE_FLAG(zone, DNS_ZONEFLG_LOADING) &&
13414
0
        !DNS_ZONE_FLAG(zone, DNS_ZONEFLG_LOADPENDING))
13415
0
    {
13416
0
      next = time_min(next, zone->refreshtime);
13417
0
    }
13418
0
    if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_LOADED)) {
13419
0
      next = time_min(next, zone->expiretime);
13420
0
    }
13421
0
    if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NEEDDUMP) &&
13422
0
        !DNS_ZONE_FLAG(zone, DNS_ZONEFLG_DUMPING))
13423
0
    {
13424
0
      INSIST(!isc_time_isepoch(&zone->dumptime));
13425
0
      next = time_min(next, zone->dumptime);
13426
0
    }
13427
0
    break;
13428
13429
0
  case dns_zone_key:
13430
0
    if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NEEDDUMP) &&
13431
0
        !DNS_ZONE_FLAG(zone, DNS_ZONEFLG_DUMPING))
13432
0
    {
13433
0
      INSIST(!isc_time_isepoch(&zone->dumptime));
13434
0
      next = time_min(next, zone->dumptime);
13435
0
    }
13436
0
    if (!DNS_ZONE_FLAG(zone, DNS_ZONEFLG_REFRESHING)) {
13437
0
      next = time_min(next, zone->refreshkeytime);
13438
0
    }
13439
0
    break;
13440
13441
0
  default:
13442
0
    break;
13443
0
  }
13444
13445
0
  if (isc_time_isepoch(&next)) {
13446
0
    zone_timer_stop(zone);
13447
0
  } else {
13448
0
    zone_timer_set(zone, &next, &now);
13449
0
  }
13450
13451
0
free:
13452
0
  isc_mem_put(zone->mctx, data, sizeof(*data));
13453
0
  isc_refcount_decrement(&zone->irefs);
13454
0
  free_needed = dns__zone_free_check(zone);
13455
0
  UNLOCK_ZONE(zone);
13456
0
  if (free_needed) {
13457
0
    dns__zone_free(zone);
13458
0
  }
13459
0
}
13460
13461
void
13462
0
dns__zone_settimer(dns_zone_t *zone, isc_time_t now) {
13463
0
  if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_EXITING)) {
13464
0
    return;
13465
0
  }
13466
13467
0
  zone_settimer_t *arg = isc_mem_get(zone->mctx, sizeof(*arg));
13468
0
  *arg = (zone_settimer_t){
13469
0
    .zone = zone,
13470
0
    .now = now,
13471
0
  };
13472
0
  isc_refcount_increment0(&zone->irefs);
13473
0
  isc_async_run(zone->loop, zone__settimer, arg);
13474
0
}
13475
13476
static void
13477
0
cancel_refresh(dns_zone_t *zone) {
13478
  /*
13479
   * 'zone' locked by caller.
13480
   */
13481
13482
0
  REQUIRE(DNS_ZONE_VALID(zone));
13483
0
  REQUIRE(LOCKED_ZONE(zone));
13484
13485
0
  ENTER;
13486
13487
0
  DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_REFRESH);
13488
0
  dns__zone_settimer(zone, isc_time_now());
13489
0
}
13490
13491
isc_result_t
13492
dns_zone_notifyreceive(dns_zone_t *zone, isc_sockaddr_t *from,
13493
0
           isc_sockaddr_t *to, dns_message_t *msg) {
13494
0
  unsigned int i;
13495
0
  dns_rdata_soa_t soa;
13496
0
  dns_rdataset_t *rdataset = NULL;
13497
0
  dns_rdata_t rdata = DNS_RDATA_INIT;
13498
0
  isc_result_t result;
13499
0
  char fromtext[ISC_SOCKADDR_FORMATSIZE];
13500
0
  int match = 0;
13501
0
  isc_netaddr_t netaddr;
13502
0
  uint32_t serial = 0;
13503
0
  bool have_serial = false;
13504
0
  dns_tsigkey_t *tsigkey;
13505
0
  const dns_name_t *tsig;
13506
13507
0
  REQUIRE(DNS_ZONE_VALID(zone));
13508
13509
  /*
13510
   * If type != T_SOA return DNS_R_NOTIMP.  We don't yet support
13511
   * ROLLOVER.
13512
   *
13513
   * SOA: RFC1996
13514
   * Check that 'from' is a valid notify source, (zone->primaries).
13515
   *  Return DNS_R_REFUSED if not.
13516
   *
13517
   * If the notify message contains a serial number check it
13518
   * against the zones serial and return if <= current serial
13519
   *
13520
   * If a refresh check is progress, if so just record the
13521
   * fact we received a NOTIFY and from where and return.
13522
   * We will perform a new refresh check when the current one
13523
   * completes. Return ISC_R_SUCCESS.
13524
   *
13525
   * Otherwise initiate a refresh check using 'from' as the
13526
   * first address to check.  Return ISC_R_SUCCESS.
13527
   */
13528
13529
0
  isc_sockaddr_format(from, fromtext, sizeof(fromtext));
13530
13531
  /*
13532
   * Notify messages are processed by the raw zone.
13533
   */
13534
0
  LOCK_ZONE(zone);
13535
0
  INSIST(zone != zone->raw);
13536
0
  if (dns__zone_inline_secure(zone)) {
13537
0
    result = dns_zone_notifyreceive(zone->raw, from, to, msg);
13538
0
    UNLOCK_ZONE(zone);
13539
0
    return result;
13540
0
  }
13541
  /*
13542
   *  We only handle NOTIFY (SOA) at the present.
13543
   */
13544
0
  if (isc_sockaddr_pf(from) == PF_INET) {
13545
0
    dns__zone_stats_increment(zone,
13546
0
            dns_zonestatscounter_notifyinv4);
13547
0
  } else {
13548
0
    dns__zone_stats_increment(zone,
13549
0
            dns_zonestatscounter_notifyinv6);
13550
0
  }
13551
0
  if (msg->counts[DNS_SECTION_QUESTION] == 0 ||
13552
0
      dns_message_findname(msg, DNS_SECTION_QUESTION, &zone->origin,
13553
0
         dns_rdatatype_soa, dns_rdatatype_none, NULL,
13554
0
         NULL) != ISC_R_SUCCESS)
13555
0
  {
13556
0
    UNLOCK_ZONE(zone);
13557
0
    if (msg->counts[DNS_SECTION_QUESTION] == 0) {
13558
0
      dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN,
13559
0
              ISC_LOG_NOTICE,
13560
0
              "NOTIFY with no question "
13561
0
              "section from: %s",
13562
0
              fromtext);
13563
0
      return DNS_R_FORMERR;
13564
0
    }
13565
0
    dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN, ISC_LOG_NOTICE,
13566
0
            "NOTIFY zone does not match");
13567
0
    return DNS_R_NOTIMP;
13568
0
  }
13569
13570
  /*
13571
   * If we are a primary zone just succeed.
13572
   */
13573
0
  if (zone->type == dns_zone_primary) {
13574
0
    UNLOCK_ZONE(zone);
13575
0
    return ISC_R_SUCCESS;
13576
0
  }
13577
13578
0
  isc_netaddr_fromsockaddr(&netaddr, from);
13579
0
  for (i = 0; i < dns_remote_count(&zone->primaries); i++) {
13580
0
    isc_sockaddr_t sockaddr = dns_remote_addr(&zone->primaries, i);
13581
0
    if (isc_sockaddr_eqaddr(from, &sockaddr)) {
13582
0
      break;
13583
0
    }
13584
0
    if (zone->view->aclenv->match_mapped &&
13585
0
        IN6_IS_ADDR_V4MAPPED(&from->type.sin6.sin6_addr) &&
13586
0
        isc_sockaddr_pf(&sockaddr) == AF_INET)
13587
0
    {
13588
0
      isc_netaddr_t na1, na2;
13589
0
      isc_netaddr_fromv4mapped(&na1, &netaddr);
13590
0
      isc_netaddr_fromsockaddr(&na2, &sockaddr);
13591
0
      if (isc_netaddr_equal(&na1, &na2)) {
13592
0
        break;
13593
0
      }
13594
0
    }
13595
0
  }
13596
13597
  /*
13598
   * Accept notify requests from non primaries if they are on
13599
   * 'zone->notifysoa.notify_acl'.
13600
   */
13601
0
  tsigkey = dns_message_gettsigkey(msg);
13602
0
  tsig = dns_tsigkey_identity(tsigkey);
13603
0
  if (i >= dns_remote_count(&zone->primaries) &&
13604
0
      zone->notifysoa.notify_acl != NULL &&
13605
0
      (dns_acl_match(&netaddr, tsig, zone->notifysoa.notify_acl,
13606
0
         zone->view->aclenv, &match,
13607
0
         NULL) == ISC_R_SUCCESS) &&
13608
0
      match > 0)
13609
0
  {
13610
    /* Accept notify. */
13611
0
  } else if (i >= dns_remote_count(&zone->primaries)) {
13612
0
    dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN, ISC_LOG_INFO,
13613
0
            "refused notify from non-primary: %s", fromtext);
13614
0
    dns__zone_stats_increment(zone, dns_zonestatscounter_notifyrej);
13615
0
    UNLOCK_ZONE(zone);
13616
0
    return DNS_R_REFUSED;
13617
0
  }
13618
13619
  /*
13620
   * If the zone is loaded and there are answers check the serial
13621
   * to see if we need to do a refresh.
13622
   */
13623
0
  if (msg->counts[DNS_SECTION_ANSWER] > 0 &&
13624
0
      DNS_ZONE_FLAG(zone, DNS_ZONEFLG_LOADED))
13625
0
  {
13626
0
    result = dns_message_findname(
13627
0
      msg, DNS_SECTION_ANSWER, &zone->origin,
13628
0
      dns_rdatatype_soa, dns_rdatatype_none, NULL, &rdataset);
13629
0
    if (result == ISC_R_SUCCESS) {
13630
0
      result = dns_rdataset_first(rdataset);
13631
0
    }
13632
0
    if (result == ISC_R_SUCCESS) {
13633
0
      uint32_t oldserial;
13634
0
      unsigned int soacount;
13635
13636
0
      dns_rdataset_current(rdataset, &rdata);
13637
0
      result = dns_rdata_tostruct(&rdata, &soa);
13638
0
      RUNTIME_CHECK(result == ISC_R_SUCCESS);
13639
0
      serial = soa.serial;
13640
0
      have_serial = true;
13641
      /*
13642
       * The following should safely be performed without DB
13643
       * lock and succeed in this context.
13644
       */
13645
0
      result = zone_get_from_db(zone, zone->db, NULL,
13646
0
              &soacount, NULL, &oldserial,
13647
0
              NULL, NULL, NULL, NULL, NULL);
13648
0
      RUNTIME_CHECK(result == ISC_R_SUCCESS);
13649
0
      RUNTIME_CHECK(soacount > 0U);
13650
0
      if (isc_serial_le(serial, oldserial)) {
13651
0
        dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN,
13652
0
                ISC_LOG_INFO,
13653
0
                "notify from %s: "
13654
0
                "zone is up to date",
13655
0
                fromtext);
13656
0
        UNLOCK_ZONE(zone);
13657
0
        return ISC_R_SUCCESS;
13658
0
      }
13659
0
    }
13660
0
  }
13661
13662
  /*
13663
   * If we got this far and there was a refresh in progress just
13664
   * let it complete.  Record where we got the notify from so we
13665
   * can perform a refresh check when the current one completes
13666
   */
13667
0
  if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_REFRESH)) {
13668
0
    DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_NEEDREFRESH);
13669
0
    UNLOCK_ZONE(zone);
13670
0
    if (have_serial) {
13671
0
      dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN,
13672
0
              ISC_LOG_INFO,
13673
0
              "notify from %s: "
13674
0
              "serial %u: refresh in progress, "
13675
0
              "refresh check queued",
13676
0
              fromtext, serial);
13677
0
    } else {
13678
0
      dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN,
13679
0
              ISC_LOG_INFO,
13680
0
              "notify from %s: "
13681
0
              "refresh in progress, "
13682
0
              "refresh check queued",
13683
0
              fromtext);
13684
0
    }
13685
0
    return ISC_R_SUCCESS;
13686
0
  }
13687
0
  if (have_serial) {
13688
0
    dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN, ISC_LOG_INFO,
13689
0
            "notify from %s: serial %u", fromtext, serial);
13690
0
  } else {
13691
0
    dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN, ISC_LOG_INFO,
13692
0
            "notify from %s: no serial", fromtext);
13693
0
  }
13694
0
  UNLOCK_ZONE(zone);
13695
13696
0
  if (to != NULL) {
13697
0
    dns_unreachcache_remove(zone->view->unreachcache, from, to);
13698
0
  }
13699
0
  dns_zone_refresh(zone);
13700
0
  return ISC_R_SUCCESS;
13701
0
}
13702
13703
void
13704
dns_zone_logv(dns_zone_t *zone, isc_logcategory_t category, int level,
13705
0
        const char *prefix, const char *fmt, va_list ap) {
13706
0
  char message[4096];
13707
0
  char namebuf[1024];
13708
0
  const char *zstr;
13709
13710
0
  REQUIRE(DNS_ZONE_VALID(zone));
13711
13712
0
  if (!isc_log_wouldlog(level)) {
13713
0
    return;
13714
0
  }
13715
13716
0
  zone_namerd_tostr(zone, namebuf, sizeof(namebuf));
13717
0
  vsnprintf(message, sizeof(message), fmt, ap);
13718
13719
0
  switch (zone->type) {
13720
0
  case dns_zone_key:
13721
0
    zstr = "managed-keys-zone";
13722
0
    break;
13723
0
  case dns_zone_redirect:
13724
0
    zstr = "redirect-zone";
13725
0
    break;
13726
0
  default:
13727
0
    zstr = "zone ";
13728
0
  }
13729
13730
0
  isc_log_write(category, DNS_LOGMODULE_ZONE, level, "%s%s%s%s: %s",
13731
0
          prefix != NULL ? prefix : "", prefix != NULL ? ": " : "",
13732
0
          zstr, namebuf, message);
13733
0
}
13734
13735
void
13736
dns_zone_logc(dns_zone_t *zone, isc_logcategory_t category, int level,
13737
0
        const char *fmt, ...) {
13738
0
  va_list ap;
13739
13740
0
  va_start(ap, fmt);
13741
0
  dns_zone_logv(zone, category, level, NULL, fmt, ap);
13742
0
  va_end(ap);
13743
0
}
13744
13745
void
13746
0
dns_zone_log(dns_zone_t *zone, int level, const char *fmt, ...) {
13747
0
  va_list ap;
13748
13749
0
  va_start(ap, fmt);
13750
0
  dns_zone_logv(zone, DNS_LOGCATEGORY_GENERAL, level, NULL, fmt, ap);
13751
0
  va_end(ap);
13752
0
}
13753
13754
static void
13755
zone_debuglogc(dns_zone_t *zone, isc_logcategory_t category, const char *me,
13756
0
         int debuglevel, const char *fmt, ...) {
13757
0
  int level = ISC_LOG_DEBUG(debuglevel);
13758
0
  va_list ap;
13759
13760
0
  va_start(ap, fmt);
13761
0
  dns_zone_logv(zone, category, level, me, fmt, ap);
13762
0
  va_end(ap);
13763
0
}
13764
13765
static void
13766
zone_debuglog(dns_zone_t *zone, const char *me, int debuglevel, const char *fmt,
13767
0
        ...) {
13768
0
  int level = ISC_LOG_DEBUG(debuglevel);
13769
0
  va_list ap;
13770
13771
0
  va_start(ap, fmt);
13772
0
  dns_zone_logv(zone, DNS_LOGCATEGORY_GENERAL, level, me, fmt, ap);
13773
0
  va_end(ap);
13774
0
}
13775
13776
static void
13777
0
dnssec_log(dns_zone_t *zone, int level, const char *fmt, ...) {
13778
0
  va_list ap;
13779
13780
0
  va_start(ap, fmt);
13781
0
  dns_zone_logv(zone, DNS_LOGCATEGORY_DNSSEC, level, NULL, fmt, ap);
13782
0
  va_end(ap);
13783
0
}
13784
13785
static int
13786
0
message_count(dns_message_t *msg, dns_section_t section, dns_rdatatype_t type) {
13787
0
  int count = 0;
13788
13789
0
  MSG_SECTION_FOREACH(msg, section, name) {
13790
0
    ISC_LIST_FOREACH_REV(name->list, curr, link) {
13791
0
      if (curr->type == type) {
13792
0
        count++;
13793
0
      }
13794
0
    }
13795
0
  }
13796
13797
0
  return count;
13798
0
}
13799
13800
const char *
13801
0
dns_zonetype_name(dns_zonetype_t type) {
13802
0
  switch (type) {
13803
0
  case dns_zone_none:
13804
0
    return "none";
13805
0
  case dns_zone_primary:
13806
0
    return "primary";
13807
0
  case dns_zone_secondary:
13808
0
    return "secondary";
13809
0
  case dns_zone_mirror:
13810
0
    return "mirror";
13811
0
  case dns_zone_stub:
13812
0
    return "stub";
13813
0
  case dns_zone_staticstub:
13814
0
    return "static-stub";
13815
0
  case dns_zone_key:
13816
0
    return "key";
13817
0
  case dns_zone_dlz:
13818
0
    return "dlz";
13819
0
  case dns_zone_redirect:
13820
0
    return "redirect";
13821
0
  default:
13822
0
    return "unknown";
13823
0
  }
13824
0
}
13825
13826
dns_zonetype_t
13827
0
dns_zone_getredirecttype(dns_zone_t *zone) {
13828
0
  REQUIRE(DNS_ZONE_VALID(zone));
13829
0
  REQUIRE(zone->type == dns_zone_redirect);
13830
13831
0
  return dns_remote_addresses(&zone->primaries) == NULL
13832
0
           ? dns_zone_primary
13833
0
           : dns_zone_secondary;
13834
0
}
13835
13836
dns_notifyctx_t *
13837
0
dns__zone_getnotifyctx(dns_zone_t *zone, dns_rdatatype_t type) {
13838
0
  REQUIRE(DNS_ZONE_VALID(zone));
13839
13840
0
  switch (type) {
13841
0
  case dns_rdatatype_soa:
13842
0
    return &zone->notifysoa;
13843
0
  case dns_rdatatype_cds:
13844
0
    return &zone->notifycds;
13845
0
  default:
13846
0
    UNREACHABLE();
13847
0
  }
13848
0
  return NULL;
13849
0
}
13850
13851
void
13852
0
dns__zone_stats_increment(dns_zone_t *zone, isc_statscounter_t counter) {
13853
0
  REQUIRE(DNS_ZONE_VALID(zone));
13854
0
  REQUIRE(LOCKED_ZONE(zone));
13855
0
  inc_stats(zone, counter);
13856
0
}
13857
13858
void
13859
0
dns__zone_lock(dns_zone_t *zone) {
13860
0
  REQUIRE(DNS_ZONE_VALID(zone));
13861
0
  LOCK_ZONE(zone);
13862
0
}
13863
13864
void
13865
0
dns__zone_unlock(dns_zone_t *zone) {
13866
0
  REQUIRE(DNS_ZONE_VALID(zone));
13867
0
  UNLOCK_ZONE(zone);
13868
0
}
13869
13870
bool
13871
0
dns__zone_locked(dns_zone_t *zone) {
13872
0
  REQUIRE(DNS_ZONE_VALID(zone));
13873
0
  return LOCKED_ZONE(zone);
13874
0
}
13875
13876
bool
13877
0
dns__zone_loaded(dns_zone_t *zone) {
13878
0
  REQUIRE(DNS_ZONE_VALID(zone));
13879
0
  return DNS_ZONE_FLAG(zone, DNS_ZONEFLG_LOADED) != 0;
13880
0
}
13881
13882
bool
13883
0
dns__zone_exiting(dns_zone_t *zone) {
13884
0
  REQUIRE(DNS_ZONE_VALID(zone));
13885
0
  return DNS_ZONE_FLAG(zone, DNS_ZONEFLG_EXITING) != 0;
13886
0
}
13887
13888
static void
13889
0
update_log_cb(void *arg, dns_zone_t *zone, int level, const char *message) {
13890
0
  UNUSED(arg);
13891
0
  dns_zone_log(zone, level, "%s", message);
13892
0
}
13893
13894
static isc_result_t
13895
dnskey_inuse(dns_zone_t *zone, dns_rdata_t *rdata, isc_mem_t *mctx,
13896
0
       dns_dnsseckeylist_t *keylist, bool *inuse) {
13897
0
  isc_result_t result;
13898
0
  dst_key_t *dstkey = NULL;
13899
13900
0
  result = dns_dnssec_keyfromrdata(dns_zone_getorigin(zone), rdata, mctx,
13901
0
           &dstkey);
13902
0
  if (result != ISC_R_SUCCESS) {
13903
0
    dns_zone_log(zone, ISC_LOG_ERROR,
13904
0
           "dns_dnssec_keyfromrdata() failed: %s",
13905
0
           isc_result_totext(result));
13906
0
    return result;
13907
0
  }
13908
13909
0
  ISC_LIST_FOREACH(*keylist, k, link) {
13910
0
    if (dst_key_pubcompare(k->key, dstkey, false)) {
13911
0
      *inuse = true;
13912
0
      break;
13913
0
    }
13914
0
  }
13915
13916
0
  dst_key_free(&dstkey);
13917
0
  return ISC_R_SUCCESS;
13918
0
}
13919
13920
static isc_result_t
13921
cdnskey_inuse(dns_zone_t *zone, dns_rdata_t *rdata,
13922
0
        dns_dnsseckeylist_t *keylist, bool *inuse) {
13923
0
  isc_result_t result;
13924
0
  dns_rdata_cdnskey_t cdnskey;
13925
13926
0
  result = dns_rdata_tostruct(rdata, &cdnskey);
13927
0
  if (result != ISC_R_SUCCESS) {
13928
0
    dns_zone_log(zone, ISC_LOG_ERROR,
13929
0
           "dns_rdata_tostruct(cdnskey) failed: %s",
13930
0
           isc_result_totext(result));
13931
0
    return result;
13932
0
  }
13933
13934
0
  ISC_LIST_FOREACH(*keylist, k, link) {
13935
0
    dns_rdata_t cdnskeyrdata = DNS_RDATA_INIT;
13936
0
    unsigned char keybuf[DNS_RDATA_MAXLENGTH];
13937
13938
0
    result = dns_dnssec_make_dnskey(k->key, keybuf, sizeof(keybuf),
13939
0
            &cdnskeyrdata);
13940
0
    if (result != ISC_R_SUCCESS) {
13941
0
      dns_zone_log(zone, ISC_LOG_ERROR,
13942
0
             "dns_dnssec_make_dnskey() failed: %s",
13943
0
             isc_result_totext(result));
13944
0
      return result;
13945
0
    }
13946
13947
0
    cdnskeyrdata.type = dns_rdatatype_cdnskey;
13948
0
    if (dns_rdata_compare(rdata, &cdnskeyrdata) == 0) {
13949
0
      *inuse = true;
13950
0
      break;
13951
0
    }
13952
0
  }
13953
13954
0
  return ISC_R_SUCCESS;
13955
0
}
13956
13957
static isc_result_t
13958
cds_inuse(dns_zone_t *zone, dns_rdata_t *rdata, dns_dnsseckeylist_t *keylist,
13959
0
    bool *inuse) {
13960
0
  isc_result_t result;
13961
0
  dns_rdata_ds_t cds;
13962
13963
0
  result = dns_rdata_tostruct(rdata, &cds);
13964
0
  if (result != ISC_R_SUCCESS) {
13965
0
    dns_zone_log(zone, ISC_LOG_ERROR,
13966
0
           "dns_rdata_tostruct(cds) failed: %s",
13967
0
           isc_result_totext(result));
13968
0
    return result;
13969
0
  }
13970
13971
0
  ISC_LIST_FOREACH(*keylist, k, link) {
13972
0
    dns_rdata_t dnskey = DNS_RDATA_INIT;
13973
0
    dns_rdata_t cdsrdata = DNS_RDATA_INIT;
13974
0
    unsigned char keybuf[DNS_RDATA_MAXLENGTH];
13975
0
    unsigned char cdsbuf[DNS_DS_BUFFERSIZE];
13976
13977
0
    if (dst_key_id(k->key) != cds.key_tag ||
13978
0
        dst_algorithm_tosecalg(dst_key_alg(k->key)) !=
13979
0
          cds.algorithm)
13980
0
    {
13981
0
      continue;
13982
0
    }
13983
0
    result = dns_dnssec_make_dnskey(k->key, keybuf, sizeof(keybuf),
13984
0
            &dnskey);
13985
0
    if (result != ISC_R_SUCCESS) {
13986
0
      dns_zone_log(zone, ISC_LOG_ERROR,
13987
0
             "dns_dnssec_make_dnskey() failed: %s",
13988
0
             isc_result_totext(result));
13989
0
      return result;
13990
0
    }
13991
0
    result = dns_ds_buildrdata(dns_zone_getorigin(zone), &dnskey,
13992
0
             cds.digest_type, cdsbuf,
13993
0
             sizeof(cdsbuf), &cdsrdata);
13994
0
    if (result != ISC_R_SUCCESS) {
13995
0
      dns_zone_log(zone, ISC_LOG_ERROR,
13996
0
             "dns_ds_buildrdata(keytag=%hu, algo=%d, "
13997
0
             "digest=%d) failed: %s",
13998
0
             cds.key_tag, cds.algorithm,
13999
0
             cds.digest_type,
14000
0
             isc_result_totext(result));
14001
0
      return result;
14002
0
    }
14003
14004
0
    cdsrdata.type = dns_rdatatype_cds;
14005
0
    if (dns_rdata_compare(rdata, &cdsrdata) == 0) {
14006
0
      *inuse = true;
14007
0
      break;
14008
0
    }
14009
0
  }
14010
14011
0
  return ISC_R_SUCCESS;
14012
0
}
14013
14014
isc_result_t
14015
0
dns_zone_dnskey_inuse(dns_zone_t *zone, dns_rdata_t *rdata, bool *inuse) {
14016
0
  dns_dnsseckeylist_t keylist;
14017
0
  isc_result_t result = ISC_R_SUCCESS;
14018
0
  isc_stdtime_t now = isc_stdtime_now();
14019
0
  isc_mem_t *mctx;
14020
0
  dns_kasp_t *kasp;
14021
0
  dns_keystorelist_t *keystores;
14022
0
  const char *keydir;
14023
14024
0
  REQUIRE(DNS_ZONE_VALID(zone));
14025
0
  REQUIRE(dns_rdatatype_iskeymaterial(rdata->type));
14026
14027
0
  mctx = zone->mctx;
14028
14029
0
  ISC_LIST_INIT(keylist);
14030
14031
0
  *inuse = false;
14032
14033
0
  kasp = dns_zone_getkasp(zone);
14034
0
  keydir = dns_zone_getkeydirectory(zone);
14035
0
  keystores = dns_zone_getkeystores(zone);
14036
14037
0
  if (kasp == NULL) {
14038
0
    return ISC_R_SUCCESS;
14039
0
  }
14040
14041
0
  dns_zone_lock_keyfiles(zone);
14042
0
  result = dns_dnssec_findmatchingkeys(dns_zone_getorigin(zone), kasp,
14043
0
               keydir, keystores, now, false,
14044
0
               mctx, &keylist);
14045
0
  dns_zone_unlock_keyfiles(zone);
14046
0
  if (result == ISC_R_NOTFOUND) {
14047
0
    return ISC_R_SUCCESS;
14048
0
  } else if (result != ISC_R_SUCCESS) {
14049
0
    dns_zone_log(zone, ISC_LOG_ERROR,
14050
0
           "dns_dnssec_findmatchingkeys() failed: %s",
14051
0
           isc_result_totext(result));
14052
0
    return result;
14053
0
  }
14054
14055
0
  switch (rdata->type) {
14056
0
  case dns_rdatatype_dnskey:
14057
0
    result = dnskey_inuse(zone, rdata, mctx, &keylist, inuse);
14058
0
    break;
14059
0
  case dns_rdatatype_cdnskey:
14060
0
    result = cdnskey_inuse(zone, rdata, &keylist, inuse);
14061
0
    break;
14062
0
  case dns_rdatatype_cds:
14063
0
    result = cds_inuse(zone, rdata, &keylist, inuse);
14064
0
    break;
14065
0
  default:
14066
0
    UNREACHABLE();
14067
0
    break;
14068
0
  }
14069
14070
0
  ISC_LIST_FOREACH(keylist, key, link) {
14071
0
    ISC_LIST_UNLINK(keylist, key, link);
14072
0
    dns_dnsseckey_destroy(mctx, &key);
14073
0
  }
14074
0
  return result;
14075
0
}
14076
14077
static isc_result_t
14078
sync_secure_journal(dns_zone_t *zone, dns_zone_t *raw, dns_journal_t *journal,
14079
        uint32_t start, uint32_t end, dns_difftuple_t **soatuplep,
14080
0
        dns_diff_t *diff) {
14081
0
  isc_result_t result;
14082
0
  dns_diff_t pending;
14083
0
  dns_difftuple_t *tuple = NULL;
14084
0
  dns_diffop_t op = DNS_DIFFOP_ADD;
14085
0
  int n_soa = 0;
14086
14087
0
  REQUIRE(soatuplep != NULL);
14088
14089
0
  if (start == end) {
14090
0
    return DNS_R_UNCHANGED;
14091
0
  }
14092
14093
0
  dns_diff_init(diff->mctx, &pending);
14094
14095
0
  CHECK(dns_journal_iter_init(journal, start, end, NULL));
14096
0
  for (result = dns_journal_first_rr(journal); result == ISC_R_SUCCESS;
14097
0
       result = dns_journal_next_rr(journal))
14098
0
  {
14099
0
    dns_name_t *name = NULL;
14100
0
    uint32_t ttl;
14101
0
    dns_rdata_t *rdata = NULL;
14102
0
    dns_journal_current_rr(journal, &name, &ttl, &rdata);
14103
14104
0
    if (rdata->type == dns_rdatatype_soa) {
14105
0
      n_soa++;
14106
0
      if (n_soa == 2) {
14107
        /*
14108
         * Save the latest raw SOA record.
14109
         */
14110
0
        if (*soatuplep != NULL) {
14111
0
          dns_difftuple_free(soatuplep);
14112
0
        }
14113
0
        dns_difftuple_create(diff->mctx, DNS_DIFFOP_ADD,
14114
0
                 name, ttl, rdata,
14115
0
                 soatuplep);
14116
0
      }
14117
0
      if (n_soa == 3) {
14118
0
        n_soa = 1;
14119
0
      }
14120
0
      continue;
14121
0
    }
14122
14123
    /* Sanity. */
14124
0
    if (n_soa == 0) {
14125
0
      dns_zone_log(raw, ISC_LOG_ERROR,
14126
0
             "corrupt journal file: '%s'\n",
14127
0
             raw->journal);
14128
0
      CLEANUP(ISC_R_FAILURE);
14129
0
    }
14130
14131
0
    if (zone->privatetype != 0 && rdata->type == zone->privatetype)
14132
0
    {
14133
0
      continue;
14134
0
    }
14135
14136
    /*
14137
     * Skip DNSSEC records that BIND maintains with inline-signing.
14138
     */
14139
0
    if (rdata->type == dns_rdatatype_nsec ||
14140
0
        rdata->type == dns_rdatatype_rrsig ||
14141
0
        rdata->type == dns_rdatatype_nsec3 ||
14142
0
        rdata->type == dns_rdatatype_nsec3param)
14143
0
    {
14144
0
      continue;
14145
0
    }
14146
    /*
14147
     * Allow DNSKEY, CDNSKEY, CDS because users should be able to
14148
     * update the zone with these records from a different provider,
14149
     * but skip records that are under our control.
14150
     */
14151
0
    if (dns_rdatatype_iskeymaterial(rdata->type)) {
14152
0
      bool inuse = false;
14153
0
      isc_result_t r = dns_zone_dnskey_inuse(zone, rdata,
14154
0
                     &inuse);
14155
0
      if (r == ISC_R_SUCCESS && inuse) {
14156
0
        continue;
14157
0
      }
14158
0
    }
14159
14160
0
    op = (n_soa == 1) ? DNS_DIFFOP_DEL : DNS_DIFFOP_ADD;
14161
14162
0
    dns_difftuple_create(diff->mctx, op, name, ttl, rdata, &tuple);
14163
0
    dns_diff_append(&pending, &tuple);
14164
0
  }
14165
0
  if (result == ISC_R_NOMORE) {
14166
0
    result = ISC_R_SUCCESS;
14167
0
  }
14168
14169
0
cleanup:
14170
0
  dns_diff_appendlistminimal(diff, &pending);
14171
0
  return result;
14172
0
}
14173
14174
/*
14175
 * Filter the key material preserving TTL changes.  If kasp in effect honour the
14176
 * existing ttl.  The lists returned by sync_secure_db/dns_db_diffx should be
14177
 * DNSSEC RRset order so we can process 'del' and 'add' in parallel rather than
14178
 * searching for TTL only changes first and processing them, then checking the
14179
 * 'in use' status on a subsequent pass.
14180
 */
14181
14182
static void
14183
filter_keymaterial(dns_zone_t *zone, dns_difftuplelist_t *del,
14184
0
       dns_difftuplelist_t *add, bool kasp, dns_ttl_t ttl) {
14185
0
  dns_difftuple_t *deltuple = ISC_LIST_HEAD(*del);
14186
0
  dns_difftuple_t *addtuple = ISC_LIST_HEAD(*add);
14187
0
  isc_result_t result;
14188
14189
0
  while (deltuple != NULL || addtuple != NULL) {
14190
0
    dns_difftuple_t *delnext = NULL, *addnext = NULL;
14191
0
    bool inuse = false;
14192
0
    if (deltuple != NULL) {
14193
0
      delnext = ISC_LIST_NEXT(deltuple, link);
14194
0
    }
14195
0
    if (addtuple != NULL) {
14196
0
      addnext = ISC_LIST_NEXT(addtuple, link);
14197
0
    }
14198
0
    if (deltuple != NULL && addtuple != NULL) {
14199
0
      int n = dns_rdata_compare(&deltuple->rdata,
14200
0
              &addtuple->rdata);
14201
0
      if (n == 0) {
14202
        /*
14203
         * If the rdata is equal then the only
14204
         * difference will be a TTL change.
14205
         */
14206
0
        if (kasp) {
14207
          /* TTL is managed by dnssec-policy */
14208
0
          ISC_LIST_UNLINK(*del, deltuple, link);
14209
0
          dns_difftuple_free(&deltuple);
14210
0
          ISC_LIST_UNLINK(*add, addtuple, link);
14211
0
          dns_difftuple_free(&addtuple);
14212
0
        }
14213
0
        deltuple = delnext;
14214
0
        addtuple = addnext;
14215
0
        continue;
14216
0
      }
14217
0
      if (n < 0) {
14218
0
        goto checkdel;
14219
0
      }
14220
0
      goto checkadd;
14221
0
    } else if (deltuple != NULL) {
14222
0
    checkdel:
14223
0
      result = dns_zone_dnskey_inuse(zone, &deltuple->rdata,
14224
0
                   &inuse);
14225
0
      if (result == ISC_R_SUCCESS && inuse) {
14226
0
        ISC_LIST_UNLINK(*del, deltuple, link);
14227
0
        dns_difftuple_free(&deltuple);
14228
0
      }
14229
0
      deltuple = delnext;
14230
0
    } else {
14231
0
    checkadd:
14232
0
      result = dns_zone_dnskey_inuse(zone, &addtuple->rdata,
14233
0
                   &inuse);
14234
0
      if (result == ISC_R_SUCCESS && inuse) {
14235
0
        ISC_LIST_UNLINK(*add, addtuple, link);
14236
0
        dns_difftuple_free(&addtuple);
14237
0
      } else if (kasp) {
14238
0
        addtuple->ttl = ttl;
14239
0
      }
14240
0
      addtuple = addnext;
14241
0
    }
14242
0
  }
14243
0
}
14244
14245
static isc_result_t
14246
sync_secure_db(dns_zone_t *seczone, dns_zone_t *raw, dns_db_t *secdb,
14247
         dns_dbversion_t *secver, dns_difftuple_t **soatuple,
14248
0
         dns_diff_t *diff) {
14249
0
  isc_result_t result;
14250
0
  dns_db_t *rawdb = NULL;
14251
0
  dns_dbversion_t *rawver = NULL;
14252
0
  dns_difftuple_t *oldtuple = NULL, *newtuple = NULL;
14253
0
  dns_rdata_soa_t oldsoa, newsoa;
14254
0
  dns_difftuplelist_t add = ISC_LIST_INITIALIZER;
14255
0
  dns_difftuplelist_t del = ISC_LIST_INITIALIZER;
14256
0
  dns_difftuplelist_t keyadd = ISC_LIST_INITIALIZER;
14257
0
  dns_difftuplelist_t keydel = ISC_LIST_INITIALIZER;
14258
0
  dns_difftuplelist_t ckeyadd = ISC_LIST_INITIALIZER;
14259
0
  dns_difftuplelist_t ckeydel = ISC_LIST_INITIALIZER;
14260
0
  dns_difftuplelist_t cdsadd = ISC_LIST_INITIALIZER;
14261
0
  dns_difftuplelist_t cdsdel = ISC_LIST_INITIALIZER;
14262
0
  dns_kasp_t *kasp = NULL;
14263
0
  dns_ttl_t keyttl = 0, ckeyttl = 0, cdsttl = 0;
14264
14265
0
  REQUIRE(DNS_ZONE_VALID(seczone));
14266
0
  REQUIRE(soatuple != NULL && *soatuple == NULL);
14267
14268
0
  if (!seczone->sourceserialset) {
14269
0
    return DNS_R_UNCHANGED;
14270
0
  }
14271
14272
0
  dns_db_attach(raw->db, &rawdb);
14273
0
  dns_db_currentversion(rawdb, &rawver);
14274
0
  result = dns_db_diffx(diff, rawdb, rawver, secdb, secver, NULL);
14275
0
  dns_db_closeversion(rawdb, &rawver, false);
14276
0
  dns_db_detach(&rawdb);
14277
14278
0
  if (result != ISC_R_SUCCESS) {
14279
0
    return result;
14280
0
  }
14281
14282
  /*
14283
   * If kasp is in effect honour the existing DNSKEY, CDNSKEY and CDS
14284
   * TTLs.
14285
   */
14286
0
  kasp = seczone->kasp;
14287
0
  if (kasp != NULL) {
14288
0
    dns_rdataset_t rdataset;
14289
0
    dns_dbnode_t *node = NULL;
14290
0
    dns_ttl_t ttl = dns_kasp_dnskeyttl(kasp);
14291
14292
0
    dns_rdataset_init(&rdataset);
14293
14294
0
    result = dns_db_getoriginnode(secdb, &node);
14295
0
    RUNTIME_CHECK(result == ISC_R_SUCCESS);
14296
14297
0
    result = dns_db_findrdataset(
14298
0
      secdb, node, secver, dns_rdatatype_dnskey,
14299
0
      dns_rdatatype_none, 0, &rdataset, NULL);
14300
0
    keyttl = (result == ISC_R_SUCCESS) ? rdataset.ttl : ttl;
14301
0
    dns_rdataset_cleanup(&rdataset);
14302
14303
0
    result = dns_db_findrdataset(
14304
0
      secdb, node, secver, dns_rdatatype_cdnskey,
14305
0
      dns_rdatatype_none, 0, &rdataset, NULL);
14306
0
    ckeyttl = (result == ISC_R_SUCCESS) ? rdataset.ttl : ttl;
14307
0
    dns_rdataset_cleanup(&rdataset);
14308
14309
0
    result = dns_db_findrdataset(
14310
0
      secdb, node, secver, dns_rdatatype_cds,
14311
0
      dns_rdatatype_none, 0, &rdataset, NULL);
14312
0
    cdsttl = (result == ISC_R_SUCCESS) ? rdataset.ttl : ttl;
14313
0
    dns_rdataset_cleanup(&rdataset);
14314
0
    dns_db_detachnode(&node);
14315
0
  }
14316
14317
0
  ISC_LIST_FOREACH(diff->tuples, tuple, link) {
14318
0
    dns_difftuplelist_t *al = &add, *dl = &del;
14319
14320
    /*
14321
     * Skip private records that BIND maintains with inline-signing.
14322
     */
14323
0
    if (seczone->privatetype != 0 &&
14324
0
        tuple->rdata.type == seczone->privatetype)
14325
0
    {
14326
0
      dns_diff_unlink(diff, tuple);
14327
0
      dns_difftuple_free(&tuple);
14328
0
      continue;
14329
0
    }
14330
14331
    /*
14332
     * Skip DNSSEC records that BIND maintains with inline-signing.
14333
     */
14334
0
    if (tuple->rdata.type == dns_rdatatype_nsec ||
14335
0
        tuple->rdata.type == dns_rdatatype_rrsig ||
14336
0
        tuple->rdata.type == dns_rdatatype_nsec3 ||
14337
0
        tuple->rdata.type == dns_rdatatype_nsec3param)
14338
0
    {
14339
0
      dns_diff_unlink(diff, tuple);
14340
0
      dns_difftuple_free(&tuple);
14341
0
      continue;
14342
0
    }
14343
14344
    /*
14345
     * Apex DNSKEY, CDNSKEY and CDS need special processing so
14346
     * split them out.
14347
     */
14348
0
    if (dns_rdatatype_iskeymaterial(tuple->rdata.type) &&
14349
0
        dns_name_equal(&tuple->name, &seczone->origin))
14350
0
    {
14351
0
      switch (tuple->rdata.type) {
14352
0
      case dns_rdatatype_dnskey:
14353
0
        al = &keyadd;
14354
0
        dl = &keydel;
14355
0
        break;
14356
0
      case dns_rdatatype_cdnskey:
14357
0
        al = &ckeyadd;
14358
0
        dl = &ckeydel;
14359
0
        break;
14360
0
      case dns_rdatatype_cds:
14361
0
        al = &cdsadd;
14362
0
        dl = &cdsdel;
14363
0
        break;
14364
0
      default:
14365
0
        UNREACHABLE();
14366
0
      }
14367
0
    }
14368
14369
0
    if (tuple->rdata.type == dns_rdatatype_soa) {
14370
0
      if (tuple->op == DNS_DIFFOP_DEL) {
14371
0
        INSIST(oldtuple == NULL);
14372
0
        oldtuple = tuple;
14373
0
      }
14374
0
      if (tuple->op == DNS_DIFFOP_ADD) {
14375
0
        INSIST(newtuple == NULL);
14376
0
        newtuple = tuple;
14377
0
      }
14378
0
    }
14379
14380
    /*
14381
     * Split into deletions and additions.
14382
     */
14383
0
    dns_diff_unlink(diff, tuple);
14384
0
    switch (tuple->op) {
14385
0
    case DNS_DIFFOP_DEL:
14386
0
    case DNS_DIFFOP_DELRESIGN:
14387
0
      ISC_LIST_APPEND(*dl, tuple, link);
14388
0
      break;
14389
0
    case DNS_DIFFOP_ADD:
14390
0
    case DNS_DIFFOP_ADDRESIGN:
14391
0
      ISC_LIST_APPEND(*al, tuple, link);
14392
0
      break;
14393
0
    default:
14394
0
      UNREACHABLE();
14395
0
    }
14396
0
  }
14397
14398
0
  if (oldtuple != NULL && newtuple != NULL) {
14399
0
    result = dns_rdata_tostruct(&oldtuple->rdata, &oldsoa);
14400
0
    RUNTIME_CHECK(result == ISC_R_SUCCESS);
14401
14402
0
    result = dns_rdata_tostruct(&newtuple->rdata, &newsoa);
14403
0
    RUNTIME_CHECK(result == ISC_R_SUCCESS);
14404
14405
    /*
14406
     * If the SOA records are the same except for the serial
14407
     * remove them from the diff.
14408
     */
14409
0
    if (oldtuple->ttl == newtuple->ttl &&
14410
0
        oldsoa.refresh == newsoa.refresh &&
14411
0
        oldsoa.retry == newsoa.retry &&
14412
0
        oldsoa.minimum == newsoa.minimum &&
14413
0
        oldsoa.expire == newsoa.expire &&
14414
0
        dns_name_equal(&oldsoa.origin, &newsoa.origin) &&
14415
0
        dns_name_equal(&oldsoa.contact, &newsoa.contact))
14416
0
    {
14417
0
      ISC_LIST_UNLINK(del, oldtuple, link);
14418
0
      dns_difftuple_free(&oldtuple);
14419
0
      ISC_LIST_UNLINK(add, newtuple, link);
14420
0
      dns_difftuple_free(&newtuple);
14421
0
    }
14422
0
  }
14423
14424
  /*
14425
   * Filter out keys we manage but still allow TTL changes.
14426
   */
14427
0
  filter_keymaterial(seczone, &keydel, &keyadd, kasp != NULL, keyttl);
14428
0
  filter_keymaterial(seczone, &ckeydel, &ckeyadd, kasp != NULL, ckeyttl);
14429
0
  filter_keymaterial(seczone, &cdsdel, &cdsadd, kasp != NULL, cdsttl);
14430
14431
  /*
14432
   * Rebuild the diff now that we have filtered it
14433
   */
14434
0
  ISC_LIST_FOREACH(del, tuple, link) {
14435
0
    ISC_LIST_UNLINK(del, tuple, link);
14436
0
    dns_diff_append(diff, &tuple);
14437
0
  }
14438
0
  ISC_LIST_FOREACH(keydel, tuple, link) {
14439
0
    ISC_LIST_UNLINK(keydel, tuple, link);
14440
0
    dns_diff_append(diff, &tuple);
14441
0
  }
14442
0
  ISC_LIST_FOREACH(ckeydel, tuple, link) {
14443
0
    ISC_LIST_UNLINK(ckeydel, tuple, link);
14444
0
    dns_diff_append(diff, &tuple);
14445
0
  }
14446
0
  ISC_LIST_FOREACH(cdsdel, tuple, link) {
14447
0
    ISC_LIST_UNLINK(cdsdel, tuple, link);
14448
0
    dns_diff_append(diff, &tuple);
14449
0
  }
14450
0
  ISC_LIST_FOREACH(add, tuple, link) {
14451
0
    ISC_LIST_UNLINK(add, tuple, link);
14452
0
    dns_diff_append(diff, &tuple);
14453
0
  }
14454
0
  ISC_LIST_FOREACH(keyadd, tuple, link) {
14455
0
    ISC_LIST_UNLINK(keyadd, tuple, link);
14456
0
    dns_diff_append(diff, &tuple);
14457
0
  }
14458
0
  ISC_LIST_FOREACH(ckeyadd, tuple, link) {
14459
0
    ISC_LIST_UNLINK(ckeyadd, tuple, link);
14460
0
    dns_diff_append(diff, &tuple);
14461
0
  }
14462
0
  ISC_LIST_FOREACH(cdsadd, tuple, link) {
14463
0
    ISC_LIST_UNLINK(cdsadd, tuple, link);
14464
0
    dns_diff_append(diff, &tuple);
14465
0
  }
14466
14467
0
  if (ISC_LIST_EMPTY(diff->tuples)) {
14468
0
    return DNS_R_UNCHANGED;
14469
0
  }
14470
14471
  /*
14472
   * If there are still SOA records in the diff they can now be removed
14473
   * saving the new SOA record.
14474
   */
14475
0
  if (oldtuple != NULL) {
14476
0
    dns_diff_unlink(diff, oldtuple);
14477
0
    dns_difftuple_free(&oldtuple);
14478
0
  }
14479
14480
0
  if (newtuple != NULL) {
14481
0
    dns_diff_unlink(diff, newtuple);
14482
0
    *soatuple = newtuple;
14483
0
  }
14484
14485
0
  return ISC_R_SUCCESS;
14486
0
}
14487
14488
static isc_result_t
14489
0
zone_get_raw_serial(dns_zone_t *raw, uint32_t *serialp) {
14490
0
  isc_result_t result;
14491
14492
0
  ZONEDB_LOCK(&raw->dblock, isc_rwlocktype_read);
14493
0
  if (raw->db != NULL) {
14494
0
    result = dns_db_getsoaserial(raw->db, NULL, serialp);
14495
0
  } else {
14496
0
    result = DNS_R_NOTLOADED;
14497
0
  }
14498
0
  ZONEDB_UNLOCK(&raw->dblock, isc_rwlocktype_read);
14499
14500
0
  return result;
14501
0
}
14502
14503
static zone_inline_sync_t *
14504
0
inline_sync_pop(dns_zone_t *zone) {
14505
0
  zone_inline_sync_t *iss = NULL;
14506
14507
0
  REQUIRE(DNS_ZONE_VALID(zone));
14508
14509
0
  LOCK_ZONE(zone);
14510
0
  if (zone->iss != NULL) {
14511
    /*
14512
     * inline_sync_run() is only called from zone maintenance, so
14513
     * zone->iss can only be parked between maintenance passes here.
14514
     */
14515
0
    iss = MOVE_OWNERSHIP(zone->iss);
14516
0
  }
14517
0
  UNLOCK_ZONE(zone);
14518
14519
0
  return iss;
14520
0
}
14521
14522
static void
14523
0
inline_sync_destroy(zone_inline_sync_t **issp) {
14524
0
  zone_inline_sync_t *iss = NULL;
14525
14526
0
  REQUIRE(issp != NULL);
14527
14528
0
  iss = *issp;
14529
0
  if (iss == NULL) {
14530
0
    return;
14531
0
  }
14532
0
  *issp = NULL;
14533
14534
0
  INSIST(iss->mctx != NULL);
14535
14536
0
  dns_diff_clear(&iss->diff);
14537
0
  dns_update_state_clear(&iss->state);
14538
0
  if (iss->db != NULL) {
14539
0
    if (iss->oldver != NULL) {
14540
0
      dns_db_closeversion(iss->db, &iss->oldver, false);
14541
0
    }
14542
0
    if (iss->newver != NULL) {
14543
0
      dns_db_closeversion(iss->db, &iss->newver, false);
14544
0
    }
14545
0
    dns_db_detach(&iss->db);
14546
0
  }
14547
0
  if (iss->raw != NULL) {
14548
0
    dns_zone_detach(&iss->raw);
14549
0
  }
14550
0
  isc_mem_putanddetach(&iss->mctx, iss, sizeof(*iss));
14551
0
}
14552
14553
static isc_result_t
14554
inline_sync_create(dns_zone_t *zone, uint32_t *endp,
14555
0
       zone_inline_sync_t **issp) {
14556
0
  isc_result_t result = ISC_R_SUCCESS;
14557
0
  zone_inline_sync_t *iss = NULL;
14558
0
  uint32_t end = 0;
14559
14560
0
  REQUIRE(DNS_ZONE_VALID(zone));
14561
0
  REQUIRE(endp != NULL);
14562
0
  REQUIRE(issp != NULL && *issp == NULL);
14563
14564
0
  iss = isc_mem_cget(zone->mctx, 1, sizeof(*iss));
14565
0
  isc_mem_attach(zone->mctx, &iss->mctx);
14566
14567
0
  LOCK_ZONE(zone);
14568
14569
  /*
14570
   * The inline_sync_run() is loop-serialized for the zone.  Install the
14571
   * transaction while attaching its resources so zone->iss stays the
14572
   * single marker for sync-in-flight.
14573
   */
14574
0
  INSIST(zone->iss == NULL);
14575
0
  zone->iss = iss;
14576
0
  dns_diff_init(iss->mctx, &iss->diff);
14577
14578
0
  ZONEDB_LOCK(&zone->dblock, isc_rwlocktype_read);
14579
0
  if (zone->db != NULL) {
14580
0
    dns_db_attach(zone->db, &iss->db);
14581
0
  } else {
14582
0
    result = ISC_R_FAILURE;
14583
0
  }
14584
0
  ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_read);
14585
14586
0
  if (zone->raw != NULL) {
14587
0
    dns_zone_attach(zone->raw, &iss->raw);
14588
0
  } else {
14589
0
    result = ISC_R_FAILURE;
14590
0
  }
14591
14592
0
  UNLOCK_ZONE(zone);
14593
14594
0
  CHECK(result);
14595
0
  CHECK(zone_get_raw_serial(iss->raw, &end));
14596
14597
0
  LOCK_ZONE(zone);
14598
0
  if (zone->sourceserialset && end == zone->sourceserial) {
14599
0
    UNLOCK_ZONE(zone);
14600
0
    result = DNS_R_UNCHANGED;
14601
0
    goto cleanup;
14602
0
  }
14603
0
  iss->end = end;
14604
0
  UNLOCK_ZONE(zone);
14605
14606
0
  dns_db_currentversion(iss->db, &iss->oldver);
14607
0
  CHECK(dns_db_newversion(iss->db, &iss->newver));
14608
14609
0
  *endp = end;
14610
0
  *issp = iss;
14611
0
  return ISC_R_SUCCESS;
14612
14613
0
cleanup:
14614
0
  iss = inline_sync_pop(zone);
14615
0
  inline_sync_destroy(&iss);
14616
0
  return result;
14617
0
}
14618
14619
static void
14620
0
zone_clear_inline_sync(dns_zone_t *zone) {
14621
0
  zone_inline_sync_t *iss = NULL;
14622
14623
0
  REQUIRE(DNS_ZONE_VALID(zone));
14624
14625
0
  iss = inline_sync_pop(zone);
14626
0
  inline_sync_destroy(&iss);
14627
0
}
14628
14629
static void
14630
0
inline_secure_bootstrap(dns_zone_t *zone) {
14631
0
  isc_result_t result = ISC_R_SUCCESS;
14632
0
  dns_db_t *rawdb = NULL, *newdb = NULL;
14633
0
  uint32_t end = 0;
14634
14635
0
  ENTER;
14636
14637
0
  LOCK_ZONE(zone);
14638
0
  if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_EXITING) ||
14639
0
      !dns__zone_inline_secure(zone))
14640
0
  {
14641
0
    CHECK(ISC_R_SHUTTINGDOWN);
14642
0
  }
14643
14644
0
  ZONEDB_LOCK(&zone->raw->dblock, isc_rwlocktype_read);
14645
0
  if (zone->raw->db != NULL) {
14646
0
    dns_db_attach(zone->raw->db, &rawdb);
14647
0
    result = dns_db_getsoaserial(rawdb, NULL, &end);
14648
0
  } else {
14649
0
    result = DNS_R_NOTLOADED;
14650
0
  }
14651
0
  ZONEDB_UNLOCK(&zone->raw->dblock, isc_rwlocktype_read);
14652
0
  CHECK(result);
14653
14654
0
  CHECK(secure_db_create_from_raw(zone, rawdb, &newdb));
14655
14656
0
  DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_NEEDNOTIFY);
14657
0
  CHECK(zone_postload(zone, newdb, isc_time_now(), ISC_R_SUCCESS));
14658
14659
0
  zone->sourceserial = end;
14660
0
  zone->sourceserialset = true;
14661
0
  zone->inline_sync_phase = inline_sync_idle;
14662
0
  zone_needdump(zone, 0);
14663
14664
0
cleanup:
14665
0
  UNLOCK_ZONE(zone);
14666
14667
0
  if (newdb != NULL) {
14668
0
    dns_db_detach(&newdb);
14669
0
  }
14670
0
  if (rawdb != NULL) {
14671
0
    dns_db_detach(&rawdb);
14672
0
  }
14673
0
  if (result != ISC_R_SUCCESS && result != DNS_R_NOTLOADED) {
14674
0
    dns_zone_log(zone, ISC_LOG_ERROR, "inline secure bootstrap: %s",
14675
0
           isc_result_totext(result));
14676
0
  }
14677
0
}
14678
14679
static isc_result_t
14680
0
inline_sync_finalize(dns_zone_t *zone, uint32_t newserial, uint32_t desired) {
14681
0
  isc_result_t result = ISC_R_SUCCESS;
14682
0
  dns_journal_t *rjournal = NULL;
14683
0
  dns_update_log_t log = { update_log_cb, NULL };
14684
0
  zone_inline_sync_t *iss = NULL;
14685
0
  uint32_t end = 0;
14686
14687
0
  ENTER;
14688
14689
0
  LOCK_ZONE(zone);
14690
0
  iss = zone->iss;
14691
0
  INSIST(iss != NULL);
14692
0
  end = iss->end;
14693
0
  UNLOCK_ZONE(zone);
14694
14695
0
  result = dns_update_signaturesinc(
14696
0
    &log, zone, iss->db, iss->oldver, iss->newver, &iss->diff,
14697
0
    zone->sigvalidityinterval, &iss->state);
14698
0
  if (result == DNS_R_CONTINUE) {
14699
0
    LOCK_ZONE(zone);
14700
0
    zone_schedule_inline_sync(zone, inline_sync_idle);
14701
0
    UNLOCK_ZONE(zone);
14702
0
    return result;
14703
0
  }
14704
14705
  /*
14706
   * If something went wrong while trying to update the secure zone and
14707
   * the latter was already signed before, do not apply raw zone deltas to
14708
   * it as that would break existing DNSSEC signatures.  However, if the
14709
   * secure zone was not yet signed (e.g. because no signing keys were
14710
   * created for it), commence applying raw zone deltas to it so that
14711
   * contents of the raw zone and the secure zone are kept in sync.
14712
   */
14713
0
  if (result != ISC_R_SUCCESS && dns_db_issecure(iss->db)) {
14714
0
    goto cleanup;
14715
0
  }
14716
14717
0
  CHECK(dns_journal_open(iss->raw->mctx, iss->raw->journal,
14718
0
             DNS_JOURNAL_WRITE, &rjournal));
14719
0
  CHECK(zone_journal(zone, &iss->diff, &end, "inline_sync"));
14720
14721
0
  dns_journal_set_sourceserial(rjournal, end);
14722
0
  dns_journal_commit(rjournal);
14723
14724
0
  LOCK_ZONE(zone);
14725
0
  DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_NEEDNOTIFY);
14726
14727
0
  zone->sourceserial = end;
14728
0
  zone->sourceserialset = true;
14729
0
  zone_needdump(zone, DNS_DUMP_DELAY);
14730
14731
  /*
14732
   * Set resign time to make sure it is set to the earliest signature
14733
   * expiration.
14734
   */
14735
0
  dns__zone_set_resigntime(zone);
14736
0
  dns__zone_settimer(zone, isc_time_now());
14737
0
  UNLOCK_ZONE(zone);
14738
14739
0
  dns_db_closeversion(iss->db, &iss->oldver, false);
14740
0
  dns_db_closeversion(iss->db, &iss->newver, true);
14741
14742
0
  if (newserial != 0) {
14743
0
    dns_zone_log(zone, ISC_LOG_INFO, "serial %u (unsigned %u)",
14744
0
           newserial, desired);
14745
0
  }
14746
14747
0
cleanup:
14748
0
  if (rjournal != NULL) {
14749
0
    dns_journal_destroy(&rjournal);
14750
0
  }
14751
14752
0
  return result;
14753
0
}
14754
14755
static void
14756
0
inline_sync_run(dns_zone_t *zone) {
14757
0
  isc_result_t result = ISC_R_SUCCESS;
14758
0
  dns_journal_t *rjournal = NULL;
14759
0
  dns_journal_t *sjournal = NULL;
14760
0
  uint32_t start = 0, end = 0;
14761
0
  dns_difftuple_t *tuple = NULL, *soatuple = NULL;
14762
0
  uint32_t newserial = 0, desired = 0;
14763
0
  zone_inline_sync_t *iss = NULL;
14764
14765
0
  ENTER;
14766
14767
0
  CHECK(inline_sync_create(zone, &end, &iss));
14768
14769
  /*
14770
   * We first attempt to sync the raw zone to the secure zone by using the
14771
   * raw zone's journal, applying all the deltas from the latest
14772
   * source-serial of the secure zone up to the current serial number of
14773
   * the raw zone.
14774
   *
14775
   * If that fails, then we'll fall back to a direct comparison between
14776
   * raw and secure zones.
14777
   */
14778
0
  CHECK(dns_journal_open(iss->raw->mctx, iss->raw->journal,
14779
0
             DNS_JOURNAL_WRITE, &rjournal));
14780
14781
0
  result = dns_journal_open(zone->mctx, zone->journal, DNS_JOURNAL_READ,
14782
0
          &sjournal);
14783
0
  if (result != ISC_R_NOTFOUND) {
14784
0
    CHECK(result);
14785
0
  }
14786
14787
0
  if (!dns_journal_get_sourceserial(rjournal, &start)) {
14788
0
    start = dns_journal_first_serial(rjournal);
14789
0
    dns_journal_set_sourceserial(rjournal, start);
14790
0
  }
14791
0
  if (sjournal != NULL) {
14792
0
    uint32_t serial;
14793
    /*
14794
     * We read the secure journal first, if that exists use its
14795
     * value provided it is greater that from the raw journal.
14796
     */
14797
0
    if (dns_journal_get_sourceserial(sjournal, &serial) &&
14798
0
        isc_serial_gt(serial, start))
14799
0
    {
14800
0
      start = serial;
14801
0
    }
14802
0
    dns_journal_destroy(&sjournal);
14803
0
  }
14804
14805
  /*
14806
   * Try to apply diffs from the raw zone's journal to the secure zone. If
14807
   * that fails, we recover by syncing up the databases directly.
14808
   */
14809
0
  result = sync_secure_journal(zone, iss->raw, rjournal, start, end,
14810
0
             &soatuple, &iss->diff);
14811
0
  if (result == DNS_R_UNCHANGED) {
14812
0
    LOCK_ZONE(zone);
14813
0
    zone->sourceserial = end;
14814
0
    zone->sourceserialset = true;
14815
0
    UNLOCK_ZONE(zone);
14816
14817
0
    goto cleanup;
14818
0
  } else if (result != ISC_R_SUCCESS) {
14819
0
    result = sync_secure_db(zone, iss->raw, iss->db, iss->oldver,
14820
0
          &soatuple, &iss->diff);
14821
0
    if (result == DNS_R_UNCHANGED) {
14822
0
      LOCK_ZONE(zone);
14823
0
      zone->sourceserial = end;
14824
0
      zone->sourceserialset = true;
14825
0
      UNLOCK_ZONE(zone);
14826
14827
0
      goto cleanup;
14828
0
    }
14829
0
    CHECK(result);
14830
0
  }
14831
14832
0
  CHECK(dns_diff_apply(&iss->diff, iss->db, iss->newver));
14833
14834
0
  if (soatuple != NULL) {
14835
0
    uint32_t oldserial;
14836
14837
0
    CHECK(dns_db_createsoatuple(iss->db, iss->oldver,
14838
0
              iss->diff.mctx, DNS_DIFFOP_DEL,
14839
0
              &tuple));
14840
0
    oldserial = dns_soa_getserial(&tuple->rdata);
14841
0
    newserial = desired = dns_soa_getserial(&soatuple->rdata);
14842
0
    if (!isc_serial_gt(newserial, oldserial)) {
14843
0
      newserial = oldserial + 1;
14844
0
      if (newserial == 0) {
14845
0
        newserial++;
14846
0
      }
14847
0
      dns_soa_setserial(newserial, &soatuple->rdata);
14848
0
    }
14849
0
    CHECK(dns_diff_applytuple(&tuple, iss->db, iss->newver,
14850
0
            &iss->diff));
14851
0
    CHECK(dns_diff_applytuple(&soatuple, iss->db, iss->newver,
14852
0
            &iss->diff));
14853
0
  } else {
14854
0
    CHECK(update_soa_serial(zone, iss->db, iss->newver, &iss->diff,
14855
0
          zone->mctx, zone->updatemethod));
14856
0
  }
14857
14858
0
cleanup:
14859
0
  if (sjournal != NULL) {
14860
0
    dns_journal_destroy(&sjournal);
14861
0
  }
14862
0
  if (rjournal != NULL) {
14863
0
    dns_journal_destroy(&rjournal);
14864
0
  }
14865
0
  if (tuple != NULL) {
14866
0
    dns_difftuple_free(&tuple);
14867
0
  }
14868
0
  if (soatuple != NULL) {
14869
0
    dns_difftuple_free(&soatuple);
14870
0
  }
14871
0
  if (result == ISC_R_SUCCESS) {
14872
0
    result = inline_sync_finalize(zone, newserial, desired);
14873
0
  }
14874
0
  if (result != DNS_R_CONTINUE) {
14875
0
    zone_clear_inline_sync(zone);
14876
    /*
14877
     * In the pull model, DNS_R_UNCHANGED and DNS_R_NOTLOADED are
14878
     * idle results.  Treating them like errors here would reset the
14879
     * maintenance timer to "now" and either spin on an already
14880
     * current raw serial or retry before raw loading finishes.
14881
     */
14882
0
    if (result != ISC_R_SUCCESS && result != DNS_R_UNCHANGED &&
14883
0
        result != DNS_R_NOTLOADED)
14884
0
    {
14885
0
      dns_zone_log(zone, ISC_LOG_ERROR, "inline_sync: %s",
14886
0
             isc_result_totext(result));
14887
0
    }
14888
0
  }
14889
0
}
14890
14891
static void
14892
0
inline_sync_resume(dns_zone_t *zone) {
14893
0
  isc_result_t result = ISC_R_SUCCESS;
14894
14895
0
  ENTER;
14896
14897
0
  LOCK_ZONE(zone);
14898
0
  INSIST(zone->iss != NULL);
14899
0
  UNLOCK_ZONE(zone);
14900
14901
0
  result = inline_sync_finalize(zone, 0, 0);
14902
0
  if (result != DNS_R_CONTINUE) {
14903
0
    zone_clear_inline_sync(zone);
14904
0
    if (result != ISC_R_SUCCESS && result != DNS_R_UNCHANGED &&
14905
0
        result != DNS_R_NOTLOADED)
14906
0
    {
14907
0
      dns_zone_log(zone, ISC_LOG_ERROR, "inline_sync: %s",
14908
0
             isc_result_totext(result));
14909
0
    }
14910
0
  }
14911
0
}
14912
14913
STATIC_ASSERT(inline_sync_idle < inline_sync_incremental &&
14914
          inline_sync_incremental < inline_sync_full,
14915
        "inline sync states must be ordered by priority");
14916
14917
static void
14918
0
zone_schedule_inline_sync(dns_zone_t *zone, inline_sync_phase_t state) {
14919
0
  INSIST(LOCKED_ZONE(zone));
14920
0
  INSIST(dns__zone_inline_secure(zone));
14921
0
  INSIST(state == inline_sync_idle || state == inline_sync_incremental ||
14922
0
         state == inline_sync_full);
14923
14924
0
  zone->inline_sync_phase = ISC_MAX(zone->inline_sync_phase, state);
14925
0
  dns__zone_settimer(zone, isc_time_now());
14926
0
}
14927
14928
static isc_result_t
14929
checkandaddsoa(dns_db_t *db, dns_dbnode_t *node, dns_dbversion_t *version,
14930
0
         dns_name_t *name, dns_rdataset_t *rdataset, uint32_t oldserial) {
14931
0
  dns_rdata_soa_t soa;
14932
0
  dns_rdata_t rdata = DNS_RDATA_INIT;
14933
0
  dns_rdatalist_t temprdatalist;
14934
0
  dns_rdataset_t temprdataset;
14935
0
  isc_buffer_t b;
14936
0
  isc_result_t result;
14937
0
  unsigned char buf[DNS_SOA_BUFFERSIZE];
14938
14939
0
  result = dns_rdataset_first(rdataset);
14940
0
  RUNTIME_CHECK(result == ISC_R_SUCCESS);
14941
0
  dns_rdataset_current(rdataset, &rdata);
14942
0
  result = dns_rdata_tostruct(&rdata, &soa);
14943
0
  RUNTIME_CHECK(result == ISC_R_SUCCESS);
14944
14945
0
  if (isc_serial_gt(soa.serial, oldserial)) {
14946
0
    return dns_db_addrdataset(db, node, version, 0, rdataset, 0,
14947
0
            NULL);
14948
0
  }
14949
  /*
14950
   * Always bump the serial.
14951
   */
14952
0
  oldserial++;
14953
0
  if (oldserial == 0) {
14954
0
    oldserial++;
14955
0
  }
14956
0
  soa.serial = oldserial;
14957
14958
  /*
14959
   * Construct a replacement rdataset.
14960
   */
14961
0
  dns_rdata_reset(&rdata);
14962
0
  isc_buffer_init(&b, buf, sizeof(buf));
14963
0
  result = dns_rdata_fromstruct(&rdata, rdataset->rdclass,
14964
0
              dns_rdatatype_soa, &soa, &b);
14965
0
  RUNTIME_CHECK(result == ISC_R_SUCCESS);
14966
0
  dns_rdatalist_init(&temprdatalist);
14967
0
  temprdatalist.rdclass = rdata.rdclass;
14968
0
  temprdatalist.type = rdata.type;
14969
0
  temprdatalist.ttl = rdataset->ttl;
14970
0
  ISC_LIST_APPEND(temprdatalist.rdata, &rdata, link);
14971
14972
0
  dns_rdataset_init(&temprdataset);
14973
0
  dns_rdatalist_tordataset(&temprdatalist, &temprdataset);
14974
14975
0
  dns_rdataset_getownercase(rdataset, name);
14976
0
  dns_rdataset_setownercase(&temprdataset, name);
14977
0
  return dns_db_addrdataset(db, node, version, 0, &temprdataset, 0, NULL);
14978
0
}
14979
14980
/*
14981
 * This function should populate an nsec3paramlist_t with the
14982
 * nsecparam_t data from a zone.
14983
 */
14984
static isc_result_t
14985
0
save_nsec3param(dns_zone_t *zone, nsec3paramlist_t *nsec3list) {
14986
0
  isc_result_t result;
14987
0
  dns_dbnode_t *node = NULL;
14988
0
  dns_rdataset_t rdataset, prdataset;
14989
0
  dns_dbversion_t *version = NULL;
14990
0
  nsec3param_t *nsec3param = NULL;
14991
0
  dns_db_t *db = NULL;
14992
0
  unsigned char buf[DNS_NSEC3PARAM_BUFFERSIZE];
14993
14994
0
  REQUIRE(DNS_ZONE_VALID(zone));
14995
0
  REQUIRE(nsec3list != NULL);
14996
0
  REQUIRE(ISC_LIST_EMPTY(*nsec3list));
14997
14998
0
  dns_rdataset_init(&rdataset);
14999
0
  dns_rdataset_init(&prdataset);
15000
15001
0
  dns_db_attach(zone->db, &db);
15002
0
  CHECK(dns_db_getoriginnode(db, &node));
15003
15004
0
  dns_db_currentversion(db, &version);
15005
0
  result = dns_db_findrdataset(db, node, version,
15006
0
             dns_rdatatype_nsec3param,
15007
0
             dns_rdatatype_none, 0, &rdataset, NULL);
15008
15009
0
  if (result != ISC_R_SUCCESS) {
15010
0
    goto getprivate;
15011
0
  }
15012
15013
  /*
15014
   * Walk nsec3param rdataset making a list of parameters (note that
15015
   * multiple simultaneous nsec3 chains are annoyingly legal -- this
15016
   * is why we use an nsec3list, even though we will usually only
15017
   * have one).
15018
   */
15019
0
  DNS_RDATASET_FOREACH(&rdataset) {
15020
0
    dns_rdata_t rdata = DNS_RDATA_INIT;
15021
0
    dns_rdata_t private = DNS_RDATA_INIT;
15022
15023
0
    dns_rdataset_current(&rdataset, &rdata);
15024
0
    isc_log_write(DNS_LOGCATEGORY_GENERAL, DNS_LOGMODULE_ZONE,
15025
0
            ISC_LOG_DEBUG(3),
15026
0
            "looping through nsec3param data");
15027
0
    nsec3param = isc_mem_get(zone->mctx, sizeof(nsec3param_t));
15028
0
    ISC_LINK_INIT(nsec3param, link);
15029
15030
    /*
15031
     * now transfer the data from the rdata to
15032
     * the nsec3param
15033
     */
15034
0
    dns_nsec3param_toprivate(&rdata, &private, zone->privatetype,
15035
0
           nsec3param->data,
15036
0
           sizeof(nsec3param->data));
15037
0
    nsec3param->length = private.length;
15038
0
    ISC_LIST_APPEND(*nsec3list, nsec3param, link);
15039
0
  }
15040
15041
0
getprivate:
15042
0
  result = dns_db_findrdataset(db, node, version, zone->privatetype,
15043
0
             dns_rdatatype_none, 0, &prdataset, NULL);
15044
0
  if (result != ISC_R_SUCCESS) {
15045
0
    goto done;
15046
0
  }
15047
15048
  /*
15049
   * walk private type records, converting them to nsec3 parameters
15050
   * using dns_nsec3param_fromprivate(), do the right thing based on
15051
   * CREATE and REMOVE flags
15052
   */
15053
0
  DNS_RDATASET_FOREACH(&prdataset) {
15054
0
    dns_rdata_t rdata = DNS_RDATA_INIT;
15055
0
    dns_rdata_t private = DNS_RDATA_INIT;
15056
15057
0
    dns_rdataset_current(&prdataset, &private);
15058
0
    isc_log_write(DNS_LOGCATEGORY_GENERAL, DNS_LOGMODULE_ZONE,
15059
0
            ISC_LOG_DEBUG(3),
15060
0
            "looping through nsec3param private data");
15061
15062
    /*
15063
     * Do we have a valid private record?
15064
     */
15065
0
    if (!dns_nsec3param_fromprivate(&private, &rdata, buf,
15066
0
            sizeof(buf)))
15067
0
    {
15068
0
      continue;
15069
0
    }
15070
15071
    /*
15072
     * Remove any NSEC3PARAM records scheduled to be removed.
15073
     */
15074
0
    if (NSEC3REMOVE(rdata.data[1])) {
15075
      /*
15076
       * Zero out the flags.
15077
       */
15078
0
      rdata.data[1] = 0;
15079
15080
0
      ISC_LIST_FOREACH(*nsec3list, nsec3p, link) {
15081
0
        if (nsec3p->length ==
15082
0
              (unsigned int)rdata.length + 1 &&
15083
0
            memcmp(rdata.data, nsec3p->data + 1,
15084
0
             nsec3p->length - 1) == 0)
15085
0
        {
15086
0
          ISC_LIST_UNLINK(*nsec3list, nsec3p,
15087
0
              link);
15088
0
          isc_mem_put(zone->mctx, nsec3p,
15089
0
                sizeof(nsec3param_t));
15090
0
        }
15091
0
      }
15092
0
      continue;
15093
0
    }
15094
15095
0
    nsec3param = isc_mem_get(zone->mctx, sizeof(nsec3param_t));
15096
0
    ISC_LINK_INIT(nsec3param, link);
15097
15098
    /*
15099
     * Copy the remaining private records so the nsec/nsec3
15100
     * chain gets created.
15101
     */
15102
0
    INSIST(private.length <= sizeof(nsec3param->data));
15103
0
    memmove(nsec3param->data, private.data, private.length);
15104
0
    nsec3param->length = private.length;
15105
0
    ISC_LIST_APPEND(*nsec3list, nsec3param, link);
15106
0
  }
15107
15108
0
done:
15109
0
  if (result == ISC_R_NOTFOUND) {
15110
0
    result = ISC_R_SUCCESS;
15111
0
  }
15112
15113
0
cleanup:
15114
0
  if (node != NULL) {
15115
0
    dns_db_detachnode(&node);
15116
0
  }
15117
0
  if (version != NULL) {
15118
0
    dns_db_closeversion(db, &version, false);
15119
0
  }
15120
0
  if (db != NULL) {
15121
0
    dns_db_detach(&db);
15122
0
  }
15123
0
  dns_rdataset_cleanup(&rdataset);
15124
0
  dns_rdataset_cleanup(&prdataset);
15125
0
  return result;
15126
0
}
15127
15128
/*
15129
 * Populate new zone db with private type records found by save_nsec3param().
15130
 */
15131
static isc_result_t
15132
restore_nsec3param(dns_zone_t *zone, dns_db_t *db, dns_dbversion_t *version,
15133
0
       nsec3paramlist_t *nsec3list) {
15134
0
  isc_result_t result = ISC_R_SUCCESS;
15135
0
  dns_diff_t diff;
15136
0
  dns_rdata_t rdata;
15137
15138
0
  REQUIRE(DNS_ZONE_VALID(zone));
15139
0
  REQUIRE(!ISC_LIST_EMPTY(*nsec3list));
15140
15141
0
  dns_diff_init(zone->mctx, &diff);
15142
15143
  /*
15144
   * Loop through the list of private-type records, set the INITIAL
15145
   * and CREATE flags, and the add the record to the apex of the tree
15146
   * in db.
15147
   */
15148
0
  ISC_LIST_FOREACH(*nsec3list, nsec3p, link) {
15149
0
    dns_rdata_init(&rdata);
15150
0
    nsec3p->data[2] = DNS_NSEC3FLAG_CREATE | DNS_NSEC3FLAG_INITIAL;
15151
0
    rdata.length = nsec3p->length;
15152
0
    rdata.data = nsec3p->data;
15153
0
    rdata.type = zone->privatetype;
15154
0
    rdata.rdclass = zone->rdclass;
15155
0
    result = update_one_rr(db, version, &diff, DNS_DIFFOP_ADD,
15156
0
               &zone->origin, 0, &rdata);
15157
0
    if (result != ISC_R_SUCCESS) {
15158
0
      break;
15159
0
    }
15160
0
  }
15161
15162
0
  dns_diff_clear(&diff);
15163
0
  return result;
15164
0
}
15165
15166
static isc_result_t
15167
copy_non_dnssec_records(dns_db_t *db, dns_dbversion_t *version, dns_db_t *rawdb,
15168
0
      dns_dbiterator_t *dbiterator, unsigned int *oldserial) {
15169
0
  dns_dbnode_t *rawnode = NULL, *node = NULL;
15170
0
  dns_fixedname_t fixed;
15171
0
  dns_name_t *name = dns_fixedname_initname(&fixed);
15172
0
  dns_rdatasetiter_t *rdsit = NULL;
15173
0
  isc_result_t result;
15174
15175
0
  result = dns_dbiterator_current(dbiterator, &rawnode, name);
15176
0
  if (result != ISC_R_SUCCESS) {
15177
0
    return ISC_R_SUCCESS;
15178
0
  }
15179
15180
0
  dns_dbiterator_pause(dbiterator);
15181
15182
0
  CHECK(dns_db_findnode(db, name, true, &node));
15183
15184
0
  CHECK(dns_db_allrdatasets(rawdb, rawnode, NULL, 0, 0, &rdsit));
15185
15186
0
  DNS_RDATASETITER_FOREACH(rdsit) {
15187
0
    dns_rdataset_t rdataset = DNS_RDATASET_INIT;
15188
0
    dns_rdatasetiter_current(rdsit, &rdataset);
15189
0
    if (rdataset.type == dns_rdatatype_nsec ||
15190
0
        rdataset.type == dns_rdatatype_rrsig ||
15191
0
        rdataset.type == dns_rdatatype_nsec3 ||
15192
0
        rdataset.type == dns_rdatatype_nsec3param)
15193
0
    {
15194
0
      dns_rdataset_disassociate(&rdataset);
15195
0
      continue;
15196
0
    }
15197
    /*
15198
     * Allow DNSKEY, CDNSKEY, CDS because users should be able to
15199
     * update the zone with these records from a different provider,
15200
     * and thus they may exist in the raw version of the zone.
15201
     */
15202
15203
0
    if (rdataset.type == dns_rdatatype_soa && oldserial != NULL) {
15204
0
      result = checkandaddsoa(db, node, version, name,
15205
0
            &rdataset, *oldserial);
15206
0
    } else {
15207
0
      result = dns_db_addrdataset(db, node, version, 0,
15208
0
                &rdataset, 0, NULL);
15209
0
    }
15210
0
    dns_rdataset_disassociate(&rdataset);
15211
0
    if (result != ISC_R_SUCCESS) {
15212
0
      break;
15213
0
    }
15214
0
  }
15215
15216
0
cleanup:
15217
0
  if (rdsit != NULL) {
15218
0
    dns_rdatasetiter_destroy(&rdsit);
15219
0
  }
15220
0
  if (rawnode) {
15221
0
    dns_db_detachnode(&rawnode);
15222
0
  }
15223
0
  if (node) {
15224
0
    dns_db_detachnode(&node);
15225
0
  }
15226
0
  return result;
15227
0
}
15228
15229
static isc_result_t
15230
0
secure_db_create_from_raw(dns_zone_t *zone, dns_db_t *rawdb, dns_db_t **dbp) {
15231
0
  isc_result_t result = ISC_R_SUCCESS;
15232
0
  dns_db_t *db = NULL;
15233
0
  dns_dbiterator_t *dbiterator = NULL;
15234
0
  dns_dbversion_t *version = NULL;
15235
0
  unsigned int oldserial = 0, *oldserialp = NULL;
15236
0
  nsec3paramlist_t nsec3list;
15237
15238
0
  REQUIRE(DNS_ZONE_VALID(zone));
15239
0
  REQUIRE(LOCKED_ZONE(zone));
15240
0
  REQUIRE(dbp != NULL && *dbp == NULL);
15241
15242
0
  ISC_LIST_INIT(nsec3list);
15243
0
  ZONEDB_LOCK(&zone->dblock, isc_rwlocktype_read);
15244
0
  if (zone->db != NULL) {
15245
0
    result = dns_db_getsoaserial(zone->db, NULL, &oldserial);
15246
0
    if (result == ISC_R_SUCCESS) {
15247
0
      oldserialp = &oldserial;
15248
0
    }
15249
15250
    /*
15251
     * assemble nsec3parameters from the old zone, and set a flag
15252
     * if any are found
15253
     */
15254
0
    result = save_nsec3param(zone, &nsec3list);
15255
0
    if (result != ISC_R_SUCCESS) {
15256
0
      ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_read);
15257
0
      goto cleanup;
15258
0
    }
15259
0
  }
15260
0
  ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_read);
15261
15262
0
  CHECK(dns_db_create(zone->mctx, zone->db_argv[0], &zone->origin,
15263
0
          dns_dbtype_zone, zone->rdclass, zone->db_argc - 1,
15264
0
          zone->db_argv + 1, &db));
15265
15266
0
  result = dns_db_setgluecachestats(db, zone->gluecachestats);
15267
0
  if (result != ISC_R_NOTIMPLEMENTED) {
15268
0
    CHECK(result);
15269
0
  }
15270
15271
0
  CHECK(dns_db_newversion(db, &version));
15272
0
  CHECK(dns_db_createiterator(rawdb, DNS_DB_NONSEC3, &dbiterator));
15273
15274
0
  DNS_DBITERATOR_FOREACH(dbiterator) {
15275
0
    CHECK(copy_non_dnssec_records(db, version, rawdb, dbiterator,
15276
0
                oldserialp));
15277
0
  }
15278
0
  dns_dbiterator_destroy(&dbiterator);
15279
15280
  /*
15281
   * Call restore_nsec3param() to create private-type records from
15282
   * the old nsec3 parameters and insert them into db
15283
   */
15284
0
  if (!ISC_LIST_EMPTY(nsec3list)) {
15285
0
    CHECK(restore_nsec3param(zone, db, version, &nsec3list));
15286
0
  }
15287
15288
0
  dns_db_closeversion(db, &version, true);
15289
0
  *dbp = MOVE_OWNERSHIP(db);
15290
15291
0
cleanup:
15292
0
  if (dbiterator != NULL) {
15293
0
    dns_dbiterator_destroy(&dbiterator);
15294
0
  }
15295
0
  while (!ISC_LIST_EMPTY(nsec3list)) {
15296
0
    nsec3param_t *nsec3p;
15297
0
    nsec3p = ISC_LIST_HEAD(nsec3list);
15298
0
    ISC_LIST_UNLINK(nsec3list, nsec3p, link);
15299
0
    isc_mem_put(zone->mctx, nsec3p, sizeof(nsec3param_t));
15300
0
  }
15301
0
  if (db != NULL) {
15302
0
    if (version != NULL) {
15303
0
      dns_db_closeversion(db, &version, false);
15304
0
    }
15305
0
    dns_db_detach(&db);
15306
0
  }
15307
15308
0
  INSIST(version == NULL);
15309
0
  return result;
15310
0
}
15311
15312
isc_result_t
15313
0
dns_zone_replacedb(dns_zone_t *zone, dns_db_t *db, bool dump) {
15314
0
  isc_result_t result;
15315
0
  dns_zone_t *secure = NULL;
15316
15317
0
  REQUIRE(DNS_ZONE_VALID(zone));
15318
0
again:
15319
0
  LOCK_ZONE(zone);
15320
0
  if (dns__zone_inline_raw(zone)) {
15321
0
    secure = zone->secure;
15322
0
    INSIST(secure != zone);
15323
0
    TRYLOCK_ZONE(result, secure);
15324
0
    if (result != ISC_R_SUCCESS) {
15325
0
      UNLOCK_ZONE(zone);
15326
0
      secure = NULL;
15327
0
      isc_thread_yield();
15328
0
      goto again;
15329
0
    }
15330
0
  }
15331
0
  ZONEDB_LOCK(&zone->dblock, isc_rwlocktype_write);
15332
0
  result = zone_replacedb(zone, db, dump);
15333
0
  ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_write);
15334
0
  if (secure != NULL) {
15335
0
    UNLOCK_ZONE(secure);
15336
0
  }
15337
0
  UNLOCK_ZONE(zone);
15338
0
  return result;
15339
0
}
15340
15341
static isc_result_t
15342
0
zone_replacedb(dns_zone_t *zone, dns_db_t *db, bool dump) {
15343
0
  dns_dbversion_t *ver;
15344
0
  isc_result_t result;
15345
0
  unsigned int soacount = 0;
15346
0
  unsigned int nscount = 0;
15347
15348
  /*
15349
   * 'zone' and 'zone->db' locked by caller.
15350
   */
15351
0
  REQUIRE(DNS_ZONE_VALID(zone));
15352
0
  REQUIRE(LOCKED_ZONE(zone));
15353
0
  if (dns__zone_inline_raw(zone)) {
15354
0
    REQUIRE(LOCKED_ZONE(zone->secure));
15355
0
  }
15356
15357
0
  result = zone_get_from_db(zone, db, &nscount, &soacount, NULL, NULL,
15358
0
          NULL, NULL, NULL, NULL, NULL);
15359
0
  if (result == ISC_R_SUCCESS) {
15360
0
    if (soacount != 1) {
15361
0
      dns_zone_log(zone, ISC_LOG_ERROR, "has %d SOA records",
15362
0
             soacount);
15363
0
      RETERR(DNS_R_BADZONE);
15364
0
    }
15365
0
    if (nscount == 0 && DNS_ZONE_OPTION(zone, DNS_ZONEOPT_CHECKNS))
15366
0
    {
15367
0
      dns_zone_log(zone, ISC_LOG_WARNING,
15368
0
             "has no NS records");
15369
0
      if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_FATALNS)) {
15370
0
        RETERR(DNS_R_BADZONE);
15371
0
      }
15372
0
    }
15373
0
  } else {
15374
0
    dns_zone_log(zone, ISC_LOG_ERROR,
15375
0
           "retrieving SOA and NS records failed: %s",
15376
0
           isc_result_totext(result));
15377
0
    return result;
15378
0
  }
15379
15380
0
  RETERR(check_nsec3param(zone, db));
15381
15382
0
  ver = NULL;
15383
0
  dns_db_currentversion(db, &ver);
15384
15385
  /*
15386
   * The initial version of a secondary zone is always dumped;
15387
   * subsequent versions may be journaled instead if this
15388
   * is enabled in the configuration.
15389
   */
15390
0
  if (zone->db != NULL && zone->journal != NULL &&
15391
0
      DNS_ZONE_OPTION(zone, DNS_ZONEOPT_IXFRFROMDIFFS) &&
15392
0
      !DNS_ZONE_FLAG(zone, DNS_ZONEFLG_FORCEXFER))
15393
0
  {
15394
0
    uint32_t serial, oldserial;
15395
15396
0
    dns_zone_log(zone, ISC_LOG_DEBUG(3), "generating diffs");
15397
15398
0
    result = dns_db_getsoaserial(db, ver, &serial);
15399
0
    if (result != ISC_R_SUCCESS) {
15400
0
      dns_zone_log(zone, ISC_LOG_ERROR,
15401
0
             "ixfr-from-differences: unable to get "
15402
0
             "new serial");
15403
0
      goto fail;
15404
0
    }
15405
15406
    /*
15407
     * This is checked in zone_postload() for primary zones.
15408
     */
15409
0
    result = zone_get_from_db(zone, zone->db, NULL, &soacount, NULL,
15410
0
            &oldserial, NULL, NULL, NULL, NULL,
15411
0
            NULL);
15412
0
    RUNTIME_CHECK(result == ISC_R_SUCCESS);
15413
0
    RUNTIME_CHECK(soacount > 0U);
15414
0
    if ((zone->type == dns_zone_secondary ||
15415
0
         (zone->type == dns_zone_redirect &&
15416
0
          dns_remote_addresses(&zone->primaries) != NULL)) &&
15417
0
        !isc_serial_gt(serial, oldserial))
15418
0
    {
15419
0
      uint32_t serialmin, serialmax;
15420
0
      serialmin = (oldserial + 1) & 0xffffffffU;
15421
0
      serialmax = (oldserial + 0x7fffffffU) & 0xffffffffU;
15422
0
      dns_zone_log(zone, ISC_LOG_ERROR,
15423
0
             "ixfr-from-differences: failed: "
15424
0
             "new serial (%u) out of range [%u - %u]",
15425
0
             serial, serialmin, serialmax);
15426
0
      result = ISC_R_RANGE;
15427
0
      goto fail;
15428
0
    }
15429
15430
0
    result = dns_db_diff(zone->mctx, db, ver, zone->db, NULL,
15431
0
             zone->journal);
15432
0
    if (result != ISC_R_SUCCESS) {
15433
0
      char strbuf[ISC_STRERRORSIZE];
15434
0
      strerror_r(errno, strbuf, sizeof(strbuf));
15435
0
      dns_zone_log(zone, ISC_LOG_ERROR,
15436
0
             "ixfr-from-differences: failed: "
15437
0
             "%s",
15438
0
             strbuf);
15439
0
      goto fallback;
15440
0
    }
15441
0
    if (dump) {
15442
0
      zone_needdump(zone, DNS_DUMP_DELAY);
15443
0
    } else {
15444
0
      zone_journal_compact(zone, zone->db, serial);
15445
0
    }
15446
0
    if (zone->type == dns_zone_primary &&
15447
0
        dns__zone_inline_raw(zone))
15448
0
    {
15449
0
      zone_schedule_inline_sync(zone->secure,
15450
0
              inline_sync_incremental);
15451
0
    }
15452
0
  } else {
15453
0
  fallback:
15454
0
    if (dump && zone->masterfile != NULL) {
15455
      /*
15456
       * If DNS_ZONEFLG_FORCEXFER was set we don't want
15457
       * to keep the old masterfile.
15458
       */
15459
0
      if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_FORCEXFER) &&
15460
0
          remove(zone->masterfile) < 0 && errno != ENOENT)
15461
0
      {
15462
0
        char strbuf[ISC_STRERRORSIZE];
15463
0
        strerror_r(errno, strbuf, sizeof(strbuf));
15464
0
        isc_log_write(DNS_LOGCATEGORY_GENERAL,
15465
0
                DNS_LOGMODULE_ZONE,
15466
0
                ISC_LOG_WARNING,
15467
0
                "unable to remove masterfile "
15468
0
                "'%s': '%s'",
15469
0
                zone->masterfile, strbuf);
15470
0
      }
15471
0
      if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_LOADED) == 0) {
15472
0
        DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_NODELAY);
15473
0
      } else {
15474
0
        zone_needdump(zone, 0);
15475
0
      }
15476
0
    }
15477
0
    if (dump && zone->journal != NULL) {
15478
      /*
15479
       * The in-memory database just changed, and
15480
       * because 'dump' is set, it didn't change by
15481
       * being loaded from disk.  Also, we have not
15482
       * journaled diffs for this change.
15483
       * Therefore, the on-disk journal is missing
15484
       * the deltas for this change.  Since it can
15485
       * no longer be used to bring the zone
15486
       * up-to-date, it is useless and should be
15487
       * removed.
15488
       */
15489
0
      isc_log_write(DNS_LOGCATEGORY_GENERAL,
15490
0
              DNS_LOGMODULE_ZONE, ISC_LOG_DEBUG(3),
15491
0
              "removing journal file");
15492
0
      if (remove(zone->journal) < 0 && errno != ENOENT) {
15493
0
        char strbuf[ISC_STRERRORSIZE];
15494
0
        strerror_r(errno, strbuf, sizeof(strbuf));
15495
0
        isc_log_write(DNS_LOGCATEGORY_GENERAL,
15496
0
                DNS_LOGMODULE_ZONE,
15497
0
                ISC_LOG_WARNING,
15498
0
                "unable to remove journal "
15499
0
                "'%s': '%s'",
15500
0
                zone->journal, strbuf);
15501
0
      }
15502
0
    }
15503
15504
0
    if (dns__zone_inline_raw(zone)) {
15505
0
      zone_schedule_inline_sync(zone->secure,
15506
0
              inline_sync_full);
15507
0
    }
15508
0
  }
15509
15510
0
  dns_db_closeversion(db, &ver, false);
15511
15512
0
  dns_zone_log(zone, ISC_LOG_DEBUG(3), "replacing zone database");
15513
15514
0
  if (zone->db != NULL) {
15515
0
    zone_detachdb(zone);
15516
0
  }
15517
0
  zone_attachdb(zone, db);
15518
0
  dns_db_setmaxrrperset(zone->db, zone->maxrrperset);
15519
0
  dns_db_setmaxtypepername(zone->db, zone->maxtypepername);
15520
0
  DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_LOADED | DNS_ZONEFLG_NEEDNOTIFY);
15521
0
  return ISC_R_SUCCESS;
15522
15523
0
fail:
15524
0
  dns_db_closeversion(db, &ver, false);
15525
0
  return result;
15526
0
}
15527
15528
/* The caller must hold the dblock as a writer. */
15529
static void
15530
0
zone_attachdb(dns_zone_t *zone, dns_db_t *db) {
15531
0
  REQUIRE(zone->db == NULL && db != NULL);
15532
15533
0
  dns_db_attach(db, &zone->db);
15534
0
}
15535
15536
/* The caller must hold the dblock as a writer. */
15537
static void
15538
0
zone_detachdb(dns_zone_t *zone) {
15539
0
  REQUIRE(zone->db != NULL);
15540
15541
0
  dns_zone_rpz_disable_db(zone, zone->db);
15542
0
  dns_zone_catz_disable_db(zone, zone->db);
15543
0
  dns_db_detach(&zone->db);
15544
0
}
15545
15546
void
15547
0
dns__zone_xfrdone(dns_zone_t *zone, uint32_t *expireopt, isc_result_t result) {
15548
0
  isc_time_t now, expiretime;
15549
0
  bool again = false;
15550
0
  unsigned int soacount;
15551
0
  unsigned int nscount;
15552
0
  uint32_t serial, refresh, retry, expire, minimum, soattl, oldexpire;
15553
0
  isc_result_t xfrresult = result;
15554
0
  bool free_needed;
15555
0
  dns_zone_t *secure = NULL;
15556
15557
0
  REQUIRE(DNS_ZONE_VALID(zone));
15558
15559
0
  dns_zone_logc(
15560
0
    zone, DNS_LOGCATEGORY_XFER_IN, ISC_LOG_DEBUG(1),
15561
0
    expireopt == NULL ? "zone transfer finished: %s"
15562
0
          : "zone transfer finished: %s, expire=%u",
15563
0
    isc_result_totext(result), expireopt != NULL ? *expireopt : 0);
15564
15565
  /*
15566
   * Obtaining a lock on the zone->secure (see zone_schedule_inline_sync)
15567
   * could result in a deadlock due to a LOR so we will spin if we
15568
   * can't obtain both locks.
15569
   */
15570
0
again:
15571
0
  LOCK_ZONE(zone);
15572
0
  if (dns__zone_inline_raw(zone)) {
15573
0
    secure = zone->secure;
15574
0
    INSIST(secure != zone);
15575
0
    TRYLOCK_ZONE(result, secure);
15576
0
    if (result != ISC_R_SUCCESS) {
15577
0
      UNLOCK_ZONE(zone);
15578
0
      secure = NULL;
15579
0
      isc_thread_yield();
15580
0
      goto again;
15581
0
    }
15582
0
  }
15583
15584
0
  INSIST(DNS_ZONE_FLAG(zone, DNS_ZONEFLG_REFRESH));
15585
0
  DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_REFRESH);
15586
0
  DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_SOABEFOREAXFR);
15587
15588
0
  now = isc_time_now();
15589
0
  switch (xfrresult) {
15590
0
  case ISC_R_SUCCESS:
15591
0
    DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_NEEDNOTIFY);
15592
0
    FALLTHROUGH;
15593
0
  case DNS_R_UPTODATE:
15594
0
    DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_FORCEXFER |
15595
0
                 DNS_ZONEFLG_FIRSTREFRESH);
15596
    /*
15597
     * Has the zone expired underneath us?
15598
     */
15599
0
    ZONEDB_LOCK(&zone->dblock, isc_rwlocktype_read);
15600
0
    if (zone->db == NULL) {
15601
0
      ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_read);
15602
0
      goto same_primary;
15603
0
    }
15604
15605
0
    oldexpire = zone->expire;
15606
15607
    /*
15608
     * Update the zone structure's data from the actual
15609
     * SOA received.
15610
     */
15611
0
    nscount = 0;
15612
0
    soacount = 0;
15613
0
    INSIST(zone->db != NULL);
15614
0
    result = zone_get_from_db(zone, zone->db, &nscount, &soacount,
15615
0
            &soattl, &serial, &refresh, &retry,
15616
0
            &expire, &minimum, NULL);
15617
0
    ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_read);
15618
0
    if (result == ISC_R_SUCCESS) {
15619
0
      if (soacount != 1) {
15620
0
        dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN,
15621
0
                ISC_LOG_ERROR,
15622
0
                "transferred zone "
15623
0
                "has %d SOA records",
15624
0
                soacount);
15625
0
        if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_HAVETIMERS))
15626
0
        {
15627
0
          zone->refresh = DNS_ZONE_DEFAULTREFRESH;
15628
0
          zone->retry = DNS_ZONE_DEFAULTRETRY;
15629
0
        }
15630
0
        DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_HAVETIMERS);
15631
0
        zone_unload(zone);
15632
0
        goto next_primary;
15633
0
      }
15634
0
      if (nscount == 0 &&
15635
0
          DNS_ZONE_OPTION(zone, DNS_ZONEOPT_CHECKNS))
15636
0
      {
15637
0
        dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN,
15638
0
                ISC_LOG_WARNING,
15639
0
                "transferred zone "
15640
0
                "has no NS records");
15641
0
        if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_FATALNS))
15642
0
        {
15643
0
          if (DNS_ZONE_FLAG(
15644
0
                zone,
15645
0
                DNS_ZONEFLG_HAVETIMERS))
15646
0
          {
15647
0
            zone->refresh =
15648
0
              DNS_ZONE_DEFAULTREFRESH;
15649
0
            zone->retry =
15650
0
              DNS_ZONE_DEFAULTRETRY;
15651
0
          }
15652
0
          DNS_ZONE_CLRFLAG(
15653
0
            zone, DNS_ZONEFLG_HAVETIMERS);
15654
0
          zone_unload(zone);
15655
0
          goto next_primary;
15656
0
        }
15657
0
      }
15658
0
      zone->refresh = RANGE(refresh, zone->minrefresh,
15659
0
                zone->maxrefresh);
15660
0
      zone->retry = RANGE(retry, zone->minretry,
15661
0
              zone->maxretry);
15662
0
      zone->expire = RANGE(expire,
15663
0
               zone->refresh + zone->retry,
15664
0
               DNS_MAX_EXPIRE);
15665
0
      zone->soattl = soattl;
15666
0
      zone->minimum = minimum;
15667
0
      DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_HAVETIMERS);
15668
0
    }
15669
15670
    /*
15671
     * Set our next refresh time.
15672
     */
15673
0
    if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NEEDREFRESH)) {
15674
0
      DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_NEEDREFRESH);
15675
0
      zone->refreshtime = now;
15676
0
    } else {
15677
0
      DNS_ZONE_JITTER_ADD(&now, zone->refresh,
15678
0
              &zone->refreshtime);
15679
0
    }
15680
15681
    /*
15682
     * Set our next expire time. If the parent returned
15683
     * an EXPIRE option use that to update zone->expiretime.
15684
     */
15685
0
    expire = zone->expire;
15686
0
    if (expireopt != NULL && *expireopt < expire) {
15687
0
      expire = *expireopt;
15688
0
    }
15689
0
    DNS_ZONE_TIME_ADD(&now, expire, &expiretime);
15690
0
    if (oldexpire != zone->expire ||
15691
0
        isc_time_compare(&expiretime, &zone->expiretime) > 0)
15692
0
    {
15693
0
      zone->expiretime = expiretime;
15694
0
      DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_EXPIRED);
15695
0
    }
15696
15697
    /*
15698
     * Set loadtime.
15699
     */
15700
0
    zone->loadtime = now;
15701
15702
0
    if (result == ISC_R_SUCCESS && xfrresult == ISC_R_SUCCESS) {
15703
0
      char buf[DNS_NAME_FORMATSIZE + sizeof(": TSIG ''")];
15704
0
      if (zone->tsigkey != NULL) {
15705
0
        char namebuf[DNS_NAME_FORMATSIZE];
15706
0
        dns_name_format(zone->tsigkey->name, namebuf,
15707
0
            sizeof(namebuf));
15708
0
        snprintf(buf, sizeof(buf), ": TSIG '%s'",
15709
0
           namebuf);
15710
0
      } else {
15711
0
        buf[0] = '\0';
15712
0
      }
15713
0
      dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN,
15714
0
              ISC_LOG_INFO, "transferred serial %u%s",
15715
0
              serial, buf);
15716
0
      if (dns__zone_inline_raw(zone)) {
15717
0
        zone_schedule_inline_sync(
15718
0
          secure, inline_sync_incremental);
15719
0
      }
15720
0
    }
15721
15722
    /*
15723
     * This is not necessary if we just performed a AXFR
15724
     * however it is necessary for an IXFR / UPTODATE and
15725
     * won't hurt with an AXFR.
15726
     */
15727
0
    if (zone->masterfile != NULL || zone->journal != NULL) {
15728
0
      unsigned int delay = DNS_DUMP_DELAY;
15729
0
      isc_interval_t i;
15730
0
      isc_time_t when;
15731
15732
      /*
15733
       * Compute effective modification time.
15734
       */
15735
0
      isc_interval_set(&i, zone->expire, 0);
15736
0
      result = isc_time_subtract(&zone->expiretime, &i,
15737
0
               &when);
15738
0
      if (result != ISC_R_SUCCESS) {
15739
0
        when = now;
15740
0
      }
15741
15742
0
      result = ISC_R_FAILURE;
15743
0
      if (zone->journal != NULL) {
15744
0
        result = isc_file_settime(zone->journal, &when);
15745
0
      }
15746
0
      if (result != ISC_R_SUCCESS && zone->masterfile != NULL)
15747
0
      {
15748
0
        result = isc_file_settime(zone->masterfile,
15749
0
                &when);
15750
0
      }
15751
15752
0
      if ((DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NODELAY) != 0) ||
15753
0
          result == ISC_R_FILENOTFOUND)
15754
0
      {
15755
0
        delay = 0;
15756
0
      }
15757
15758
0
      if ((result == ISC_R_SUCCESS ||
15759
0
           result == ISC_R_FILENOTFOUND) &&
15760
0
          zone->masterfile != NULL)
15761
0
      {
15762
0
        zone_needdump(zone, delay);
15763
0
      } else if (result != ISC_R_SUCCESS) {
15764
0
        dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN,
15765
0
                ISC_LOG_ERROR,
15766
0
                "transfer: could not set file "
15767
0
                "modification time of '%s': %s",
15768
0
                zone->masterfile,
15769
0
                isc_result_totext(result));
15770
0
      }
15771
0
    }
15772
0
    DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_NODELAY);
15773
0
    dns__zone_stats_increment(zone,
15774
0
            dns_zonestatscounter_xfrsuccess);
15775
0
    break;
15776
15777
0
  case DNS_R_BADIXFR:
15778
    /* Force retry with AXFR. */
15779
0
    DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_NOIXFR);
15780
0
    goto same_primary;
15781
15782
0
  case ISC_R_SHUTTINGDOWN:
15783
0
    dns_remote_reset(&zone->primaries, true);
15784
0
    break;
15785
15786
0
  default:
15787
0
  next_primary:
15788
    /*
15789
     * Skip to next failed / untried primary.
15790
     */
15791
0
    dns_remote_next(&zone->primaries, true);
15792
0
  same_primary:
15793
0
    if (dns_remote_done(&zone->primaries)) {
15794
0
      dns_remote_reset(&zone->primaries, false);
15795
0
    } else {
15796
0
      DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_REFRESH);
15797
0
      again = true;
15798
0
    }
15799
0
    dns__zone_stats_increment(zone, dns_zonestatscounter_xfrfail);
15800
0
    break;
15801
0
  }
15802
0
  dns__zone_settimer(zone, now);
15803
15804
  /*
15805
   * We are called as the done callback of a zone
15806
   * transfer object that just entered its shutting-down state or
15807
   * failed to start.  Since we are no longer responsible for shutting
15808
   * it down, we can detach our reference.
15809
   */
15810
0
  if (zone->xfr != NULL) {
15811
0
    dns_xfrin_detach(&zone->xfr);
15812
0
  }
15813
15814
0
  if (zone->tsigkey != NULL) {
15815
0
    dns_tsigkey_detach(&zone->tsigkey);
15816
0
  }
15817
15818
0
  if (zone->transport != NULL) {
15819
0
    dns_transport_detach(&zone->transport);
15820
0
  }
15821
15822
  /*
15823
   * Handle any deferred journal compaction.
15824
   */
15825
0
  if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NEEDCOMPACT)) {
15826
0
    dns_db_t *db = NULL;
15827
0
    if (dns_zone_getdb(zone, &db) == ISC_R_SUCCESS) {
15828
0
      zone_journal_compact(zone, db, zone->compact_serial);
15829
0
      dns_db_detach(&db);
15830
0
      DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_NEEDCOMPACT);
15831
0
    }
15832
0
  }
15833
15834
0
  if (secure != NULL) {
15835
0
    UNLOCK_ZONE(secure);
15836
0
  }
15837
  /*
15838
   * This transfer finishing freed up a transfer quota slot.
15839
   * Let any other zones waiting for quota have it.
15840
   */
15841
0
  if (zone->loop != NULL &&
15842
0
      zone->statelist == &dns_g_zonemgr->xfrin_in_progress)
15843
0
  {
15844
0
    UNLOCK_ZONE(zone);
15845
0
    RWLOCK(&dns_g_zonemgr->rwlock, isc_rwlocktype_write);
15846
0
    ISC_LIST_UNLINK(dns_g_zonemgr->xfrin_in_progress, zone,
15847
0
        statelink);
15848
0
    zone->statelist = NULL;
15849
0
    dns__zonemgr_resume_xfrs(dns_g_zonemgr, false);
15850
0
    RWUNLOCK(&dns_g_zonemgr->rwlock, isc_rwlocktype_write);
15851
0
    LOCK_ZONE(zone);
15852
0
  }
15853
15854
  /*
15855
   * Retry with a different server if necessary.
15856
   */
15857
0
  if (again && !DNS_ZONE_FLAG(zone, DNS_ZONEFLG_EXITING)) {
15858
0
    queue_soa_query(zone);
15859
0
  }
15860
15861
0
  isc_refcount_decrement(&zone->irefs);
15862
0
  free_needed = dns__zone_free_check(zone);
15863
0
  UNLOCK_ZONE(zone);
15864
0
  if (free_needed) {
15865
0
    dns__zone_free(zone);
15866
0
  }
15867
0
}
15868
15869
static void
15870
0
zone_loaddone(void *arg, isc_result_t result) {
15871
0
  dns_load_t *load = arg;
15872
0
  dns_zone_t *zone;
15873
0
  isc_result_t postload_result, tresult;
15874
0
  dns_zone_t *secure = NULL;
15875
15876
0
  zone = load->zone;
15877
15878
0
  ENTER;
15879
15880
  /*
15881
   * If zone loading failed, remove the update db callbacks prior
15882
   * to calling the list of callbacks in the zone load structure.
15883
   */
15884
0
  if (result != ISC_R_SUCCESS && result != DNS_R_SEENINCLUDE) {
15885
0
    dns_zone_rpz_disable_db(zone, load->db);
15886
0
    dns_zone_catz_disable_db(zone, load->db);
15887
0
  }
15888
15889
0
  tresult = dns_db_endload(load->db, &load->callbacks);
15890
0
  if (tresult != ISC_R_SUCCESS &&
15891
0
      (result == ISC_R_SUCCESS || result == DNS_R_SEENINCLUDE))
15892
0
  {
15893
0
    result = tresult;
15894
0
  }
15895
15896
  /*
15897
   * Lock hierarchy: zmgr, zone, secure.
15898
   */
15899
0
again:
15900
0
  LOCK_ZONE(zone);
15901
0
  INSIST(zone != zone->raw);
15902
0
  if (dns__zone_inline_raw(zone)) {
15903
0
    secure = zone->secure;
15904
0
    TRYLOCK_ZONE(tresult, secure);
15905
0
    if (tresult != ISC_R_SUCCESS) {
15906
0
      UNLOCK_ZONE(zone);
15907
0
      secure = NULL;
15908
0
      isc_thread_yield();
15909
0
      goto again;
15910
0
    }
15911
0
  }
15912
0
  postload_result = zone_postload(zone, load->db, load->loadtime, result);
15913
0
  if (postload_result == ISC_R_SUCCESS && dns__zone_inline_secure(zone)) {
15914
0
    zone_schedule_inline_sync(zone, inline_sync_incremental);
15915
0
  }
15916
0
  DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_LOADING);
15917
0
  zone_idetach(&load->callbacks.zone);
15918
  /*
15919
   * Leave the zone frozen if the reload fails.
15920
   */
15921
0
  if ((result == ISC_R_SUCCESS || result == DNS_R_SEENINCLUDE) &&
15922
0
      DNS_ZONE_FLAG(zone, DNS_ZONEFLG_THAW))
15923
0
  {
15924
0
    zone->update_disabled = false;
15925
0
  }
15926
0
  DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_THAW);
15927
0
  if (secure != NULL) {
15928
0
    UNLOCK_ZONE(secure);
15929
0
  }
15930
0
  UNLOCK_ZONE(zone);
15931
15932
0
  dns_db_detach(&load->db);
15933
0
  if (zone->loadctx != NULL) {
15934
0
    dns_loadctx_detach(&zone->loadctx);
15935
0
  }
15936
0
  isc_mem_put(zone->mctx, load, sizeof(*load));
15937
15938
0
  dns_zone_idetach(&zone);
15939
0
}
15940
15941
static void
15942
0
queue_xfrin(dns_zone_t *zone) {
15943
0
  isc_result_t result;
15944
0
  dns_zonemgr_t *zmgr = dns_g_zonemgr;
15945
15946
0
  ENTER;
15947
15948
0
  INSIST(zone->statelist == NULL);
15949
15950
0
  RWLOCK(&zmgr->rwlock, isc_rwlocktype_write);
15951
0
  ISC_LIST_APPEND(zmgr->waiting_for_xfrin, zone, statelink);
15952
0
  isc_refcount_increment0(&zone->irefs);
15953
0
  zone->statelist = &zmgr->waiting_for_xfrin;
15954
0
  result = dns__zonemgr_start_xfrin_ifquota(zmgr, zone);
15955
0
  RWUNLOCK(&zmgr->rwlock, isc_rwlocktype_write);
15956
15957
0
  if (result == ISC_R_QUOTA) {
15958
0
    dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN, ISC_LOG_INFO,
15959
0
            "zone transfer deferred due to quota");
15960
0
  } else if (result != ISC_R_SUCCESS) {
15961
0
    dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN, ISC_LOG_ERROR,
15962
0
            "starting zone transfer: %s",
15963
0
            isc_result_totext(result));
15964
0
  }
15965
0
}
15966
15967
/*
15968
 * Update forwarding support.
15969
 */
15970
15971
static void
15972
0
forward_destroy(dns_forward_t *forward) {
15973
0
  forward->magic = 0;
15974
0
  if (forward->request != NULL) {
15975
0
    dns_request_destroy(&forward->request);
15976
0
  }
15977
0
  if (forward->msgbuf != NULL) {
15978
0
    isc_buffer_free(&forward->msgbuf);
15979
0
  }
15980
0
  if (forward->transport != NULL) {
15981
0
    dns_transport_detach(&forward->transport);
15982
0
  }
15983
0
  if (forward->zone != NULL) {
15984
0
    LOCK(&forward->zone->lock);
15985
0
    if (ISC_LINK_LINKED(forward, link)) {
15986
0
      ISC_LIST_UNLINK(forward->zone->forwards, forward, link);
15987
0
    }
15988
0
    UNLOCK(&forward->zone->lock);
15989
0
    dns_zone_idetach(&forward->zone);
15990
0
  }
15991
0
  isc_mem_putanddetach(&forward->mctx, forward, sizeof(*forward));
15992
0
}
15993
15994
static isc_result_t
15995
0
sendtoprimary(dns_forward_t *forward) {
15996
0
  isc_result_t result;
15997
0
  isc_sockaddr_t src, any;
15998
0
  dns_zone_t *zone = forward->zone;
15999
0
  bool tls_transport_invalid = false;
16000
0
  isc_tlsctx_cache_t *zmgr_tlsctx_cache = NULL;
16001
16002
0
  LOCK_ZONE(zone);
16003
16004
0
  if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_EXITING)) {
16005
0
    UNLOCK_ZONE(zone);
16006
0
    return ISC_R_CANCELED;
16007
0
  }
16008
16009
0
next:
16010
0
  if (forward->which >= dns_remote_count(&forward->zone->primaries)) {
16011
0
    UNLOCK_ZONE(zone);
16012
0
    return ISC_R_NOMORE;
16013
0
  }
16014
16015
0
  forward->addr = dns_remote_addr(&zone->primaries, forward->which);
16016
16017
0
  if (isc_sockaddr_disabled(&forward->addr)) {
16018
0
    forward->which++;
16019
0
    goto next;
16020
0
  }
16021
16022
  /*
16023
   * Always use TCP regardless of whether the original update used TCP.
16024
   */
16025
0
  switch (isc_sockaddr_pf(&forward->addr)) {
16026
0
  case PF_INET:
16027
0
    isc_sockaddr_any(&any);
16028
0
    src = zone->primaries.sources[forward->which];
16029
0
    if (isc_sockaddr_equal(&src, &any)) {
16030
0
      src = zone_addr4_tosockaddr(&zone->xfrsource4);
16031
0
    }
16032
0
    break;
16033
0
  case PF_INET6:
16034
0
    isc_sockaddr_any6(&any);
16035
0
    src = zone->primaries.sources[forward->which];
16036
0
    if (isc_sockaddr_equal(&src, &any)) {
16037
0
      src = zone_addr6_tosockaddr(&zone->xfrsource6);
16038
0
    }
16039
0
    break;
16040
0
  default:
16041
0
    result = ISC_R_NOTIMPLEMENTED;
16042
0
    goto unlock;
16043
0
  }
16044
16045
0
  if (forward->transport != NULL) {
16046
0
    dns_transport_detach(&forward->transport);
16047
0
  }
16048
16049
0
  if (dns_remote_tlsname(&zone->primaries) != NULL &&
16050
0
      zone->primaries.tlsnames[forward->which] != NULL)
16051
0
  {
16052
0
    dns_view_t *view = dns_zone_getview(zone);
16053
0
    dns_name_t *tlsname = zone->primaries.tlsnames[forward->which];
16054
16055
0
    result = dns_view_gettransport(view, DNS_TRANSPORT_TLS, tlsname,
16056
0
                 &forward->transport);
16057
16058
0
    if (result != ISC_R_SUCCESS) {
16059
      /* Log the error message when unlocked. */
16060
0
      tls_transport_invalid = true;
16061
0
      goto unlock;
16062
0
    }
16063
0
  }
16064
16065
0
  dns__zonemgr_tlsctx_attach(dns_g_zonemgr, &zmgr_tlsctx_cache);
16066
0
  const unsigned int connect_timeout = isc_nm_getprimariestimeout() /
16067
0
               MS_PER_SEC;
16068
0
  result = dns_request_createraw(
16069
0
    forward->zone->view->requestmgr, forward->msgbuf, &src,
16070
0
    &forward->addr, forward->transport, zmgr_tlsctx_cache,
16071
0
    forward->options, connect_timeout, TCP_REQUEST_TIMEOUT, 0, 0,
16072
0
    forward->zone->loop, forward_callback, forward,
16073
0
    &forward->request);
16074
16075
0
  isc_tlsctx_cache_detach(&zmgr_tlsctx_cache);
16076
16077
0
  if (result == ISC_R_SUCCESS) {
16078
0
    if (!ISC_LINK_LINKED(forward, link)) {
16079
0
      ISC_LIST_APPEND(zone->forwards, forward, link);
16080
0
    }
16081
0
  }
16082
16083
0
unlock:
16084
0
  UNLOCK_ZONE(zone);
16085
16086
0
  if (tls_transport_invalid) {
16087
0
    dns_zone_log(zone, ISC_LOG_ERROR,
16088
0
           "could not get TLS configuration "
16089
0
           "for dynamic update: %s",
16090
0
           isc_result_totext(result));
16091
0
  }
16092
16093
0
  return result;
16094
0
}
16095
16096
static void
16097
0
forward_callback(void *arg) {
16098
0
  dns_request_t *request = (dns_request_t *)arg;
16099
0
  dns_forward_t *forward = dns_request_getarg(request);
16100
0
  dns_message_t *msg = NULL;
16101
0
  char primary[ISC_SOCKADDR_FORMATSIZE];
16102
0
  isc_result_t result;
16103
0
  dns_zone_t *zone;
16104
16105
0
  INSIST(DNS_FORWARD_VALID(forward));
16106
0
  zone = forward->zone;
16107
0
  INSIST(DNS_ZONE_VALID(zone));
16108
16109
0
  ENTER;
16110
16111
0
  isc_sockaddr_format(&forward->addr, primary, sizeof(primary));
16112
16113
0
  result = dns_request_getresult(request);
16114
0
  if (result != ISC_R_SUCCESS) {
16115
0
    dns_zone_log(zone, ISC_LOG_INFO,
16116
0
           "could not forward dynamic update to %s: %s",
16117
0
           primary, isc_result_totext(result));
16118
0
    goto next_primary;
16119
0
  }
16120
16121
0
  dns_message_create(zone->mctx, NULL, NULL, DNS_MESSAGE_INTENTPARSE,
16122
0
         &msg);
16123
16124
0
  result = dns_request_getresponse(request, msg,
16125
0
           DNS_MESSAGEPARSE_PRESERVEORDER |
16126
0
             DNS_MESSAGEPARSE_CLONEBUFFER);
16127
0
  if (result != ISC_R_SUCCESS) {
16128
0
    goto next_primary;
16129
0
  }
16130
16131
  /*
16132
   * Unexpected opcode.
16133
   */
16134
0
  if (msg->opcode != dns_opcode_update) {
16135
0
    char opcode[128];
16136
0
    isc_buffer_t rb;
16137
16138
0
    isc_buffer_init(&rb, opcode, sizeof(opcode));
16139
0
    (void)dns_opcode_totext(msg->opcode, &rb);
16140
16141
0
    dns_zone_log(zone, ISC_LOG_INFO,
16142
0
           "forwarding dynamic update: "
16143
0
           "unexpected opcode (%.*s) from %s",
16144
0
           (int)rb.used, opcode, primary);
16145
0
    goto next_primary;
16146
0
  }
16147
16148
0
  switch (msg->rcode) {
16149
  /*
16150
   * Pass these rcodes back to client.
16151
   */
16152
0
  case dns_rcode_noerror:
16153
0
  case dns_rcode_yxdomain:
16154
0
  case dns_rcode_yxrrset:
16155
0
  case dns_rcode_nxrrset:
16156
0
  case dns_rcode_refused:
16157
0
  case dns_rcode_nxdomain: {
16158
0
    char rcode[128];
16159
0
    isc_buffer_t rb;
16160
16161
0
    isc_buffer_init(&rb, rcode, sizeof(rcode));
16162
0
    (void)dns_rcode_totext(msg->rcode, &rb);
16163
0
    dns_zone_log(zone, ISC_LOG_INFO,
16164
0
           "forwarded dynamic update: "
16165
0
           "primary %s returned: %.*s",
16166
0
           primary, (int)rb.used, rcode);
16167
0
    break;
16168
0
  }
16169
16170
  /* These should not occur if the primaries/zone are valid. */
16171
0
  case dns_rcode_notzone:
16172
0
  case dns_rcode_notauth: {
16173
0
    char rcode[128];
16174
0
    isc_buffer_t rb;
16175
16176
0
    isc_buffer_init(&rb, rcode, sizeof(rcode));
16177
0
    (void)dns_rcode_totext(msg->rcode, &rb);
16178
0
    dns_zone_log(zone, ISC_LOG_WARNING,
16179
0
           "forwarding dynamic update: "
16180
0
           "unexpected response: primary %s returned: %.*s",
16181
0
           primary, (int)rb.used, rcode);
16182
0
    goto next_primary;
16183
0
  }
16184
16185
  /* Try another server for these rcodes. */
16186
0
  case dns_rcode_formerr:
16187
0
  case dns_rcode_servfail:
16188
0
  case dns_rcode_notimp:
16189
0
  case dns_rcode_badvers:
16190
0
  default:
16191
0
    goto next_primary;
16192
0
  }
16193
16194
  /* call callback */
16195
0
  (forward->callback)(forward->callback_arg, ISC_R_SUCCESS, msg);
16196
0
  msg = NULL;
16197
0
  dns_request_destroy(&forward->request);
16198
0
  forward_destroy(forward);
16199
0
  return;
16200
16201
0
next_primary:
16202
0
  if (msg != NULL) {
16203
0
    dns_message_detach(&msg);
16204
0
  }
16205
0
  forward->which++;
16206
0
  dns_request_destroy(&forward->request);
16207
0
  result = sendtoprimary(forward);
16208
0
  if (result != ISC_R_SUCCESS) {
16209
    /* call callback */
16210
0
    dns_zone_log(zone, ISC_LOG_DEBUG(3),
16211
0
           "exhausted dynamic update forwarder list");
16212
0
    (forward->callback)(forward->callback_arg, result, NULL);
16213
0
    forward_destroy(forward);
16214
0
  }
16215
0
}
16216
16217
isc_result_t
16218
dns_zone_forwardupdate(dns_zone_t *zone, dns_message_t *msg,
16219
0
           dns_updatecallback_t callback, void *callback_arg) {
16220
0
  dns_forward_t *forward;
16221
0
  isc_result_t result;
16222
0
  isc_region_t *mr;
16223
16224
0
  REQUIRE(DNS_ZONE_VALID(zone));
16225
0
  REQUIRE(msg != NULL);
16226
0
  REQUIRE(callback != NULL);
16227
16228
0
  forward = isc_mem_get(zone->mctx, sizeof(*forward));
16229
0
  *forward = (dns_forward_t){ .callback = callback,
16230
0
            .callback_arg = callback_arg,
16231
0
            .options = DNS_REQUESTOPT_TCP };
16232
0
  ISC_LINK_INIT(forward, link);
16233
0
  forward->magic = FORWARD_MAGIC;
16234
16235
  /*
16236
   * If we have a SIG(0) signed message we need to preserve the
16237
   * query id as that is included in the SIG(0) computation.
16238
   */
16239
0
  if (msg->sig0 != NULL) {
16240
0
    forward->options |= DNS_REQUESTOPT_FIXEDID;
16241
0
  }
16242
16243
0
  mr = dns_message_getrawmessage(msg);
16244
0
  if (mr == NULL) {
16245
0
    CLEANUP(ISC_R_UNEXPECTEDEND);
16246
0
  }
16247
16248
0
  isc_buffer_allocate(zone->mctx, &forward->msgbuf, mr->length);
16249
0
  CHECK(isc_buffer_copyregion(forward->msgbuf, mr));
16250
16251
0
  isc_mem_attach(zone->mctx, &forward->mctx);
16252
0
  dns_zone_iattach(zone, &forward->zone);
16253
0
  result = sendtoprimary(forward);
16254
16255
0
cleanup:
16256
0
  if (result != ISC_R_SUCCESS) {
16257
0
    forward_destroy(forward);
16258
0
  }
16259
0
  return result;
16260
0
}
16261
16262
static isc_mutex_t *
16263
0
zone_keymgmt_getlock(dns_zone_t *zone) {
16264
0
  uint32_t hash = dns_name_hash(&zone->origin);
16265
0
  return &keymgmt_buckets_g[hash % ARRAY_SIZE(keymgmt_buckets_g)].lock;
16266
0
}
16267
16268
void
16269
2
dns__zone_keymgmt_initialize(void) {
16270
2.05k
  for (size_t idx = 0; idx < ARRAY_SIZE(keymgmt_buckets_g); ++idx) {
16271
2.04k
    isc_mutex_init(&keymgmt_buckets_g[idx].lock);
16272
2.04k
  }
16273
2
}
16274
16275
void
16276
0
dns__zone_keymgmt_shutdown(void) {
16277
0
  for (size_t idx = 0; idx < ARRAY_SIZE(keymgmt_buckets_g); ++idx) {
16278
0
    isc_mutex_destroy(&keymgmt_buckets_g[idx].lock);
16279
0
  }
16280
0
}
16281
16282
static void
16283
0
zone_saveunique(dns_zone_t *zone, const char *path, const char *templat) {
16284
0
  char *buf;
16285
0
  int buflen;
16286
0
  isc_result_t result;
16287
16288
0
  buflen = strlen(path) + strlen(templat) + 2;
16289
16290
0
  buf = isc_mem_get(zone->mctx, buflen);
16291
16292
0
  CHECK(isc_file_template(path, templat, buf, buflen));
16293
16294
0
  CHECK(isc_file_renameunique(path, buf));
16295
16296
0
  dns_zone_log(zone, ISC_LOG_WARNING,
16297
0
         "unable to load from '%s'; "
16298
0
         "renaming file to '%s' for failure analysis and "
16299
0
         "retransferring.",
16300
0
         path, buf);
16301
16302
0
cleanup:
16303
0
  isc_mem_put(zone->mctx, buf, buflen);
16304
0
}
16305
16306
void
16307
0
dns_zone_stopxfr(dns_zone_t *zone) {
16308
0
  dns_xfrin_t *xfr = NULL;
16309
16310
0
  REQUIRE(DNS_ZONE_VALID(zone));
16311
16312
0
  RWLOCK(&dns_g_zonemgr->rwlock, isc_rwlocktype_read);
16313
0
  LOCK_ZONE(zone);
16314
0
  if (zone->statelist == &dns_g_zonemgr->xfrin_in_progress &&
16315
0
      zone->xfr != NULL)
16316
0
  {
16317
0
    dns_xfrin_attach(zone->xfr, &xfr);
16318
0
  }
16319
0
  UNLOCK_ZONE(zone);
16320
0
  RWUNLOCK(&dns_g_zonemgr->rwlock, isc_rwlocktype_read);
16321
16322
0
  if (xfr != NULL) {
16323
0
    dns_xfrin_shutdown(xfr);
16324
0
    dns_xfrin_detach(&xfr);
16325
0
  }
16326
0
}
16327
16328
void
16329
0
dns_zone_forcexfr(dns_zone_t *zone) {
16330
0
  REQUIRE(DNS_ZONE_VALID(zone));
16331
16332
0
  if (zone->type == dns_zone_primary ||
16333
0
      (zone->type == dns_zone_redirect &&
16334
0
       dns_remote_addresses(&zone->primaries) == NULL))
16335
0
  {
16336
0
    return;
16337
0
  }
16338
16339
0
  LOCK_ZONE(zone);
16340
0
  DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_FORCEXFER);
16341
0
  UNLOCK_ZONE(zone);
16342
0
  dns_zone_refresh(zone);
16343
0
}
16344
16345
bool
16346
0
dns_zone_isforced(dns_zone_t *zone) {
16347
0
  REQUIRE(DNS_ZONE_VALID(zone));
16348
16349
0
  return DNS_ZONE_FLAG(zone, DNS_ZONEFLG_FORCEXFER);
16350
0
}
16351
16352
static void
16353
0
zone_namerd_tostr(dns_zone_t *zone, char *buf, size_t length) {
16354
0
  isc_result_t result = ISC_R_FAILURE;
16355
0
  isc_buffer_t buffer;
16356
16357
0
  REQUIRE(buf != NULL);
16358
0
  REQUIRE(length > 1U);
16359
16360
  /*
16361
   * Leave space for terminating '\0'.
16362
   */
16363
0
  isc_buffer_init(&buffer, buf, (unsigned int)length - 1);
16364
0
  if (zone->type != dns_zone_redirect && zone->type != dns_zone_key) {
16365
0
    if (dns_name_dynamic(&zone->origin)) {
16366
0
      result = dns_name_totext(
16367
0
        &zone->origin, DNS_NAME_OMITFINALDOT, &buffer);
16368
0
    }
16369
0
    if (result != ISC_R_SUCCESS &&
16370
0
        isc_buffer_availablelength(&buffer) >=
16371
0
          (sizeof("<UNKNOWN>") - 1))
16372
0
    {
16373
0
      isc_buffer_putstr(&buffer, "<UNKNOWN>");
16374
0
    }
16375
16376
0
    if (isc_buffer_availablelength(&buffer) > 0) {
16377
0
      isc_buffer_putstr(&buffer, "/");
16378
0
    }
16379
0
    (void)dns_rdataclass_totext(zone->rdclass, &buffer);
16380
0
  }
16381
16382
0
  const char *viewname = dns__viewname_display(&zone->viewname);
16383
0
  if (viewname != NULL &&
16384
0
      strlen(viewname) < isc_buffer_availablelength(&buffer))
16385
0
  {
16386
0
    isc_buffer_putstr(&buffer, "/");
16387
0
    isc_buffer_putstr(&buffer, viewname);
16388
0
  }
16389
  /* Logging also runs without the zone lock.  These configuration
16390
   * fields are changed before publication or with exclusive access. */
16391
0
  if (zone->raw != NULL && 9U < isc_buffer_availablelength(&buffer)) {
16392
0
    isc_buffer_putstr(&buffer, " (signed)");
16393
0
  }
16394
0
  if (zone->secure != NULL && 11U < isc_buffer_availablelength(&buffer)) {
16395
0
    isc_buffer_putstr(&buffer, " (unsigned)");
16396
0
  }
16397
16398
0
  buf[isc_buffer_usedlength(&buffer)] = '\0';
16399
0
}
16400
16401
isc_result_t
16402
dns_zone_getxfr(dns_zone_t *zone, dns_xfrin_t **xfrp, bool *is_firstrefresh,
16403
    bool *is_running, bool *is_deferred, bool *is_presoa,
16404
0
    bool *is_pending, bool *needs_refresh) {
16405
0
  REQUIRE(DNS_ZONE_VALID(zone));
16406
0
  REQUIRE(xfrp != NULL && *xfrp == NULL);
16407
16408
0
  if (zone->loop == NULL) {
16409
0
    return ISC_R_FAILURE;
16410
0
  }
16411
16412
  /* Reset. */
16413
0
  *is_firstrefresh = false;
16414
0
  *is_running = false;
16415
0
  *is_deferred = false;
16416
0
  *is_presoa = false;
16417
0
  *is_pending = false;
16418
0
  *needs_refresh = false;
16419
16420
0
  RWLOCK(&dns_g_zonemgr->rwlock, isc_rwlocktype_read);
16421
0
  LOCK_ZONE(zone);
16422
0
  *is_firstrefresh = DNS_ZONE_FLAG(zone, DNS_ZONEFLG_FIRSTREFRESH);
16423
0
  if (zone->xfr != NULL) {
16424
0
    dns_xfrin_attach(zone->xfr, xfrp);
16425
0
  }
16426
0
  if (zone->statelist == &dns_g_zonemgr->xfrin_in_progress) {
16427
0
    *is_running = true;
16428
    /*
16429
     * The NEEDREFRESH flag is set only when a notify was received
16430
     * while the current zone transfer is running.
16431
     */
16432
0
    *needs_refresh = DNS_ZONE_FLAG(zone, DNS_ZONEFLG_NEEDREFRESH);
16433
0
  } else if (zone->statelist == &dns_g_zonemgr->waiting_for_xfrin) {
16434
0
    *is_deferred = true;
16435
0
  } else if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_REFRESH)) {
16436
0
    if (zone->request != NULL) {
16437
0
      *is_presoa = true;
16438
0
    } else {
16439
0
      *is_pending = true;
16440
0
    }
16441
0
  } else {
16442
    /*
16443
     * No operation is ongoing or pending, just check if the zone
16444
     * needs a refresh by looking at the refresh and expire times.
16445
     */
16446
0
    if (zone->type == dns_zone_secondary ||
16447
0
        zone->type == dns_zone_mirror ||
16448
0
        zone->type == dns_zone_stub)
16449
0
    {
16450
0
      isc_time_t now = isc_time_now();
16451
0
      if (isc_time_compare(&now, &zone->refreshtime) >= 0 ||
16452
0
          isc_time_compare(&now, &zone->expiretime) >= 0)
16453
0
      {
16454
0
        *needs_refresh = true;
16455
0
      }
16456
0
    }
16457
0
  }
16458
0
  UNLOCK_ZONE(zone);
16459
0
  RWUNLOCK(&dns_g_zonemgr->rwlock, isc_rwlocktype_read);
16460
16461
0
  return ISC_R_SUCCESS;
16462
0
}
16463
16464
void
16465
0
dns_zone_lock_keyfiles(dns_zone_t *zone) {
16466
0
  REQUIRE(DNS_ZONE_VALID(zone));
16467
16468
0
  if (zone->kasp == NULL) {
16469
    /* No need to lock, nothing is writing key files. */
16470
0
    return;
16471
0
  }
16472
16473
0
  isc_mutex_lock(zone_keymgmt_getlock(zone));
16474
0
}
16475
16476
void
16477
0
dns_zone_unlock_keyfiles(dns_zone_t *zone) {
16478
0
  REQUIRE(DNS_ZONE_VALID(zone));
16479
16480
0
  if (zone->kasp == NULL) {
16481
    /* No need to lock, nothing is writing key files. */
16482
0
    return;
16483
0
  }
16484
16485
0
  isc_mutex_unlock(zone_keymgmt_getlock(zone));
16486
0
}
16487
16488
isc_result_t
16489
dns_zone_checknames(dns_zone_t *zone, const dns_name_t *name,
16490
0
        dns_rdata_t *rdata) {
16491
0
  bool ok = true;
16492
0
  bool fail = false;
16493
0
  char namebuf[DNS_NAME_FORMATSIZE];
16494
0
  char namebuf2[DNS_NAME_FORMATSIZE];
16495
0
  char typebuf[DNS_RDATATYPE_FORMATSIZE];
16496
0
  int level = ISC_LOG_WARNING;
16497
0
  dns_name_t bad;
16498
16499
0
  REQUIRE(DNS_ZONE_VALID(zone));
16500
16501
0
  if (!DNS_ZONE_OPTION(zone, DNS_ZONEOPT_CHECKNAMES) &&
16502
0
      rdata->type != dns_rdatatype_nsec3)
16503
0
  {
16504
0
    return ISC_R_SUCCESS;
16505
0
  }
16506
16507
0
  if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_CHECKNAMESFAIL) ||
16508
0
      rdata->type == dns_rdatatype_nsec3)
16509
0
  {
16510
0
    level = ISC_LOG_ERROR;
16511
0
    fail = true;
16512
0
  }
16513
16514
0
  ok = dns_rdata_checkowner(name, rdata->rdclass, rdata->type, true);
16515
0
  if (!ok) {
16516
0
    dns_name_format(name, namebuf, sizeof(namebuf));
16517
0
    dns_rdatatype_format(rdata->type, typebuf, sizeof(typebuf));
16518
0
    dns_zone_log(zone, level, "%s/%s: %s", namebuf, typebuf,
16519
0
           isc_result_totext(DNS_R_BADOWNERNAME));
16520
0
    if (fail) {
16521
0
      return DNS_R_BADOWNERNAME;
16522
0
    }
16523
0
  }
16524
16525
0
  dns_name_init(&bad);
16526
0
  ok = dns_rdata_checknames(rdata, name, &bad);
16527
0
  if (!ok) {
16528
0
    dns_name_format(name, namebuf, sizeof(namebuf));
16529
0
    dns_name_format(&bad, namebuf2, sizeof(namebuf2));
16530
0
    dns_rdatatype_format(rdata->type, typebuf, sizeof(typebuf));
16531
0
    dns_zone_log(zone, level, "%s/%s: %s: %s ", namebuf, typebuf,
16532
0
           namebuf2, isc_result_totext(DNS_R_BADNAME));
16533
0
    if (fail) {
16534
0
      return DNS_R_BADNAME;
16535
0
    }
16536
0
  }
16537
16538
0
  return ISC_R_SUCCESS;
16539
0
}
16540
16541
/*
16542
 * Called when a dynamic update for an NSEC3PARAM record is received.
16543
 *
16544
 * If set, transform the NSEC3 salt into human-readable form so that it can be
16545
 * logged.  Then call zone_addnsec3chain(), passing NSEC3PARAM RDATA to it.
16546
 */
16547
isc_result_t
16548
0
dns_zone_addnsec3chain(dns_zone_t *zone, dns_rdata_nsec3param_t *nsec3param) {
16549
0
  isc_result_t result;
16550
0
  char salt[255 * 2 + 1];
16551
16552
0
  REQUIRE(DNS_ZONE_VALID(zone));
16553
16554
0
  result = dns_nsec3param_salttotext(nsec3param, salt, sizeof(salt));
16555
0
  RUNTIME_CHECK(result == ISC_R_SUCCESS);
16556
0
  dnssec_log(zone, ISC_LOG_NOTICE,
16557
0
       "dns_zone_addnsec3chain(hash=%u, iterations=%u, salt=%s)",
16558
0
       nsec3param->hash, nsec3param->iterations, salt);
16559
0
  LOCK_ZONE(zone);
16560
0
  result = zone_addnsec3chain(zone, nsec3param);
16561
0
  UNLOCK_ZONE(zone);
16562
16563
0
  return result;
16564
0
}
16565
16566
static isc_result_t
16567
zone_signwithkey(dns_zone_t *zone, dst_algorithm_t algorithm, uint16_t keyid,
16568
0
     bool deleteit, bool fullsign) {
16569
0
  dns_signing_t *signing = NULL;
16570
0
  isc_result_t result = ISC_R_SUCCESS;
16571
0
  isc_time_t now;
16572
0
  dns_db_t *db = NULL;
16573
16574
0
  signing = isc_mem_get(zone->mctx, sizeof *signing);
16575
16576
0
  signing->magic = 0;
16577
0
  signing->db = NULL;
16578
0
  signing->dbiterator = NULL;
16579
0
  signing->algorithm = algorithm;
16580
0
  signing->keyid = keyid;
16581
0
  signing->deleteit = deleteit;
16582
0
  signing->fullsign = fullsign;
16583
0
  signing->done = false;
16584
16585
0
  now = isc_time_now();
16586
16587
0
  ZONEDB_LOCK(&zone->dblock, isc_rwlocktype_read);
16588
0
  if (zone->db != NULL) {
16589
0
    dns_db_attach(zone->db, &db);
16590
0
  }
16591
0
  ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_read);
16592
16593
0
  if (db == NULL) {
16594
0
    CLEANUP(ISC_R_NOTFOUND);
16595
0
  }
16596
16597
0
  dns_db_attach(db, &signing->db);
16598
16599
0
  ISC_LIST_FOREACH(zone->signing, current, link) {
16600
0
    if (current->db == signing->db &&
16601
0
        current->algorithm == signing->algorithm &&
16602
0
        current->keyid == signing->keyid)
16603
0
    {
16604
0
      if (current->deleteit != signing->deleteit) {
16605
0
        current->done = true;
16606
0
      } else {
16607
0
        goto cleanup;
16608
0
      }
16609
0
    }
16610
0
  }
16611
16612
0
  result = dns_db_createiterator(signing->db, 0, &signing->dbiterator);
16613
16614
0
  if (result == ISC_R_SUCCESS) {
16615
0
    result = dns_dbiterator_first(signing->dbiterator);
16616
0
  }
16617
0
  if (result == ISC_R_SUCCESS) {
16618
0
    dns_dbiterator_pause(signing->dbiterator);
16619
0
    ISC_LIST_INITANDAPPEND(zone->signing, signing, link);
16620
0
    signing = NULL;
16621
0
    if (isc_time_isepoch(&zone->signingtime)) {
16622
0
      zone->signingtime = now;
16623
0
      if (zone->loop != NULL) {
16624
0
        dns__zone_settimer(zone, now);
16625
0
      }
16626
0
    }
16627
0
  }
16628
16629
0
cleanup:
16630
0
  if (signing != NULL) {
16631
0
    if (signing->db != NULL) {
16632
0
      dns_db_detach(&signing->db);
16633
0
    }
16634
0
    if (signing->dbiterator != NULL) {
16635
0
      dns_dbiterator_destroy(&signing->dbiterator);
16636
0
    }
16637
0
    isc_mem_put(zone->mctx, signing, sizeof *signing);
16638
0
  }
16639
0
  if (db != NULL) {
16640
0
    dns_db_detach(&db);
16641
0
  }
16642
0
  return result;
16643
0
}
16644
16645
/* Called once; *timep should be set to the current time. */
16646
static isc_result_t
16647
0
next_keyevent(dst_key_t *key, isc_stdtime_t *timep) {
16648
0
  isc_result_t result;
16649
0
  isc_stdtime_t now, then = 0, event;
16650
0
  int i;
16651
16652
0
  now = *timep;
16653
16654
0
  for (i = 0; i < DST_MAX_TIMES; i++) {
16655
0
    result = dst_key_gettime(key, i, &event);
16656
0
    if (result == ISC_R_SUCCESS && event > now &&
16657
0
        (then == 0 || event < then))
16658
0
    {
16659
0
      then = event;
16660
0
    }
16661
0
  }
16662
16663
0
  if (then != 0) {
16664
0
    *timep = then;
16665
0
    return ISC_R_SUCCESS;
16666
0
  }
16667
16668
0
  return ISC_R_NOTFOUND;
16669
0
}
16670
16671
static isc_result_t
16672
rr_exists(dns_db_t *db, dns_dbversion_t *ver, dns_name_t *name,
16673
0
    const dns_rdata_t *rdata, bool *flag) {
16674
0
  dns_rdataset_t rdataset;
16675
0
  dns_dbnode_t *node = NULL;
16676
0
  isc_result_t result;
16677
16678
0
  dns_rdataset_init(&rdataset);
16679
0
  if (rdata->type == dns_rdatatype_nsec3) {
16680
0
    CHECK(dns_db_findnsec3node(db, name, false, &node));
16681
0
  } else {
16682
0
    CHECK(dns_db_findnode(db, name, false, &node));
16683
0
  }
16684
0
  result = dns_db_findrdataset(db, node, ver, rdata->type, 0,
16685
0
             (isc_stdtime_t)0, &rdataset, NULL);
16686
0
  if (result == ISC_R_NOTFOUND) {
16687
0
    *flag = false;
16688
0
    result = ISC_R_SUCCESS;
16689
0
    goto cleanup;
16690
0
  }
16691
16692
0
  bool matched = false;
16693
0
  DNS_RDATASET_FOREACH(&rdataset) {
16694
0
    dns_rdata_t myrdata = DNS_RDATA_INIT;
16695
0
    dns_rdataset_current(&rdataset, &myrdata);
16696
0
    if (dns_rdata_compare(&myrdata, rdata) == 0) {
16697
0
      matched = true;
16698
0
      break;
16699
0
    }
16700
0
  }
16701
0
  dns_rdataset_disassociate(&rdataset);
16702
0
  *flag = matched;
16703
16704
0
cleanup:
16705
0
  if (node != NULL) {
16706
0
    dns_db_detachnode(&node);
16707
0
  }
16708
0
  return result;
16709
0
}
16710
16711
/*
16712
 * Add records to signal the state of signing or of key removal.
16713
 */
16714
static isc_result_t
16715
add_signing_records(dns_db_t *db, dns_rdatatype_t privatetype,
16716
0
        dns_dbversion_t *ver, dns_diff_t *diff, bool sign_all) {
16717
0
  dns_difftuple_t *newtuple = NULL;
16718
0
  dns_rdata_dnskey_t dnskey;
16719
0
  dns_rdata_t rdata = DNS_RDATA_INIT;
16720
0
  bool flag;
16721
0
  isc_region_t r;
16722
0
  isc_result_t result = ISC_R_SUCCESS;
16723
0
  uint16_t keyid;
16724
0
  unsigned char data[SIGNING_RECORD_SIZE];
16725
0
  dns_name_t *name = dns_db_origin(db);
16726
0
  dns_difftuplelist_t add = ISC_LIST_INITIALIZER;
16727
0
  dns_difftuplelist_t del = ISC_LIST_INITIALIZER;
16728
0
  dns_difftuplelist_t tuples = ISC_LIST_INITIALIZER;
16729
16730
  /*
16731
   * Move non DNSKEY and not DNSSEC DNSKEY records to tuples
16732
   * and sort the remaining DNSKEY records to add and del.
16733
   */
16734
0
  ISC_LIST_FOREACH(diff->tuples, tuple, link) {
16735
0
    if (tuple->rdata.type != dns_rdatatype_dnskey) {
16736
0
      dns_diff_unlink(diff, tuple);
16737
0
      ISC_LIST_APPEND(tuples, tuple, link);
16738
0
      continue;
16739
0
    }
16740
16741
0
    result = dns_rdata_tostruct(&tuple->rdata, &dnskey);
16742
0
    RUNTIME_CHECK(result == ISC_R_SUCCESS);
16743
0
    if ((dnskey.flags & DNS_KEYOWNER_ZONE) == 0) {
16744
0
      dns_diff_unlink(diff, tuple);
16745
0
      ISC_LIST_APPEND(tuples, tuple, link);
16746
0
      continue;
16747
0
    }
16748
16749
0
    dns_diff_unlink(diff, tuple);
16750
0
    switch (tuple->op) {
16751
0
    case DNS_DIFFOP_DEL:
16752
0
    case DNS_DIFFOP_DELRESIGN:
16753
0
      ISC_LIST_APPEND(del, tuple, link);
16754
0
      break;
16755
0
    case DNS_DIFFOP_ADD:
16756
0
    case DNS_DIFFOP_ADDRESIGN:
16757
0
      ISC_LIST_APPEND(add, tuple, link);
16758
0
      break;
16759
0
    default:
16760
0
      UNREACHABLE();
16761
0
    }
16762
0
  }
16763
16764
  /*
16765
   * Put the tuples that don't need more processing back onto
16766
   * diff->tuples.
16767
   */
16768
0
  ISC_LIST_FOREACH(tuples, tuple, link) {
16769
0
    ISC_LIST_UNLINK(tuples, tuple, link);
16770
0
    dns_diff_append(diff, &tuple);
16771
0
  }
16772
16773
  /*
16774
   * Filter out DNSKEY TTL changes and put them back onto diff->tuples.
16775
   */
16776
0
  ISC_LIST_FOREACH(del, deltuple, link) {
16777
0
    ISC_LIST_FOREACH(add, addtuple, link) {
16778
0
      int n = dns_rdata_compare(&deltuple->rdata,
16779
0
              &addtuple->rdata);
16780
0
      if (n == 0) {
16781
0
        ISC_LIST_UNLINK(del, deltuple, link);
16782
0
        dns_diff_append(diff, &deltuple);
16783
0
        ISC_LIST_UNLINK(add, addtuple, link);
16784
0
        dns_diff_append(diff, &addtuple);
16785
0
        break;
16786
0
      }
16787
0
    }
16788
0
  }
16789
16790
  /*
16791
   * Combine any remaining DNSKEY changes together.
16792
   */
16793
0
  ISC_LIST_APPENDLIST(tuples, add, link);
16794
0
  ISC_LIST_APPENDLIST(tuples, del, link);
16795
16796
  /*
16797
   * Add private records for keys that have been removed
16798
   * or added.
16799
   */
16800
0
  ISC_LIST_FOREACH(tuples, tuple, link) {
16801
0
    dst_algorithm_t algorithm;
16802
0
    dns_rdata_toregion(&tuple->rdata, &r);
16803
16804
0
    keyid = dst_region_computeid(&r);
16805
16806
0
    algorithm = dst_algorithm_fromdata(dnskey.algorithm,
16807
0
               dnskey.data, dnskey.datalen);
16808
0
    data[0] = dnskey.algorithm;
16809
0
    data[1] = (keyid & 0xff00) >> 8;
16810
0
    data[2] = (keyid & 0xff);
16811
0
    data[3] = (tuple->op == DNS_DIFFOP_ADD) ? 0 : 1;
16812
0
    data[4] = 0;
16813
0
    data[5] = (algorithm & 0xff00) >> 8;
16814
0
    data[6] = (algorithm & 0xff);
16815
0
    rdata.data = data;
16816
0
    rdata.length = algorithm < 256 ? OLD_SIGNING_RECORD_SIZE
16817
0
                 : sizeof(data);
16818
0
    rdata.type = privatetype;
16819
0
    rdata.rdclass = tuple->rdata.rdclass;
16820
16821
0
    if (sign_all || tuple->op == DNS_DIFFOP_DEL) {
16822
0
      CHECK(rr_exists(db, ver, name, &rdata, &flag));
16823
0
      if (flag) {
16824
0
        continue;
16825
0
      }
16826
16827
0
      dns_difftuple_create(diff->mctx, DNS_DIFFOP_ADD, name,
16828
0
               0, &rdata, &newtuple);
16829
0
      CHECK(dns_diff_applytuple(&newtuple, db, ver, diff));
16830
0
      INSIST(newtuple == NULL);
16831
0
    }
16832
16833
    /*
16834
     * Remove any record which says this operation has already
16835
     * completed.
16836
     */
16837
0
    data[4] = 1;
16838
0
    CHECK(rr_exists(db, ver, name, &rdata, &flag));
16839
0
    if (flag) {
16840
0
      dns_difftuple_create(diff->mctx, DNS_DIFFOP_DEL, name,
16841
0
               0, &rdata, &newtuple);
16842
0
      CHECK(dns_diff_applytuple(&newtuple, db, ver, diff));
16843
0
      INSIST(newtuple == NULL);
16844
0
    }
16845
0
  }
16846
16847
0
cleanup:
16848
  /*
16849
   * Put the DNSKEY changes we cared about back on diff->tuples.
16850
   */
16851
0
  ISC_LIST_FOREACH(tuples, tuple, link) {
16852
0
    ISC_LIST_UNLINK(tuples, tuple, link);
16853
0
    dns_diff_append(diff, &tuple);
16854
0
  }
16855
0
  INSIST(ISC_LIST_EMPTY(add));
16856
0
  INSIST(ISC_LIST_EMPTY(del));
16857
0
  INSIST(ISC_LIST_EMPTY(tuples));
16858
0
  return result;
16859
0
}
16860
16861
/*
16862
 * See if dns__zone_updatesigs() will update signature for RRset 'rrtype' at
16863
 * the apex, and if not tickle them and cause to sign so that newly activated
16864
 * keys are used.
16865
 */
16866
static isc_result_t
16867
tickle_apex_rrset(dns_rdatatype_t rrtype, dns_zone_t *zone, dns_db_t *db,
16868
      dns_dbversion_t *ver, isc_stdtime_t now, dns_diff_t *diff,
16869
      dns__zonediff_t *zonediff, dst_key_t **keys,
16870
      unsigned int nkeys, isc_stdtime_t inception,
16871
0
      isc_stdtime_t keyexpire) {
16872
0
  isc_result_t result;
16873
0
  bool apexsig = false;
16874
16875
0
  ISC_LIST_FOREACH(diff->tuples, tuple, link) {
16876
0
    if (tuple->rdata.type == rrtype &&
16877
0
        dns_name_equal(&tuple->name, &zone->origin))
16878
0
    {
16879
0
      apexsig = true;
16880
0
      break;
16881
0
    }
16882
0
  }
16883
16884
0
  if (!apexsig) {
16885
0
    result = del_sigs(zone, db, ver, &zone->origin, rrtype,
16886
0
          zonediff, keys, nkeys, now, false);
16887
0
    if (result != ISC_R_SUCCESS) {
16888
0
      dnssec_log(zone, ISC_LOG_ERROR,
16889
0
           "sign_apex:del_sigs -> %s",
16890
0
           isc_result_totext(result));
16891
0
      return result;
16892
0
    }
16893
0
    result = add_sigs(db, ver, &zone->origin, zone, rrtype,
16894
0
          zonediff->diff, keys, nkeys, zone->mctx, now,
16895
0
          inception, keyexpire);
16896
0
    if (result != ISC_R_SUCCESS) {
16897
0
      dnssec_log(zone, ISC_LOG_ERROR,
16898
0
           "sign_apex:add_sigs -> %s",
16899
0
           isc_result_totext(result));
16900
0
      return result;
16901
0
    }
16902
0
  }
16903
16904
0
  return ISC_R_SUCCESS;
16905
0
}
16906
16907
static isc_result_t
16908
sign_apex(dns_zone_t *zone, dns_db_t *db, dns_dbversion_t *ver,
16909
0
    isc_stdtime_t now, dns_diff_t *diff, dns__zonediff_t *zonediff) {
16910
0
  isc_result_t result;
16911
0
  isc_stdtime_t inception, soaexpire, keyexpire;
16912
0
  dst_key_t *zone_keys[DNS_MAXZONEKEYS];
16913
0
  unsigned int nkeys = 0, i;
16914
16915
0
  result = dns_zone_findkeys(zone, db, ver, now, zone->mctx,
16916
0
           DNS_MAXZONEKEYS, zone_keys, &nkeys);
16917
0
  if (result != ISC_R_SUCCESS) {
16918
0
    dnssec_log(zone, ISC_LOG_ERROR,
16919
0
         "sign_apex:dns_zone_findkeys -> %s",
16920
0
         isc_result_totext(result));
16921
0
    return result;
16922
0
  }
16923
16924
0
  inception = now - 3600; /* Allow for clock skew. */
16925
0
  soaexpire = now + dns_zone_getsigvalidityinterval(zone);
16926
16927
0
  keyexpire = dns_zone_getkeyvalidityinterval(zone);
16928
0
  if (keyexpire == 0) {
16929
0
    keyexpire = soaexpire - 1;
16930
0
  } else {
16931
0
    keyexpire += now;
16932
0
  }
16933
16934
  /*
16935
   * See if dns__zone_updatesigs() will update DNSKEY/CDS/CDNSKEY
16936
   * signature and if not cause them to sign so that newly activated
16937
   * keys are used.
16938
   */
16939
0
  CHECK(tickle_apex_rrset(dns_rdatatype_dnskey, zone, db, ver, now, diff,
16940
0
        zonediff, zone_keys, nkeys, inception,
16941
0
        keyexpire));
16942
0
  CHECK(tickle_apex_rrset(dns_rdatatype_cds, zone, db, ver, now, diff,
16943
0
        zonediff, zone_keys, nkeys, inception,
16944
0
        keyexpire));
16945
0
  CHECK(tickle_apex_rrset(dns_rdatatype_cdnskey, zone, db, ver, now, diff,
16946
0
        zonediff, zone_keys, nkeys, inception,
16947
0
        keyexpire));
16948
16949
0
  result = dns__zone_updatesigs(diff, db, ver, zone_keys, nkeys, zone,
16950
0
              inception, soaexpire, keyexpire, now,
16951
0
              zonediff);
16952
0
  if (result != ISC_R_SUCCESS) {
16953
0
    dnssec_log(zone, ISC_LOG_ERROR,
16954
0
         "sign_apex:dns__zone_updatesigs -> %s",
16955
0
         isc_result_totext(result));
16956
0
  }
16957
16958
0
cleanup:
16959
0
  for (i = 0; i < nkeys; i++) {
16960
0
    dst_key_free(&zone_keys[i]);
16961
0
  }
16962
0
  return result;
16963
0
}
16964
16965
static isc_result_t
16966
clean_nsec3param(dns_zone_t *zone, dns_db_t *db, dns_dbversion_t *ver,
16967
0
     dns_diff_t *diff) {
16968
0
  isc_result_t result;
16969
0
  dns_dbnode_t *node = NULL;
16970
0
  dns_rdataset_t rdataset;
16971
16972
0
  dns_rdataset_init(&rdataset);
16973
0
  CHECK(dns_db_getoriginnode(db, &node));
16974
16975
0
  result = dns_db_findrdataset(db, node, ver, dns_rdatatype_dnskey,
16976
0
             dns_rdatatype_none, 0, &rdataset, NULL);
16977
0
  dns_rdataset_cleanup(&rdataset);
16978
0
  if (result != ISC_R_NOTFOUND) {
16979
0
    goto cleanup;
16980
0
  }
16981
16982
0
  result = dns_nsec3param_deletechains(db, ver, zone, true, diff);
16983
16984
0
cleanup:
16985
0
  if (node != NULL) {
16986
0
    dns_db_detachnode(&node);
16987
0
  }
16988
0
  return result;
16989
0
}
16990
16991
/*
16992
 * Given an RRSIG rdataset and an algorithm, determine whether there
16993
 * are any signatures using that algorithm.
16994
 */
16995
static bool
16996
0
signed_with_alg(dns_rdataset_t *rdataset, dst_algorithm_t alg) {
16997
0
  dst_algorithm_t sigalg;
16998
16999
0
  REQUIRE(rdataset == NULL || rdataset->type == dns_rdatatype_rrsig);
17000
0
  if (rdataset == NULL || !dns_rdataset_isassociated(rdataset)) {
17001
0
    return false;
17002
0
  }
17003
17004
0
  DNS_RDATASET_FOREACH(rdataset) {
17005
0
    dns_rdata_t rdata = DNS_RDATA_INIT;
17006
0
    dns_rdata_rrsig_t rrsig;
17007
17008
0
    dns_rdataset_current(rdataset, &rdata);
17009
0
    dns_rdata_tostruct(&rdata, &rrsig);
17010
0
    sigalg = dst_algorithm_fromdata(rrsig.algorithm,
17011
0
            rrsig.signature, rrsig.siglen);
17012
0
    if (sigalg == alg) {
17013
0
      return true;
17014
0
    }
17015
0
  }
17016
17017
0
  return false;
17018
0
}
17019
17020
static isc_result_t
17021
add_chains(dns_zone_t *zone, dns_db_t *db, dns_dbversion_t *ver,
17022
0
     dns_diff_t *diff) {
17023
0
  dns_name_t *origin;
17024
0
  bool build_nsec3;
17025
0
  isc_result_t result;
17026
17027
0
  origin = dns_db_origin(db);
17028
0
  CHECK(dns_private_chains(db, ver, zone->privatetype, NULL,
17029
0
         &build_nsec3));
17030
0
  if (build_nsec3) {
17031
0
    CHECK(dns_nsec3_addnsec3sx(db, ver, origin, zone_nsecttl(zone),
17032
0
             false, zone->privatetype, diff));
17033
0
  }
17034
0
  CHECK(updatesecure(db, ver, origin, zone_nsecttl(zone), true, diff));
17035
17036
0
cleanup:
17037
0
  return result;
17038
0
}
17039
17040
static void
17041
0
dnssec_report(const char *format, ...) {
17042
0
  va_list args;
17043
0
  va_start(args, format);
17044
0
  isc_log_vwrite(DNS_LOGCATEGORY_DNSSEC, DNS_LOGMODULE_ZONE, ISC_LOG_INFO,
17045
0
           format, args);
17046
0
  va_end(args);
17047
0
}
17048
17049
static void
17050
0
checkds_destroy(dns_checkds_t *checkds, bool locked) {
17051
0
  REQUIRE(DNS_CHECKDS_VALID(checkds));
17052
17053
0
  dns_zone_log(checkds->zone, ISC_LOG_DEBUG(3),
17054
0
         "checkds: destroy DS query");
17055
17056
0
  if (checkds->zone != NULL) {
17057
0
    if (!locked) {
17058
0
      LOCK_ZONE(checkds->zone);
17059
0
    }
17060
0
    REQUIRE(LOCKED_ZONE(checkds->zone));
17061
0
    if (ISC_LINK_LINKED(checkds, link)) {
17062
0
      ISC_LIST_UNLINK(checkds->zone->checkds_requests,
17063
0
          checkds, link);
17064
0
    }
17065
0
    if (!locked) {
17066
0
      UNLOCK_ZONE(checkds->zone);
17067
0
    }
17068
0
    if (locked) {
17069
0
      zone_idetach(&checkds->zone);
17070
0
    } else {
17071
0
      dns_zone_idetach(&checkds->zone);
17072
0
    }
17073
0
  }
17074
0
  if (checkds->find != NULL) {
17075
0
    dns_adb_destroyfind(&checkds->find);
17076
0
  }
17077
0
  if (checkds->request != NULL) {
17078
0
    dns_request_destroy(&checkds->request);
17079
0
  }
17080
0
  if (dns_name_dynamic(&checkds->ns)) {
17081
0
    dns_name_free(&checkds->ns, checkds->mctx);
17082
0
  }
17083
0
  if (checkds->key != NULL) {
17084
0
    dns_tsigkey_detach(&checkds->key);
17085
0
  }
17086
0
  if (checkds->transport != NULL) {
17087
0
    dns_transport_detach(&checkds->transport);
17088
0
  }
17089
0
  INSIST(checkds->rlevent == NULL);
17090
0
  isc_mem_putanddetach(&checkds->mctx, checkds, sizeof(*checkds));
17091
0
}
17092
17093
static isc_result_t
17094
make_dnskey(dst_key_t *key, unsigned char *buf, int bufsize,
17095
0
      dns_rdata_t *target) {
17096
0
  isc_buffer_t b;
17097
0
  isc_region_t r;
17098
17099
0
  isc_buffer_init(&b, buf, bufsize);
17100
0
  RETERR(dst_key_todns(key, &b));
17101
17102
0
  dns_rdata_reset(target);
17103
0
  isc_buffer_usedregion(&b, &r);
17104
0
  dns_rdata_fromregion(target, dst_key_class(key), dns_rdatatype_dnskey,
17105
0
           &r);
17106
0
  return ISC_R_SUCCESS;
17107
0
}
17108
17109
static bool
17110
do_checkds(dns_zone_t *zone, dst_key_t *key, isc_stdtime_t now,
17111
0
     bool dspublish) {
17112
0
  dns_kasp_t *kasp = zone->kasp;
17113
0
  isc_result_t result;
17114
0
  uint32_t count = 0;
17115
0
  uint32_t num;
17116
17117
0
  switch (zone->checkdstype) {
17118
0
  case dns_checkdstype_yes:
17119
0
    num = zone->parent_nscount;
17120
0
    break;
17121
0
  case dns_checkdstype_explicit:
17122
0
    num = dns_remote_count(&zone->parentals);
17123
0
    break;
17124
0
  case dns_checkdstype_no:
17125
0
  default:
17126
0
    dns_zone_log(zone, ISC_LOG_WARNING,
17127
0
           "checkds: option is disabled");
17128
0
    return false;
17129
0
  }
17130
17131
0
  if (dspublish) {
17132
0
    (void)dst_key_getnum(key, DST_NUM_DSPUBCOUNT, &count);
17133
0
    count += 1;
17134
0
    dst_key_setnum(key, DST_NUM_DSPUBCOUNT, count);
17135
0
    dns_zone_log(zone, ISC_LOG_DEBUG(3),
17136
0
           "checkds: %u DS published "
17137
0
           "for key %u",
17138
0
           count, dst_key_id(key));
17139
17140
0
    if (count != num) {
17141
0
      return false;
17142
0
    }
17143
0
  } else {
17144
0
    (void)dst_key_getnum(key, DST_NUM_DSDELCOUNT, &count);
17145
0
    count += 1;
17146
0
    dst_key_setnum(key, DST_NUM_DSDELCOUNT, count);
17147
0
    dns_zone_log(zone, ISC_LOG_DEBUG(3),
17148
0
           "checkds: %u DS withdrawn "
17149
0
           "for key %u",
17150
0
           count, dst_key_id(key));
17151
17152
0
    if (count != num) {
17153
0
      return false;
17154
0
    }
17155
0
  }
17156
17157
0
  dns_zone_log(zone, ISC_LOG_DEBUG(3),
17158
0
         "checkds: checkds %s for key "
17159
0
         "%u",
17160
0
         dspublish ? "published" : "withdrawn", dst_key_id(key));
17161
17162
0
  dns_zone_lock_keyfiles(zone);
17163
0
  result = dns_keymgr_checkds_id(kasp, &zone->checkds_ok, now, now,
17164
0
               dspublish, dst_key_id(key),
17165
0
               dst_key_alg(key));
17166
0
  dns_zone_unlock_keyfiles(zone);
17167
17168
0
  if (result != ISC_R_SUCCESS) {
17169
0
    dns_zone_log(zone, ISC_LOG_WARNING,
17170
0
           "checkds: checkds for key %u failed: %s",
17171
0
           dst_key_id(key), isc_result_totext(result));
17172
0
    return false;
17173
0
  }
17174
17175
0
  return true;
17176
0
}
17177
17178
static isc_result_t
17179
0
validate_ds(dns_zone_t *zone, dns_message_t *message) {
17180
0
  UNUSED(zone);
17181
0
  UNUSED(message);
17182
17183
  /* Get closest trust anchor */
17184
17185
  /* Check that trust anchor is (grand)parent of zone. */
17186
17187
  /* Find the DNSKEY signing the message. */
17188
17189
  /* Check that DNSKEY is in chain of trust. */
17190
17191
  /* Validate DS RRset. */
17192
17193
0
  return ISC_R_SUCCESS;
17194
0
}
17195
17196
static void
17197
0
checkds_done(void *arg) {
17198
0
  dns_request_t *request = (dns_request_t *)arg;
17199
0
  dns_checkds_t *checkds = dns_request_getarg(request);
17200
0
  char addrbuf[ISC_SOCKADDR_FORMATSIZE];
17201
0
  char rcode[128];
17202
0
  dns_zone_t *zone = NULL;
17203
0
  dns_db_t *db = NULL;
17204
0
  dns_dbversion_t *version = NULL;
17205
0
  dns_dnsseckeylist_t keys;
17206
0
  dns_kasp_t *kasp = NULL;
17207
0
  dns_message_t *message = NULL;
17208
0
  dns_rdataset_t *ds_rrset = NULL;
17209
0
  isc_buffer_t buf;
17210
0
  isc_result_t result;
17211
0
  isc_stdtime_t now;
17212
0
  isc_time_t timenow;
17213
0
  bool rekey = false;
17214
0
  bool empty = false;
17215
17216
0
  REQUIRE(DNS_CHECKDS_VALID(checkds));
17217
17218
0
  zone = checkds->zone;
17219
17220
0
  ISC_LIST_INIT(keys);
17221
17222
0
  kasp = zone->kasp;
17223
0
  INSIST(kasp != NULL);
17224
17225
0
  isc_buffer_init(&buf, rcode, sizeof(rcode));
17226
0
  isc_sockaddr_format(&checkds->dst, addrbuf, sizeof(addrbuf));
17227
17228
0
  dns_zone_log(zone, ISC_LOG_DEBUG(1), "checkds: DS query to %s: done",
17229
0
         addrbuf);
17230
17231
0
  dns_message_create(zone->mctx, NULL, NULL, DNS_MESSAGE_INTENTPARSE,
17232
0
         &message);
17233
0
  INSIST(message != NULL);
17234
17235
0
  CHECK(dns_request_getresult(request));
17236
0
  CHECK(dns_request_getresponse(request, message,
17237
0
              DNS_MESSAGEPARSE_PRESERVEORDER));
17238
0
  CHECK(dns_rcode_totext(message->rcode, &buf));
17239
17240
0
  dns_zone_log(zone, ISC_LOG_DEBUG(3),
17241
0
         "checkds: DS response from %s: %.*s", addrbuf,
17242
0
         (int)buf.used, rcode);
17243
17244
  /* Validate response. */
17245
0
  CHECK(validate_ds(zone, message));
17246
17247
  /* Check RCODE. */
17248
0
  if (message->rcode != dns_rcode_noerror) {
17249
0
    dns_zone_log(zone, ISC_LOG_NOTICE,
17250
0
           "checkds: bad DS response from %s: %.*s", addrbuf,
17251
0
           (int)buf.used, rcode);
17252
0
    goto cleanup;
17253
0
  }
17254
17255
  /* Make sure that either AA or RA bit is set. */
17256
0
  if ((message->flags & DNS_MESSAGEFLAG_AA) == 0 &&
17257
0
      (message->flags & DNS_MESSAGEFLAG_RA) == 0)
17258
0
  {
17259
0
    dns_zone_log(zone, ISC_LOG_NOTICE,
17260
0
           "checkds: bad DS response from %s: expected AA or "
17261
0
           "RA bit set",
17262
0
           addrbuf);
17263
0
    goto cleanup;
17264
0
  }
17265
17266
  /* Lookup DS RRset. */
17267
17268
0
  MSG_SECTION_FOREACH(message, DNS_SECTION_ANSWER, name) {
17269
0
    if (dns_name_compare(&zone->origin, name) != 0) {
17270
0
      continue;
17271
0
    }
17272
17273
0
    ISC_LIST_FOREACH(name->list, rdataset, link) {
17274
0
      if (rdataset->type != dns_rdatatype_ds &&
17275
0
          rdataset->type != dns_rdatatype_deleg)
17276
0
      {
17277
0
        goto next;
17278
0
      }
17279
17280
0
      ds_rrset = rdataset;
17281
0
      break;
17282
0
    }
17283
17284
0
    if (ds_rrset != NULL) {
17285
0
      break;
17286
0
    }
17287
17288
0
  next:;
17289
0
  }
17290
17291
0
  if (ds_rrset == NULL) {
17292
0
    empty = true;
17293
0
    dns_zone_log(zone, ISC_LOG_NOTICE,
17294
0
           "checkds: empty DS response from %s", addrbuf);
17295
0
  }
17296
17297
0
  timenow = isc_time_now();
17298
0
  now = isc_time_seconds(&timenow);
17299
17300
0
  CHECK(dns_zone_getdb(zone, &db));
17301
0
  dns_db_currentversion(db, &version);
17302
17303
0
  KASP_LOCK(kasp);
17304
0
  LOCK_ZONE(zone);
17305
0
  ISC_LIST_FOREACH(zone->checkds_ok, key, link) {
17306
0
    bool alldone = false, found = false;
17307
0
    bool checkdspub = false, checkdsdel = false, ksk = false;
17308
0
    dst_key_state_t ds_state = DST_KEY_STATE_NA;
17309
0
    isc_stdtime_t published = 0, withdrawn = 0;
17310
17311
    /* Is this key have the KSK role? */
17312
0
    (void)dst_key_role(key->key, &ksk, NULL);
17313
0
    if (!ksk) {
17314
0
      continue;
17315
0
    }
17316
17317
    /* Do we need to check the DS RRset for this key? */
17318
0
    (void)dst_key_getstate(key->key, DST_KEY_DS, &ds_state);
17319
0
    (void)dst_key_gettime(key->key, DST_TIME_DSPUBLISH, &published);
17320
0
    (void)dst_key_gettime(key->key, DST_TIME_DSDELETE, &withdrawn);
17321
17322
0
    if (ds_state == DST_KEY_STATE_RUMOURED && published == 0) {
17323
0
      checkdspub = true;
17324
0
    } else if (ds_state == DST_KEY_STATE_UNRETENTIVE &&
17325
0
         withdrawn == 0)
17326
0
    {
17327
0
      checkdsdel = true;
17328
0
    }
17329
0
    if (!checkdspub && !checkdsdel) {
17330
0
      continue;
17331
0
    }
17332
17333
0
    if (empty) {
17334
0
      goto dswithdrawn;
17335
0
    }
17336
17337
    /* Find the appropriate DS record. */
17338
0
    DNS_RDATASET_FOREACH(ds_rrset) {
17339
0
      dns_rdata_ds_t ds;
17340
0
      dns_rdata_t dnskey = DNS_RDATA_INIT;
17341
0
      dns_rdata_t dsrdata = DNS_RDATA_INIT;
17342
0
      dns_rdata_t rdata = DNS_RDATA_INIT;
17343
0
      isc_result_t r;
17344
0
      unsigned char dsbuf[DNS_DS_BUFFERSIZE];
17345
0
      unsigned char keybuf[DNS_RDATA_MAXLENGTH];
17346
17347
0
      dns_rdataset_current(ds_rrset, &rdata);
17348
0
      r = dns_rdata_tostruct(&rdata, &ds);
17349
0
      if (r != ISC_R_SUCCESS) {
17350
0
        continue;
17351
0
      }
17352
      /* Check key tag and algorithm. */
17353
0
      if (dst_key_id(key->key) != ds.key_tag) {
17354
0
        continue;
17355
0
      }
17356
0
      if (dst_algorithm_tosecalg(dst_key_alg(key->key)) !=
17357
0
          ds.algorithm)
17358
0
      {
17359
0
        continue;
17360
0
      }
17361
      /* Derive DS from DNSKEY, see if the rdata is equal. */
17362
0
      make_dnskey(key->key, keybuf, sizeof(keybuf), &dnskey);
17363
0
      r = dns_ds_buildrdata(&zone->origin, &dnskey,
17364
0
                ds.digest_type, dsbuf,
17365
0
                sizeof(dsbuf), &dsrdata);
17366
0
      if (r != ISC_R_SUCCESS) {
17367
0
        continue;
17368
0
      }
17369
0
      if (dns_rdata_compare(&rdata, &dsrdata) == 0) {
17370
0
        found = true;
17371
0
        if (checkdspub) {
17372
          /* DS Published. */
17373
0
          alldone = do_checkds(zone, key->key,
17374
0
                   now, true);
17375
0
          if (alldone) {
17376
0
            rekey = true;
17377
0
          }
17378
0
        }
17379
0
      }
17380
0
    }
17381
17382
0
  dswithdrawn:
17383
    /* DS withdrawn. */
17384
0
    if (checkdsdel && !found) {
17385
0
      alldone = do_checkds(zone, key->key, now, false);
17386
0
      if (alldone) {
17387
0
        rekey = true;
17388
0
      }
17389
0
    }
17390
0
  }
17391
0
  UNLOCK_ZONE(zone);
17392
0
  KASP_UNLOCK(kasp);
17393
17394
  /* Rekey after checkds. */
17395
0
  if (rekey) {
17396
0
    dns_zone_rekey(zone, false, false);
17397
0
  }
17398
17399
0
cleanup:
17400
0
  if (result != ISC_R_SUCCESS) {
17401
0
    dns_zone_log(zone, ISC_LOG_DEBUG(3),
17402
0
           "checkds: DS request failed: %s",
17403
0
           isc_result_totext(result));
17404
0
  }
17405
17406
0
  if (version != NULL) {
17407
0
    dns_db_closeversion(db, &version, false);
17408
0
  }
17409
0
  if (db != NULL) {
17410
0
    dns_db_detach(&db);
17411
0
  }
17412
17413
0
  ISC_LIST_FOREACH(keys, key, link) {
17414
0
    ISC_LIST_UNLINK(keys, key, link);
17415
0
    dns_dnsseckey_destroy(dns_zone_getmctx(zone), &key);
17416
0
  }
17417
17418
0
  checkds_destroy(checkds, false);
17419
0
  dns_message_detach(&message);
17420
0
}
17421
17422
static bool
17423
checkds_isqueued(dns_zone_t *zone, dns_name_t *name, isc_sockaddr_t *addr,
17424
0
     dns_tsigkey_t *key, dns_transport_t *transport) {
17425
0
  ISC_LIST_FOREACH(zone->checkds_requests, checkds, link) {
17426
0
    if (checkds->request != NULL) {
17427
0
      continue;
17428
0
    }
17429
0
    if (name != NULL && dns_name_equal(name, &checkds->ns)) {
17430
0
      return true;
17431
0
    }
17432
0
    if (addr != NULL && isc_sockaddr_equal(addr, &checkds->dst) &&
17433
0
        checkds->key == key && checkds->transport == transport)
17434
0
    {
17435
0
      return true;
17436
0
    }
17437
0
  }
17438
0
  return false;
17439
0
}
17440
17441
static void
17442
0
checkds_create(isc_mem_t *mctx, unsigned int flags, dns_checkds_t **checkdsp) {
17443
0
  dns_checkds_t *checkds;
17444
17445
0
  REQUIRE(checkdsp != NULL && *checkdsp == NULL);
17446
17447
0
  checkds = isc_mem_get(mctx, sizeof(*checkds));
17448
0
  *checkds = (dns_checkds_t){
17449
0
    .magic = CHECKDS_MAGIC,
17450
0
    .flags = flags,
17451
0
    .link = ISC_LINK_INITIALIZER,
17452
0
    .mctx = isc_mem_ref(mctx),
17453
0
    .ns = DNS_NAME_INITEMPTY,
17454
0
  };
17455
17456
0
  isc_sockaddr_any(&checkds->dst);
17457
17458
0
  *checkdsp = checkds;
17459
0
}
17460
17461
static void
17462
0
checkds_createmessage(dns_zone_t *zone, dns_message_t **messagep) {
17463
0
  dns_message_t *message = NULL;
17464
17465
0
  dns_linkedname_t *tempname = NULL;
17466
0
  dns_rdataset_t *temprdataset = NULL;
17467
17468
0
  REQUIRE(DNS_ZONE_VALID(zone));
17469
0
  REQUIRE(messagep != NULL && *messagep == NULL);
17470
17471
0
  dns_message_create(zone->mctx, NULL, NULL, DNS_MESSAGE_INTENTRENDER,
17472
0
         &message);
17473
17474
0
  message->opcode = dns_opcode_query;
17475
0
  message->rdclass = zone->rdclass;
17476
0
  message->flags |= DNS_MESSAGEFLAG_RD;
17477
17478
0
  dns_message_gettempname(message, &tempname);
17479
17480
0
  dns_message_gettemprdataset(message, &temprdataset);
17481
17482
  /*
17483
   * Make question.
17484
   */
17485
0
  dns_name_init(dns_name(tempname));
17486
0
  dns_name_clone(&zone->origin, dns_name(tempname));
17487
0
  dns_rdataset_makequestion(temprdataset, zone->rdclass,
17488
0
          dns_rdatatype_ds);
17489
0
  ISC_LIST_APPEND(tempname->list, temprdataset, link);
17490
0
  dns_message_addname(message, tempname, DNS_SECTION_QUESTION);
17491
0
  tempname = NULL;
17492
0
  temprdataset = NULL;
17493
17494
0
  *messagep = message;
17495
0
}
17496
17497
/*
17498
 * XXXAG should check for DNS_ZONEFLG_EXITING
17499
 */
17500
static void
17501
0
process_checkds_adb_event(void *arg) {
17502
0
  dns_adbfind_t *find = (dns_adbfind_t *)arg;
17503
0
  dns_checkds_t *checkds = (dns_checkds_t *)find->cbarg;
17504
0
  dns_adbstatus_t astat = find->status;
17505
17506
0
  REQUIRE(DNS_CHECKDS_VALID(checkds));
17507
0
  REQUIRE(find == checkds->find);
17508
17509
0
  switch (astat) {
17510
0
  case DNS_ADB_MOREADDRESSES:
17511
0
    dns_adb_destroyfind(&checkds->find);
17512
0
    checkds_find_address(checkds);
17513
0
    return;
17514
17515
0
  case DNS_ADB_NOMOREADDRESSES:
17516
0
    LOCK_ZONE(checkds->zone);
17517
0
    checkds_send_tons(checkds);
17518
0
    UNLOCK_ZONE(checkds->zone);
17519
0
    break;
17520
17521
0
  default:
17522
0
    break;
17523
0
  }
17524
17525
0
  checkds_destroy(checkds, false);
17526
0
}
17527
17528
static void
17529
0
checkds_find_address(dns_checkds_t *checkds) {
17530
0
  isc_result_t result;
17531
0
  unsigned int options;
17532
0
  dns_adb_t *adb = NULL;
17533
0
  dns_view_t *view = NULL;
17534
17535
0
  REQUIRE(DNS_CHECKDS_VALID(checkds));
17536
17537
0
  view = checkds->zone->view;
17538
0
  options = DNS_ADBFIND_WANTEVENT;
17539
0
  if (isc_net_probeipv4() != ISC_R_DISABLED) {
17540
0
    options |= DNS_ADBFIND_INET;
17541
0
  }
17542
0
  if (isc_net_probeipv6() != ISC_R_DISABLED) {
17543
0
    options |= DNS_ADBFIND_INET6;
17544
0
  }
17545
17546
0
  dns_view_getadb(view, &adb);
17547
0
  if (adb == NULL) {
17548
0
    goto destroy;
17549
0
  }
17550
17551
0
  result = dns_adb_createfind(
17552
0
    adb, checkds->zone->loop, process_checkds_adb_event, checkds,
17553
0
    &checkds->ns, options, 0, checkds->zone->view->dstport, 0, NULL,
17554
0
    NULL, NULL, view->max_delegation_servers, &checkds->find, NULL);
17555
0
  dns_adb_detach(&adb);
17556
17557
  /* Something failed? */
17558
0
  if (result != ISC_R_SUCCESS) {
17559
0
    goto destroy;
17560
0
  }
17561
17562
  /* More addresses pending? */
17563
0
  if ((checkds->find->options & DNS_ADBFIND_WANTEVENT) != 0) {
17564
0
    return;
17565
0
  }
17566
17567
  /* We have as many addresses as we can get. */
17568
0
  LOCK_ZONE(checkds->zone);
17569
0
  checkds_send_tons(checkds);
17570
0
  UNLOCK_ZONE(checkds->zone);
17571
17572
0
destroy:
17573
0
  checkds_destroy(checkds, false);
17574
0
}
17575
17576
static void
17577
0
checkds_send_toaddr(void *arg) {
17578
0
  dns_checkds_t *checkds = (dns_checkds_t *)arg;
17579
0
  isc_result_t result;
17580
0
  dns_message_t *message = NULL;
17581
0
  isc_netaddr_t dstip;
17582
0
  dns_tsigkey_t *key = NULL;
17583
0
  char addrbuf[ISC_SOCKADDR_FORMATSIZE];
17584
0
  isc_sockaddr_t src;
17585
0
  unsigned int options;
17586
0
  bool have_checkdssource = false;
17587
0
  bool canceled = checkds->rlevent->canceled;
17588
0
  isc_tlsctx_cache_t *zmgr_tlsctx_cache = NULL;
17589
17590
0
  REQUIRE(DNS_CHECKDS_VALID(checkds));
17591
17592
0
  isc_rlevent_free(&checkds->rlevent);
17593
17594
0
  LOCK_ZONE(checkds->zone);
17595
17596
0
  if (DNS_ZONE_FLAG(checkds->zone, DNS_ZONEFLG_LOADED) == 0 || canceled ||
17597
0
      DNS_ZONE_FLAG(checkds->zone, DNS_ZONEFLG_EXITING) ||
17598
0
      checkds->zone->view->requestmgr == NULL ||
17599
0
      checkds->zone->db == NULL)
17600
0
  {
17601
0
    CLEANUP(ISC_R_CANCELED);
17602
0
  }
17603
17604
  /*
17605
   * The raw IPv4 address should also exist.  Don't send to the
17606
   * mapped form.
17607
   */
17608
0
  if (isc_sockaddr_pf(&checkds->dst) == PF_INET6 &&
17609
0
      IN6_IS_ADDR_V4MAPPED(&checkds->dst.type.sin6.sin6_addr))
17610
0
  {
17611
0
    isc_sockaddr_format(&checkds->dst, addrbuf, sizeof(addrbuf));
17612
0
    dns_zone_log(checkds->zone, ISC_LOG_DEBUG(3),
17613
0
           "checkds: ignoring IPv6 mapped IPV4 address: %s",
17614
0
           addrbuf);
17615
0
    CLEANUP(ISC_R_CANCELED);
17616
0
  }
17617
17618
0
  isc_netaddr_fromsockaddr(&dstip, &checkds->dst);
17619
17620
0
  checkds_createmessage(checkds->zone, &message);
17621
17622
0
  isc_sockaddr_format(&checkds->dst, addrbuf, sizeof(addrbuf));
17623
0
  if (checkds->key != NULL) {
17624
    /* Transfer ownership of key */
17625
0
    key = checkds->key;
17626
0
    checkds->key = NULL;
17627
0
  } else {
17628
0
    result = dns_view_getpeertsig(checkds->zone->view, &dstip,
17629
0
                &key);
17630
0
    if (result != ISC_R_SUCCESS && result != ISC_R_NOTFOUND) {
17631
0
      dns_zone_log(checkds->zone, ISC_LOG_ERROR,
17632
0
             "checkds: DS query to %s not sent. "
17633
0
             "Peer TSIG key lookup failure.",
17634
0
             addrbuf);
17635
0
      goto cleanup_message;
17636
0
    }
17637
0
  }
17638
17639
0
  if (key != NULL) {
17640
0
    char namebuf[DNS_NAME_FORMATSIZE];
17641
17642
0
    dns_name_format(key->name, namebuf, sizeof(namebuf));
17643
0
    dns_zone_log(checkds->zone, ISC_LOG_DEBUG(3),
17644
0
           "checkds: sending DS query to %s : TSIG (%s)",
17645
0
           addrbuf, namebuf);
17646
0
  } else {
17647
0
    dns_zone_log(checkds->zone, ISC_LOG_DEBUG(3),
17648
0
           "checkds: sending DS query to %s", addrbuf);
17649
0
  }
17650
0
  options = 0;
17651
0
  if (checkds->zone->view->peers != NULL) {
17652
0
    dns_peer_t *peer = NULL;
17653
0
    bool usetcp = false;
17654
0
    result = dns_peerlist_peerbyaddr(checkds->zone->view->peers,
17655
0
             &dstip, &peer);
17656
0
    if (result == ISC_R_SUCCESS) {
17657
0
      result = dns_peer_getquerysource(peer, &src);
17658
0
      if (result == ISC_R_SUCCESS) {
17659
0
        have_checkdssource = true;
17660
0
      }
17661
0
      result = dns_peer_getforcetcp(peer, &usetcp);
17662
0
      if (result == ISC_R_SUCCESS && usetcp) {
17663
0
        options |= DNS_FETCHOPT_TCP;
17664
0
      }
17665
0
    }
17666
0
  }
17667
0
  switch (isc_sockaddr_pf(&checkds->dst)) {
17668
0
  case PF_INET:
17669
0
    if (!have_checkdssource) {
17670
0
      isc_sockaddr_t any;
17671
0
      isc_sockaddr_any(&any);
17672
17673
0
      src = checkds->src;
17674
0
      if (isc_sockaddr_equal(&src, &any)) {
17675
0
        src = zone_addr4_tosockaddr(
17676
0
          &checkds->zone->parentalsrc4);
17677
0
      }
17678
0
    }
17679
0
    break;
17680
0
  case PF_INET6:
17681
0
    if (!have_checkdssource) {
17682
0
      isc_sockaddr_t any;
17683
0
      isc_sockaddr_any6(&any);
17684
17685
0
      src = checkds->src;
17686
0
      if (isc_sockaddr_equal(&src, &any)) {
17687
0
        src = zone_addr6_tosockaddr(
17688
0
          &checkds->zone->parentalsrc6);
17689
0
      }
17690
0
    }
17691
0
    break;
17692
0
  default:
17693
0
    result = ISC_R_NOTIMPLEMENTED;
17694
0
    goto cleanup_key;
17695
0
  }
17696
17697
0
  dns_zone_log(checkds->zone, ISC_LOG_DEBUG(3),
17698
0
         "checkds: create request for DS query to %s", addrbuf);
17699
17700
0
  options |= DNS_REQUESTOPT_TCP;
17701
17702
0
  dns__zonemgr_tlsctx_attach(dns_g_zonemgr, &zmgr_tlsctx_cache);
17703
0
  const unsigned int connect_timeout = isc_nm_getinitialtimeout() /
17704
0
               MS_PER_SEC;
17705
17706
0
  result = dns_request_create(
17707
0
    checkds->zone->view->requestmgr, message, &src, &checkds->dst,
17708
0
    checkds->transport, zmgr_tlsctx_cache, options, key,
17709
0
    connect_timeout, TCP_REQUEST_TIMEOUT, UDP_REQUEST_TIMEOUT,
17710
0
    UDP_REQUEST_RETRIES, checkds->zone->loop, checkds_done, checkds,
17711
0
    &checkds->request);
17712
0
  if (result != ISC_R_SUCCESS) {
17713
0
    dns_zone_log(checkds->zone, ISC_LOG_DEBUG(3),
17714
0
           "checkds: dns_request_create() to %s failed: %s",
17715
0
           addrbuf, isc_result_totext(result));
17716
0
  }
17717
17718
0
  isc_tlsctx_cache_detach(&zmgr_tlsctx_cache);
17719
17720
0
cleanup_key:
17721
0
  if (key != NULL) {
17722
0
    dns_tsigkey_detach(&key);
17723
0
  }
17724
0
cleanup_message:
17725
0
  dns_message_detach(&message);
17726
0
cleanup:
17727
0
  UNLOCK_ZONE(checkds->zone);
17728
0
  if (result != ISC_R_SUCCESS) {
17729
0
    checkds_destroy(checkds, false);
17730
0
  }
17731
0
}
17732
17733
static void
17734
0
checkds_send_tons(dns_checkds_t *checkds) {
17735
0
  isc_sockaddr_t dst;
17736
0
  isc_result_t result;
17737
0
  dns_checkds_t *newcheckds = NULL;
17738
0
  dns_zone_t *zone = NULL;
17739
17740
  /*
17741
   * Zone lock held by caller.
17742
   */
17743
0
  REQUIRE(DNS_CHECKDS_VALID(checkds));
17744
0
  REQUIRE(LOCKED_ZONE(checkds->zone));
17745
17746
0
  zone = checkds->zone;
17747
17748
0
  if (DNS_ZONE_FLAG(checkds->zone, DNS_ZONEFLG_EXITING)) {
17749
0
    return;
17750
0
  }
17751
17752
0
  ISC_LIST_FOREACH(checkds->find->list, ai, publink) {
17753
0
    dst = ai->sockaddr;
17754
0
    if (checkds_isqueued(zone, NULL, &dst, NULL, NULL)) {
17755
0
      continue;
17756
0
    }
17757
17758
0
    newcheckds = NULL;
17759
0
    checkds_create(checkds->mctx, 0, &newcheckds);
17760
0
    zone_iattach(zone, &newcheckds->zone);
17761
0
    ISC_LIST_APPEND(newcheckds->zone->checkds_requests, newcheckds,
17762
0
        link);
17763
0
    newcheckds->dst = dst;
17764
0
    dns_name_dup(&checkds->ns, checkds->mctx, &newcheckds->ns);
17765
0
    switch (isc_sockaddr_pf(&newcheckds->dst)) {
17766
0
    case PF_INET:
17767
0
      isc_sockaddr_any(&newcheckds->src);
17768
0
      break;
17769
0
    case PF_INET6:
17770
0
      isc_sockaddr_any6(&newcheckds->src);
17771
0
      break;
17772
0
    default:
17773
0
      UNREACHABLE();
17774
0
    }
17775
17776
0
    CHECK(isc_ratelimiter_enqueue(
17777
0
      dns_g_zonemgr->checkdsrl, newcheckds->zone->loop,
17778
0
      checkds_send_toaddr, newcheckds, &newcheckds->rlevent));
17779
0
    newcheckds = NULL;
17780
0
  }
17781
17782
0
cleanup:
17783
0
  if (newcheckds != NULL) {
17784
0
    checkds_destroy(newcheckds, true);
17785
0
  }
17786
0
}
17787
17788
static void
17789
0
checkds_send(dns_zone_t *zone) {
17790
0
  dns_view_t *view = dns_zone_getview(zone);
17791
0
  isc_result_t result;
17792
0
  unsigned int flags = 0;
17793
0
  unsigned int i = 0;
17794
17795
  /*
17796
   * Zone lock held by caller.
17797
   */
17798
0
  REQUIRE(LOCKED_ZONE(zone));
17799
17800
0
  dns_zone_log(zone, ISC_LOG_DEBUG(3),
17801
0
         "checkds: start sending DS queries to %u parentals",
17802
0
         dns_remote_count(&zone->parentals));
17803
17804
0
  if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_EXITING)) {
17805
0
    dns_zone_log(zone, ISC_LOG_DEBUG(3),
17806
0
           "checkds: abort, named exiting");
17807
0
    return;
17808
0
  }
17809
17810
0
  dns_remote_reset(&zone->parentals, false);
17811
0
  while (!dns_remote_done(&zone->parentals)) {
17812
0
    dns_tsigkey_t *key = NULL;
17813
0
    dns_transport_t *transport = NULL;
17814
0
    isc_sockaddr_t src, dst;
17815
0
    dns_checkds_t *checkds = NULL;
17816
17817
0
    i++;
17818
17819
0
    dst = dns_remote_curraddr(&zone->parentals);
17820
0
    if (isc_sockaddr_disabled(&dst)) {
17821
0
      goto next;
17822
0
    }
17823
17824
0
    if (dns_remote_keyname(&zone->parentals) != NULL) {
17825
0
      dns_name_t *keyname =
17826
0
        dns_remote_keyname(&zone->parentals);
17827
0
      (void)dns_view_gettsig(view, keyname, &key);
17828
0
    }
17829
17830
0
    if (dns_remote_tlsname(&zone->parentals) != NULL) {
17831
0
      dns_name_t *tlsname =
17832
0
        dns_remote_tlsname(&zone->parentals);
17833
0
      result = dns_view_gettransport(view, DNS_TRANSPORT_TLS,
17834
0
                   tlsname, &transport);
17835
0
      if (result == ISC_R_SUCCESS) {
17836
0
        dns_zone_logc(
17837
0
          zone, DNS_LOGCATEGORY_XFER_IN,
17838
0
          ISC_LOG_INFO,
17839
0
          "got TLS configuration for checkds");
17840
0
      } else {
17841
0
        dns_zone_logc(zone, DNS_LOGCATEGORY_XFER_IN,
17842
0
                ISC_LOG_ERROR,
17843
0
                "could not get TLS configuration "
17844
0
                "for checkds: %s",
17845
0
                isc_result_totext(result));
17846
0
        if (key != NULL) {
17847
0
          dns_tsigkey_detach(&key);
17848
0
        }
17849
0
        goto next;
17850
0
      }
17851
0
    }
17852
17853
0
    src = dns_remote_sourceaddr(&zone->parentals);
17854
0
    INSIST(isc_sockaddr_pf(&src) == isc_sockaddr_pf(&dst));
17855
17856
0
    if (checkds_isqueued(zone, NULL, &dst, key, transport)) {
17857
0
      dns_zone_log(zone, ISC_LOG_DEBUG(3),
17858
0
             "checkds: DS query to parent "
17859
0
             "%d is queued",
17860
0
             i);
17861
0
      if (key != NULL) {
17862
0
        dns_tsigkey_detach(&key);
17863
0
      }
17864
0
      if (transport != NULL) {
17865
0
        dns_transport_detach(&transport);
17866
0
      }
17867
0
      goto next;
17868
0
    }
17869
17870
0
    dns_zone_log(zone, ISC_LOG_DEBUG(3),
17871
0
           "checkds: create DS query for "
17872
0
           "parent %d",
17873
0
           i);
17874
17875
0
    checkds_create(zone->mctx, flags, &checkds);
17876
0
    zone_iattach(zone, &checkds->zone);
17877
0
    dns_name_dup(dns_rootname, checkds->mctx, &checkds->ns);
17878
0
    checkds->src = src;
17879
0
    checkds->dst = dst;
17880
17881
0
    INSIST(checkds->key == NULL);
17882
0
    if (key != NULL) {
17883
0
      checkds->key = key;
17884
0
      key = NULL;
17885
0
    }
17886
17887
0
    INSIST(checkds->transport == NULL);
17888
0
    if (transport != NULL) {
17889
0
      checkds->transport = transport;
17890
0
      transport = NULL;
17891
0
    }
17892
17893
0
    ISC_LIST_APPEND(zone->checkds_requests, checkds, link);
17894
0
    result = isc_ratelimiter_enqueue(
17895
0
      dns_g_zonemgr->checkdsrl, checkds->zone->loop,
17896
0
      checkds_send_toaddr, checkds, &checkds->rlevent);
17897
0
    if (result != ISC_R_SUCCESS) {
17898
0
      dns_zone_log(zone, ISC_LOG_DEBUG(3),
17899
0
             "checkds: send DS query to "
17900
0
             "parent %d failed",
17901
0
             i);
17902
0
      checkds_destroy(checkds, true);
17903
0
    }
17904
17905
0
  next:
17906
0
    dns_remote_next(&zone->parentals, false);
17907
0
  }
17908
0
}
17909
17910
/*
17911
 * Fetch NS records from parent zone.
17912
 */
17913
static isc_result_t
17914
0
nsfetch_start(dns_zonefetch_t *fetch) {
17915
0
  dns_nsfetch_t *nsfetch;
17916
17917
0
  REQUIRE(fetch->fetchtype == ZONEFETCHTYPE_NS);
17918
17919
0
  nsfetch = &fetch->fetchdata.nsfetch;
17920
17921
  /* Derive parent domain. Check for root domain. */
17922
0
  if (!dns_name_belowroot(&nsfetch->pname)) {
17923
0
    return ISC_R_NOTFOUND;
17924
0
  }
17925
17926
0
  dns_name_split(&nsfetch->pname,
17927
0
           dns_name_countlabels(&nsfetch->pname) - 1U, NULL,
17928
0
           &nsfetch->pname);
17929
17930
0
  fetch->qtype = dns_rdatatype_ns;
17931
0
  fetch->qname = &nsfetch->pname;
17932
17933
0
  return ISC_R_SUCCESS;
17934
0
}
17935
17936
/*
17937
 * Retry an NS RRset lookup, one level up. In other words, this function should
17938
 * be called on an dns_nsfetch structure where the response yielded in a NODATA
17939
 * response. This must be because there is an empty non-terminal inbetween the
17940
 * child and parent zone.
17941
 */
17942
static void
17943
0
nsfetch_continue(dns_zonefetch_t *fetch) {
17944
0
  dns_zone_t *zone = fetch->zone;
17945
17946
0
  REQUIRE(fetch->fetchtype == ZONEFETCHTYPE_NS);
17947
17948
#ifdef ENABLE_AFL
17949
  if (!dns_fuzzing_resolver) {
17950
#endif /* ifdef ENABLE_AFL */
17951
0
    LOCK_ZONE(zone);
17952
0
    zone->fetchcount[ZONEFETCHTYPE_NS]++;
17953
17954
0
    dns_zonefetch_reschedule(fetch);
17955
17956
0
    if (isc_log_wouldlog(ISC_LOG_DEBUG(3))) {
17957
0
      dnssec_log(zone, ISC_LOG_DEBUG(3),
17958
0
           "Creating parent NS fetch in "
17959
0
           "nsfetch_continue()");
17960
0
    }
17961
0
    UNLOCK_ZONE(zone);
17962
#ifdef ENABLE_AFL
17963
  }
17964
#endif /* ifdef ENABLE_AFL */
17965
0
}
17966
17967
static void
17968
0
nsfetch_cancel(dns_zonefetch_t *fetch) {
17969
0
  dns_zone_t *zone;
17970
17971
0
  REQUIRE(fetch->fetchtype == ZONEFETCHTYPE_NS);
17972
0
  REQUIRE(DNS_ZONE_VALID(fetch->zone));
17973
0
  REQUIRE(LOCKED_ZONE(fetch->zone));
17974
17975
0
  zone = fetch->zone;
17976
17977
0
  zone->fetchcount[ZONEFETCHTYPE_NS]--;
17978
0
}
17979
17980
static void
17981
0
nsfetch_cleanup(dns_zonefetch_t *fetch) {
17982
0
  REQUIRE(fetch->fetchtype == ZONEFETCHTYPE_NS);
17983
0
}
17984
17985
/*
17986
 * An NS RRset has been fetched from the parent of a zone whose DS RRset needs
17987
 * to be checked; scan the RRset and start sending queries to the parental
17988
 * agents.
17989
 */
17990
static isc_result_t
17991
0
nsfetch_checkds(dns_zonefetch_t *fetch, isc_result_t eresult) {
17992
0
  dns_nsfetch_t *nsfetch;
17993
0
  isc_result_t result = ISC_R_NOMORE;
17994
0
  dns_zone_t *zone = NULL;
17995
0
  dns_name_t *pname = NULL;
17996
0
  char pnamebuf[DNS_NAME_FORMATSIZE];
17997
0
  dns_rdataset_t *nsrrset = NULL;
17998
17999
0
  REQUIRE(fetch != NULL);
18000
0
  REQUIRE(fetch->fetchtype == ZONEFETCHTYPE_NS);
18001
0
  REQUIRE(DNS_ZONE_VALID(fetch->zone));
18002
0
  REQUIRE(LOCKED_ZONE(fetch->zone));
18003
18004
0
  nsfetch = &fetch->fetchdata.nsfetch;
18005
0
  zone = fetch->zone;
18006
0
  nsrrset = &fetch->rrset;
18007
0
  pname = &nsfetch->pname;
18008
18009
0
  zone->fetchcount[ZONEFETCHTYPE_NS]--;
18010
18011
0
  dns_name_format(pname, pnamebuf, sizeof(pnamebuf));
18012
0
  dnssec_log(zone, ISC_LOG_DEBUG(3),
18013
0
       "Returned from '%s' NS fetch in nsfetch_checkds(): %s",
18014
0
       pnamebuf, isc_result_totext(eresult));
18015
18016
0
  if (eresult == DNS_R_NCACHENXRRSET || eresult == DNS_R_NXRRSET) {
18017
0
    dnssec_log(zone, ISC_LOG_DEBUG(3),
18018
0
         "NODATA response for NS '%s', level up", pnamebuf);
18019
0
    return DNS_R_CONTINUE;
18020
0
  }
18021
18022
0
  CHECK(dns_zonefetch_verify(fetch, eresult, dns_trust_secure));
18023
18024
  /* Record the number of NS records we found. */
18025
0
  zone->parent_nscount = dns_rdataset_count(nsrrset);
18026
18027
0
  UNLOCK_ZONE(zone);
18028
18029
  /* Look up the addresses for the found parental name servers. */
18030
0
  DNS_RDATASET_FOREACH(nsrrset) {
18031
0
    dns_checkds_t *checkds = NULL;
18032
0
    dns_rdata_t rdata = DNS_RDATA_INIT;
18033
0
    dns_rdata_ns_t ns;
18034
0
    bool isqueued;
18035
18036
0
    dns_rdataset_current(nsrrset, &rdata);
18037
0
    result = dns_rdata_tostruct(&rdata, &ns);
18038
0
    RUNTIME_CHECK(result == ISC_R_SUCCESS);
18039
18040
0
    dns_rdata_reset(&rdata);
18041
18042
0
    LOCK_ZONE(zone);
18043
0
    isqueued = checkds_isqueued(zone, &ns.name, NULL, NULL, NULL);
18044
0
    UNLOCK_ZONE(zone);
18045
0
    if (isqueued) {
18046
0
      continue;
18047
0
    }
18048
0
    checkds_create(zone->mctx, 0, &checkds);
18049
18050
0
    if (isc_log_wouldlog(ISC_LOG_DEBUG(3))) {
18051
0
      char nsnamebuf[DNS_NAME_FORMATSIZE];
18052
0
      dns_name_format(&ns.name, nsnamebuf, sizeof(nsnamebuf));
18053
0
      dns_zone_log(zone, ISC_LOG_DEBUG(3),
18054
0
             "checkds: send DS query to NS %s",
18055
0
             nsnamebuf);
18056
0
    }
18057
18058
0
    LOCK_ZONE(zone);
18059
0
    zone_iattach(zone, &checkds->zone);
18060
0
    dns_name_dup(&ns.name, zone->mctx, &checkds->ns);
18061
0
    ISC_LIST_APPEND(zone->checkds_requests, checkds, link);
18062
0
    UNLOCK_ZONE(zone);
18063
18064
0
    checkds_find_address(checkds);
18065
0
  }
18066
18067
0
  LOCK_ZONE(zone);
18068
18069
0
cleanup:
18070
0
  if (result != ISC_R_SUCCESS) {
18071
0
    dnssec_log(
18072
0
      zone, ISC_LOG_ERROR,
18073
0
      "checkds: error during parental-agents processing: %s",
18074
0
      isc_result_totext(result));
18075
0
  }
18076
18077
0
  return result;
18078
0
}
18079
18080
static void
18081
0
zone_checkds(dns_zone_t *zone) {
18082
0
  bool cdscheck = false;
18083
0
  dns_checkdstype_t checkdstype = zone->checkdstype;
18084
18085
0
  if (checkdstype == dns_checkdstype_no) {
18086
0
    return;
18087
0
  }
18088
18089
0
  ISC_LIST_FOREACH(zone->checkds_ok, key, link) {
18090
0
    dst_key_state_t ds_state = DST_KEY_STATE_NA;
18091
0
    bool ksk = false;
18092
0
    isc_stdtime_t published = 0, withdrawn = 0;
18093
18094
    /* Is this key have the KSK role? */
18095
0
    (void)dst_key_role(key->key, &ksk, NULL);
18096
0
    if (!ksk) {
18097
0
      continue;
18098
0
    }
18099
18100
    /* Do we need to check the DS RRset? */
18101
0
    (void)dst_key_getstate(key->key, DST_KEY_DS, &ds_state);
18102
0
    (void)dst_key_gettime(key->key, DST_TIME_DSPUBLISH, &published);
18103
0
    (void)dst_key_gettime(key->key, DST_TIME_DSDELETE, &withdrawn);
18104
18105
0
    if (ds_state == DST_KEY_STATE_RUMOURED && published == 0) {
18106
0
      dst_key_setnum(key->key, DST_NUM_DSPUBCOUNT, 0);
18107
0
      cdscheck = true;
18108
0
    } else if (ds_state == DST_KEY_STATE_UNRETENTIVE &&
18109
0
         withdrawn == 0)
18110
0
    {
18111
0
      dst_key_setnum(key->key, DST_NUM_DSDELCOUNT, 0);
18112
0
      cdscheck = true;
18113
0
    }
18114
0
  }
18115
18116
0
  if (!cdscheck) {
18117
0
    return;
18118
0
  }
18119
18120
0
  if (checkdstype == dns_checkdstype_explicit) {
18121
    /* Request the DS RRset. */
18122
0
    LOCK_ZONE(zone);
18123
0
    checkds_send(zone);
18124
0
    UNLOCK_ZONE(zone);
18125
0
    return;
18126
0
  }
18127
18128
0
  INSIST(checkdstype == dns_checkdstype_yes);
18129
18130
#ifdef ENABLE_AFL
18131
  if (!dns_fuzzing_resolver) {
18132
#endif /* ifdef ENABLE_AFL */
18133
0
    dns_zonefetch_t *fetch = NULL;
18134
0
    dns_nsfetch_t *nsfetch = NULL;
18135
18136
0
    fetch = isc_mem_get(zone->mctx, sizeof(dns_zonefetch_t));
18137
0
    *fetch = (dns_zonefetch_t){
18138
0
      .zone = zone,
18139
0
      .fetchtype = ZONEFETCHTYPE_NS,
18140
0
      .fetchmethods =
18141
0
        (dns_zonefetch_methods_t){
18142
0
          .start_fetch = nsfetch_start,
18143
0
          .continue_fetch = nsfetch_continue,
18144
0
          .cancel_fetch = nsfetch_cancel,
18145
0
          .cleanup_fetch = nsfetch_cleanup,
18146
0
          .done_fetch = nsfetch_checkds,
18147
0
        },
18148
0
    };
18149
0
    isc_mem_attach(zone->mctx, &fetch->mctx);
18150
18151
0
    LOCK_ZONE(zone);
18152
0
    zone->fetchcount[ZONEFETCHTYPE_NS]++;
18153
18154
0
    nsfetch = &fetch->fetchdata.nsfetch;
18155
0
    dns_name_init(&nsfetch->pname);
18156
0
    dns_name_clone(&zone->origin, &nsfetch->pname);
18157
18158
0
    dns_zonefetch_schedule(fetch, &zone->origin);
18159
18160
0
    if (isc_log_wouldlog(ISC_LOG_DEBUG(3))) {
18161
0
      dnssec_log(
18162
0
        zone, ISC_LOG_DEBUG(3),
18163
0
        "Creating parent NS fetch in zone_checkds()");
18164
0
    }
18165
0
    UNLOCK_ZONE(zone);
18166
#ifdef ENABLE_AFL
18167
  }
18168
#endif /* ifdef ENABLE_AFL */
18169
0
}
18170
18171
static unsigned char _dsync_data[] = "\x06_dsync";
18172
static dns_name_t _dsync = DNS_NAME_INITNONABSOLUTE(_dsync_data);
18173
18174
static isc_result_t
18175
0
dsyncfetch_start(dns_zonefetch_t *fetch) {
18176
0
  dns_dsyncfetch_t *dsyncfetch;
18177
0
  dns_zone_t *zone;
18178
0
  dns_name_t *dsyncname, prefix;
18179
0
  unsigned int nlabels;
18180
0
  isc_result_t result;
18181
18182
0
  REQUIRE(fetch->fetchtype == ZONEFETCHTYPE_DSYNC);
18183
0
  REQUIRE(DNS_ZONE_VALID(fetch->zone));
18184
18185
0
  dsyncfetch = &fetch->fetchdata.dsyncfetch;
18186
0
  zone = fetch->zone;
18187
18188
  /*
18189
   * The dsync owner name is build up of <prefix>._dsync.<parent-name>.
18190
   * The prefix is the relative domain name of the child consisting of
18191
   * the labels under the zonecut.
18192
   */
18193
0
  dsyncname = dns_fixedname_initname(&dsyncfetch->dsyncname);
18194
18195
0
  nlabels = dns_name_countlabels(&dsyncfetch->pname);
18196
0
  dns_name_init(&prefix);
18197
0
  dns_name_split(dns_name(&fetch->name), nlabels, &prefix, NULL);
18198
18199
0
  result = dns_name_concatenate(&prefix, &_dsync, dsyncname);
18200
0
  if (result != ISC_R_SUCCESS) {
18201
0
    dnssec_log(zone, ISC_LOG_ERROR,
18202
0
         "dsyncfetch: failed to create parent DSYNC fetch "
18203
0
         "(child part): %s",
18204
0
         isc_result_totext(result));
18205
0
    return result;
18206
0
  }
18207
18208
0
  result = dns_name_concatenate(dsyncname, &dsyncfetch->pname, dsyncname);
18209
0
  if (result != ISC_R_SUCCESS) {
18210
0
    dnssec_log(zone, ISC_LOG_ERROR,
18211
0
         "dsyncfetch: failed to create parent DSYNC fetch "
18212
0
         "(parent part): %s",
18213
0
         isc_result_totext(result));
18214
0
    return result;
18215
0
  }
18216
18217
0
  fetch->qtype = dns_rdatatype_dsync;
18218
0
  fetch->qname = dsyncname;
18219
18220
0
  return ISC_R_SUCCESS;
18221
0
}
18222
18223
/*
18224
 * Retry an DSYNC RRset lookup.
18225
 */
18226
static void
18227
0
dsyncfetch_continue(dns_zonefetch_t *fetch) {
18228
0
  dns_zone_t *zone;
18229
18230
0
  REQUIRE(fetch->fetchtype == ZONEFETCHTYPE_DSYNC);
18231
0
  REQUIRE(DNS_ZONE_VALID(fetch->zone));
18232
18233
0
  zone = fetch->zone;
18234
18235
#ifdef ENABLE_AFL
18236
  if (!dns_fuzzing_resolver) {
18237
#endif /* ifdef ENABLE_AFL */
18238
0
    LOCK_ZONE(zone);
18239
0
    zone->fetchcount[ZONEFETCHTYPE_DSYNC]++;
18240
18241
0
    dns_zonefetch_reschedule(fetch);
18242
18243
0
    if (isc_log_wouldlog(ISC_LOG_DEBUG(3))) {
18244
0
      dnssec_log(zone, ISC_LOG_DEBUG(3),
18245
0
           "Creating parent DSYNC fetch in "
18246
0
           "dsyncfetch_continue()");
18247
0
    }
18248
0
    UNLOCK_ZONE(zone);
18249
#ifdef ENABLE_AFL
18250
  }
18251
#endif /* ifdef ENABLE_AFL */
18252
0
}
18253
18254
static void
18255
0
dsyncfetch_cancel(dns_zonefetch_t *fetch) {
18256
0
  dns_zone_t *zone;
18257
18258
0
  REQUIRE(fetch->fetchtype == ZONEFETCHTYPE_DSYNC);
18259
0
  REQUIRE(DNS_ZONE_VALID(fetch->zone));
18260
0
  REQUIRE(LOCKED_ZONE(fetch->zone));
18261
18262
0
  zone = fetch->zone;
18263
18264
0
  zone->fetchcount[ZONEFETCHTYPE_DSYNC]--;
18265
0
}
18266
18267
static void
18268
0
dsyncfetch_cleanup(dns_zonefetch_t *fetch) {
18269
0
  REQUIRE(fetch->fetchtype == ZONEFETCHTYPE_DSYNC);
18270
0
}
18271
18272
/*
18273
 * A DSYNC RRset has been fetched; scan the RRset and start sending
18274
 * NOTIFY(CDS) queries to them.
18275
 */
18276
static isc_result_t
18277
0
dsyncfetch_done(dns_zonefetch_t *fetch, isc_result_t eresult) {
18278
0
  dns_dsyncfetch_t *dsyncfetch;
18279
0
  isc_result_t result = ISC_R_NOMORE;
18280
0
  dns_notify_t *notify = NULL;
18281
0
  dns_zone_t *zone = NULL;
18282
0
  dns_name_t *dsyncname = NULL;
18283
0
  char dsyncnamebuf[DNS_NAME_FORMATSIZE];
18284
0
  dns_rdataset_t *rrset = NULL;
18285
0
  in_port_t port = 0;
18286
0
  dns_fixedname_t fixed;
18287
0
  dns_name_t *target = dns_fixedname_initname(&fixed);
18288
18289
0
  REQUIRE(fetch != NULL);
18290
0
  REQUIRE(fetch->fetchtype == ZONEFETCHTYPE_DSYNC);
18291
0
  REQUIRE(DNS_ZONE_VALID(fetch->zone));
18292
0
  REQUIRE(LOCKED_ZONE(fetch->zone));
18293
18294
0
  dsyncfetch = &fetch->fetchdata.dsyncfetch;
18295
0
  zone = fetch->zone;
18296
0
  rrset = &fetch->rrset;
18297
0
  dsyncname = dns_name(&dsyncfetch->dsyncname);
18298
18299
0
  zone->fetchcount[ZONEFETCHTYPE_DSYNC]--;
18300
18301
0
  dns_name_format(dsyncname, dsyncnamebuf, sizeof(dsyncnamebuf));
18302
0
  dns_zone_log(zone, ISC_LOG_DEBUG(3),
18303
0
         "dsyncfetch: Returned from '%s' DSYNC fetch in "
18304
0
         "dsyncfetch_done(): %s",
18305
0
         dsyncnamebuf, isc_result_totext(eresult));
18306
18307
0
  result = dns_zonefetch_verify(fetch, eresult, dns_trust_secure);
18308
0
  if (result != ISC_R_SUCCESS) {
18309
0
    goto done;
18310
0
  }
18311
18312
0
  UNLOCK_ZONE(zone);
18313
18314
  /* Notify targets. */
18315
0
  dns_rdata_dsync_t dsync;
18316
0
  unsigned int count = 0;
18317
0
  for (result = dns_rdataset_first(rrset); result == ISC_R_SUCCESS;
18318
0
       result = dns_rdataset_next(rrset))
18319
0
  {
18320
0
    dns_rdata_t rdata = DNS_RDATA_INIT;
18321
18322
0
    dns_rdataset_current(rrset, &rdata);
18323
0
    result = dns_rdata_tostruct(&rdata, &dsync);
18324
0
    RUNTIME_CHECK(result == ISC_R_SUCCESS);
18325
18326
0
    dns_rdata_reset(&rdata);
18327
0
    if (dsync.scheme != DNS_DSYNCSCHEME_NOTIFY) {
18328
0
      dns_zone_log(zone, ISC_LOG_DEBUG(1),
18329
0
             "dsyncfetch: unsupported DSYNC scheme %u, "
18330
0
             "ignoring",
18331
0
             dsync.scheme);
18332
0
      continue;
18333
0
    }
18334
18335
0
    if (dsync.type != dns_rdatatype_cds) {
18336
0
      char typebuf[DNS_RDATATYPE_FORMATSIZE];
18337
0
      dns_rdatatype_format(dsync.type, typebuf,
18338
0
               sizeof(typebuf));
18339
18340
0
      dns_zone_log(zone, ISC_LOG_DEBUG(1),
18341
0
             "dsyncfetch: DSYNC RRtype %s not "
18342
0
             "supported, ignoring",
18343
0
             result == ISC_R_SUCCESS ? typebuf
18344
0
                   : "UNKNOWN");
18345
0
      continue;
18346
0
    }
18347
18348
    /* Save matched DSYNC record. */
18349
0
    if (count == 0) {
18350
0
      port = dsync.port;
18351
0
      dns_name_copy(&dsync.target, target);
18352
0
    }
18353
18354
0
    count++;
18355
0
    if (count > 1) {
18356
0
      dns_zone_log(zone, ISC_LOG_WARNING,
18357
0
             "dsyncfetch: multiple DSYNC records "
18358
0
             "matching NOTIFY scheme and CDS RRtype, "
18359
0
             "dropping response");
18360
0
      result = DNS_R_INVALIDDSYNC;
18361
0
      break;
18362
0
    }
18363
0
  }
18364
18365
0
  LOCK_ZONE(zone);
18366
18367
0
  if (result == ISC_R_NOMORE) {
18368
0
    result = ISC_R_SUCCESS;
18369
0
  } else {
18370
    /* We didn't scan the complete RRset. */
18371
0
    goto done;
18372
0
  }
18373
18374
  /*
18375
   * Only one NOTIFY can be queued per type.
18376
   * Currently the only supported scheme/type is NOTIFY CDS.
18377
   * The port and target from the first matched DSYNC record are saved in
18378
   * 'port' and 'target'.
18379
   */
18380
0
  if (count != 1) {
18381
    /*
18382
     * Either count equals zero, and there is nothing to be queued.
18383
     * Or count > 1, then this is an invalid DSYNC RRset.
18384
     */
18385
0
    goto done;
18386
0
  }
18387
18388
0
  bool isqueued = dns_notify_isqueued(&zone->notifycds, dns_rdatatype_cds,
18389
0
              port, 0, target, NULL, NULL, NULL);
18390
18391
0
  UNLOCK_ZONE(zone);
18392
18393
0
  if (!isqueued) {
18394
0
    dns_notify_create(zone->mctx, dns_rdatatype_cds, port,
18395
0
          DNS_NOTIFY_NOSOA, &notify);
18396
0
    if (isc_log_wouldlog(ISC_LOG_DEBUG(3))) {
18397
0
      char tbuf[DNS_NAME_FORMATSIZE];
18398
0
      dns_name_format(target, tbuf, sizeof(tbuf));
18399
0
      dns_zone_log(zone, ISC_LOG_DEBUG(3),
18400
0
             "dsyncfetch: send NOTIFY(CDS) query to %s",
18401
0
             tbuf);
18402
0
    }
18403
0
    dns_zone_iattach(zone, &notify->zone);
18404
0
    dns_name_dup(target, zone->mctx, &notify->ns);
18405
0
    LOCK_ZONE(zone);
18406
0
    ISC_LIST_APPEND(zone->notifycds.notifies, notify, link);
18407
0
    UNLOCK_ZONE(zone);
18408
0
    dns_notify_find_address(notify);
18409
0
  }
18410
18411
0
  LOCK_ZONE(zone);
18412
18413
0
done:
18414
0
  if (result != ISC_R_SUCCESS) {
18415
0
    dns_zone_log(zone, ISC_LOG_DEBUG(3),
18416
0
           "dsyncfetch: error processing DSYNC RRset: %s",
18417
0
           isc_result_totext(result));
18418
0
  }
18419
18420
0
  return result;
18421
0
}
18422
18423
/*
18424
 * An NS RRset has been fetched from the parent of a zone whose DSYNC RRset
18425
 * needs to be queried; scan the RRset and start resolving those queries.
18426
 */
18427
static isc_result_t
18428
0
nsfetch_dsync(dns_zonefetch_t *fetch, isc_result_t eresult) {
18429
0
  dns_nsfetch_t *nsfetch;
18430
0
  isc_result_t result = ISC_R_NOMORE;
18431
0
  dns_zone_t *zone = NULL;
18432
0
  dns_name_t *pname = NULL;
18433
0
  char pnamebuf[DNS_NAME_FORMATSIZE];
18434
18435
0
  REQUIRE(fetch != NULL);
18436
0
  REQUIRE(fetch->fetchtype == ZONEFETCHTYPE_NS);
18437
0
  REQUIRE(DNS_ZONE_VALID(fetch->zone));
18438
0
  REQUIRE(LOCKED_ZONE(fetch->zone));
18439
18440
0
  nsfetch = &fetch->fetchdata.nsfetch;
18441
0
  zone = fetch->zone;
18442
0
  pname = &nsfetch->pname;
18443
18444
0
  zone->fetchcount[ZONEFETCHTYPE_NS]--;
18445
18446
0
  dns_name_format(pname, pnamebuf, sizeof(pnamebuf));
18447
0
  dnssec_log(zone, ISC_LOG_DEBUG(3),
18448
0
       "Returned from '%s' NS fetch in nsfetch_dsync(): %s",
18449
0
       pnamebuf, isc_result_totext(eresult));
18450
18451
0
  if (eresult == DNS_R_NCACHENXRRSET || eresult == DNS_R_NXRRSET) {
18452
0
    dnssec_log(zone, ISC_LOG_DEBUG(3),
18453
0
         "NODATA response for NS '%s', level up", pnamebuf);
18454
0
    return DNS_R_CONTINUE;
18455
0
  }
18456
18457
0
  result = dns_zonefetch_verify(fetch, eresult, dns_trust_secure);
18458
0
  if (result != ISC_R_SUCCESS) {
18459
0
    goto done;
18460
0
  }
18461
18462
#ifdef ENABLE_AFL
18463
  if (!dns_fuzzing_resolver) {
18464
#endif /* ifdef ENABLE_AFL */
18465
0
    dns_zonefetch_t *zfetch = NULL;
18466
0
    dns_dsyncfetch_t *dsyncfetch;
18467
18468
0
    zfetch = isc_mem_get(zone->mctx, sizeof(dns_zonefetch_t));
18469
0
    *zfetch = (dns_zonefetch_t){
18470
0
      .zone = zone,
18471
0
      .fetchtype = ZONEFETCHTYPE_DSYNC,
18472
0
      .fetchmethods =
18473
0
        (dns_zonefetch_methods_t){
18474
0
          .start_fetch = dsyncfetch_start,
18475
0
          .continue_fetch = dsyncfetch_continue,
18476
0
          .cancel_fetch = dsyncfetch_cancel,
18477
0
          .cleanup_fetch = dsyncfetch_cleanup,
18478
0
          .done_fetch = dsyncfetch_done,
18479
0
        },
18480
0
    };
18481
0
    isc_mem_attach(zone->mctx, &zfetch->mctx);
18482
18483
0
    zone->fetchcount[ZONEFETCHTYPE_DSYNC]++;
18484
18485
0
    dsyncfetch = &zfetch->fetchdata.dsyncfetch;
18486
0
    dns_name_init(&dsyncfetch->pname);
18487
0
    dns_name_clone(pname, &dsyncfetch->pname);
18488
18489
0
    dns_zonefetch_schedule(zfetch, &zone->origin);
18490
18491
0
    if (isc_log_wouldlog(ISC_LOG_DEBUG(3))) {
18492
0
      dnssec_log(zone, ISC_LOG_DEBUG(3),
18493
0
           "Creating parent DSYNC fetch in "
18494
0
           "nsfetch_dsync()");
18495
0
    }
18496
#ifdef ENABLE_AFL
18497
  }
18498
#endif /* ifdef ENABLE_AFL */
18499
18500
0
done:
18501
0
  return result;
18502
0
}
18503
18504
static void
18505
0
zone_notifycds(dns_zone_t *zone) {
18506
0
  dns_notifytype_t notifytype = zone->notifycds.notifytype;
18507
18508
0
  if (notifytype == dns_notifytype_no) {
18509
0
    return;
18510
0
  }
18511
18512
0
  INSIST(notifytype == dns_notifytype_yes);
18513
18514
#ifdef ENABLE_AFL
18515
  if (!dns_fuzzing_resolver) {
18516
#endif /* ifdef ENABLE_AFL */
18517
0
    dns_zonefetch_t *fetch = NULL;
18518
0
    dns_nsfetch_t *nsfetch;
18519
18520
0
    fetch = isc_mem_get(zone->mctx, sizeof(dns_zonefetch_t));
18521
0
    *fetch = (dns_zonefetch_t){
18522
0
      .zone = zone,
18523
0
      .fetchtype = ZONEFETCHTYPE_NS,
18524
0
      .fetchmethods =
18525
0
        (dns_zonefetch_methods_t){
18526
0
          .start_fetch = nsfetch_start,
18527
0
          .continue_fetch = nsfetch_continue,
18528
0
          .cancel_fetch = nsfetch_cancel,
18529
0
          .cleanup_fetch = nsfetch_cleanup,
18530
0
          .done_fetch = nsfetch_dsync,
18531
0
        },
18532
0
    };
18533
0
    isc_mem_attach(zone->mctx, &fetch->mctx);
18534
18535
0
    LOCK_ZONE(zone);
18536
0
    zone->fetchcount[ZONEFETCHTYPE_NS]++;
18537
18538
0
    nsfetch = &fetch->fetchdata.nsfetch;
18539
0
    dns_name_init(&nsfetch->pname);
18540
0
    dns_name_clone(&zone->origin, &nsfetch->pname);
18541
18542
0
    dns_zonefetch_schedule(fetch, &zone->origin);
18543
18544
0
    if (isc_log_wouldlog(ISC_LOG_DEBUG(3))) {
18545
0
      dnssec_log(
18546
0
        zone, ISC_LOG_DEBUG(3),
18547
0
        "Creating parent NS fetch in zone_notifyds()");
18548
0
    }
18549
0
    UNLOCK_ZONE(zone);
18550
#ifdef ENABLE_AFL
18551
  }
18552
#endif /* ifdef ENABLE_AFL */
18553
0
}
18554
18555
static void
18556
update_ttl(dns_rdataset_t *rdataset, dns_name_t *name, dns_ttl_t ttl,
18557
0
     dns_diff_t *diff) {
18558
0
  dns_diff_t pending;
18559
18560
0
  dns_diff_init(diff->mctx, &pending);
18561
18562
  /*
18563
   * Delete everything using the existing TTL.
18564
   */
18565
0
  DNS_RDATASET_FOREACH(rdataset) {
18566
0
    dns_difftuple_t *tuple = NULL;
18567
0
    dns_rdata_t rdata = DNS_RDATA_INIT;
18568
18569
0
    dns_rdataset_current(rdataset, &rdata);
18570
0
    dns_difftuple_create(diff->mctx, DNS_DIFFOP_DEL, name,
18571
0
             rdataset->ttl, &rdata, &tuple);
18572
0
    dns_diff_append(&pending, &tuple);
18573
0
  }
18574
18575
  /*
18576
   * Add everything using the new TTL.
18577
   */
18578
0
  DNS_RDATASET_FOREACH(rdataset) {
18579
0
    dns_difftuple_t *tuple = NULL;
18580
0
    dns_rdata_t rdata = DNS_RDATA_INIT;
18581
18582
0
    dns_rdataset_current(rdataset, &rdata);
18583
0
    dns_difftuple_create(diff->mctx, DNS_DIFFOP_ADD, name, ttl,
18584
0
             &rdata, &tuple);
18585
0
    dns_diff_append(&pending, &tuple);
18586
0
  }
18587
0
  dns_diff_appendlistminimal(diff, &pending);
18588
0
}
18589
18590
static isc_result_t
18591
zone_verifykeys(dns_zone_t *zone, dns_dnsseckeylist_t *newkeys,
18592
0
    uint32_t purgeval, isc_stdtime_t now) {
18593
  /*
18594
   * Make sure that the existing keys are also present in the new keylist.
18595
   */
18596
0
  ISC_LIST_FOREACH(zone->keyring, key1, link) {
18597
0
    bool found = false;
18598
18599
0
    if (dst_key_is_unused(key1->key)) {
18600
0
      continue;
18601
0
    }
18602
0
    if (dns_keymgr_key_may_be_purged(key1->key, purgeval, now)) {
18603
0
      continue;
18604
0
    }
18605
0
    if (key1->purge) {
18606
0
      continue;
18607
0
    }
18608
18609
0
    ISC_LIST_FOREACH(*newkeys, key2, link) {
18610
0
      if (dst_key_compare(key1->key, key2->key)) {
18611
0
        found = true;
18612
0
        break;
18613
0
      }
18614
0
    }
18615
18616
0
    if (!found) {
18617
0
      char keystr[DST_KEY_FORMATSIZE];
18618
0
      dst_key_format(key1->key, keystr, sizeof(keystr));
18619
0
      dnssec_log(zone, ISC_LOG_DEBUG(1),
18620
0
           "verifykeys: key %s - not available",
18621
0
           keystr);
18622
0
      return ISC_R_NOTFOUND;
18623
0
    }
18624
0
  }
18625
18626
  /* All good. */
18627
0
  return ISC_R_SUCCESS;
18628
0
}
18629
18630
static void
18631
0
remove_rdataset(dns_zone_t *zone, dns_diff_t *diff, dns_rdataset_t *rdataset) {
18632
0
  if (!dns_rdataset_isassociated(rdataset)) {
18633
0
    return;
18634
0
  }
18635
18636
0
  DNS_RDATASET_FOREACH(rdataset) {
18637
0
    dns_rdata_t rdata = DNS_RDATA_INIT;
18638
0
    dns_difftuple_t *tuple = NULL;
18639
18640
0
    dns_rdataset_current(rdataset, &rdata);
18641
0
    dns_difftuple_create(zone->mctx, DNS_DIFFOP_DEL, &zone->origin,
18642
0
             rdataset->ttl, &rdata, &tuple);
18643
0
    dns_diff_append(diff, &tuple);
18644
0
  }
18645
0
  return;
18646
0
}
18647
18648
static void
18649
0
add_tuple(dns_diff_t *diff, dns_difftuple_t *tuple) {
18650
0
  dns_difftuple_t *copy = NULL;
18651
18652
0
  dns_difftuple_copy(tuple, &copy);
18653
0
  dns_diff_append(diff, &copy);
18654
0
}
18655
18656
static void
18657
zone_apply_skrbundle(dns_zone_t *zone, dns_skrbundle_t *bundle,
18658
         dns_rdataset_t *dnskeyset, dns_rdataset_t *cdsset,
18659
0
         dns_rdataset_t *cdnskeyset, dns_diff_t *diff) {
18660
0
  dns_kasp_t *kasp = zone->kasp;
18661
0
  dns_diff_t pending;
18662
18663
0
  REQUIRE(DNS_ZONE_VALID(zone));
18664
0
  REQUIRE(DNS_KASP_VALID(kasp));
18665
0
  REQUIRE(DNS_SKRBUNDLE_VALID(bundle));
18666
0
  dns_diff_init(diff->mctx, &pending);
18667
18668
  /* Remove existing DNSKEY, CDS, and CDNSKEY records. */
18669
0
  remove_rdataset(zone, diff, dnskeyset);
18670
0
  remove_rdataset(zone, diff, cdsset);
18671
0
  remove_rdataset(zone, diff, cdnskeyset);
18672
18673
  /* Add the records from the bundle. */
18674
0
  ISC_LIST_FOREACH(bundle->diff.tuples, tuple, link) {
18675
0
    switch (tuple->rdata.type) {
18676
0
    case dns_rdatatype_dnskey:
18677
0
      add_tuple(&pending, tuple);
18678
0
      break;
18679
0
    case dns_rdatatype_cdnskey:
18680
0
    case dns_rdatatype_cds:
18681
0
      add_tuple(&pending, tuple);
18682
0
      break;
18683
0
    case dns_rdatatype_rrsig:
18684
      /* Not interested in right now */
18685
0
      break;
18686
0
    default:
18687
0
      INSIST(0);
18688
0
    }
18689
0
  }
18690
0
  if (!ISC_LIST_EMPTY(pending.tuples)) {
18691
0
    dns_diff_appendlistminimal(diff, &pending);
18692
0
  }
18693
0
}
18694
18695
static void
18696
0
zone_rekey(dns_zone_t *zone) {
18697
0
  isc_result_t result;
18698
0
  dns_db_t *db = NULL;
18699
0
  dns_dbnode_t *node = NULL;
18700
0
  dns_dbversion_t *ver = NULL;
18701
0
  dns_rdataset_t cdsset, soaset, soasigs, keyset, keysigs, cdnskeyset;
18702
0
  dns_dnsseckeylist_t dnskeys, keys, rmkeys;
18703
0
  dns_diff_t diff, _sig_diff;
18704
0
  dns_kasp_t *kasp;
18705
0
  dns_skrbundle_t *bundle = NULL;
18706
0
  dns__zonediff_t zonediff;
18707
0
  bool commit = false, newactive = false;
18708
0
  bool newalg = false;
18709
0
  bool fullsign;
18710
0
  bool notifycds = false;
18711
0
  bool offlineksk = false;
18712
0
  bool keymgr_done = false;
18713
0
  bool kasp_change = false;
18714
0
  uint8_t options = 0;
18715
0
  uint32_t sigval = 0;
18716
0
  dns_ttl_t ttl = 3600;
18717
0
  const char *dir = NULL;
18718
0
  isc_mem_t *mctx = NULL;
18719
0
  isc_stdtime_t now, nexttime = 0;
18720
0
  isc_time_t timenow;
18721
0
  isc_interval_t ival;
18722
0
  char timebuf[80];
18723
18724
0
  REQUIRE(DNS_ZONE_VALID(zone));
18725
18726
0
  ISC_LIST_INIT(dnskeys);
18727
0
  ISC_LIST_INIT(keys);
18728
0
  ISC_LIST_INIT(rmkeys);
18729
0
  dns_rdataset_init(&soaset);
18730
0
  dns_rdataset_init(&soasigs);
18731
0
  dns_rdataset_init(&keyset);
18732
0
  dns_rdataset_init(&keysigs);
18733
0
  dns_rdataset_init(&cdsset);
18734
0
  dns_rdataset_init(&cdnskeyset);
18735
0
  mctx = zone->mctx;
18736
0
  dns_diff_init(mctx, &diff);
18737
0
  dns_diff_init(mctx, &_sig_diff);
18738
0
  zonediff_init(&zonediff, &_sig_diff);
18739
18740
0
  CHECK(dns_zone_getdb(zone, &db));
18741
0
  CHECK(dns_db_newversion(db, &ver));
18742
0
  CHECK(dns_db_getoriginnode(db, &node));
18743
18744
0
  timenow = isc_time_now();
18745
0
  now = isc_time_seconds(&timenow);
18746
18747
0
  kasp = zone->kasp;
18748
0
  dir = dns_zone_getkeydirectory(zone);
18749
18750
0
  dnssec_log(zone, ISC_LOG_INFO, "reconfiguring zone keys");
18751
18752
  /* Get the SOA record's TTL */
18753
0
  CHECK(dns_db_findrdataset(db, node, ver, dns_rdatatype_soa,
18754
0
          dns_rdatatype_none, 0, &soaset, &soasigs));
18755
0
  ttl = soaset.ttl;
18756
0
  dns_rdataset_disassociate(&soaset);
18757
18758
0
  if (kasp != NULL) {
18759
0
    ttl = dns_kasp_dnskeyttl(kasp);
18760
0
    offlineksk = dns_kasp_offlineksk(kasp);
18761
0
    sigval = dns_kasp_sigvalidity_dnskey(kasp);
18762
0
  }
18763
18764
  /* Get the current DNSKEY rdataset */
18765
0
  result = dns_db_findrdataset(db, node, ver, dns_rdatatype_dnskey,
18766
0
             dns_rdatatype_none, 0, &keyset, &keysigs);
18767
0
  if (result == ISC_R_SUCCESS) {
18768
    /*
18769
     * If we don't have a policy then use the DNSKEY ttl
18770
     * if it exists.  Otherwise update the DNSKEY ttl if
18771
     * needed.
18772
     */
18773
0
    if (kasp == NULL) {
18774
0
      ttl = keyset.ttl;
18775
0
    } else if (ttl != keyset.ttl && !offlineksk) {
18776
0
      update_ttl(&keyset, &zone->origin, ttl, &diff);
18777
0
      dnssec_log(zone, ISC_LOG_INFO,
18778
0
           "Updating DNSKEY TTL from %u to %u",
18779
0
           keyset.ttl, ttl);
18780
0
      keyset.ttl = ttl;
18781
0
    }
18782
18783
0
    dns_zone_lock_keyfiles(zone);
18784
18785
0
    result = dns_dnssec_keylistfromrdataset(
18786
0
      &zone->origin, kasp, dir, mctx, &keyset, &keysigs,
18787
0
      &soasigs, false, false, &dnskeys);
18788
18789
0
    dns_zone_unlock_keyfiles(zone);
18790
18791
0
    CHECK(result);
18792
0
  } else if (result != ISC_R_NOTFOUND) {
18793
0
    goto cleanup;
18794
0
  }
18795
18796
  /* Get the current CDS rdataset */
18797
0
  result = dns_db_findrdataset(db, node, ver, dns_rdatatype_cds,
18798
0
             dns_rdatatype_none, 0, &cdsset, NULL);
18799
0
  if (result != ISC_R_SUCCESS) {
18800
0
    dns_rdataset_cleanup(&cdsset);
18801
0
  } else if (kasp != NULL && ttl != cdsset.ttl && !offlineksk) {
18802
0
    update_ttl(&cdsset, &zone->origin, ttl, &diff);
18803
0
    dnssec_log(zone, ISC_LOG_INFO, "Updating CDS TTL from %u to %u",
18804
0
         cdsset.ttl, ttl);
18805
0
    cdsset.ttl = ttl;
18806
0
  }
18807
18808
  /* Get the current CDNSKEY rdataset */
18809
0
  result = dns_db_findrdataset(db, node, ver, dns_rdatatype_cdnskey,
18810
0
             dns_rdatatype_none, 0, &cdnskeyset, NULL);
18811
0
  if (result != ISC_R_SUCCESS) {
18812
0
    dns_rdataset_cleanup(&cdnskeyset);
18813
0
  } else if (kasp != NULL && ttl != cdnskeyset.ttl && !offlineksk) {
18814
0
    update_ttl(&cdnskeyset, &zone->origin, ttl, &diff);
18815
0
    dnssec_log(zone, ISC_LOG_INFO,
18816
0
         "Updating CDNSKEY TTL from %u to %u", cdnskeyset.ttl,
18817
0
         ttl);
18818
0
    cdnskeyset.ttl = ttl;
18819
0
  }
18820
18821
  /*
18822
   * True when called from "rndc sign".  Indicates the zone should be
18823
   * fully signed now.
18824
   */
18825
0
  fullsign = DNS_ZONE_OPTION(zone, DNS_ZONEOPT_FULLSIGN);
18826
0
  if (fullsign) {
18827
0
    options |= DNS_KEYMGRATTR_FULLSIGN;
18828
0
  }
18829
18830
  /*
18831
   * True when called from "rndc dnssec -step". Indicates the zone
18832
   * is allowed to do the next step(s) in the keymgr process.
18833
   */
18834
0
  if (DNS_ZONE_OPTION(zone, DNS_ZONEOPT_FORCEKEYMGR)) {
18835
0
    options |= DNS_KEYMGRATTR_FORCESTEP;
18836
0
  }
18837
18838
0
  if (offlineksk) {
18839
    /* Lookup the correct bundle in the SKR. */
18840
0
    LOCK_ZONE(zone);
18841
0
    if (zone->skr == NULL) {
18842
0
      UNLOCK_ZONE(zone);
18843
0
      dnssec_log(zone, ISC_LOG_DEBUG(1),
18844
0
           "zone_rekey:dns_skr_lookup failed: "
18845
0
           "no SKR available");
18846
0
      CLEANUP(DNS_R_NOSKRFILE);
18847
0
    }
18848
0
    bundle = dns_skr_lookup(zone->skr, now, sigval);
18849
0
    zone->skrbundle = bundle;
18850
0
    UNLOCK_ZONE(zone);
18851
18852
0
    if (bundle == NULL) {
18853
0
      char nowstr[26]; /* Minimal buf per ctime_r() spec. */
18854
0
      char utc[sizeof("YYYYMMDDHHSSMM")];
18855
0
      isc_buffer_t b;
18856
0
      isc_region_t r;
18857
0
      isc_buffer_init(&b, utc, sizeof(utc));
18858
18859
0
      isc_stdtime_tostring(now, nowstr, sizeof(nowstr));
18860
0
      (void)dns_time32_totext(now, &b);
18861
0
      isc_buffer_usedregion(&b, &r);
18862
0
      dnssec_log(zone, ISC_LOG_DEBUG(1),
18863
0
           "zone_rekey:dns_skr_lookup failed: "
18864
0
           "no available SKR bundle for time "
18865
0
           "%.*s (%s)",
18866
0
           (int)r.length, r.base, nowstr);
18867
0
      CLEANUP(DNS_R_NOSKRBUNDLE);
18868
0
    }
18869
18870
0
    zone_apply_skrbundle(zone, bundle, &keyset, &cdsset,
18871
0
             &cdnskeyset, &diff);
18872
18873
0
    dns_skrbundle_t *next = ISC_LIST_NEXT(bundle, link);
18874
0
    if (next != NULL) {
18875
0
      if (nexttime == 0) {
18876
0
        nexttime = next->inception;
18877
0
      }
18878
0
    } else {
18879
0
      dnssec_log(zone, ISC_LOG_WARNING,
18880
0
           "zone_rekey: last bundle in skr, please "
18881
0
           "import new skr file");
18882
0
    }
18883
0
  }
18884
18885
  /*
18886
   * DNSSEC Key and Signing Policy
18887
   */
18888
18889
0
  KASP_LOCK(kasp);
18890
18891
0
  dns_zone_lock_keyfiles(zone);
18892
0
  result = dns_dnssec_findmatchingkeys(&zone->origin, kasp, dir,
18893
0
               dns_zone_getkeystores(zone), now,
18894
0
               false, mctx, &keys);
18895
0
  dns_zone_unlock_keyfiles(zone);
18896
18897
0
  if (result != ISC_R_SUCCESS) {
18898
0
    dnssec_log(zone, ISC_LOG_DEBUG(1),
18899
0
         "zone_rekey:dns_dnssec_findmatchingkeys failed: %s",
18900
0
         isc_result_totext(result));
18901
0
  }
18902
18903
0
  if (kasp != NULL && !offlineksk) {
18904
    /* Verify new keys. */
18905
0
    isc_result_t ret = zone_verifykeys(
18906
0
      zone, &keys, dns_kasp_purgekeys(kasp), now);
18907
0
    if (ret != ISC_R_SUCCESS) {
18908
0
      dnssec_log(zone, ISC_LOG_ERROR,
18909
0
           "zone_rekey:zone_verifykeys failed: "
18910
0
           "some key files are missing");
18911
0
      KASP_UNLOCK(kasp);
18912
0
      goto cleanup;
18913
0
    }
18914
18915
    /*
18916
     * Check DS at parental agents. Clear ongoing checks.
18917
     */
18918
0
    LOCK_ZONE(zone);
18919
0
    checkds_cancel(zone);
18920
0
    clear_keylist(&zone->checkds_ok, zone->mctx);
18921
0
    ISC_LIST_INIT(zone->checkds_ok);
18922
0
    UNLOCK_ZONE(zone);
18923
18924
0
    ret = dns_zone_getdnsseckeys(zone, db, ver, now,
18925
0
               &zone->checkds_ok);
18926
0
    if (ret == ISC_R_SUCCESS) {
18927
0
      zone_checkds(zone);
18928
0
    } else {
18929
0
      dnssec_log(zone,
18930
0
           (ret == ISC_R_NOTFOUND) ? ISC_LOG_DEBUG(1)
18931
0
                 : ISC_LOG_ERROR,
18932
0
           "zone_rekey:dns_zone_getdnsseckeys failed: "
18933
0
           "%s",
18934
0
           isc_result_totext(ret));
18935
0
    }
18936
18937
    /* Run keymgr. */
18938
0
    if (result == ISC_R_SUCCESS || result == ISC_R_NOTFOUND) {
18939
0
      dns_zone_lock_keyfiles(zone);
18940
0
      result = dns_keymgr_run(&zone->origin, zone->rdclass,
18941
0
            mctx, &keys, &dnskeys, dir,
18942
0
            kasp, options, now, &nexttime);
18943
0
      dns_zone_unlock_keyfiles(zone);
18944
18945
0
      if (result == ISC_R_SUCCESS) {
18946
0
        kasp_change = true;
18947
0
        keymgr_done = true;
18948
0
      } else if (result == DNS_R_UNCHANGED) {
18949
0
        result = ISC_R_SUCCESS;
18950
0
        keymgr_done = true;
18951
0
      } else {
18952
0
        dnssec_log(zone, ISC_LOG_ERROR,
18953
0
             "zone_rekey:dns_keymgr_run "
18954
0
             "failed: %s",
18955
0
             isc_result_totext(result));
18956
0
        KASP_UNLOCK(kasp);
18957
0
        goto cleanup;
18958
0
      }
18959
0
    }
18960
0
  } else if (offlineksk) {
18961
    /*
18962
     * With offline-ksk enabled we don't run the keymgr.
18963
     * Instead we derive the states from the timing metadata.
18964
     */
18965
0
    dns_zone_lock_keyfiles(zone);
18966
0
    result = dns_keymgr_offline(&zone->origin, &keys, kasp, now,
18967
0
              &nexttime);
18968
0
    dns_zone_unlock_keyfiles(zone);
18969
18970
0
    if (result == ISC_R_SUCCESS) {
18971
0
      keymgr_done = true;
18972
0
    } else {
18973
0
      dnssec_log(zone, ISC_LOG_ERROR,
18974
0
           "zone_rekey:dns_keymgr_offline "
18975
0
           "failed: %s",
18976
0
           isc_result_totext(result));
18977
0
    }
18978
0
  }
18979
18980
0
  KASP_UNLOCK(kasp);
18981
18982
  /*
18983
   * Update CDS, CDNSKEY and DNSKEY record sets if the keymgr ran
18984
   * successfully (dns_keymgr_run returned ISC_R_SUCCESS), or in
18985
   * case of DNSSEC management without dnssec-policy if we have keys
18986
   * (dns_dnssec_findmatchingkeys returned ISC_R_SUCCESS).
18987
   */
18988
0
  if (result == ISC_R_SUCCESS) {
18989
0
    dns_kasp_digestlist_t digests;
18990
0
    bool cdsdel = false;
18991
0
    bool cdnskeydel = false;
18992
0
    bool cdnskeypub = true;
18993
0
    bool sane_diff, sane_dnskey;
18994
0
    isc_stdtime_t when;
18995
18996
0
    result = dns_dnssec_updatekeys(&dnskeys, &keys, &rmkeys,
18997
0
                 &zone->origin, ttl, &diff, mctx,
18998
0
                 dnssec_report);
18999
    /*
19000
     * Keys couldn't be updated for some reason;
19001
     * try again later.
19002
     */
19003
0
    if (result != ISC_R_SUCCESS) {
19004
0
      dnssec_log(zone, ISC_LOG_ERROR,
19005
0
           "zone_rekey:couldn't update zone keys: %s",
19006
0
           isc_result_totext(result));
19007
0
      goto cleanup;
19008
0
    }
19009
19010
0
    if (offlineksk) {
19011
      /* We can skip a lot of things */
19012
0
      goto post_sync;
19013
0
    }
19014
19015
    /*
19016
     * Publish CDS/CDNSKEY DELETE records if the zone is
19017
     * transitioning from secure to insecure.
19018
     */
19019
0
    if (kasp != NULL) {
19020
0
      if (strcmp(dns_kasp_getname(kasp), "insecure") == 0) {
19021
0
        cdsdel = true;
19022
0
        cdnskeydel = true;
19023
0
      }
19024
0
      digests = dns_kasp_digests(kasp);
19025
0
      cdnskeypub = dns_kasp_cdnskey(kasp);
19026
0
    } else {
19027
      /* Check if there is a CDS DELETE record. */
19028
0
      if (dns_rdataset_isassociated(&cdsset)) {
19029
0
        DNS_RDATASET_FOREACH(&cdsset) {
19030
0
          dns_rdata_t crdata = DNS_RDATA_INIT;
19031
0
          dns_rdataset_current(&cdsset, &crdata);
19032
          /*
19033
           * CDS deletion record has this form
19034
           * "0 0 0 00" which is 5 zero octets.
19035
           */
19036
0
          if (crdata.length == 5U &&
19037
0
              memcmp(crdata.data,
19038
0
               (unsigned char[5]){ 0, 0, 0,
19039
0
                       0, 0 },
19040
0
               5) == 0)
19041
0
          {
19042
0
            cdsdel = true;
19043
0
            break;
19044
0
          }
19045
0
        }
19046
0
      }
19047
19048
      /* Check if there is a CDNSKEY DELETE record. */
19049
0
      if (dns_rdataset_isassociated(&cdnskeyset)) {
19050
0
        DNS_RDATASET_FOREACH(&cdnskeyset) {
19051
0
          dns_rdata_t crdata = DNS_RDATA_INIT;
19052
0
          dns_rdataset_current(&cdnskeyset,
19053
0
                   &crdata);
19054
          /*
19055
           * CDNSKEY deletion record has this form
19056
           * "0 3 0 AA==" which is 2 zero octets,
19057
           * a 3, and 2 zero octets.
19058
           */
19059
0
          if (crdata.length == 5U &&
19060
0
              memcmp(crdata.data,
19061
0
               (unsigned char[5]){ 0, 0, 3,
19062
0
                       0, 0 },
19063
0
               5) == 0)
19064
0
          {
19065
0
            cdnskeydel = true;
19066
0
            break;
19067
0
          }
19068
0
        }
19069
0
      }
19070
19071
0
      digests = dns_kasp_digests(zone->defaultkasp);
19072
0
    }
19073
19074
    /*
19075
     * Update CDS / CDNSKEY records.
19076
     */
19077
0
    result = dns_dnssec_syncupdate(&dnskeys, &rmkeys, &cdsset,
19078
0
                 &cdnskeyset, now, &digests,
19079
0
                 cdnskeypub, ttl, &diff, mctx);
19080
0
    if (result == ISC_R_SUCCESS) {
19081
0
      notifycds = true;
19082
0
    } else if (result != DNS_R_UNCHANGED) {
19083
0
      dnssec_log(zone, ISC_LOG_ERROR,
19084
0
           "zone_rekey:couldn't update CDS/CDNSKEY: %s",
19085
0
           isc_result_totext(result));
19086
0
      goto cleanup;
19087
0
    }
19088
19089
0
    if (cdsdel || cdnskeydel) {
19090
      /*
19091
       * Only publish CDS/CDNSKEY DELETE records if there is
19092
       * a KSK that can be used to verify the RRset. This
19093
       * means there must be a key with the KSK role that is
19094
       * published and is used for signing.
19095
       */
19096
0
      bool allow = false;
19097
0
      ISC_LIST_FOREACH(dnskeys, key, link) {
19098
0
        dst_key_t *dstk = key->key;
19099
19100
0
        if (dst_key_is_published(dstk, now, &when) &&
19101
0
            dst_key_is_signing(dstk, DST_BOOL_KSK, now,
19102
0
                   &when))
19103
0
        {
19104
0
          allow = true;
19105
0
          break;
19106
0
        }
19107
0
      }
19108
0
      if (cdsdel) {
19109
0
        cdsdel = allow;
19110
0
      }
19111
0
      if (cdnskeydel) {
19112
0
        cdnskeydel = allow;
19113
0
      }
19114
0
    }
19115
0
    result = dns_dnssec_syncdelete(
19116
0
      &cdsset, &cdnskeyset, &zone->origin, zone->rdclass, ttl,
19117
0
      &diff, mctx, cdsdel, cdnskeydel);
19118
0
    if (result == ISC_R_SUCCESS) {
19119
0
      notifycds = true;
19120
0
    } else if (result != DNS_R_UNCHANGED) {
19121
0
      dnssec_log(zone, ISC_LOG_ERROR,
19122
0
           "zone_rekey:couldn't update CDS/CDNSKEY "
19123
0
           "DELETE records: %s",
19124
0
           isc_result_totext(result));
19125
0
      goto cleanup;
19126
0
    }
19127
19128
0
  post_sync:
19129
    /*
19130
     * See if any pre-existing keys have newly become active;
19131
     * also, see if any new key is for a new algorithm, as in that
19132
     * event, we need to sign the zone fully.  (If there's a new
19133
     * key, but it's for an already-existing algorithm, then
19134
     * the zone signing can be handled incrementally.)
19135
     */
19136
0
    ISC_LIST_FOREACH(dnskeys, key, link) {
19137
0
      if (!key->first_sign) {
19138
0
        continue;
19139
0
      }
19140
19141
0
      newactive = true;
19142
19143
0
      if (!dns_rdataset_isassociated(&keysigs)) {
19144
0
        newalg = true;
19145
0
        break;
19146
0
      }
19147
19148
0
      if (signed_with_alg(&keysigs, dst_key_alg(key->key))) {
19149
        /*
19150
         * This isn't a new algorithm; clear
19151
         * first_sign so we won't sign the
19152
         * whole zone with this key later.
19153
         */
19154
0
        key->first_sign = false;
19155
0
      } else {
19156
0
        newalg = true;
19157
0
        break;
19158
0
      }
19159
0
    }
19160
19161
    /*
19162
     * A sane diff is one that is not empty, and that does not
19163
     * introduce a zone with NSEC only DNSKEYs along with NSEC3
19164
     * chains.
19165
     */
19166
0
    sane_dnskey = dns_zone_check_dnskey_nsec3(zone, db, ver, &diff,
19167
0
                NULL, 0);
19168
0
    sane_diff = !ISC_LIST_EMPTY(diff.tuples) && sane_dnskey;
19169
0
    if (!sane_dnskey) {
19170
0
      dnssec_log(zone, ISC_LOG_ERROR,
19171
0
           "NSEC only DNSKEYs and NSEC3 chains not "
19172
0
           "allowed");
19173
0
    }
19174
19175
0
    if (newactive || fullsign || sane_diff || kasp_change) {
19176
0
      CHECK(dns_diff_apply(&diff, db, ver));
19177
0
      CHECK(clean_nsec3param(zone, db, ver, &diff));
19178
0
      CHECK(add_signing_records(db, zone->privatetype, ver,
19179
0
              &diff, newalg || fullsign));
19180
0
      CHECK(update_soa_serial(zone, db, ver, &diff, mctx,
19181
0
            zone->updatemethod));
19182
0
      CHECK(add_chains(zone, db, ver, &diff));
19183
0
      CHECK(sign_apex(zone, db, ver, now, &diff, &zonediff));
19184
0
      CHECK(zone_journal(zone, zonediff.diff, NULL,
19185
0
             "zone_rekey"));
19186
0
      commit = true;
19187
0
    }
19188
0
  }
19189
19190
0
  dns_db_closeversion(db, &ver, true);
19191
19192
0
  LOCK_ZONE(zone);
19193
19194
0
  if (commit) {
19195
0
    dns_stats_t *dnssecsignstats =
19196
0
      dns_zone_getdnssecsignstats(zone);
19197
19198
0
    DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_NEEDNOTIFY);
19199
19200
0
    zone_needdump(zone, DNS_DUMP_DELAY);
19201
19202
0
    dns__zone_settimer(zone, timenow);
19203
19204
    /* Remove any signatures from removed keys.  */
19205
0
    ISC_LIST_FOREACH(rmkeys, key, link) {
19206
0
      result = zone_signwithkey(zone, dst_key_alg(key->key),
19207
0
              dst_key_id(key->key), true,
19208
0
              false);
19209
0
      if (result != ISC_R_SUCCESS) {
19210
0
        dnssec_log(zone, ISC_LOG_ERROR,
19211
0
             "zone_signwithkey failed: "
19212
0
             "%s",
19213
0
             isc_result_totext(result));
19214
0
      }
19215
19216
      /* Clear DNSSEC sign statistics. */
19217
0
      if (dnssecsignstats != NULL) {
19218
0
        dns_dnssecsignstats_clear(
19219
0
          dnssecsignstats, dst_key_id(key->key),
19220
0
          dst_key_alg(key->key));
19221
        /*
19222
         * Also clear the dnssec-sign
19223
         * statistics of the revoked key id.
19224
         */
19225
0
        dns_dnssecsignstats_clear(
19226
0
          dnssecsignstats, dst_key_rid(key->key),
19227
0
          dst_key_alg(key->key));
19228
0
      }
19229
0
    }
19230
19231
0
    if (fullsign) {
19232
      /*
19233
       * "rndc sign" was called, so we now sign the zone
19234
       * with all active keys, whether they're new or not.
19235
       */
19236
0
      ISC_LIST_FOREACH(dnskeys, key, link) {
19237
0
        if (key->force_sign || key->hint_sign) {
19238
0
          result = zone_signwithkey(
19239
0
            zone, dst_key_alg(key->key),
19240
0
            dst_key_id(key->key), false,
19241
0
            true);
19242
0
          if (result != ISC_R_SUCCESS) {
19243
0
            dnssec_log(zone, ISC_LOG_ERROR,
19244
0
                 "zone_signwithkey "
19245
0
                 "failed: "
19246
0
                 "%s",
19247
0
                 isc_result_totext(
19248
0
                   result));
19249
0
          }
19250
0
        }
19251
0
      }
19252
      /*
19253
       * ...and remove signatures for all inactive keys.
19254
       */
19255
0
      ISC_LIST_FOREACH(dnskeys, key, link) {
19256
0
        if (!key->force_sign && !key->hint_sign) {
19257
0
          result = zone_signwithkey(
19258
0
            zone, dst_key_alg(key->key),
19259
0
            dst_key_id(key->key), true,
19260
0
            false);
19261
0
          if (result != ISC_R_SUCCESS) {
19262
0
            dnssec_log(zone, ISC_LOG_ERROR,
19263
0
                 "zone_signwithkey "
19264
0
                 "failed: "
19265
0
                 "%s",
19266
0
                 isc_result_totext(
19267
0
                   result));
19268
0
          }
19269
0
        }
19270
0
      }
19271
19272
0
    } else if (newalg) {
19273
      /*
19274
       * We haven't been told to sign fully, but a new
19275
       * algorithm was added to the DNSKEY.  We sign
19276
       * the full zone, but only with newly active
19277
       * keys.
19278
       */
19279
0
      ISC_LIST_FOREACH(dnskeys, key, link) {
19280
0
        if (!key->first_sign) {
19281
0
          continue;
19282
0
        }
19283
19284
0
        result = zone_signwithkey(
19285
0
          zone, dst_key_alg(key->key),
19286
0
          dst_key_id(key->key), false, false);
19287
0
        if (result != ISC_R_SUCCESS) {
19288
0
          dnssec_log(zone, ISC_LOG_ERROR,
19289
0
               "zone_signwithkey failed: "
19290
0
               "%s",
19291
0
               isc_result_totext(result));
19292
0
        }
19293
0
      }
19294
0
    }
19295
19296
    /*
19297
     * Clear fullsign flag, if it was set, so we don't do
19298
     * another full signing next time.
19299
     */
19300
0
    DNS_ZONE_CLROPTION(zone, DNS_ZONEOPT_FULLSIGN);
19301
19302
    /*
19303
     * Cause the zone to add/delete NSEC3 chains for the
19304
     * deferred NSEC3PARAM changes.
19305
     */
19306
0
    ISC_LIST_FOREACH(zonediff.diff->tuples, tuple, link) {
19307
0
      unsigned char buf[DNS_NSEC3PARAM_BUFFERSIZE];
19308
0
      dns_rdata_t rdata = DNS_RDATA_INIT;
19309
0
      dns_rdata_nsec3param_t nsec3param;
19310
19311
0
      if (tuple->rdata.type != zone->privatetype ||
19312
0
          tuple->op != DNS_DIFFOP_ADD)
19313
0
      {
19314
0
        continue;
19315
0
      }
19316
19317
0
      if (!dns_nsec3param_fromprivate(&tuple->rdata, &rdata,
19318
0
              buf, sizeof(buf)))
19319
0
      {
19320
0
        continue;
19321
0
      }
19322
19323
0
      result = dns_rdata_tostruct(&rdata, &nsec3param);
19324
0
      RUNTIME_CHECK(result == ISC_R_SUCCESS);
19325
0
      if (nsec3param.flags == 0) {
19326
0
        continue;
19327
0
      }
19328
19329
0
      result = zone_addnsec3chain(zone, &nsec3param);
19330
0
      if (result != ISC_R_SUCCESS) {
19331
0
        dnssec_log(zone, ISC_LOG_ERROR,
19332
0
             "zone_addnsec3chain failed: %s",
19333
0
             isc_result_totext(result));
19334
0
      }
19335
0
    }
19336
19337
    /*
19338
     * Activate any NSEC3 chain updates that may have
19339
     * been scheduled before this rekey.
19340
     */
19341
0
    if (fullsign || newalg) {
19342
0
      resume_addnsec3chain(zone);
19343
0
    }
19344
19345
    /*
19346
     * Schedule the next resigning event
19347
     */
19348
0
    dns__zone_set_resigntime(zone);
19349
0
  }
19350
19351
0
  isc_time_settoepoch(&zone->refreshkeytime);
19352
19353
  /*
19354
   * If keymgr provided a next time, use the calculated next rekey time.
19355
   */
19356
0
  if (kasp != NULL) {
19357
0
    isc_time_t timenext;
19358
0
    uint32_t nexttime_seconds;
19359
19360
    /*
19361
     * Set the key refresh timer to the next scheduled key event
19362
     * or to 'dnssec-loadkeys-interval' seconds in the future
19363
     * if no next key event is scheduled (nexttime == 0).
19364
     */
19365
0
    if (nexttime > 0) {
19366
0
      nexttime_seconds = nexttime - now;
19367
0
    } else {
19368
0
      nexttime_seconds = zone->refreshkeyinterval;
19369
0
    }
19370
19371
0
    DNS_ZONE_TIME_ADD(&timenow, nexttime_seconds, &timenext);
19372
0
    zone->refreshkeytime = timenext;
19373
0
    dns__zone_settimer(zone, timenow);
19374
0
    isc_time_formattimestamp(&zone->refreshkeytime, timebuf, 80);
19375
19376
0
    dnssec_log(zone, ISC_LOG_DEBUG(3),
19377
0
         "next key event in %u seconds", nexttime_seconds);
19378
0
    dnssec_log(zone, ISC_LOG_INFO, "next key event: %s", timebuf);
19379
0
  } else {
19380
    /*
19381
     * If we're doing key maintenance, set the key refresh timer to
19382
     * the next scheduled key event or to 'dnssec-loadkeys-interval'
19383
     * seconds in the future, whichever is sooner.
19384
     */
19385
0
    isc_time_t timethen;
19386
0
    isc_stdtime_t then;
19387
19388
0
    DNS_ZONE_TIME_ADD(&timenow, zone->refreshkeyinterval,
19389
0
          &timethen);
19390
0
    zone->refreshkeytime = timethen;
19391
19392
0
    ISC_LIST_FOREACH(dnskeys, key, link) {
19393
0
      then = now;
19394
0
      result = next_keyevent(key->key, &then);
19395
0
      if (result != ISC_R_SUCCESS) {
19396
0
        continue;
19397
0
      }
19398
19399
0
      DNS_ZONE_TIME_ADD(&timenow, then - now, &timethen);
19400
0
      if (isc_time_compare(&timethen, &zone->refreshkeytime) <
19401
0
          0)
19402
0
      {
19403
0
        zone->refreshkeytime = timethen;
19404
0
      }
19405
0
    }
19406
19407
0
    dns__zone_settimer(zone, timenow);
19408
19409
0
    isc_time_formattimestamp(&zone->refreshkeytime, timebuf, 80);
19410
0
    dnssec_log(zone, ISC_LOG_INFO, "next key event: %s", timebuf);
19411
0
  }
19412
0
  UNLOCK_ZONE(zone);
19413
19414
  /*
19415
   * Remember which keys have been used.
19416
   */
19417
0
  if (!ISC_LIST_EMPTY(zone->keyring)) {
19418
0
    clear_keylist(&zone->keyring, zone->mctx);
19419
0
  }
19420
19421
0
  ISC_LIST_FOREACH(dnskeys, key, link) {
19422
0
    if (isc_log_wouldlog(ISC_LOG_DEBUG(3))) {
19423
      /* This debug log is used in the kasp system test */
19424
0
      char algbuf[DST_ALG_FORMATSIZE];
19425
0
      dst_algorithm_format(dst_key_alg(key->key), algbuf,
19426
0
               sizeof(algbuf));
19427
0
      dnssec_log(zone, ISC_LOG_DEBUG(3),
19428
0
           "zone_rekey done: key %hu/%s",
19429
0
           dst_key_id(key->key), algbuf);
19430
0
    }
19431
0
    ISC_LIST_UNLINK(dnskeys, key, link);
19432
0
    ISC_LIST_APPEND(zone->keyring, key, link);
19433
0
  }
19434
19435
0
  if (keymgr_done && isc_log_wouldlog(ISC_LOG_DEBUG(3))) {
19436
0
    char namebuf[DNS_NAME_FORMATSIZE];
19437
19438
0
    dns_name_format(&zone->origin, namebuf, sizeof(namebuf));
19439
0
    dnssec_log(zone, ISC_LOG_DEBUG(3), "keymgr: %s done", namebuf);
19440
0
  }
19441
19442
  /*
19443
   * If the CDS/CDNSKEY RRset has changed, send NOTIFY(CDS) to endpoints.
19444
   */
19445
0
  if (notifycds) {
19446
0
    zone_notifycds(zone);
19447
0
  }
19448
19449
0
  result = ISC_R_SUCCESS;
19450
19451
0
cleanup:
19452
0
  LOCK_ZONE(zone);
19453
0
  if (result != ISC_R_SUCCESS) {
19454
    /*
19455
     * Something went wrong; try again in ten minutes or
19456
     * after a key refresh interval, whichever is shorter.
19457
     */
19458
0
    int loglevel = ISC_LOG_DEBUG(3);
19459
0
    if (result != DNS_R_NOTLOADED) {
19460
0
      loglevel = ISC_LOG_ERROR;
19461
0
    }
19462
0
    dnssec_log(zone, loglevel,
19463
0
         "zone_rekey failure: %s (retry in %u seconds)",
19464
0
         isc_result_totext(result),
19465
0
         ISC_MIN(zone->refreshkeyinterval, 600));
19466
0
    isc_interval_set(&ival, ISC_MIN(zone->refreshkeyinterval, 600),
19467
0
         0);
19468
0
    isc_time_nowplusinterval(&zone->refreshkeytime, &ival);
19469
0
  }
19470
19471
  /*
19472
   * Clear forcekeymgr flag, if it was set, so we don't do
19473
   * another force next time.
19474
   */
19475
0
  DNS_ZONE_CLROPTION(zone, DNS_ZONEOPT_FORCEKEYMGR);
19476
19477
0
  UNLOCK_ZONE(zone);
19478
19479
0
  dns_diff_clear(&diff);
19480
0
  dns_diff_clear(&_sig_diff);
19481
19482
0
  clear_keylist(&dnskeys, mctx);
19483
0
  clear_keylist(&keys, mctx);
19484
0
  clear_keylist(&rmkeys, mctx);
19485
19486
0
  if (ver != NULL) {
19487
0
    dns_db_closeversion(db, &ver, false);
19488
0
  }
19489
0
  dns_rdataset_cleanup(&cdsset);
19490
0
  dns_rdataset_cleanup(&keyset);
19491
0
  dns_rdataset_cleanup(&keysigs);
19492
0
  dns_rdataset_cleanup(&soasigs);
19493
0
  dns_rdataset_cleanup(&cdnskeyset);
19494
0
  if (node != NULL) {
19495
0
    dns_db_detachnode(&node);
19496
0
  }
19497
0
  if (db != NULL) {
19498
0
    dns_db_detach(&db);
19499
0
  }
19500
19501
0
  INSIST(ver == NULL);
19502
0
}
19503
19504
void
19505
0
dns_zone_rekey(dns_zone_t *zone, bool fullsign, bool forcekeymgr) {
19506
0
  isc_time_t now;
19507
19508
0
  if (zone->type == dns_zone_primary && zone->loop != NULL) {
19509
0
    LOCK_ZONE(zone);
19510
19511
0
    if (fullsign) {
19512
0
      DNS_ZONE_SETOPTION(zone, DNS_ZONEOPT_FULLSIGN);
19513
0
    }
19514
0
    if (forcekeymgr) {
19515
0
      DNS_ZONE_SETOPTION(zone, DNS_ZONEOPT_FORCEKEYMGR);
19516
0
    }
19517
19518
0
    now = isc_time_now();
19519
0
    zone->refreshkeytime = now;
19520
0
    dns__zone_settimer(zone, now);
19521
19522
0
    UNLOCK_ZONE(zone);
19523
0
  }
19524
0
}
19525
19526
isc_result_t
19527
dns_zone_dnssecstatus(dns_zone_t *zone, dns_kasp_t *kasp,
19528
          dns_dnsseckeylist_t *keys, isc_stdtime_t now,
19529
0
          bool verbose, char *out, size_t out_len) {
19530
0
  isc_result_t result;
19531
0
  isc_buffer_t buf;
19532
0
  isc_time_t refreshkeytime;
19533
0
  isc_stdtime_t refresh;
19534
0
  char timestr[26];
19535
0
  char namebuf[DNS_NAME_FORMATSIZE];
19536
19537
0
  REQUIRE(DNS_ZONE_VALID(zone));
19538
0
  REQUIRE(out != NULL);
19539
19540
0
  dns_zone_nameonly(zone, namebuf, sizeof(namebuf));
19541
0
  isc_buffer_init(&buf, out, out_len);
19542
19543
0
  RETERR(isc_buffer_printf(
19544
0
    &buf, "DNSSEC status for zone '%s' using policy '%s':\n",
19545
0
    namebuf, dns_kasp_getname(kasp)));
19546
19547
0
  isc_stdtime_tostring(now, timestr, sizeof(timestr));
19548
0
  RETERR(isc_buffer_printf(&buf, "Current time:   %s\n", timestr));
19549
19550
0
  dns_zone_getrefreshkeytime(zone, &refreshkeytime);
19551
0
  refresh = isc_time_seconds(&refreshkeytime);
19552
0
  isc_stdtime_tostring(refresh, timestr, sizeof(timestr));
19553
0
  RETERR(isc_buffer_printf(&buf, "Next key event: %s\n", timestr));
19554
19555
0
  bool checkds = zone->checkdstype != dns_checkdstype_no;
19556
0
  LOCK(&kasp->lock);
19557
0
  result = dns_keymgr_status(kasp, keys, &buf, now, verbose, checkds);
19558
0
  UNLOCK(&kasp->lock);
19559
19560
0
  return result;
19561
0
}
19562
19563
isc_result_t
19564
dns_zone_nscheck(dns_zone_t *zone, dns_db_t *db, dns_dbversion_t *version,
19565
0
     unsigned int *errors) {
19566
0
  isc_result_t result;
19567
0
  dns_dbnode_t *node = NULL;
19568
19569
0
  REQUIRE(DNS_ZONE_VALID(zone));
19570
0
  REQUIRE(errors != NULL);
19571
19572
0
  RETERR(dns_db_getoriginnode(db, &node));
19573
0
  result = zone_count_ns_rr(zone, db, node, version, NULL, errors, false);
19574
0
  dns_db_detachnode(&node);
19575
0
  return result;
19576
0
}
19577
19578
isc_result_t
19579
0
dns_zone_cdscheck(dns_zone_t *zone, dns_db_t *db, dns_dbversion_t *version) {
19580
0
  isc_result_t result;
19581
0
  dns_dbnode_t *node = NULL;
19582
0
  dns_rdataset_t dnskey, cds, cdnskey;
19583
0
  unsigned char algorithms[DST_MAX_ALGS];
19584
0
  unsigned int i;
19585
0
  bool empty = false;
19586
19587
0
  enum { notexpected = 0, expected = 1, found = 2 };
19588
19589
0
  REQUIRE(DNS_ZONE_VALID(zone));
19590
19591
0
  RETERR(dns_db_getoriginnode(db, &node));
19592
19593
0
  dns_rdataset_init(&cds);
19594
0
  dns_rdataset_init(&dnskey);
19595
0
  dns_rdataset_init(&cdnskey);
19596
19597
0
  result = dns_db_findrdataset(db, node, version, dns_rdatatype_cds,
19598
0
             dns_rdatatype_none, 0, &cds, NULL);
19599
0
  if (result != ISC_R_NOTFOUND) {
19600
0
    CHECK(result);
19601
0
  }
19602
19603
0
  result = dns_db_findrdataset(db, node, version, dns_rdatatype_cdnskey,
19604
0
             dns_rdatatype_none, 0, &cdnskey, NULL);
19605
0
  if (result != ISC_R_NOTFOUND) {
19606
0
    CHECK(result);
19607
0
  }
19608
19609
0
  if (!dns_rdataset_isassociated(&cds) &&
19610
0
      !dns_rdataset_isassociated(&cdnskey))
19611
0
  {
19612
0
    result = ISC_R_SUCCESS;
19613
0
    goto cleanup;
19614
0
  }
19615
19616
0
  result = dns_db_findrdataset(db, node, version, dns_rdatatype_dnskey,
19617
0
             dns_rdatatype_none, 0, &dnskey, NULL);
19618
0
  if (result == ISC_R_NOTFOUND) {
19619
0
    empty = true;
19620
0
  } else {
19621
0
    CHECK(result);
19622
0
  }
19623
19624
  /*
19625
   * For each DNSSEC algorithm in the CDS RRset there must be
19626
   * a matching DNSKEY record with the exception of a CDS deletion
19627
   * record which must be by itself.
19628
   */
19629
0
  if (dns_rdataset_isassociated(&cds)) {
19630
0
    bool logged_digest_type[DNS_DSDIGEST_MAX + 1] = { 0 };
19631
0
    bool delete = false;
19632
0
    memset(algorithms, notexpected, sizeof(algorithms));
19633
0
    DNS_RDATASET_FOREACH(&cds) {
19634
0
      dns_rdata_t crdata = DNS_RDATA_INIT;
19635
0
      dns_rdata_cds_t structcds;
19636
19637
0
      dns_rdataset_current(&cds, &crdata);
19638
      /*
19639
       * CDS deletion record has this form "0 0 0 00" which
19640
       * is 5 zero octets.
19641
       */
19642
0
      if (crdata.length == 5U &&
19643
0
          memcmp(crdata.data,
19644
0
           (unsigned char[5]){ 0, 0, 0, 0, 0 }, 5) == 0)
19645
0
      {
19646
0
        delete = true;
19647
0
        continue;
19648
0
      }
19649
19650
0
      if (empty) {
19651
0
        CLEANUP(DNS_R_BADCDS);
19652
0
      }
19653
19654
0
      CHECK(dns_rdata_tostruct(&crdata, &structcds));
19655
19656
      /*
19657
       * Log deprecated CDS digest types.
19658
       */
19659
0
      switch (structcds.digest_type) {
19660
0
      case DNS_DSDIGEST_SHA1:
19661
0
      case DNS_DSDIGEST_GOST:
19662
0
        if (!logged_digest_type[structcds.digest_type])
19663
0
        {
19664
0
          char algbuf[DNS_DSDIGEST_FORMATSIZE];
19665
0
          dns_dsdigest_format(
19666
0
            structcds.digest_type, algbuf,
19667
0
            sizeof(algbuf));
19668
0
          dnssec_log(zone, ISC_LOG_WARNING,
19669
0
               "deprecated CDS digest type "
19670
0
               "%u (%s)",
19671
0
               structcds.digest_type,
19672
0
               algbuf);
19673
0
          logged_digest_type[structcds.digest_type] =
19674
0
            true;
19675
0
        }
19676
0
        break;
19677
0
      }
19678
19679
0
      if (structcds.algorithm != DNS_KEYALG_PRIVATEDNS &&
19680
0
          structcds.algorithm != DNS_KEYALG_PRIVATEOID)
19681
0
      {
19682
0
        if (algorithms[structcds.algorithm] == 0) {
19683
0
          algorithms[structcds.algorithm] =
19684
0
            expected;
19685
0
        }
19686
0
        DNS_RDATASET_FOREACH(&dnskey) {
19687
0
          dns_rdata_t rdata = DNS_RDATA_INIT;
19688
0
          dns_rdata_dnskey_t structdnskey;
19689
19690
0
          dns_rdataset_current(&dnskey, &rdata);
19691
0
          dns_rdata_tostruct(&rdata,
19692
0
                 &structdnskey);
19693
19694
0
          if (structdnskey.algorithm ==
19695
0
              structcds.algorithm)
19696
0
          {
19697
0
            algorithms[structcds.algorithm] =
19698
0
              found;
19699
0
          }
19700
0
        }
19701
0
      } else {
19702
0
        dns_rdata_t rdata = DNS_RDATA_INIT;
19703
0
        dns_rdata_dnskey_t structdnskey;
19704
0
        dst_algorithm_t dnskeyalg;
19705
19706
        /* Convert CDS to DS */
19707
0
        crdata.type = dns_rdatatype_ds;
19708
0
        result = dns_dnssec_matchdskey(&zone->origin,
19709
0
                     &crdata, &dnskey,
19710
0
                     &rdata);
19711
0
        if (result != ISC_R_SUCCESS) {
19712
0
          CLEANUP(DNS_R_BADCDS);
19713
0
        }
19714
0
        CHECK(dns_rdata_tostruct(&rdata,
19715
0
               &structdnskey));
19716
0
        dnskeyalg = dst_algorithm_fromdata(
19717
0
          structdnskey.algorithm,
19718
0
          structdnskey.data,
19719
0
          structdnskey.datalen);
19720
0
        algorithms[dnskeyalg] = found;
19721
0
      }
19722
0
    }
19723
0
    for (i = 0; i < sizeof(algorithms); i++) {
19724
0
      if (delete) {
19725
0
        if (algorithms[i] != notexpected) {
19726
0
          CLEANUP(DNS_R_BADCDS);
19727
0
        }
19728
0
      } else if (algorithms[i] == expected) {
19729
0
        CLEANUP(DNS_R_BADCDS);
19730
0
      }
19731
0
    }
19732
0
  }
19733
19734
  /*
19735
   * For each DNSSEC algorithm in the CDNSKEY RRset there must be
19736
   * a matching DNSKEY record with the exception of a CDNSKEY deletion
19737
   * record which must be by itself.
19738
   */
19739
0
  if (dns_rdataset_isassociated(&cdnskey)) {
19740
0
    bool delete = false;
19741
0
    memset(algorithms, notexpected, sizeof(algorithms));
19742
0
    DNS_RDATASET_FOREACH(&cdnskey) {
19743
0
      dns_rdata_t crdata = DNS_RDATA_INIT;
19744
0
      dns_rdata_cdnskey_t structcdnskey;
19745
0
      dst_algorithm_t cdnskeyalg;
19746
19747
0
      dns_rdataset_current(&cdnskey, &crdata);
19748
      /*
19749
       * CDNSKEY deletion record has this form
19750
       * "0 3 0 AA==" which is 2 zero octets, a 3,
19751
       * and 2 zero octets.
19752
       */
19753
0
      if (crdata.length == 5U &&
19754
0
          memcmp(crdata.data,
19755
0
           (unsigned char[5]){ 0, 0, 3, 0, 0 }, 5) == 0)
19756
0
      {
19757
0
        delete = true;
19758
0
        continue;
19759
0
      }
19760
19761
0
      if (empty) {
19762
0
        CLEANUP(DNS_R_BADCDNSKEY);
19763
0
      }
19764
19765
0
      CHECK(dns_rdata_tostruct(&crdata, &structcdnskey));
19766
0
      cdnskeyalg = dst_algorithm_fromdata(
19767
0
        structcdnskey.algorithm, structcdnskey.data,
19768
0
        structcdnskey.datalen);
19769
0
      if (algorithms[cdnskeyalg] == 0) {
19770
0
        algorithms[cdnskeyalg] = expected;
19771
0
      }
19772
0
      DNS_RDATASET_FOREACH(&dnskey) {
19773
0
        dns_rdata_t rdata = DNS_RDATA_INIT;
19774
0
        dns_rdata_dnskey_t structdnskey;
19775
0
        dst_algorithm_t dnskeyalg;
19776
19777
0
        dns_rdataset_current(&dnskey, &rdata);
19778
0
        CHECK(dns_rdata_tostruct(&rdata,
19779
0
               &structdnskey));
19780
0
        dnskeyalg = dst_algorithm_fromdata(
19781
0
          structdnskey.algorithm,
19782
0
          structdnskey.data,
19783
0
          structdnskey.datalen);
19784
19785
0
        if (dnskeyalg == cdnskeyalg) {
19786
0
          algorithms[cdnskeyalg] = found;
19787
0
        }
19788
0
      }
19789
0
    }
19790
0
    for (i = 0; i < sizeof(algorithms); i++) {
19791
0
      if (delete) {
19792
0
        if (algorithms[i] != notexpected) {
19793
0
          CLEANUP(DNS_R_BADCDNSKEY);
19794
0
        }
19795
0
      } else if (algorithms[i] == expected) {
19796
0
        CLEANUP(DNS_R_BADCDNSKEY);
19797
0
      }
19798
0
    }
19799
0
  }
19800
0
  result = ISC_R_SUCCESS;
19801
19802
0
cleanup:
19803
0
  dns_rdataset_cleanup(&cds);
19804
0
  dns_rdataset_cleanup(&dnskey);
19805
0
  dns_rdataset_cleanup(&cdnskey);
19806
0
  dns_db_detachnode(&node);
19807
0
  return result;
19808
0
}
19809
19810
isc_result_t
19811
0
dns_zone_dlzpostload(dns_zone_t *zone, dns_db_t *db) {
19812
0
  isc_time_t loadtime;
19813
0
  isc_result_t result;
19814
0
  dns_zone_t *secure = NULL;
19815
19816
0
  loadtime = isc_time_now();
19817
19818
  /*
19819
   * Lock hierarchy: zmgr, zone, secure.
19820
   */
19821
0
again:
19822
0
  LOCK_ZONE(zone);
19823
0
  INSIST(zone != zone->raw);
19824
0
  if (dns__zone_inline_raw(zone)) {
19825
0
    secure = zone->secure;
19826
0
    TRYLOCK_ZONE(result, secure);
19827
0
    if (result != ISC_R_SUCCESS) {
19828
0
      UNLOCK_ZONE(zone);
19829
0
      secure = NULL;
19830
0
      isc_thread_yield();
19831
0
      goto again;
19832
0
    }
19833
0
  }
19834
0
  result = zone_postload(zone, db, loadtime, ISC_R_SUCCESS);
19835
0
  if (result == ISC_R_SUCCESS && dns__zone_inline_secure(zone)) {
19836
0
    zone_schedule_inline_sync(zone, inline_sync_incremental);
19837
0
  }
19838
0
  if (secure != NULL) {
19839
0
    UNLOCK_ZONE(secure);
19840
0
  }
19841
0
  UNLOCK_ZONE(zone);
19842
0
  return result;
19843
0
}
19844
19845
/*
19846
 * Link a fresh raw zone to its signed counterpart on the same event loop.
19847
 */
19848
isc_result_t
19849
0
dns_zone_link(dns_zone_t *zone, dns_zone_t *raw) {
19850
0
  REQUIRE(DNS_ZONE_VALID(zone));
19851
0
  REQUIRE(zone->loop != NULL);
19852
0
  REQUIRE(zone->raw == NULL);
19853
19854
0
  REQUIRE(DNS_ZONE_VALID(raw));
19855
0
  REQUIRE(raw->secure == NULL);
19856
19857
0
  REQUIRE(zone != raw);
19858
19859
  /*
19860
   * Lock hierarchy: zone, raw. No global registration is needed.
19861
   */
19862
0
  LOCK_ZONE(zone);
19863
0
  LOCK_ZONE(raw);
19864
19865
0
  REQUIRE(raw->timer == NULL);
19866
0
  if (raw->loop != NULL) {
19867
0
    isc_loop_detach(&raw->loop);
19868
0
  }
19869
0
  raw->tid = zone->tid;
19870
0
  isc_loop_attach(zone->loop, &raw->loop);
19871
19872
  /* dns_zone_attach(raw, &zone->raw); */
19873
0
  isc_refcount_increment(&raw->references);
19874
0
  zone->raw = raw;
19875
19876
  /* dns_zone_iattach(zone, &raw->secure); */
19877
0
  zone_iattach(zone, &raw->secure);
19878
19879
0
  UNLOCK_ZONE(raw);
19880
0
  UNLOCK_ZONE(zone);
19881
0
  return ISC_R_SUCCESS;
19882
0
}
19883
19884
void
19885
0
dns_zone_getraw(dns_zone_t *zone, dns_zone_t **raw) {
19886
0
  REQUIRE(DNS_ZONE_VALID(zone));
19887
0
  REQUIRE(raw != NULL && *raw == NULL);
19888
19889
0
  LOCK(&zone->lock);
19890
0
  INSIST(zone != zone->raw);
19891
0
  if (zone->raw != NULL) {
19892
0
    dns_zone_attach(zone->raw, raw);
19893
0
  }
19894
0
  UNLOCK(&zone->lock);
19895
0
}
19896
19897
bool
19898
0
dns_zone_israw(dns_zone_t *zone) {
19899
0
  bool israw;
19900
0
  REQUIRE(DNS_ZONE_VALID(zone));
19901
0
  LOCK(&zone->lock);
19902
0
  israw = zone->secure != NULL;
19903
0
  UNLOCK(&zone->lock);
19904
0
  return israw;
19905
0
}
19906
19907
bool
19908
0
dns_zone_issecure(dns_zone_t *zone) {
19909
0
  bool issecure;
19910
0
  REQUIRE(DNS_ZONE_VALID(zone));
19911
0
  LOCK(&zone->lock);
19912
0
  issecure = zone->raw != NULL;
19913
0
  UNLOCK(&zone->lock);
19914
0
  return issecure;
19915
0
}
19916
19917
0
#define PENDINGFLAGS (DNS_NSEC3FLAG_CREATE | DNS_NSEC3FLAG_INITIAL)
19918
19919
static void
19920
zone_process_keydone(dns_zone_t *zone,
19921
0
         const zone_maintenance_request_t *request) {
19922
0
  bool commit = false;
19923
0
  isc_result_t result;
19924
0
  dns_dbversion_t *oldver = NULL, *newver = NULL;
19925
0
  dns_db_t *db = NULL;
19926
0
  dns_dbnode_t *node = NULL;
19927
0
  dns_rdataset_t rdataset;
19928
0
  dns_diff_t diff;
19929
0
  dns_update_log_t log = { update_log_cb, NULL };
19930
0
  bool clear_pending = false;
19931
19932
0
  INSIST(DNS_ZONE_VALID(zone));
19933
19934
0
  ENTER;
19935
19936
0
  dns_rdataset_init(&rdataset);
19937
0
  dns_diff_init(zone->mctx, &diff);
19938
19939
0
  ZONEDB_LOCK(&zone->dblock, isc_rwlocktype_read);
19940
0
  if (zone->db != NULL) {
19941
0
    dns_db_attach(zone->db, &db);
19942
0
  }
19943
0
  ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_read);
19944
0
  if (db == NULL) {
19945
0
    goto cleanup;
19946
0
  }
19947
19948
0
  dns_db_currentversion(db, &oldver);
19949
0
  result = dns_db_newversion(db, &newver);
19950
0
  if (result != ISC_R_SUCCESS) {
19951
0
    dnssec_log(zone, ISC_LOG_ERROR,
19952
0
         "keydone:dns_db_newversion -> %s",
19953
0
         isc_result_totext(result));
19954
0
    goto cleanup;
19955
0
  }
19956
19957
0
  CHECK(dns_db_getoriginnode(db, &node));
19958
19959
0
  result = dns_db_findrdataset(db, node, newver, zone->privatetype,
19960
0
             dns_rdatatype_none, 0, &rdataset, NULL);
19961
0
  if (result != ISC_R_SUCCESS) {
19962
0
    INSIST(!dns_rdataset_isassociated(&rdataset));
19963
0
    goto cleanup;
19964
0
  }
19965
19966
0
  DNS_RDATASET_FOREACH(&rdataset) {
19967
0
    dns_rdata_t rdata = DNS_RDATA_INIT;
19968
0
    bool found = false;
19969
19970
0
    dns_rdataset_current(&rdataset, &rdata);
19971
19972
0
    if (request->u.keydone.all) {
19973
      /* Old (5) and new (7) forms */
19974
0
      if ((rdata.length == OLD_SIGNING_RECORD_SIZE ||
19975
0
           rdata.length == SIGNING_RECORD_SIZE) &&
19976
0
          rdata.data[0] != 0 && rdata.data[3] == 0 &&
19977
0
          rdata.data[4] == 1)
19978
0
      {
19979
0
        found = true;
19980
0
      } else if (rdata.data[0] == 0 &&
19981
0
           (rdata.data[2] & PENDINGFLAGS) != 0)
19982
0
      {
19983
0
        found = true;
19984
0
        clear_pending = true;
19985
0
      }
19986
0
    } else if (rdata.length == OLD_SIGNING_RECORD_SIZE &&
19987
0
         memcmp(rdata.data, request->u.keydone.data,
19988
0
          OLD_SIGNING_RECORD_SIZE) == 0)
19989
0
    {
19990
0
      found = true;
19991
0
    } else if (rdata.length == SIGNING_RECORD_SIZE &&
19992
0
         memcmp(rdata.data, request->u.keydone.data,
19993
0
          SIGNING_RECORD_SIZE) == 0)
19994
0
    {
19995
0
      found = true;
19996
0
    }
19997
19998
0
    if (found) {
19999
0
      CHECK(update_one_rr(db, newver, &diff, DNS_DIFFOP_DEL,
20000
0
              &zone->origin, rdataset.ttl,
20001
0
              &rdata));
20002
0
    }
20003
0
  }
20004
20005
0
  if (!ISC_LIST_EMPTY(diff.tuples)) {
20006
    /* Write changes to journal file. */
20007
0
    CHECK(update_soa_serial(zone, db, newver, &diff, zone->mctx,
20008
0
          zone->updatemethod));
20009
20010
0
    result = dns_update_signatures(&log, zone, db, oldver, newver,
20011
0
                 &diff,
20012
0
                 zone->sigvalidityinterval);
20013
0
    if (!clear_pending) {
20014
0
      CHECK(result);
20015
0
    }
20016
20017
0
    CHECK(zone_journal(zone, &diff, NULL, "keydone"));
20018
0
    commit = true;
20019
20020
0
    LOCK_ZONE(zone);
20021
0
    DNS_ZONE_SETFLAG(zone,
20022
0
         DNS_ZONEFLG_LOADED | DNS_ZONEFLG_NEEDNOTIFY);
20023
0
    zone_needdump(zone, 30);
20024
0
    UNLOCK_ZONE(zone);
20025
0
  }
20026
20027
0
cleanup:
20028
0
  dns_rdataset_cleanup(&rdataset);
20029
0
  if (db != NULL) {
20030
0
    if (node != NULL) {
20031
0
      dns_db_detachnode(&node);
20032
0
    }
20033
0
    if (oldver != NULL) {
20034
0
      dns_db_closeversion(db, &oldver, false);
20035
0
    }
20036
0
    if (newver != NULL) {
20037
0
      dns_db_closeversion(db, &newver, commit);
20038
0
    }
20039
0
    dns_db_detach(&db);
20040
0
  }
20041
0
  dns_diff_clear(&diff);
20042
20043
0
  INSIST(oldver == NULL);
20044
0
  INSIST(newver == NULL);
20045
0
}
20046
20047
isc_result_t
20048
0
dns_zone_keydone(dns_zone_t *zone, const char *keystr) {
20049
0
  isc_result_t result = ISC_R_SUCCESS;
20050
0
  zone_maintenance_request_t *request = NULL;
20051
0
  isc_buffer_t b;
20052
0
  bool all = false;
20053
20054
0
  REQUIRE(DNS_ZONE_VALID(zone));
20055
20056
0
  LOCK_ZONE(zone);
20057
20058
0
  all = strcasecmp(keystr, "all") == 0;
20059
0
  request = isc_mem_get(zone->mctx, sizeof(*request));
20060
0
  *request = (zone_maintenance_request_t){
20061
0
    .link = ISC_LINK_INITIALIZER,
20062
0
    .type = zone_maintenance_request_keydone,
20063
0
    .u.keydone = {
20064
0
      .all = all,
20065
0
    },
20066
0
  };
20067
20068
0
  if (!all) {
20069
0
    isc_textregion_t r;
20070
0
    const char *algstr = NULL;
20071
0
    dns_keytag_t keyid;
20072
0
    dst_algorithm_t alg;
20073
0
    size_t n;
20074
20075
0
    n = sscanf(keystr, "%hu/", &keyid);
20076
0
    if (n == 0U) {
20077
0
      CLEANUP(ISC_R_FAILURE);
20078
0
    }
20079
20080
0
    algstr = strchr(keystr, '/');
20081
0
    if (algstr != NULL) {
20082
0
      algstr++;
20083
0
    } else {
20084
0
      CLEANUP(ISC_R_FAILURE);
20085
0
    }
20086
20087
0
    n = sscanf(algstr, "%u", &alg);
20088
0
    if (n == 0U) {
20089
0
      r.base = UNCONST(algstr);
20090
0
      r.length = strlen(algstr);
20091
0
      CHECK(dst_algorithm_fromtext(&alg, &r));
20092
0
    }
20093
20094
    /* construct a private-type rdata */
20095
0
    isc_buffer_init(&b, request->u.keydone.data,
20096
0
        sizeof(request->u.keydone.data));
20097
0
    isc_buffer_putuint8(&b, dst_algorithm_tosecalg(alg));
20098
0
    isc_buffer_putuint16(&b, keyid);
20099
0
    isc_buffer_putuint8(&b, 0);
20100
0
    isc_buffer_putuint8(&b, 1);
20101
0
    isc_buffer_putuint16(&b, alg);
20102
0
  }
20103
20104
0
  ISC_LIST_APPEND(zone->maintenance_queue, request, link);
20105
0
  if (zone->loop != NULL && zone_maintenance_request_pending(zone)) {
20106
0
    isc_time_t now = isc_time_now();
20107
0
    dns__zone_settimer(zone, now);
20108
0
  }
20109
0
  request = NULL;
20110
20111
0
cleanup:
20112
0
  if (request != NULL) {
20113
0
    isc_mem_put(zone->mctx, request, sizeof(*request));
20114
0
  }
20115
0
  UNLOCK_ZONE(zone);
20116
0
  return result;
20117
0
}
20118
20119
static void
20120
salt2text(unsigned char *salt, uint8_t saltlen, unsigned char *text,
20121
0
    unsigned int textlen) {
20122
0
  isc_region_t r;
20123
0
  isc_buffer_t buf;
20124
0
  isc_result_t result;
20125
20126
0
  r.base = salt;
20127
0
  r.length = (unsigned int)saltlen;
20128
20129
0
  isc_buffer_init(&buf, text, textlen);
20130
0
  result = isc_hex_totext(&r, 2, "", &buf);
20131
0
  if (result == ISC_R_SUCCESS) {
20132
0
    text[saltlen * 2] = 0;
20133
0
  } else {
20134
0
    text[0] = 0;
20135
0
  }
20136
0
}
20137
20138
/*
20139
 * Check whether NSEC3 chain addition or removal specified by the private-type
20140
 * record passed with the event was already queued (or even fully performed).
20141
 * If not, modify the relevant private-type records at the zone apex and call
20142
 * resume_addnsec3chain().
20143
 */
20144
static void
20145
0
rss_post(dns_zone_t *zone, nsec3param_t *np) {
20146
0
  bool commit = false;
20147
0
  isc_result_t result;
20148
0
  dns_dbversion_t *oldver = NULL, *newver = NULL;
20149
0
  dns_db_t *db = NULL;
20150
0
  dns_dbnode_t *node = NULL;
20151
0
  dns_rdataset_t prdataset, nrdataset;
20152
0
  dns_diff_t diff;
20153
0
  dns_update_log_t log = { update_log_cb, NULL };
20154
0
  bool nseconly;
20155
0
  bool exists = false;
20156
20157
0
  ENTER;
20158
20159
0
  dns_rdataset_init(&prdataset);
20160
0
  dns_rdataset_init(&nrdataset);
20161
0
  dns_diff_init(zone->mctx, &diff);
20162
20163
0
  ZONEDB_LOCK(&zone->dblock, isc_rwlocktype_read);
20164
0
  if (zone->db != NULL) {
20165
0
    dns_db_attach(zone->db, &db);
20166
0
  }
20167
0
  ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_read);
20168
0
  if (db == NULL) {
20169
0
    goto cleanup;
20170
0
  }
20171
20172
0
  dns_db_currentversion(db, &oldver);
20173
0
  result = dns_db_newversion(db, &newver);
20174
0
  if (result != ISC_R_SUCCESS) {
20175
0
    dnssec_log(zone, ISC_LOG_ERROR,
20176
0
         "setnsec3param:dns_db_newversion -> %s",
20177
0
         isc_result_totext(result));
20178
0
    goto cleanup;
20179
0
  }
20180
20181
0
  CHECK(dns_db_getoriginnode(db, &node));
20182
20183
  /*
20184
   * Do we need to look up the NSEC3 parameters?
20185
   */
20186
0
  if (np->lookup) {
20187
0
    dns_rdata_nsec3param_t param;
20188
0
    dns_rdata_t nrdata = DNS_RDATA_INIT;
20189
0
    dns_rdata_t prdata = DNS_RDATA_INIT;
20190
0
    unsigned char nbuf[DNS_NSEC3PARAM_BUFFERSIZE];
20191
0
    unsigned char saltbuf[255];
20192
0
    isc_buffer_t b;
20193
20194
0
    param.salt = (isc_region_t){ .base = NULL };
20195
0
    result = dns__zone_lookup_nsec3param(zone, &np->rdata, &param,
20196
0
                 saltbuf, np->resalt);
20197
0
    if (result == ISC_R_SUCCESS) {
20198
      /*
20199
       * Success because the NSEC3PARAM already exists, but
20200
       * function returns void, so goto cleanup.
20201
       */
20202
0
      goto cleanup;
20203
0
    }
20204
0
    if (result != DNS_R_NSEC3RESALT && result != ISC_R_NOTFOUND) {
20205
0
      dnssec_log(zone, ISC_LOG_DEBUG(3),
20206
0
           "setnsec3param:lookup nsec3param -> %s",
20207
0
           isc_result_totext(result));
20208
0
      goto cleanup;
20209
0
    }
20210
20211
0
    INSIST(param.salt.base != NULL);
20212
20213
    /* Update NSEC3 parameters. */
20214
0
    np->rdata.hash = param.hash;
20215
0
    np->rdata.flags = param.flags;
20216
0
    np->rdata.iterations = param.iterations;
20217
0
    np->rdata.salt.length = param.salt.length;
20218
0
    np->rdata.salt = param.salt;
20219
20220
0
    isc_buffer_init(&b, nbuf, sizeof(nbuf));
20221
0
    CHECK(dns_rdata_fromstruct(&nrdata, zone->rdclass,
20222
0
             dns_rdatatype_nsec3param, &np->rdata,
20223
0
             &b));
20224
0
    dns_nsec3param_toprivate(&nrdata, &prdata, zone->privatetype,
20225
0
           np->data, sizeof(np->data));
20226
0
    np->length = prdata.length;
20227
0
    np->nsec = false;
20228
0
  }
20229
20230
  /*
20231
   * Does a private-type record already exist for this chain?
20232
   */
20233
0
  result = dns_db_findrdataset(db, node, newver, zone->privatetype,
20234
0
             dns_rdatatype_none, 0, &prdataset, NULL);
20235
0
  if (result == ISC_R_SUCCESS) {
20236
0
    DNS_RDATASET_FOREACH(&prdataset) {
20237
0
      dns_rdata_t rdata = DNS_RDATA_INIT;
20238
0
      dns_rdataset_current(&prdataset, &rdata);
20239
20240
0
      if (np->length == rdata.length &&
20241
0
          memcmp(rdata.data, np->data, np->length) == 0)
20242
0
      {
20243
0
        exists = true;
20244
0
        break;
20245
0
      }
20246
0
    }
20247
0
  } else if (result != ISC_R_NOTFOUND) {
20248
0
    INSIST(!dns_rdataset_isassociated(&prdataset));
20249
0
    goto cleanup;
20250
0
  }
20251
20252
  /*
20253
   * Does the chain already exist?
20254
   */
20255
0
  result = dns_db_findrdataset(db, node, newver, dns_rdatatype_nsec3param,
20256
0
             dns_rdatatype_none, 0, &nrdataset, NULL);
20257
0
  if (result == ISC_R_SUCCESS) {
20258
0
    DNS_RDATASET_FOREACH(&nrdataset) {
20259
0
      dns_rdata_t rdata = DNS_RDATA_INIT;
20260
0
      dns_rdataset_current(&nrdataset, &rdata);
20261
20262
0
      if (np->length == ((unsigned int)rdata.length + 1) &&
20263
0
          memcmp(rdata.data, np->data + 1, np->length - 1) ==
20264
0
            0)
20265
0
      {
20266
0
        exists = true;
20267
0
        break;
20268
0
      }
20269
0
    }
20270
0
  } else if (result != ISC_R_NOTFOUND) {
20271
0
    INSIST(!dns_rdataset_isassociated(&nrdataset));
20272
0
    goto cleanup;
20273
0
  }
20274
20275
  /*
20276
   * We need to remove any existing NSEC3 chains if the supplied NSEC3
20277
   * parameters are supposed to replace the current ones or if we are
20278
   * switching to NSEC.
20279
   */
20280
0
  if (!exists && np->replace && (np->length != 0 || np->nsec)) {
20281
0
    CHECK(dns_nsec3param_deletechains(db, newver, zone, !np->nsec,
20282
0
              &diff));
20283
0
  }
20284
20285
0
  if (!exists && np->length != 0) {
20286
    /*
20287
     * We're creating an NSEC3 chain.  Add the private-type record
20288
     * passed in the request parameters to the zone apex.
20289
     *
20290
     * If the zone is not currently capable of supporting an NSEC3
20291
     * chain (due to the DNSKEY RRset at the zone apex not existing
20292
     * or containing at least one key using an NSEC-only
20293
     * algorithm), add the INITIAL flag, so these parameters can be
20294
     * used later when NSEC3 becomes available.
20295
     */
20296
0
    dns_rdata_t rdata = DNS_RDATA_INIT;
20297
20298
0
    np->data[2] |= DNS_NSEC3FLAG_CREATE;
20299
0
    result = dns_nsec_nseconly(db, newver, NULL, &nseconly);
20300
0
    if (result == ISC_R_NOTFOUND || nseconly) {
20301
0
      np->data[2] |= DNS_NSEC3FLAG_INITIAL;
20302
0
    }
20303
20304
0
    rdata.length = np->length;
20305
0
    rdata.data = np->data;
20306
0
    rdata.type = zone->privatetype;
20307
0
    rdata.rdclass = zone->rdclass;
20308
0
    CHECK(update_one_rr(db, newver, &diff, DNS_DIFFOP_ADD,
20309
0
            &zone->origin, 0, &rdata));
20310
0
  }
20311
20312
  /*
20313
   * If we changed anything in the zone, write changes to journal file
20314
   * and set commit to true so that resume_addnsec3chain() will be
20315
   * called below in order to kick off adding/removing relevant NSEC3
20316
   * records.
20317
   */
20318
0
  if (!ISC_LIST_EMPTY(diff.tuples)) {
20319
0
    CHECK(update_soa_serial(zone, db, newver, &diff, zone->mctx,
20320
0
          zone->updatemethod));
20321
0
    result = dns_update_signatures(&log, zone, db, oldver, newver,
20322
0
                 &diff,
20323
0
                 zone->sigvalidityinterval);
20324
0
    if (result != ISC_R_NOTFOUND) {
20325
0
      CHECK(result);
20326
0
    }
20327
0
    CHECK(zone_journal(zone, &diff, NULL, "setnsec3param"));
20328
0
    commit = true;
20329
0
  }
20330
20331
0
cleanup:
20332
0
  dns_rdataset_cleanup(&prdataset);
20333
0
  dns_rdataset_cleanup(&nrdataset);
20334
0
  if (node != NULL) {
20335
0
    dns_db_detachnode(&node);
20336
0
  }
20337
0
  if (oldver != NULL) {
20338
0
    dns_db_closeversion(db, &oldver, false);
20339
0
  }
20340
0
  if (newver != NULL) {
20341
0
    dns_db_closeversion(db, &newver, commit);
20342
0
  }
20343
0
  if (db != NULL) {
20344
0
    dns_db_detach(&db);
20345
0
  }
20346
0
  if (commit) {
20347
0
    LOCK_ZONE(zone);
20348
0
    DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_LOADED);
20349
0
    zone_needdump(zone, 30);
20350
0
    resume_addnsec3chain(zone);
20351
0
    UNLOCK_ZONE(zone);
20352
0
  }
20353
0
  dns_diff_clear(&diff);
20354
20355
0
  INSIST(oldver == NULL);
20356
0
  INSIST(newver == NULL);
20357
0
}
20358
20359
/*
20360
 * Check if zone has NSEC3PARAM (and thus a chain) with the right parameters.
20361
 *
20362
 * If 'salt' is NULL, a match is found if the salt has the requested length,
20363
 * otherwise the NSEC3 salt must match the requested salt value too.
20364
 *
20365
 * Returns  ISC_R_SUCCESS, if a match is found, or an error if no match is
20366
 * found, or if the db lookup failed.
20367
 */
20368
isc_result_t
20369
dns__zone_lookup_nsec3param(dns_zone_t *zone, dns_rdata_nsec3param_t *lookup,
20370
          dns_rdata_nsec3param_t *param,
20371
0
          unsigned char saltbuf[255], bool resalt) {
20372
0
  isc_result_t result = ISC_R_UNEXPECTED;
20373
0
  dns_dbnode_t *node = NULL;
20374
0
  dns_db_t *db = NULL;
20375
0
  dns_dbversion_t *version = NULL;
20376
0
  dns_rdataset_t rdataset;
20377
0
  dns_rdata_nsec3param_t nsec3param;
20378
20379
0
  REQUIRE(DNS_ZONE_VALID(zone));
20380
20381
0
  dns_rdataset_init(&rdataset);
20382
20383
0
  ZONEDB_LOCK(&zone->dblock, isc_rwlocktype_read);
20384
0
  if (zone->db != NULL) {
20385
0
    dns_db_attach(zone->db, &db);
20386
0
  }
20387
0
  ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_read);
20388
0
  if (db == NULL) {
20389
0
    result = ISC_R_FAILURE;
20390
0
    goto setparam;
20391
0
  }
20392
20393
0
  result = dns_db_findnode(db, &zone->origin, false, &node);
20394
0
  if (result != ISC_R_SUCCESS) {
20395
0
    dns_zone_log(zone, ISC_LOG_ERROR,
20396
0
           "dns__zone_lookup_nsec3param:"
20397
0
           "dns_db_findnode -> %s",
20398
0
           isc_result_totext(result));
20399
0
    result = ISC_R_FAILURE;
20400
0
    goto setparam;
20401
0
  }
20402
0
  dns_db_currentversion(db, &version);
20403
20404
0
  result = dns_db_findrdataset(db, node, version,
20405
0
             dns_rdatatype_nsec3param,
20406
0
             dns_rdatatype_none, 0, &rdataset, NULL);
20407
0
  if (result != ISC_R_SUCCESS) {
20408
0
    INSIST(!dns_rdataset_isassociated(&rdataset));
20409
0
    if (result != ISC_R_NOTFOUND) {
20410
0
      dns_zone_log(zone, ISC_LOG_ERROR,
20411
0
             "dns__zone_lookup_nsec3param:"
20412
0
             "dns_db_findrdataset -> %s",
20413
0
             isc_result_totext(result));
20414
0
    }
20415
0
    goto setparam;
20416
0
  }
20417
20418
0
  result = ISC_R_NOTFOUND;
20419
0
  DNS_RDATASET_FOREACH(&rdataset) {
20420
0
    dns_rdata_t rdata = DNS_RDATA_INIT;
20421
0
    dns_rdataset_current(&rdataset, &rdata);
20422
0
    dns_rdata_tostruct(&rdata, &nsec3param);
20423
20424
    /* Check parameters. */
20425
0
    if (nsec3param.hash != lookup->hash) {
20426
0
      continue;
20427
0
    }
20428
0
    if (nsec3param.iterations != lookup->iterations) {
20429
0
      continue;
20430
0
    }
20431
0
    if (nsec3param.salt.length != lookup->salt.length) {
20432
0
      continue;
20433
0
    }
20434
0
    if (lookup->salt.base != NULL) {
20435
0
      if (memcmp(nsec3param.salt.base, lookup->salt.base,
20436
0
           lookup->salt.length) != 0)
20437
0
      {
20438
0
        continue;
20439
0
      }
20440
0
    }
20441
    /* Found a match. */
20442
0
    result = ISC_R_SUCCESS;
20443
0
    param->hash = nsec3param.hash;
20444
0
    param->flags = nsec3param.flags;
20445
0
    param->iterations = nsec3param.iterations;
20446
0
    param->salt = nsec3param.salt;
20447
0
    break;
20448
0
  }
20449
20450
0
setparam:
20451
0
  if (result != ISC_R_SUCCESS) {
20452
    /* Found no match. */
20453
0
    param->hash = lookup->hash;
20454
0
    param->flags = lookup->flags;
20455
0
    param->iterations = lookup->iterations;
20456
0
    param->salt = lookup->salt;
20457
0
  }
20458
20459
0
  if (result != ISC_R_NOTFOUND) {
20460
0
    CHECK(result);
20461
0
  }
20462
20463
0
  if (param->salt.length == 0) {
20464
0
    param->salt.base = (unsigned char *)"-";
20465
0
  } else if (resalt || param->salt.base == NULL) {
20466
0
    unsigned char *newsalt;
20467
0
    unsigned char salttext[255 * 2 + 1];
20468
0
    do {
20469
      /* Generate a new salt. */
20470
0
      result = dns_nsec3_generate_salt(saltbuf,
20471
0
               param->salt.length);
20472
0
      if (result != ISC_R_SUCCESS) {
20473
0
        break;
20474
0
      }
20475
0
      newsalt = saltbuf;
20476
0
      salt2text(newsalt, param->salt.length, salttext,
20477
0
          sizeof(salttext));
20478
0
      dnssec_log(zone, ISC_LOG_INFO, "generated salt: %s",
20479
0
           salttext);
20480
      /* Check for salt conflict. */
20481
0
      if (param->salt.base != NULL &&
20482
0
          memcmp(newsalt, param->salt.base,
20483
0
           param->salt.length) == 0)
20484
0
      {
20485
0
        result = ISC_R_SUCCESS;
20486
0
      } else {
20487
0
        param->salt.base = newsalt;
20488
0
        result = DNS_R_NSEC3RESALT;
20489
0
      }
20490
0
    } while (result == ISC_R_SUCCESS);
20491
20492
0
    INSIST(result != ISC_R_SUCCESS);
20493
0
  }
20494
20495
0
cleanup:
20496
0
  dns_rdataset_cleanup(&rdataset);
20497
0
  if (node != NULL) {
20498
0
    dns_db_detachnode(&node);
20499
0
  }
20500
0
  if (version != NULL) {
20501
0
    dns_db_closeversion(db, &version, false);
20502
0
  }
20503
0
  if (db != NULL) {
20504
0
    dns_db_detach(&db);
20505
0
  }
20506
20507
0
  return result;
20508
0
}
20509
20510
/*
20511
 * Called when an "rndc signing -nsec3param ..." command is received, or the
20512
 * 'dnssec-policy' has changed.
20513
 *
20514
 * Allocate and prepare an nsec3param_t structure which holds information about
20515
 * the NSEC3 changes requested for the zone:
20516
 *
20517
 *   - if NSEC3 is to be disabled ("-nsec3param none"), only set the "nsec"
20518
 *     field of the structure to true and the "replace" field to the value
20519
 *     of the "replace" argument, leaving other fields initialized to zeros, to
20520
 *     signal that the zone should be signed using NSEC instead of NSEC3,
20521
 *
20522
 *   - otherwise, prepare NSEC3PARAM RDATA that will eventually be inserted at
20523
 *     the zone apex, convert it to a private-type record and store the latter
20524
 *     in the "data" field of the nsec3param_t structure.
20525
 *
20526
 * Once the nsec3param_t structure is prepared, queue it for zone maintenance.
20527
 * The request is processed once the zone DB is loaded and no inline-signing
20528
 * transaction is active.
20529
 */
20530
isc_result_t
20531
dns_zone_setnsec3param(dns_zone_t *zone, uint8_t hash, uint8_t flags,
20532
           uint16_t iter, isc_region_t *salt, bool replace,
20533
0
           bool resalt) {
20534
0
  isc_result_t result = ISC_R_SUCCESS;
20535
0
  dns_rdata_nsec3param_t param, lookup;
20536
0
  dns_rdata_t nrdata = DNS_RDATA_INIT;
20537
0
  dns_rdata_t prdata = DNS_RDATA_INIT;
20538
0
  unsigned char nbuf[DNS_NSEC3PARAM_BUFFERSIZE];
20539
0
  unsigned char saltbuf[255];
20540
0
  zone_maintenance_request_t *request = NULL;
20541
0
  nsec3param_t *np = NULL;
20542
0
  isc_buffer_t b;
20543
0
  bool do_lookup = false;
20544
20545
0
  REQUIRE(DNS_ZONE_VALID(zone));
20546
20547
0
  LOCK_ZONE(zone);
20548
20549
  /*
20550
   * First check if the requested NSEC3 parameters are already
20551
   * set, if so, no need to set again.
20552
   */
20553
0
  if (hash != 0) {
20554
0
    lookup.hash = hash;
20555
0
    lookup.flags = flags;
20556
0
    lookup.iterations = iter;
20557
0
    lookup.salt = *salt;
20558
0
    param.salt = (isc_region_t){ .base = NULL };
20559
0
    result = dns__zone_lookup_nsec3param(zone, &lookup, &param,
20560
0
                 saltbuf, resalt);
20561
0
    if (result == ISC_R_SUCCESS) {
20562
0
      UNLOCK_ZONE(zone);
20563
0
      return ISC_R_SUCCESS;
20564
0
    }
20565
    /*
20566
     * Schedule lookup if lookup above failed (may happen if
20567
     * zone db is NULL for example).
20568
     */
20569
0
    do_lookup = (param.salt.base == NULL) ? true : false;
20570
0
  }
20571
20572
0
  request = isc_mem_get(zone->mctx, sizeof(*request));
20573
0
  *request = (zone_maintenance_request_t){
20574
0
    .link = ISC_LINK_INITIALIZER,
20575
0
    .type = zone_maintenance_request_setnsec3param,
20576
0
    .u.nsec3param = {
20577
0
      .replace = replace,
20578
0
      .resalt = resalt,
20579
0
      .lookup = do_lookup,
20580
0
    },
20581
0
  };
20582
20583
0
  np = &request->u.nsec3param;
20584
0
  if (hash == 0) {
20585
0
    np->nsec = true;
20586
0
    dnssec_log(zone, ISC_LOG_DEBUG(3), "setnsec3param:nsec");
20587
0
  } else {
20588
0
    param.common.rdclass = zone->rdclass;
20589
0
    param.common.rdtype = dns_rdatatype_nsec3param;
20590
    /*
20591
     * nsec3 specific param set in
20592
     * dns__zone_lookup_nsec3param()
20593
     */
20594
0
    isc_buffer_init(&b, nbuf, sizeof(nbuf));
20595
20596
0
    if (param.salt.base != NULL) {
20597
0
      CHECK(dns_rdata_fromstruct(&nrdata, zone->rdclass,
20598
0
               dns_rdatatype_nsec3param,
20599
0
               &param, &b));
20600
0
      dns_nsec3param_toprivate(&nrdata, &prdata,
20601
0
             zone->privatetype, np->data,
20602
0
             sizeof(np->data));
20603
0
      np->length = prdata.length;
20604
0
    }
20605
20606
0
    np->rdata = param;
20607
20608
0
    if (isc_log_wouldlog(ISC_LOG_DEBUG(3))) {
20609
0
      unsigned char salttext[255 * 2 + 1];
20610
0
      if (param.salt.base != NULL) {
20611
0
        salt2text(param.salt.base, param.salt.length,
20612
0
            salttext, sizeof(salttext));
20613
0
      }
20614
0
      dnssec_log(zone, ISC_LOG_DEBUG(3),
20615
0
           "setnsec3param:nsec3 %u %u %u %u:%s",
20616
0
           param.hash, param.flags, param.iterations,
20617
0
           param.salt.length,
20618
0
           param.salt.base == NULL ? "unknown"
20619
0
                 : (char *)salttext);
20620
0
    }
20621
0
  }
20622
20623
  /*
20624
   * Queue the request and let zone maintenance process it once the zone
20625
   * DB is loaded and no inline-signing transaction is active.
20626
   */
20627
0
  ISC_LIST_APPEND(zone->maintenance_queue, request, link);
20628
0
  if (zone->loop != NULL && zone_maintenance_request_pending(zone)) {
20629
0
    isc_time_t now = isc_time_now();
20630
0
    dns__zone_settimer(zone, now);
20631
0
  }
20632
0
  request = NULL;
20633
20634
0
  result = ISC_R_SUCCESS;
20635
20636
0
cleanup:
20637
0
  if (request != NULL) {
20638
0
    isc_mem_put(zone->mctx, request, sizeof(*request));
20639
0
  }
20640
0
  UNLOCK_ZONE(zone);
20641
0
  return result;
20642
0
}
20643
20644
unsigned int
20645
0
dns_zone_getincludes(dns_zone_t *zone, char ***includesp) {
20646
0
  char **array = NULL;
20647
0
  unsigned int n = 0, count = 0;
20648
20649
0
  REQUIRE(DNS_ZONE_VALID(zone));
20650
0
  REQUIRE(includesp != NULL && *includesp == NULL);
20651
20652
0
  LOCK_ZONE(zone);
20653
0
  ISC_LIST_FOREACH(zone->includes, include, link) {
20654
0
    count++;
20655
0
  }
20656
0
  if (count == 0) {
20657
0
    goto done;
20658
0
  }
20659
20660
0
  array = isc_mem_allocate(zone->mctx, sizeof(char *) * count);
20661
0
  ISC_LIST_FOREACH(zone->includes, include, link) {
20662
0
    INSIST(n < count);
20663
0
    array[n++] = isc_mem_strdup(zone->mctx, include->name);
20664
0
  }
20665
0
  INSIST(n == count);
20666
0
  *includesp = array;
20667
20668
0
done:
20669
0
  UNLOCK_ZONE(zone);
20670
0
  return n;
20671
0
}
20672
20673
static void
20674
zone_process_setserial(dns_zone_t *zone,
20675
0
           const zone_maintenance_request_t *request) {
20676
0
  uint32_t oldserial, desired;
20677
0
  bool commit = false;
20678
0
  isc_result_t result;
20679
0
  dns_dbversion_t *oldver = NULL, *newver = NULL;
20680
0
  dns_db_t *db = NULL;
20681
0
  dns_diff_t diff;
20682
0
  dns_update_log_t log = { update_log_cb, NULL };
20683
0
  dns_difftuple_t *oldtuple = NULL, *newtuple = NULL;
20684
20685
0
  INSIST(DNS_ZONE_VALID(zone));
20686
20687
0
  ENTER;
20688
20689
0
  if (zone->update_disabled) {
20690
0
    goto disabled;
20691
0
  }
20692
20693
0
  desired = request->u.setserial.serial;
20694
20695
0
  dns_diff_init(zone->mctx, &diff);
20696
20697
0
  ZONEDB_LOCK(&zone->dblock, isc_rwlocktype_read);
20698
0
  if (zone->db != NULL) {
20699
0
    dns_db_attach(zone->db, &db);
20700
0
  }
20701
0
  ZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_read);
20702
0
  if (db == NULL) {
20703
0
    goto cleanup;
20704
0
  }
20705
20706
0
  dns_db_currentversion(db, &oldver);
20707
0
  result = dns_db_newversion(db, &newver);
20708
0
  if (result != ISC_R_SUCCESS) {
20709
0
    dns_zone_log(zone, ISC_LOG_ERROR,
20710
0
           "setserial:dns_db_newversion -> %s",
20711
0
           isc_result_totext(result));
20712
0
    goto cleanup;
20713
0
  }
20714
20715
0
  CHECK(dns_db_createsoatuple(db, oldver, diff.mctx, DNS_DIFFOP_DEL,
20716
0
            &oldtuple));
20717
0
  dns_difftuple_copy(oldtuple, &newtuple);
20718
0
  newtuple->op = DNS_DIFFOP_ADD;
20719
20720
0
  oldserial = dns_soa_getserial(&oldtuple->rdata);
20721
0
  if (desired == 0U) {
20722
0
    desired = 1;
20723
0
  }
20724
0
  if (!isc_serial_gt(desired, oldserial)) {
20725
0
    if (desired != oldserial) {
20726
0
      dns_zone_log(zone, ISC_LOG_INFO,
20727
0
             "setserial: desired serial (%u) "
20728
0
             "out of range (%u-%u)",
20729
0
             desired, oldserial + 1,
20730
0
             oldserial + 0x7fffffff);
20731
0
    }
20732
0
    goto cleanup;
20733
0
  }
20734
20735
0
  dns_soa_setserial(desired, &newtuple->rdata);
20736
0
  CHECK(dns_diff_applytuple(&oldtuple, db, newver, &diff));
20737
0
  CHECK(dns_diff_applytuple(&newtuple, db, newver, &diff));
20738
0
  result = dns_update_signatures(&log, zone, db, oldver, newver, &diff,
20739
0
               zone->sigvalidityinterval);
20740
0
  if (result != ISC_R_NOTFOUND) {
20741
0
    CHECK(result);
20742
0
  }
20743
20744
  /* Write changes to journal file. */
20745
0
  CHECK(zone_journal(zone, &diff, NULL, "setserial"));
20746
0
  commit = true;
20747
20748
0
  LOCK_ZONE(zone);
20749
0
  zone_needdump(zone, 30);
20750
0
  UNLOCK_ZONE(zone);
20751
20752
0
cleanup:
20753
0
  if (oldtuple != NULL) {
20754
0
    dns_difftuple_free(&oldtuple);
20755
0
  }
20756
0
  if (newtuple != NULL) {
20757
0
    dns_difftuple_free(&newtuple);
20758
0
  }
20759
0
  if (oldver != NULL) {
20760
0
    dns_db_closeversion(db, &oldver, false);
20761
0
  }
20762
0
  if (newver != NULL) {
20763
0
    dns_db_closeversion(db, &newver, commit);
20764
0
  }
20765
0
  if (db != NULL) {
20766
0
    dns_db_detach(&db);
20767
0
  }
20768
0
  dns_diff_clear(&diff);
20769
20770
0
disabled:
20771
0
  INSIST(oldver == NULL);
20772
0
  INSIST(newver == NULL);
20773
0
}
20774
20775
isc_result_t
20776
0
dns_zone_setserial(dns_zone_t *zone, uint32_t serial) {
20777
0
  isc_result_t result = ISC_R_SUCCESS;
20778
0
  zone_maintenance_request_t *request = NULL;
20779
20780
0
  REQUIRE(DNS_ZONE_VALID(zone));
20781
20782
0
  LOCK_ZONE(zone);
20783
20784
0
  if (!dns__zone_inline_secure(zone)) {
20785
0
    if (!dns_zone_isdynamic(zone, true)) {
20786
0
      CLEANUP(DNS_R_NOTDYNAMIC);
20787
0
    }
20788
0
  }
20789
20790
0
  if (zone->update_disabled) {
20791
0
    CLEANUP(DNS_R_FROZEN);
20792
0
  }
20793
20794
0
  request = isc_mem_get(zone->mctx, sizeof(*request));
20795
0
  *request = (zone_maintenance_request_t){
20796
0
    .link = ISC_LINK_INITIALIZER,
20797
0
    .type = zone_maintenance_request_setserial,
20798
0
    .u.setserial = {
20799
0
      .serial = serial,
20800
0
    },
20801
0
  };
20802
0
  ISC_LIST_APPEND(zone->maintenance_queue, request, link);
20803
0
  if (zone->loop != NULL && zone_maintenance_request_pending(zone)) {
20804
0
    isc_time_t now = isc_time_now();
20805
0
    dns__zone_settimer(zone, now);
20806
0
  }
20807
0
  request = NULL;
20808
20809
0
cleanup:
20810
0
  if (request != NULL) {
20811
0
    isc_mem_put(zone->mctx, request, sizeof(*request));
20812
0
  }
20813
0
  UNLOCK_ZONE(zone);
20814
0
  return result;
20815
0
}
20816
20817
static void
20818
0
zone_process_maintenance_request(dns_zone_t *zone) {
20819
0
  zone_maintenance_request_t *request = NULL;
20820
20821
0
  LOCK_ZONE(zone);
20822
0
  if (zone_maintenance_request_pending(zone)) {
20823
0
    request = ISC_LIST_HEAD(zone->maintenance_queue);
20824
0
    ISC_LIST_UNLINK(zone->maintenance_queue, request, link);
20825
0
  }
20826
0
  UNLOCK_ZONE(zone);
20827
20828
0
  if (request == NULL) {
20829
0
    return;
20830
0
  }
20831
20832
0
  switch (request->type) {
20833
0
  case zone_maintenance_request_setnsec3param:
20834
0
    rss_post(zone, &request->u.nsec3param);
20835
0
    break;
20836
0
  case zone_maintenance_request_keydone:
20837
0
    zone_process_keydone(zone, request);
20838
0
    break;
20839
0
  case zone_maintenance_request_setserial:
20840
0
    zone_process_setserial(zone, request);
20841
0
    break;
20842
0
  default:
20843
0
    UNREACHABLE();
20844
0
  }
20845
20846
0
  isc_mem_put(zone->mctx, request, sizeof(*request));
20847
0
}
20848
20849
bool
20850
0
dns_zone_isloaded(dns_zone_t *zone) {
20851
0
  REQUIRE(DNS_ZONE_VALID(zone));
20852
20853
0
  return DNS_ZONE_FLAG(zone, DNS_ZONEFLG_LOADED);
20854
0
}
20855
20856
static void
20857
0
db_namerd_tostr(dns_db_t *db, dns_view_t *view, char *buf, size_t length) {
20858
0
  char originbuf[DNS_NAME_FORMATSIZE];
20859
0
  char classbuf[DNS_RDATACLASS_FORMATSIZE];
20860
0
  const char *viewname = "";
20861
20862
0
  dns_name_format(dns_db_origin(db), originbuf, sizeof(originbuf));
20863
0
  dns_rdataclass_format(dns_db_class(db), classbuf, sizeof(classbuf));
20864
0
  if (view != NULL && strcmp(view->name, "_bind") != 0 &&
20865
0
      strcmp(view->name, "_default") != 0)
20866
0
  {
20867
0
    viewname = view->name;
20868
0
  }
20869
0
  snprintf(buf, length, "%.*s/%s%s%.1000s", DNS_NAME_MAXTEXT, originbuf,
20870
0
     classbuf, viewname[0] != '\0' ? "/" : "", viewname);
20871
0
}
20872
20873
isc_result_t
20874
0
dns_zone_verifydb(dns_view_t *view, dns_db_t *db, dns_dbversion_t *ver) {
20875
0
  dns_dbversion_t *version = NULL;
20876
0
  dns_keytable_t *secroots = NULL;
20877
0
  isc_result_t result;
20878
0
  dns_name_t *origin;
20879
0
  char name[2048];
20880
20881
0
  REQUIRE(view == NULL || DNS_VIEW_VALID(view));
20882
0
  REQUIRE(db != NULL);
20883
20884
0
  db_namerd_tostr(db, view, name, sizeof(name));
20885
20886
0
  if (ver == NULL) {
20887
0
    dns_db_currentversion(db, &version);
20888
0
  } else {
20889
0
    version = ver;
20890
0
  }
20891
20892
0
  if (view != NULL) {
20893
0
    result = dns_view_getsecroots(view, &secroots);
20894
0
    CHECK(result);
20895
0
  }
20896
20897
0
  origin = dns_db_origin(db);
20898
0
  result = dns_zoneverify_dnssec(name, db, version, origin, secroots,
20899
0
               db->mctx, true, false, dnssec_report);
20900
20901
0
cleanup:
20902
0
  if (secroots != NULL) {
20903
0
    dns_keytable_detach(&secroots);
20904
0
  }
20905
20906
0
  if (ver == NULL) {
20907
0
    dns_db_closeversion(db, &version, false);
20908
0
  }
20909
20910
0
  if (result != ISC_R_SUCCESS) {
20911
0
    isc_log_write(DNS_LOGCATEGORY_DNSSEC, DNS_LOGMODULE_ZONE,
20912
0
            ISC_LOG_ERROR,
20913
0
            "zone %s: zone verification failed: %s", name,
20914
0
            isc_result_totext(result));
20915
0
    result = DNS_R_VERIFYFAILURE;
20916
0
  }
20917
20918
0
  return result;
20919
0
}
20920
20921
static dns_ttl_t
20922
0
zone_nsecttl(dns_zone_t *zone) {
20923
0
  REQUIRE(DNS_ZONE_VALID(zone));
20924
20925
0
  return ISC_MIN(zone->minimum, zone->soattl);
20926
0
}
20927
20928
void
20929
dns_zonemgr_set_tlsctx_cache(dns_zonemgr_t *zmgr,
20930
0
           isc_tlsctx_cache_t *tlsctx_cache) {
20931
0
  REQUIRE(DNS_ZONEMGR_VALID(zmgr));
20932
0
  REQUIRE(tlsctx_cache != NULL);
20933
20934
0
  RWLOCK(&zmgr->tlsctx_cache_rwlock, isc_rwlocktype_write);
20935
20936
0
  if (zmgr->tlsctx_cache != NULL) {
20937
0
    isc_tlsctx_cache_detach(&zmgr->tlsctx_cache);
20938
0
  }
20939
20940
0
  isc_tlsctx_cache_attach(tlsctx_cache, &zmgr->tlsctx_cache);
20941
20942
0
  RWUNLOCK(&zmgr->tlsctx_cache_rwlock, isc_rwlocktype_write);
20943
0
}
20944
20945
void
20946
dns__zonemgr_tlsctx_attach(dns_zonemgr_t *zmgr,
20947
0
         isc_tlsctx_cache_t **ptlsctx_cache) {
20948
0
  REQUIRE(DNS_ZONEMGR_VALID(zmgr));
20949
0
  REQUIRE(ptlsctx_cache != NULL && *ptlsctx_cache == NULL);
20950
20951
0
  RWLOCK(&zmgr->tlsctx_cache_rwlock, isc_rwlocktype_read);
20952
20953
0
  INSIST(zmgr->tlsctx_cache != NULL);
20954
0
  isc_tlsctx_cache_attach(zmgr->tlsctx_cache, ptlsctx_cache);
20955
20956
0
  RWUNLOCK(&zmgr->tlsctx_cache_rwlock, isc_rwlocktype_read);
20957
0
}
20958
20959
isc_result_t
20960
0
dns_zone_makedb(dns_zone_t *zone, dns_db_t **dbp) {
20961
0
  REQUIRE(DNS_ZONE_VALID(zone));
20962
0
  REQUIRE(dbp != NULL && *dbp == NULL);
20963
20964
0
  dns_db_t *db = NULL;
20965
20966
0
  isc_result_t result = dns_db_create(
20967
0
    zone->mctx, zone->db_argv[0], &zone->origin,
20968
0
    (zone->type == dns_zone_stub) ? dns_dbtype_stub
20969
0
                : dns_dbtype_zone,
20970
0
    zone->rdclass, zone->db_argc - 1, zone->db_argv + 1, &db);
20971
0
  if (result != ISC_R_SUCCESS) {
20972
0
    return result;
20973
0
  }
20974
20975
0
  switch (zone->type) {
20976
0
  case dns_zone_primary:
20977
0
  case dns_zone_secondary:
20978
0
  case dns_zone_mirror:
20979
0
    result = dns_db_setgluecachestats(db, zone->gluecachestats);
20980
0
    if (result == ISC_R_NOTIMPLEMENTED) {
20981
0
      result = ISC_R_SUCCESS;
20982
0
    }
20983
0
    if (result != ISC_R_SUCCESS) {
20984
0
      dns_db_detach(&db);
20985
0
      return result;
20986
0
    }
20987
0
    break;
20988
0
  default:
20989
0
    break;
20990
0
  }
20991
20992
0
  dns_db_setmaxrrperset(db, zone->maxrrperset);
20993
0
  dns_db_setmaxtypepername(db, zone->maxtypepername);
20994
20995
0
  *dbp = db;
20996
20997
0
  return ISC_R_SUCCESS;
20998
0
}
20999
21000
isc_result_t
21001
0
dns_zone_import_skr(dns_zone_t *zone, const char *file) {
21002
0
  dns_skr_t *skr = NULL;
21003
0
  isc_result_t result;
21004
21005
0
  REQUIRE(DNS_ZONE_VALID(zone));
21006
0
  REQUIRE(zone->kasp != NULL);
21007
0
  REQUIRE(file != NULL);
21008
21009
0
  dns_skr_create(zone->mctx, file, &zone->origin, zone->rdclass, &skr);
21010
21011
0
  CHECK(dns_skr_read(zone->mctx, file, &zone->origin, zone->rdclass,
21012
0
         dns_kasp_dnskeyttl(zone->kasp), &skr));
21013
21014
0
  dns_zone_setskr(zone, skr);
21015
0
  dnssec_log(zone, ISC_LOG_DEBUG(1), "imported skr file %s", file);
21016
21017
0
cleanup:
21018
0
  dns_skr_detach(&skr);
21019
21020
0
  return result;
21021
0
}
21022
21023
void
21024
0
dns_zone_setplugins(dns_zone_t *zone, void *plugins) {
21025
0
  REQUIRE(DNS_ZONE_VALID(zone));
21026
0
  REQUIRE(zone->plugins == NULL);
21027
0
  REQUIRE(zone->ops != NULL && zone->ops->plugins_free != NULL);
21028
21029
0
  zone->plugins = plugins;
21030
0
}
21031
21032
void
21033
0
dns_zone_unloadplugins(dns_zone_t *zone) {
21034
0
  if (zone->hooktable != NULL) {
21035
0
    INSIST(zone->ops->hooktable_free);
21036
0
    zone->ops->hooktable_free(zone->mctx, &zone->hooktable);
21037
0
    INSIST(zone->hooktable == NULL);
21038
0
  }
21039
21040
0
  if (zone->plugins != NULL) {
21041
0
    INSIST(zone->ops->plugins_free);
21042
0
    zone->ops->plugins_free(zone->mctx, &zone->plugins);
21043
0
    INSIST(zone->plugins == NULL);
21044
0
  }
21045
0
}
21046
21047
bool
21048
0
dns_zone_isexpired(dns_zone_t *zone) {
21049
0
  REQUIRE(DNS_ZONE_VALID(zone));
21050
21051
  return DNS_ZONE_FLAG(zone, DNS_ZONEFLG_EXPIRED);
21052
0
}