summaryrefslogtreecommitdiffstats
path: root/lib/dns/dnssec.c
blob: 5678c05cbd8e9c644d89cfff24c354575833dcc4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
/*
 * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
 *
 * SPDX-License-Identifier: MPL-2.0
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, you can obtain one at https://mozilla.org/MPL/2.0/.
 *
 * See the COPYRIGHT file distributed with this work for additional
 * information regarding copyright ownership.
 */

/*! \file */

#include <ctype.h>
#include <inttypes.h>
#include <stdbool.h>
#include <stdlib.h>

#include <isc/buffer.h>
#include <isc/dir.h>
#include <isc/mem.h>
#include <isc/print.h>
#include <isc/result.h>
#include <isc/serial.h>
#include <isc/string.h>
#include <isc/util.h>

#include <dns/db.h>
#include <dns/diff.h>
#include <dns/dnssec.h>
#include <dns/fixedname.h>
#include <dns/kasp.h>
#include <dns/keyvalues.h>
#include <dns/log.h>
#include <dns/message.h>
#include <dns/rdata.h>
#include <dns/rdatalist.h>
#include <dns/rdataset.h>
#include <dns/rdatastruct.h>
#include <dns/stats.h>
#include <dns/tsig.h> /* for DNS_TSIG_FUDGE */

isc_stats_t *dns_dnssec_stats;

#define is_response(msg) ((msg->flags & DNS_MESSAGEFLAG_QR) != 0)

#define RETERR(x)                            \
	do {                                 \
		result = (x);                \
		if (result != ISC_R_SUCCESS) \
			goto failure;        \
	} while (0)

#define TYPE_SIGN   0
#define TYPE_VERIFY 1

static isc_result_t
digest_callback(void *arg, isc_region_t *data);

static int
rdata_compare_wrapper(const void *rdata1, const void *rdata2);

static isc_result_t
rdataset_to_sortedarray(dns_rdataset_t *set, isc_mem_t *mctx,
			dns_rdata_t **rdata, int *nrdata);

static isc_result_t
digest_callback(void *arg, isc_region_t *data) {
	dst_context_t *ctx = arg;

	return (dst_context_adddata(ctx, data));
}

static void
inc_stat(isc_statscounter_t counter) {
	if (dns_dnssec_stats != NULL) {
		isc_stats_increment(dns_dnssec_stats, counter);
	}
}

/*
 * Make qsort happy.
 */
static int
rdata_compare_wrapper(const void *rdata1, const void *rdata2) {
	return (dns_rdata_compare((const dns_rdata_t *)rdata1,
				  (const dns_rdata_t *)rdata2));
}

/*
 * Sort the rdataset into an array.
 */
static isc_result_t
rdataset_to_sortedarray(dns_rdataset_t *set, isc_mem_t *mctx,
			dns_rdata_t **rdata, int *nrdata) {
	isc_result_t ret;
	int i = 0, n;
	dns_rdata_t *data;
	dns_rdataset_t rdataset;

	n = dns_rdataset_count(set);

	data = isc_mem_get(mctx, n * sizeof(dns_rdata_t));

	dns_rdataset_init(&rdataset);
	dns_rdataset_clone(set, &rdataset);
	ret = dns_rdataset_first(&rdataset);
	if (ret != ISC_R_SUCCESS) {
		dns_rdataset_disassociate(&rdataset);
		isc_mem_put(mctx, data, n * sizeof(dns_rdata_t));
		return (ret);
	}

	/*
	 * Put them in the array.
	 */
	do {
		dns_rdata_init(&data[i]);
		dns_rdataset_current(&rdataset, &data[i++]);
	} while (dns_rdataset_next(&rdataset) == ISC_R_SUCCESS);

	/*
	 * Sort the array.
	 */
	qsort(data, n, sizeof(dns_rdata_t), rdata_compare_wrapper);
	*rdata = data;
	*nrdata = n;
	dns_rdataset_disassociate(&rdataset);
	return (ISC_R_SUCCESS);
}

isc_result_t
dns_dnssec_keyfromrdata(const dns_name_t *name, const dns_rdata_t *rdata,
			isc_mem_t *mctx, dst_key_t **key) {
	isc_buffer_t b;
	isc_region_t r;

	INSIST(name != NULL);
	INSIST(rdata != NULL);
	INSIST(mctx != NULL);
	INSIST(key != NULL);
	INSIST(*key == NULL);
	REQUIRE(rdata->type == dns_rdatatype_key ||
		rdata->type == dns_rdatatype_dnskey);

	dns_rdata_toregion(rdata, &r);
	isc_buffer_init(&b, r.base, r.length);
	isc_buffer_add(&b, r.length);
	return (dst_key_fromdns(name, rdata->rdclass, &b, mctx, key));
}

static isc_result_t
digest_sig(dst_context_t *ctx, bool downcase, dns_rdata_t *sigrdata,
	   dns_rdata_rrsig_t *rrsig) {
	isc_region_t r;
	isc_result_t ret;
	dns_fixedname_t fname;

	dns_rdata_toregion(sigrdata, &r);
	INSIST(r.length >= 19);

	r.length = 18;
	ret = dst_context_adddata(ctx, &r);
	if (ret != ISC_R_SUCCESS) {
		return (ret);
	}
	if (downcase) {
		dns_fixedname_init(&fname);

		RUNTIME_CHECK(dns_name_downcase(&rrsig->signer,
						dns_fixedname_name(&fname),
						NULL) == ISC_R_SUCCESS);
		dns_name_toregion(dns_fixedname_name(&fname), &r);
	} else {
		dns_name_toregion(&rrsig->signer, &r);
	}

	return (dst_context_adddata(ctx, &r));
}

isc_result_t
dns_dnssec_sign(const dns_name_t *name, dns_rdataset_t *set, dst_key_t *key,
		isc_stdtime_t *inception, isc_stdtime_t *expire,
		isc_mem_t *mctx, isc_buffer_t *buffer, dns_rdata_t *sigrdata) {
	dns_rdata_rrsig_t sig;
	dns_rdata_t tmpsigrdata;
	dns_rdata_t *rdatas;
	int nrdatas, i;
	isc_buffer_t sigbuf, envbuf;
	isc_region_t r;
	dst_context_t *ctx = NULL;
	isc_result_t ret;
	isc_buffer_t *databuf = NULL;
	char data[256 + 8];
	uint32_t flags;
	unsigned int sigsize;
	dns_fixedname_t fnewname;
	dns_fixedname_t fsigner;

	REQUIRE(name != NULL);
	REQUIRE(dns_name_countlabels(name) <= 255);
	REQUIRE(set != NULL);
	REQUIRE(key != NULL);
	REQUIRE(inception != NULL);
	REQUIRE(expire != NULL);
	REQUIRE(mctx != NULL);
	REQUIRE(sigrdata != NULL);

	if (*inception >= *expire) {
		return (DNS_R_INVALIDTIME);
	}

	/*
	 * Is the key allowed to sign data?
	 */
	flags = dst_key_flags(key);
	if ((flags & DNS_KEYTYPE_NOAUTH) != 0) {
		return (DNS_R_KEYUNAUTHORIZED);
	}
	if ((flags & DNS_KEYFLAG_OWNERMASK) != DNS_KEYOWNER_ZONE) {
		return (DNS_R_KEYUNAUTHORIZED);
	}

	sig.mctx = mctx;
	sig.common.rdclass = set->rdclass;
	sig.common.rdtype = dns_rdatatype_rrsig;
	ISC_LINK_INIT(&sig.common, link);

	/*
	 * Downcase signer.
	 */
	dns_name_init(&sig.signer, NULL);
	dns_fixedname_init(&fsigner);
	RUNTIME_CHECK(dns_name_downcase(dst_key_name(key),
					dns_fixedname_name(&fsigner),
					NULL) == ISC_R_SUCCESS);
	dns_name_clone(dns_fixedname_name(&fsigner), &sig.signer);

	sig.covered = set->type;
	sig.algorithm = dst_key_alg(key);
	sig.labels = dns_name_countlabels(name) - 1;
	if (dns_name_iswildcard(name)) {
		sig.labels--;
	}
	sig.originalttl = set->ttl;
	sig.timesigned = *inception;
	sig.timeexpire = *expire;
	sig.keyid = dst_key_id(key);
	ret = dst_key_sigsize(key, &sigsize);
	if (ret != ISC_R_SUCCESS) {
		return (ret);
	}
	sig.siglen = sigsize;
	/*
	 * The actual contents of sig.signature are not important yet, since
	 * they're not used in digest_sig().
	 */
	sig.signature = isc_mem_get(mctx, sig.siglen);

	isc_buffer_allocate(mctx, &databuf, sigsize + 256 + 18);

	dns_rdata_init(&tmpsigrdata);
	ret = dns_rdata_fromstruct(&tmpsigrdata, sig.common.rdclass,
				   sig.common.rdtype, &sig, databuf);
	if (ret != ISC_R_SUCCESS) {
		goto cleanup_databuf;
	}

	ret = dst_context_create(key, mctx, DNS_LOGCATEGORY_DNSSEC, true, 0,
				 &ctx);
	if (ret != ISC_R_SUCCESS) {
		goto cleanup_databuf;
	}

	/*
	 * Digest the SIG rdata.
	 */
	ret = digest_sig(ctx, false, &tmpsigrdata, &sig);
	if (ret != ISC_R_SUCCESS) {
		goto cleanup_context;
	}

	dns_fixedname_init(&fnewname);
	RUNTIME_CHECK(dns_name_downcase(name, dns_fixedname_name(&fnewname),
					NULL) == ISC_R_SUCCESS);
	dns_name_toregion(dns_fixedname_name(&fnewname), &r);

	/*
	 * Create an envelope for each rdata: <name|type|class|ttl>.
	 */
	isc_buffer_init(&envbuf, data, sizeof(data));
	memmove(data, r.base, r.length);
	isc_buffer_add(&envbuf, r.length);
	isc_buffer_putuint16(&envbuf, set->type);
	isc_buffer_putuint16(&envbuf, set->rdclass);
	isc_buffer_putuint32(&envbuf, set->ttl);

	ret = rdataset_to_sortedarray(set, mctx, &rdatas, &nrdatas);
	if (ret != ISC_R_SUCCESS) {
		goto cleanup_context;
	}
	isc_buffer_usedregion(&envbuf, &r);

	for (i = 0; i < nrdatas; i++) {
		uint16_t len;
		isc_buffer_t lenbuf;
		isc_region_t lenr;

		/*
		 * Skip duplicates.
		 */
		if (i > 0 && dns_rdata_compare(&rdatas[i], &rdatas[i - 1]) == 0)
		{
			continue;
		}

		/*
		 * Digest the envelope.
		 */
		ret = dst_context_adddata(ctx, &r);
		if (ret != ISC_R_SUCCESS) {
			goto cleanup_array;
		}

		/*
		 * Digest the length of the rdata.
		 */
		isc_buffer_init(&lenbuf, &len, sizeof(len));
		INSIST(rdatas[i].length < 65536);
		isc_buffer_putuint16(&lenbuf, (uint16_t)rdatas[i].length);
		isc_buffer_usedregion(&lenbuf, &lenr);
		ret = dst_context_adddata(ctx, &lenr);
		if (ret != ISC_R_SUCCESS) {
			goto cleanup_array;
		}

		/*
		 * Digest the rdata.
		 */
		ret = dns_rdata_digest(&rdatas[i], digest_callback, ctx);
		if (ret != ISC_R_SUCCESS) {
			goto cleanup_array;
		}
	}

	isc_buffer_init(&sigbuf, sig.signature, sig.siglen);
	ret = dst_context_sign(ctx, &sigbuf);
	if (ret != ISC_R_SUCCESS) {
		goto cleanup_array;
	}
	isc_buffer_usedregion(&sigbuf, &r);
	if (r.length != sig.siglen) {
		ret = ISC_R_NOSPACE;
		goto cleanup_array;
	}

	ret = dns_rdata_fromstruct(sigrdata, sig.common.rdclass,
				   sig.common.rdtype, &sig, buffer);

cleanup_array:
	isc_mem_put(mctx, rdatas, nrdatas * sizeof(dns_rdata_t));
cleanup_context:
	dst_context_destroy(&ctx);
cleanup_databuf:
	isc_buffer_free(&databuf);
	isc_mem_put(mctx, sig.signature, sig.siglen);

	return (ret);
}

isc_result_t
dns_dnssec_verify(const dns_name_t *name, dns_rdataset_t *set, dst_key_t *key,
		  bool ignoretime, unsigned int maxbits, isc_mem_t *mctx,
		  dns_rdata_t *sigrdata, dns_name_t *wild) {
	dns_rdata_rrsig_t sig;
	dns_fixedname_t fnewname;
	isc_region_t r;
	isc_buffer_t envbuf;
	dns_rdata_t *rdatas;
	int nrdatas, i;
	isc_stdtime_t now;
	isc_result_t ret;
	unsigned char data[300];
	dst_context_t *ctx = NULL;
	int labels = 0;
	uint32_t flags;
	bool downcase = false;

	REQUIRE(name != NULL);
	REQUIRE(set != NULL);
	REQUIRE(key != NULL);
	REQUIRE(mctx != NULL);
	REQUIRE(sigrdata != NULL && sigrdata->type == dns_rdatatype_rrsig);

	ret = dns_rdata_tostruct(sigrdata, &sig, NULL);
	if (ret != ISC_R_SUCCESS) {
		return (ret);
	}

	if (set->type != sig.covered) {
		return (DNS_R_SIGINVALID);
	}

	if (isc_serial_lt(sig.timeexpire, sig.timesigned)) {
		inc_stat(dns_dnssecstats_fail);
		return (DNS_R_SIGINVALID);
	}

	if (!ignoretime) {
		isc_stdtime_get(&now);

		/*
		 * Is SIG temporally valid?
		 */
		if (isc_serial_lt((uint32_t)now, sig.timesigned)) {
			inc_stat(dns_dnssecstats_fail);
			return (DNS_R_SIGFUTURE);
		} else if (isc_serial_lt(sig.timeexpire, (uint32_t)now)) {
			inc_stat(dns_dnssecstats_fail);
			return (DNS_R_SIGEXPIRED);
		}
	}

	/*
	 * NS, SOA and DNSSKEY records are signed by their owner.
	 * DS records are signed by the parent.
	 */
	switch (set->type) {
	case dns_rdatatype_ns:
	case dns_rdatatype_soa:
	case dns_rdatatype_dnskey:
		if (!dns_name_equal(name, &sig.signer)) {
			inc_stat(dns_dnssecstats_fail);
			return (DNS_R_SIGINVALID);
		}
		break;
	case dns_rdatatype_ds:
		if (dns_name_equal(name, &sig.signer)) {
			inc_stat(dns_dnssecstats_fail);
			return (DNS_R_SIGINVALID);
		}
		FALLTHROUGH;
	default:
		if (!dns_name_issubdomain(name, &sig.signer)) {
			inc_stat(dns_dnssecstats_fail);
			return (DNS_R_SIGINVALID);
		}
		break;
	}

	/*
	 * Is the key allowed to sign data?
	 */
	flags = dst_key_flags(key);
	if ((flags & DNS_KEYTYPE_NOAUTH) != 0) {
		inc_stat(dns_dnssecstats_fail);
		return (DNS_R_KEYUNAUTHORIZED);
	}
	if ((flags & DNS_KEYFLAG_OWNERMASK) != DNS_KEYOWNER_ZONE) {
		inc_stat(dns_dnssecstats_fail);
		return (DNS_R_KEYUNAUTHORIZED);
	}

again:
	ret = dst_context_create(key, mctx, DNS_LOGCATEGORY_DNSSEC, false,
				 maxbits, &ctx);
	if (ret != ISC_R_SUCCESS) {
		goto cleanup_struct;
	}

	/*
	 * Digest the SIG rdata (not including the signature).
	 */
	ret = digest_sig(ctx, downcase, sigrdata, &sig);
	if (ret != ISC_R_SUCCESS) {
		goto cleanup_context;
	}

	/*
	 * If the name is an expanded wildcard, use the wildcard name.
	 */
	dns_fixedname_init(&fnewname);
	labels = dns_name_countlabels(name) - 1;
	RUNTIME_CHECK(dns_name_downcase(name, dns_fixedname_name(&fnewname),
					NULL) == ISC_R_SUCCESS);
	if (labels - sig.labels > 0) {
		dns_name_split(dns_fixedname_name(&fnewname), sig.labels + 1,
			       NULL, dns_fixedname_name(&fnewname));
	}

	dns_name_toregion(dns_fixedname_name(&fnewname), &r);

	/*
	 * Create an envelope for each rdata: <name|type|class|ttl>.
	 */
	isc_buffer_init(&envbuf, data, sizeof(data));
	if (labels - sig.labels > 0) {
		isc_buffer_putuint8(&envbuf, 1);
		isc_buffer_putuint8(&envbuf, '*');
		memmove(data + 2, r.base, r.length);
	} else {
		memmove(data, r.base, r.length);
	}
	isc_buffer_add(&envbuf, r.length);
	isc_buffer_putuint16(&envbuf, set->type);
	isc_buffer_putuint16(&envbuf, set->rdclass);
	isc_buffer_putuint32(&envbuf, sig.originalttl);

	ret = rdataset_to_sortedarray(set, mctx, &rdatas, &nrdatas);
	if (ret != ISC_R_SUCCESS) {
		goto cleanup_context;
	}

	isc_buffer_usedregion(&envbuf, &r);

	for (i = 0; i < nrdatas; i++) {
		uint16_t len;
		isc_buffer_t lenbuf;
		isc_region_t lenr;

		/*
		 * Skip duplicates.
		 */
		if (i > 0 && dns_rdata_compare(&rdatas[i], &rdatas[i - 1]) == 0)
		{
			continue;
		}

		/*
		 * Digest the envelope.
		 */
		ret = dst_context_adddata(ctx, &r);
		if (ret != ISC_R_SUCCESS) {
			goto cleanup_array;
		}

		/*
		 * Digest the rdata length.
		 */
		isc_buffer_init(&lenbuf, &len, sizeof(len));
		INSIST(rdatas[i].length < 65536);
		isc_buffer_putuint16(&lenbuf, (uint16_t)rdatas[i].length);
		isc_buffer_usedregion(&lenbuf, &lenr);

		/*
		 * Digest the rdata.
		 */
		ret = dst_context_adddata(ctx, &lenr);
		if (ret != ISC_R_SUCCESS) {
			goto cleanup_array;
		}
		ret = dns_rdata_digest(&rdatas[i], digest_callback, ctx);
		if (ret != ISC_R_SUCCESS) {
			goto cleanup_array;
		}
	}

	r.base = sig.signature;
	r.length = sig.siglen;
	ret = dst_context_verify2(ctx, maxbits, &r);
	if (ret == ISC_R_SUCCESS && downcase) {
		char namebuf[DNS_NAME_FORMATSIZE];
		dns_name_format(&sig.signer, namebuf, sizeof(namebuf));
		isc_log_write(dns_lctx, DNS_LOGCATEGORY_DNSSEC,
			      DNS_LOGMODULE_DNSSEC, ISC_LOG_DEBUG(1),
			      "successfully validated after lower casing "
			      "signer '%s'",
			      namebuf);
		inc_stat(dns_dnssecstats_downcase);
	} else if (ret == ISC_R_SUCCESS) {
		inc_stat(dns_dnssecstats_asis);
	}

cleanup_array:
	isc_mem_put(mctx, rdatas, nrdatas * sizeof(dns_rdata_t));
cleanup_context:
	dst_context_destroy(&ctx);
	if (ret == DST_R_VERIFYFAILURE && !downcase) {
		downcase = true;
		goto again;
	}
cleanup_struct:
	dns_rdata_freestruct(&sig);

	if (ret == DST_R_VERIFYFAILURE) {
		ret = DNS_R_SIGINVALID;
	}

	if (ret != ISC_R_SUCCESS) {
		inc_stat(dns_dnssecstats_fail);
	}

	if (ret == ISC_R_SUCCESS && labels - sig.labels > 0) {
		if (wild != NULL) {
			RUNTIME_CHECK(dns_name_concatenate(
					      dns_wildcardname,
					      dns_fixedname_name(&fnewname),
					      wild, NULL) == ISC_R_SUCCESS);
		}
		inc_stat(dns_dnssecstats_wildcard);
		ret = DNS_R_FROMWILDCARD;
	}
	return (ret);
}

bool
dns_dnssec_keyactive(dst_key_t *key, isc_stdtime_t now) {
	isc_result_t result;
	isc_stdtime_t publish, active, revoke, remove;
	bool hint_publish, hint_zsign, hint_ksign, hint_revoke, hint_remove;
	int major, minor;
	bool ksk = false, zsk = false;
	isc_result_t ret;

	/* Is this an old-style key? */
	result = dst_key_getprivateformat(key, &major, &minor);
	RUNTIME_CHECK(result == ISC_R_SUCCESS);

	/* Is this a KSK? */
	ret = dst_key_getbool(key, DST_BOOL_KSK, &ksk);
	if (ret != ISC_R_SUCCESS) {
		ksk = ((dst_key_flags(key) & DNS_KEYFLAG_KSK) != 0);
	}
	ret = dst_key_getbool(key, DST_BOOL_ZSK, &zsk);
	if (ret != ISC_R_SUCCESS) {
		zsk = ((dst_key_flags(key) & DNS_KEYFLAG_KSK) == 0);
	}

	/*
	 * Smart signing started with key format 1.3; prior to that, all
	 * keys are assumed active.
	 */
	if (major == 1 && minor <= 2) {
		return (true);
	}

	hint_publish = dst_key_is_published(key, now, &publish);
	hint_zsign = dst_key_is_signing(key, DST_BOOL_ZSK, now, &active);
	hint_ksign = dst_key_is_signing(key, DST_BOOL_KSK, now, &active);
	hint_revoke = dst_key_is_revoked(key, now, &revoke);
	hint_remove = dst_key_is_removed(key, now, &remove);

	if (hint_remove) {
		return (false);
	}
	if (hint_publish && hint_revoke) {
		return (true);
	}
	if (hint_zsign && zsk) {
		return (true);
	}
	if (hint_ksign && ksk) {
		return (true);
	}
	return (false);
}

/*%<
 * Indicate whether a key is scheduled to to have CDS/CDNSKEY records
 * published now.
 *
 * Returns true if.
 *  - kasp says the DS record should be published (e.g. the DS state is in
 *    RUMOURED or OMNIPRESENT state).
 * Or:
 *  - SyncPublish is set and in the past, AND
 *  - SyncDelete is unset or in the future
 */
static bool
syncpublish(dst_key_t *key, isc_stdtime_t now) {
	isc_result_t result;
	isc_stdtime_t when;
	dst_key_state_t state;
	int major, minor;
	bool publish;

	/*
	 * Is this an old-style key?
	 */
	result = dst_key_getprivateformat(key, &major, &minor);
	RUNTIME_CHECK(result == ISC_R_SUCCESS);

	/*
	 * Smart signing started with key format 1.3
	 */
	if (major == 1 && minor <= 2) {
		return (false);
	}

	/* Check kasp state first. */
	result = dst_key_getstate(key, DST_KEY_DS, &state);
	if (result == ISC_R_SUCCESS) {
		return (state == DST_KEY_STATE_RUMOURED ||
			state == DST_KEY_STATE_OMNIPRESENT);
	}

	/* If no kasp state, check timings. */
	publish = false;
	result = dst_key_gettime(key, DST_TIME_SYNCPUBLISH, &when);
	if (result == ISC_R_SUCCESS && when <= now) {
		publish = true;
	}
	result = dst_key_gettime(key, DST_TIME_SYNCDELETE, &when);
	if (result == ISC_R_SUCCESS && when < now) {
		publish = false;
	}
	return (publish);
}

/*%<
 * Indicate whether a key is scheduled to to have CDS/CDNSKEY records
 * deleted now.
 *
 * Returns true if:
 *  - kasp says the DS record should be unpublished (e.g. the DS state is in
 *    UNRETENTIVE or HIDDEN state).
 * Or:
 * - SyncDelete is set and in the past.
 */
static bool
syncdelete(dst_key_t *key, isc_stdtime_t now) {
	isc_result_t result;
	isc_stdtime_t when;
	dst_key_state_t state;
	int major, minor;

	/*
	 * Is this an old-style key?
	 */
	result = dst_key_getprivateformat(key, &major, &minor);
	RUNTIME_CHECK(result == ISC_R_SUCCESS);

	/*
	 * Smart signing started with key format 1.3.
	 */
	if (major == 1 && minor <= 2) {
		return (false);
	}

	/* Check kasp state first. */
	result = dst_key_getstate(key, DST_KEY_DS, &state);
	if (result == ISC_R_SUCCESS) {
		return (state == DST_KEY_STATE_UNRETENTIVE ||
			state == DST_KEY_STATE_HIDDEN);
	}

	/* If no kasp state, check timings. */
	result = dst_key_gettime(key, DST_TIME_SYNCDELETE, &when);
	if (result != ISC_R_SUCCESS) {
		return (false);
	}
	if (when <= now) {
		return (true);
	}
	return (false);
}

#define is_zone_key(key) \
	((dst_key_flags(key) & DNS_KEYFLAG_OWNERMASK) == DNS_KEYOWNER_ZONE)

isc_result_t
dns_dnssec_findzonekeys(dns_db_t *db, dns_dbversion_t *ver, dns_dbnode_t *node,
			const dns_name_t *name, const char *directory,
			isc_stdtime_t now, isc_mem_t *mctx,
			unsigned int maxkeys, dst_key_t **keys,
			unsigned int *nkeys) {
	dns_rdataset_t rdataset;
	dns_rdata_t rdata = DNS_RDATA_INIT;
	isc_result_t result;
	dst_key_t *pubkey = NULL;
	unsigned int count = 0;

	REQUIRE(nkeys != NULL);
	REQUIRE(keys != NULL);

	*nkeys = 0;
	memset(keys, 0, sizeof(*keys) * maxkeys);
	dns_rdataset_init(&rdataset);
	RETERR(dns_db_findrdataset(db, node, ver, dns_rdatatype_dnskey, 0, 0,
				   &rdataset, NULL));
	RETERR(dns_rdataset_first(&rdataset));
	while (result == ISC_R_SUCCESS && count < maxkeys) {
		pubkey = NULL;
		dns_rdataset_current(&rdataset, &rdata);
		RETERR(dns_dnssec_keyfromrdata(name, &rdata, mctx, &pubkey));
		dst_key_setttl(pubkey, rdataset.ttl);

		if (!is_zone_key(pubkey) ||
		    (dst_key_flags(pubkey) & DNS_KEYTYPE_NOAUTH) != 0)
		{
			goto next;
		}
		/* Corrupted .key file? */
		if (!dns_name_equal(name, dst_key_name(pubkey))) {
			goto next;
		}
		keys[count] = NULL;
		result = dst_key_fromfile(
			dst_key_name(pubkey), dst_key_id(pubkey),
			dst_key_alg(pubkey),
			DST_TYPE_PUBLIC | DST_TYPE_PRIVATE | DST_TYPE_STATE,
			directory, mctx, &keys[count]);

		/*
		 * If the key was revoked and the private file
		 * doesn't exist, maybe it was revoked internally
		 * by named.  Try loading the unrevoked version.
		 */
		if (result == ISC_R_FILENOTFOUND) {
			uint32_t flags;
			flags = dst_key_flags(pubkey);
			if ((flags & DNS_KEYFLAG_REVOKE) != 0) {
				dst_key_setflags(pubkey,
						 flags & ~DNS_KEYFLAG_REVOKE);
				result = dst_key_fromfile(
					dst_key_name(pubkey),
					dst_key_id(pubkey), dst_key_alg(pubkey),
					DST_TYPE_PUBLIC | DST_TYPE_PRIVATE |
						DST_TYPE_STATE,
					directory, mctx, &keys[count]);
				if (result == ISC_R_SUCCESS &&
				    dst_key_pubcompare(pubkey, keys[count],
						       false))
				{
					dst_key_setflags(keys[count], flags);
				}
				dst_key_setflags(pubkey, flags);
			}
		}

		if (result != ISC_R_SUCCESS) {
			char filename[DNS_NAME_FORMATSIZE +
				      DNS_SECALG_FORMATSIZE +
				      sizeof("key file for //65535")];
			isc_result_t result2;
			isc_buffer_t buf;

			isc_buffer_init(&buf, filename, NAME_MAX);
			result2 = dst_key_getfilename(
				dst_key_name(pubkey), dst_key_id(pubkey),
				dst_key_alg(pubkey),
				(DST_TYPE_PUBLIC | DST_TYPE_PRIVATE |
				 DST_TYPE_STATE),
				directory, mctx, &buf);
			if (result2 != ISC_R_SUCCESS) {
				char namebuf[DNS_NAME_FORMATSIZE];
				char algbuf[DNS_SECALG_FORMATSIZE];

				dns_name_format(dst_key_name(pubkey), namebuf,
						sizeof(namebuf));
				dns_secalg_format(dst_key_alg(pubkey), algbuf,
						  sizeof(algbuf));
				snprintf(filename, sizeof(filename) - 1,
					 "key file for %s/%s/%d", namebuf,
					 algbuf, dst_key_id(pubkey));
			}

			isc_log_write(dns_lctx, DNS_LOGCATEGORY_GENERAL,
				      DNS_LOGMODULE_DNSSEC, ISC_LOG_WARNING,
				      "dns_dnssec_findzonekeys2: error "
				      "reading %s: %s",
				      filename, isc_result_totext(result));
		}

		if (result == ISC_R_FILENOTFOUND || result == ISC_R_NOPERM) {
			keys[count] = pubkey;
			pubkey = NULL;
			count++;
			goto next;
		}

		if (result != ISC_R_SUCCESS) {
			goto failure;
		}

		/*
		 * If a key is marked inactive, skip it
		 */
		if (!dns_dnssec_keyactive(keys[count], now)) {
			dst_key_setinactive(pubkey, true);
			dst_key_free(&keys[count]);
			keys[count] = pubkey;
			pubkey = NULL;
			count++;
			goto next;
		}

		/*
		 * Whatever the key's default TTL may have
		 * been, the rdataset TTL takes priority.
		 */
		dst_key_setttl(keys[count], rdataset.ttl);

		if ((dst_key_flags(keys[count]) & DNS_KEYTYPE_NOAUTH) != 0) {
			/* We should never get here. */
			dst_key_free(&keys[count]);
			goto next;
		}
		count++;
	next:
		if (pubkey != NULL) {
			dst_key_free(&pubkey);
		}
		dns_rdata_reset(&rdata);
		result = dns_rdataset_next(&rdataset);
	}
	if (result != ISC_R_NOMORE) {
		goto failure;
	}
	if (count == 0) {
		result = ISC_R_NOTFOUND;
	} else {
		result = ISC_R_SUCCESS;
	}

failure:
	if (dns_rdataset_isassociated(&rdataset)) {
		dns_rdataset_disassociate(&rdataset);
	}
	if (pubkey != NULL) {
		dst_key_free(&pubkey);
	}
	if (result != ISC_R_SUCCESS) {
		while (count > 0) {
			dst_key_free(&keys[--count]);
		}
	}
	*nkeys = count;
	return (result);
}

isc_result_t
dns_dnssec_signmessage(dns_message_t *msg, dst_key_t *key) {
	dns_rdata_sig_t sig; /* SIG(0) */
	unsigned char data[512];
	unsigned char header[DNS_MESSAGE_HEADERLEN];
	isc_buffer_t headerbuf, databuf, sigbuf;
	unsigned int sigsize;
	isc_buffer_t *dynbuf = NULL;
	dns_rdata_t *rdata;
	dns_rdatalist_t *datalist;
	dns_rdataset_t *dataset;
	isc_region_t r;
	isc_stdtime_t now;
	dst_context_t *ctx = NULL;
	isc_mem_t *mctx;
	isc_result_t result;

	REQUIRE(msg != NULL);
	REQUIRE(key != NULL);

	if (is_response(msg)) {
		REQUIRE(msg->query.base != NULL);
	}

	mctx = msg->mctx;

	memset(&sig, 0, sizeof(sig));

	sig.mctx = mctx;
	sig.common.rdclass = dns_rdataclass_any;
	sig.common.rdtype = dns_rdatatype_sig; /* SIG(0) */
	ISC_LINK_INIT(&sig.common, link);

	sig.covered = 0;
	sig.algorithm = dst_key_alg(key);
	sig.labels = 0; /* the root name */
	sig.originalttl = 0;

	if (msg->fuzzing) {
		now = msg->fuzztime;
	} else {
		isc_stdtime_get(&now);
	}
	sig.timesigned = now - DNS_TSIG_FUDGE;
	sig.timeexpire = now + DNS_TSIG_FUDGE;

	sig.keyid = dst_key_id(key);

	dns_name_init(&sig.signer, NULL);
	dns_name_clone(dst_key_name(key), &sig.signer);

	sig.siglen = 0;
	sig.signature = NULL;

	isc_buffer_init(&databuf, data, sizeof(data));

	RETERR(dst_context_create(key, mctx, DNS_LOGCATEGORY_DNSSEC, true, 0,
				  &ctx));

	/*
	 * Digest the fields of the SIG - we can cheat and use
	 * dns_rdata_fromstruct.  Since siglen is 0, the digested data
	 * is identical to dns format.
	 */
	RETERR(dns_rdata_fromstruct(NULL, dns_rdataclass_any,
				    dns_rdatatype_sig /* SIG(0) */, &sig,
				    &databuf));
	isc_buffer_usedregion(&databuf, &r);
	RETERR(dst_context_adddata(ctx, &r));

	/*
	 * If this is a response, digest the query.
	 */
	if (is_response(msg)) {
		RETERR(dst_context_adddata(ctx, &msg->query));
	}

	/*
	 * Digest the header.
	 */
	isc_buffer_init(&headerbuf, header, sizeof(header));
	dns_message_renderheader(msg, &headerbuf);
	isc_buffer_usedregion(&headerbuf, &r);
	RETERR(dst_context_adddata(ctx, &r));

	/*
	 * Digest the remainder of the message.
	 */
	isc_buffer_usedregion(msg->buffer, &r);
	isc_region_consume(&r, DNS_MESSAGE_HEADERLEN);
	RETERR(dst_context_adddata(ctx, &r));

	RETERR(dst_key_sigsize(key, &sigsize));
	sig.siglen = sigsize;
	sig.signature = isc_mem_get(mctx, sig.siglen);

	isc_buffer_init(&sigbuf, sig.signature, sig.siglen);
	RETERR(dst_context_sign(ctx, &sigbuf));
	dst_context_destroy(&ctx);

	rdata = NULL;
	RETERR(dns_message_gettemprdata(msg, &rdata));
	isc_buffer_allocate(msg->mctx, &dynbuf, 1024);
	RETERR(dns_rdata_fromstruct(rdata, dns_rdataclass_any,
				    dns_rdatatype_sig /* SIG(0) */, &sig,
				    dynbuf));

	isc_mem_put(mctx, sig.signature, sig.siglen);

	dns_message_takebuffer(msg, &dynbuf);

	datalist = NULL;
	RETERR(dns_message_gettemprdatalist(msg, &datalist));
	datalist->rdclass = dns_rdataclass_any;
	datalist->type = dns_rdatatype_sig; /* SIG(0) */
	ISC_LIST_APPEND(datalist->rdata, rdata, link);
	dataset = NULL;
	RETERR(dns_message_gettemprdataset(msg, &dataset));
	RUNTIME_CHECK(dns_rdatalist_tordataset(datalist, dataset) ==
		      ISC_R_SUCCESS);
	msg->sig0 = dataset;

	return (ISC_R_SUCCESS);

failure:
	if (dynbuf != NULL) {
		isc_buffer_free(&dynbuf);
	}
	if (sig.signature != NULL) {
		isc_mem_put(mctx, sig.signature, sig.siglen);
	}
	if (ctx != NULL) {
		dst_context_destroy(&ctx);
	}

	return (result);
}

isc_result_t
dns_dnssec_verifymessage(isc_buffer_t *source, dns_message_t *msg,
			 dst_key_t *key) {
	dns_rdata_sig_t sig; /* SIG(0) */
	unsigned char header[DNS_MESSAGE_HEADERLEN];
	dns_rdata_t rdata = DNS_RDATA_INIT;
	isc_region_t r, source_r, sig_r, header_r;
	isc_stdtime_t now;
	dst_context_t *ctx = NULL;
	isc_mem_t *mctx;
	isc_result_t result;
	uint16_t addcount, addcount_n;
	bool signeedsfree = false;

	REQUIRE(source != NULL);
	REQUIRE(msg != NULL);
	REQUIRE(key != NULL);

	mctx = msg->mctx;

	msg->verify_attempted = 1;
	msg->verified_sig = 0;
	msg->sig0status = dns_tsigerror_badsig;

	if (is_response(msg)) {
		if (msg->query.base == NULL) {
			return (DNS_R_UNEXPECTEDTSIG);
		}
	}

	isc_buffer_usedregion(source, &source_r);

	RETERR(dns_rdataset_first(msg->sig0));
	dns_rdataset_current(msg->sig0, &rdata);

	RETERR(dns_rdata_tostruct(&rdata, &sig, NULL));
	signeedsfree = true;

	if (sig.labels != 0) {
		result = DNS_R_SIGINVALID;
		goto failure;
	}

	if (isc_serial_lt(sig.timeexpire, sig.timesigned)) {
		result = DNS_R_SIGINVALID;
		msg->sig0status = dns_tsigerror_badtime;
		goto failure;
	}

	if (msg->fuzzing) {
		now = msg->fuzztime;
	} else {
		isc_stdtime_get(&now);
	}

	if (isc_serial_lt((uint32_t)now, sig.timesigned)) {
		result = DNS_R_SIGFUTURE;
		msg->sig0status = dns_tsigerror_badtime;
		goto failure;
	} else if (isc_serial_lt(sig.timeexpire, (uint32_t)now)) {
		result = DNS_R_SIGEXPIRED;
		msg->sig0status = dns_tsigerror_badtime;
		goto failure;
	}

	if (!dns_name_equal(dst_key_name(key), &sig.signer)) {
		result = DNS_R_SIGINVALID;
		msg->sig0status = dns_tsigerror_badkey;
		goto failure;
	}

	RETERR(dst_context_create(key, mctx, DNS_LOGCATEGORY_DNSSEC, false, 0,
				  &ctx));

	/*
	 * Digest the SIG(0) record, except for the signature.
	 */
	dns_rdata_toregion(&rdata, &r);
	r.length -= sig.siglen;
	RETERR(dst_context_adddata(ctx, &r));

	/*
	 * If this is a response, digest the query.
	 */
	if (is_response(msg)) {
		RETERR(dst_context_adddata(ctx, &msg->query));
	}

	/*
	 * Extract the header.
	 */
	memmove(header, source_r.base, DNS_MESSAGE_HEADERLEN);

	/*
	 * Decrement the additional field counter.
	 */
	memmove(&addcount, &header[DNS_MESSAGE_HEADERLEN - 2], 2);
	addcount_n = ntohs(addcount);
	addcount = htons((uint16_t)(addcount_n - 1));
	memmove(&header[DNS_MESSAGE_HEADERLEN - 2], &addcount, 2);

	/*
	 * Digest the modified header.
	 */
	header_r.base = (unsigned char *)header;
	header_r.length = DNS_MESSAGE_HEADERLEN;
	RETERR(dst_context_adddata(ctx, &header_r));

	/*
	 * Digest all non-SIG(0) records.
	 */
	r.base = source_r.base + DNS_MESSAGE_HEADERLEN;
	r.length = msg->sigstart - DNS_MESSAGE_HEADERLEN;
	RETERR(dst_context_adddata(ctx, &r));

	sig_r.base = sig.signature;
	sig_r.length = sig.siglen;
	result = dst_context_verify(ctx, &sig_r);
	if (result != ISC_R_SUCCESS) {
		msg->sig0status = dns_tsigerror_badsig;
		goto failure;
	}

	msg->verified_sig = 1;
	msg->sig0status = dns_rcode_noerror;

	dst_context_destroy(&ctx);
	dns_rdata_freestruct(&sig);

	return (ISC_R_SUCCESS);

failure:
	if (signeedsfree) {
		dns_rdata_freestruct(&sig);
	}
	if (ctx != NULL) {
		dst_context_destroy(&ctx);
	}

	return (result);
}

/*%
 * Does this key ('rdata') self sign the rrset ('rdataset')?
 */
bool
dns_dnssec_selfsigns(dns_rdata_t *rdata, const dns_name_t *name,
		     dns_rdataset_t *rdataset, dns_rdataset_t *sigrdataset,
		     bool ignoretime, isc_mem_t *mctx) {
	INSIST(rdataset->type == dns_rdatatype_key ||
	       rdataset->type == dns_rdatatype_dnskey);
	if (rdataset->type == dns_rdatatype_key) {
		INSIST(sigrdataset->type == dns_rdatatype_sig);
		INSIST(sigrdataset->covers == dns_rdatatype_key);
	} else {
		INSIST(sigrdataset->type == dns_rdatatype_rrsig);
		INSIST(sigrdataset->covers == dns_rdatatype_dnskey);
	}

	return (dns_dnssec_signs(rdata, name, rdataset, sigrdataset, ignoretime,
				 mctx));
}

bool
dns_dnssec_signs(dns_rdata_t *rdata, const dns_name_t *name,
		 dns_rdataset_t *rdataset, dns_rdataset_t *sigrdataset,
		 bool ignoretime, isc_mem_t *mctx) {
	dst_key_t *dstkey = NULL;
	dns_keytag_t keytag;
	dns_rdata_dnskey_t key;
	dns_rdata_rrsig_t sig;
	dns_rdata_t sigrdata = DNS_RDATA_INIT;
	isc_result_t result;

	INSIST(sigrdataset->type == dns_rdatatype_rrsig);
	if (sigrdataset->covers != rdataset->type) {
		return (false);
	}

	result = dns_dnssec_keyfromrdata(name, rdata, mctx, &dstkey);
	if (result != ISC_R_SUCCESS) {
		return (false);
	}
	result = dns_rdata_tostruct(rdata, &key, NULL);
	RUNTIME_CHECK(result == ISC_R_SUCCESS);

	keytag = dst_key_id(dstkey);
	for (result = dns_rdataset_first(sigrdataset); result == ISC_R_SUCCESS;
	     result = dns_rdataset_next(sigrdataset))
	{
		dns_rdata_reset(&sigrdata);
		dns_rdataset_current(sigrdataset, &sigrdata);
		result = dns_rdata_tostruct(&sigrdata, &sig, NULL);
		RUNTIME_CHECK(result == ISC_R_SUCCESS);

		if (sig.algorithm == key.algorithm && sig.keyid == keytag) {
			result = dns_dnssec_verify(name, rdataset, dstkey,
						   ignoretime, 0, mctx,
						   &sigrdata, NULL);
			if (result == ISC_R_SUCCESS) {
				dst_key_free(&dstkey);
				return (true);
			}
		}
	}
	dst_key_free(&dstkey);
	return (false);
}

isc_result_t
dns_dnsseckey_create(isc_mem_t *mctx, dst_key_t **dstkey,
		     dns_dnsseckey_t **dkp) {
	isc_result_t result;
	dns_dnsseckey_t *dk;
	int major, minor;

	REQUIRE(dkp != NULL && *dkp == NULL);
	dk = isc_mem_get(mctx, sizeof(dns_dnsseckey_t));

	dk->key = *dstkey;
	*dstkey = NULL;
	dk->force_publish = false;
	dk->force_sign = false;
	dk->hint_publish = false;
	dk->hint_sign = false;
	dk->hint_revoke = false;
	dk->hint_remove = false;
	dk->first_sign = false;
	dk->is_active = false;
	dk->purge = false;
	dk->prepublish = 0;
	dk->source = dns_keysource_unknown;
	dk->index = 0;

	/* KSK or ZSK? */
	result = dst_key_getbool(dk->key, DST_BOOL_KSK, &dk->ksk);
	if (result != ISC_R_SUCCESS) {
		dk->ksk = ((dst_key_flags(dk->key) & DNS_KEYFLAG_KSK) != 0);
	}
	result = dst_key_getbool(dk->key, DST_BOOL_ZSK, &dk->zsk);
	if (result != ISC_R_SUCCESS) {
		dk->zsk = ((dst_key_flags(dk->key) & DNS_KEYFLAG_KSK) == 0);
	}

	/* Is this an old-style key? */
	result = dst_key_getprivateformat(dk->key, &major, &minor);
	INSIST(result == ISC_R_SUCCESS);

	/* Smart signing started with key format 1.3 */
	dk->legacy = (major == 1 && minor <= 2);

	ISC_LINK_INIT(dk, link);
	*dkp = dk;
	return (ISC_R_SUCCESS);
}

void
dns_dnsseckey_destroy(isc_mem_t *mctx, dns_dnsseckey_t **dkp) {
	dns_dnsseckey_t *dk;

	REQUIRE(dkp != NULL && *dkp != NULL);
	dk = *dkp;
	*dkp = NULL;
	if (dk->key != NULL) {
		dst_key_free(&dk->key);
	}
	isc_mem_put(mctx, dk, sizeof(dns_dnsseckey_t));
}

void
dns_dnssec_get_hints(dns_dnsseckey_t *key, isc_stdtime_t now) {
	isc_stdtime_t publish = 0, active = 0, revoke = 0, remove = 0;

	REQUIRE(key != NULL && key->key != NULL);

	key->hint_publish = dst_key_is_published(key->key, now, &publish);
	key->hint_sign = dst_key_is_signing(key->key, DST_BOOL_ZSK, now,
					    &active);
	key->hint_revoke = dst_key_is_revoked(key->key, now, &revoke);
	key->hint_remove = dst_key_is_removed(key->key, now, &remove);

	/*
	 * Activation date is set (maybe in the future), but publication date
	 * isn't. Most likely the user wants to publish now and activate later.
	 * Most likely because this is true for most rollovers, except for:
	 * 1. The unpopular ZSK Double-RRSIG method.
	 * 2. When introducing a new algorithm.
	 * These two cases are rare enough that we will set hint_publish
	 * anyway when hint_sign is set, because BIND 9 natively does not
	 * support the ZSK Double-RRSIG method, and when introducing a new
	 * algorithm, we strive to publish its signatures and DNSKEY records
	 * at the same time.
	 */
	if (key->hint_sign && publish == 0) {
		key->hint_publish = true;
	}

	/*
	 * If activation date is in the future, make note of how far off.
	 */
	if (key->hint_publish && active > now) {
		key->prepublish = active - now;
	}

	/*
	 * Metadata says revoke.  If the key is published, we *have to* sign
	 * with it per RFC5011 -- even if it was not active before.
	 *
	 * If it hasn't already been done, we should also revoke it now.
	 */
	if (key->hint_publish && key->hint_revoke) {
		uint32_t flags;
		key->hint_sign = true;
		flags = dst_key_flags(key->key);
		if ((flags & DNS_KEYFLAG_REVOKE) == 0) {
			flags |= DNS_KEYFLAG_REVOKE;
			dst_key_setflags(key->key, flags);
		}
	}

	/*
	 * Metadata says delete, so don't publish this key or sign with it
	 * (note that signatures of a removed key may still be reused).
	 */
	if (key->hint_remove) {
		key->hint_publish = false;
		key->hint_sign = false;
	}
}

/*%
 * Get a list of DNSSEC keys from the key repository.
 */
isc_result_t
dns_dnssec_findmatchingkeys(const dns_name_t *origin, const char *directory,
			    isc_stdtime_t now, isc_mem_t *mctx,
			    dns_dnsseckeylist_t *keylist) {
	isc_result_t result = ISC_R_SUCCESS;
	bool dir_open = false;
	dns_dnsseckeylist_t list;
	isc_dir_t dir;
	dns_dnsseckey_t *key = NULL;
	dst_key_t *dstkey = NULL;
	char namebuf[DNS_NAME_FORMATSIZE];
	isc_buffer_t b;
	unsigned int len, i, alg;

	REQUIRE(keylist != NULL);
	ISC_LIST_INIT(list);
	isc_dir_init(&dir);

	isc_buffer_init(&b, namebuf, sizeof(namebuf) - 1);
	RETERR(dns_name_tofilenametext(origin, false, &b));
	len = isc_buffer_usedlength(&b);
	namebuf[len] = '\0';

	if (directory == NULL) {
		directory = ".";
	}
	RETERR(isc_dir_open(&dir, directory));
	dir_open = true;

	while (isc_dir_read(&dir) == ISC_R_SUCCESS) {
		if (dir.entry.name[0] != 'K' || dir.entry.length < len + 1 ||
		    dir.entry.name[len + 1] != '+' ||
		    strncasecmp(dir.entry.name + 1, namebuf, len) != 0)
		{
			continue;
		}

		alg = 0;
		for (i = len + 1 + 1; i < dir.entry.length; i++) {
			if (!isdigit((unsigned char)dir.entry.name[i])) {
				break;
			}
			alg *= 10;
			alg += dir.entry.name[i] - '0';
		}

		/*
		 * Did we not read exactly 3 digits?
		 * Did we overflow?
		 * Did we correctly terminate?
		 */
		if (i != len + 1 + 1 + 3 || i >= dir.entry.length ||
		    dir.entry.name[i] != '+')
		{
			continue;
		}

		for (i++; i < dir.entry.length; i++) {
			if (!isdigit((unsigned char)dir.entry.name[i])) {
				break;
			}
		}

		/*
		 * Did we not read exactly 5 more digits?
		 * Did we overflow?
		 * Did we correctly terminate?
		 */
		if (i != len + 1 + 1 + 3 + 1 + 5 || i >= dir.entry.length ||
		    strcmp(dir.entry.name + i, ".private") != 0)
		{
			continue;
		}

		dstkey = NULL;
		result = dst_key_fromnamedfile(
			dir.entry.name, directory,
			DST_TYPE_PUBLIC | DST_TYPE_PRIVATE | DST_TYPE_STATE,
			mctx, &dstkey);

		switch (alg) {
		case DST_ALG_HMACMD5:
		case DST_ALG_HMACSHA1:
		case DST_ALG_HMACSHA224:
		case DST_ALG_HMACSHA256:
		case DST_ALG_HMACSHA384:
		case DST_ALG_HMACSHA512:
		case DST_ALG_DH:
			if (result == DST_R_BADKEYTYPE) {
				continue;
			}
		}

		if (result != ISC_R_SUCCESS) {
			isc_log_write(dns_lctx, DNS_LOGCATEGORY_GENERAL,
				      DNS_LOGMODULE_DNSSEC, ISC_LOG_WARNING,
				      "dns_dnssec_findmatchingkeys: "
				      "error reading key file %s: %s",
				      dir.entry.name,
				      isc_result_totext(result));
			continue;
		}

		RETERR(dns_dnsseckey_create(mctx, &dstkey, &key));
		key->source = dns_keysource_repository;
		dns_dnssec_get_hints(key, now);

		if (key->legacy) {
			dns_dnsseckey_destroy(mctx, &key);
		} else {
			ISC_LIST_APPEND(list, key, link);
			key = NULL;
		}
	}

	if (!ISC_LIST_EMPTY(list)) {
		result = ISC_R_SUCCESS;
		ISC_LIST_APPENDLIST(*keylist, list, link);
	} else {
		result = ISC_R_NOTFOUND;
	}

failure:
	if (dir_open) {
		isc_dir_close(&dir);
	}
	INSIST(key == NULL);
	while ((key = ISC_LIST_HEAD(list)) != NULL) {
		ISC_LIST_UNLINK(list, key, link);
		INSIST(key->key != NULL);
		dst_key_free(&key->key);
		dns_dnsseckey_destroy(mctx, &key);
	}
	if (dstkey != NULL) {
		dst_key_free(&dstkey);
	}
	return (result);
}

/*%
 * Add 'newkey' to 'keylist' if it's not already there.
 *
 * If 'savekeys' is true, then we need to preserve all
 * the keys in the keyset, regardless of whether they have
 * metadata indicating they should be deactivated or removed.
 */
static isc_result_t
addkey(dns_dnsseckeylist_t *keylist, dst_key_t **newkey, bool savekeys,
       isc_mem_t *mctx) {
	dns_dnsseckey_t *key;
	isc_result_t result;

	/* Skip duplicates */
	for (key = ISC_LIST_HEAD(*keylist); key != NULL;
	     key = ISC_LIST_NEXT(key, link))
	{
		if (dst_key_id(key->key) == dst_key_id(*newkey) &&
		    dst_key_alg(key->key) == dst_key_alg(*newkey) &&
		    dns_name_equal(dst_key_name(key->key),
				   dst_key_name(*newkey)))
		{
			break;
		}
	}

	if (key != NULL) {
		/*
		 * Found a match.  If the old key was only public and the
		 * new key is private, replace the old one; otherwise
		 * leave it.  But either way, mark the key as having
		 * been found in the zone.
		 */
		if (dst_key_isprivate(key->key)) {
			dst_key_free(newkey);
		} else if (dst_key_isprivate(*newkey)) {
			dst_key_free(&key->key);
			key->key = *newkey;
		}

		key->source = dns_keysource_zoneapex;
		return (ISC_R_SUCCESS);
	}

	result = dns_dnsseckey_create(mctx, newkey, &key);
	if (result != ISC_R_SUCCESS) {
		return (result);
	}
	if (key->legacy || savekeys) {
		key->force_publish = true;
		key->force_sign = dst_key_isprivate(key->key);
	}
	key->source = dns_keysource_zoneapex;
	ISC_LIST_APPEND(*keylist, key, link);
	*newkey = NULL;
	return (ISC_R_SUCCESS);
}

/*%
 * Mark all keys which signed the DNSKEY/SOA RRsets as "active",
 * for future reference.
 */
static isc_result_t
mark_active_keys(dns_dnsseckeylist_t *keylist, dns_rdataset_t *rrsigs) {
	isc_result_t result = ISC_R_SUCCESS;
	dns_rdata_t rdata = DNS_RDATA_INIT;
	dns_rdataset_t sigs;
	dns_dnsseckey_t *key;

	REQUIRE(rrsigs != NULL && dns_rdataset_isassociated(rrsigs));

	dns_rdataset_init(&sigs);
	dns_rdataset_clone(rrsigs, &sigs);
	for (key = ISC_LIST_HEAD(*keylist); key != NULL;
	     key = ISC_LIST_NEXT(key, link))
	{
		uint16_t keyid, sigid;
		dns_secalg_t keyalg, sigalg;
		keyid = dst_key_id(key->key);
		keyalg = dst_key_alg(key->key);

		for (result = dns_rdataset_first(&sigs);
		     result == ISC_R_SUCCESS; result = dns_rdataset_next(&sigs))
		{
			dns_rdata_rrsig_t sig;

			dns_rdata_reset(&rdata);
			dns_rdataset_current(&sigs, &rdata);
			result = dns_rdata_tostruct(&rdata, &sig, NULL);
			RUNTIME_CHECK(result == ISC_R_SUCCESS);
			sigalg = sig.algorithm;
			sigid = sig.keyid;
			if (keyid == sigid && keyalg == sigalg) {
				key->is_active = true;
				break;
			}
		}
	}

	if (result == ISC_R_NOMORE) {
		result = ISC_R_SUCCESS;
	}

	if (dns_rdataset_isassociated(&sigs)) {
		dns_rdataset_disassociate(&sigs);
	}
	return (result);
}

/*%
 * Add the contents of a DNSKEY rdataset 'keyset' to 'keylist'.
 */
isc_result_t
dns_dnssec_keylistfromrdataset(const dns_name_t *origin, const char *directory,
			       isc_mem_t *mctx, dns_rdataset_t *keyset,
			       dns_rdataset_t *keysigs, dns_rdataset_t *soasigs,
			       bool savekeys, bool publickey,
			       dns_dnsseckeylist_t *keylist) {
	dns_rdataset_t keys;
	dns_rdata_t rdata = DNS_RDATA_INIT;
	dst_key_t *dnskey = NULL, *pubkey = NULL, *privkey = NULL;
	isc_result_t result;

	REQUIRE(keyset != NULL && dns_rdataset_isassociated(keyset));

	dns_rdataset_init(&keys);

	dns_rdataset_clone(keyset, &keys);
	for (result = dns_rdataset_first(&keys); result == ISC_R_SUCCESS;
	     result = dns_rdataset_next(&keys))
	{
		dns_rdata_reset(&rdata);
		dns_rdataset_current(&keys, &rdata);

		REQUIRE(rdata.type == dns_rdatatype_key ||
			rdata.type == dns_rdatatype_dnskey);
		REQUIRE(rdata.length > 3);

		/* Skip unsupported algorithms */
		if (!dst_algorithm_supported(rdata.data[3])) {
			goto skip;
		}

		RETERR(dns_dnssec_keyfromrdata(origin, &rdata, mctx, &dnskey));
		dst_key_setttl(dnskey, keys.ttl);

		if (!is_zone_key(dnskey) ||
		    (dst_key_flags(dnskey) & DNS_KEYTYPE_NOAUTH) != 0)
		{
			goto skip;
		}

		/* Corrupted .key file? */
		if (!dns_name_equal(origin, dst_key_name(dnskey))) {
			goto skip;
		}

		if (publickey) {
			RETERR(addkey(keylist, &dnskey, savekeys, mctx));
			goto skip;
		}

		/* Try to read the public key. */
		result = dst_key_fromfile(
			dst_key_name(dnskey), dst_key_id(dnskey),
			dst_key_alg(dnskey), (DST_TYPE_PUBLIC | DST_TYPE_STATE),
			directory, mctx, &pubkey);
		if (result == ISC_R_FILENOTFOUND || result == ISC_R_NOPERM) {
			result = ISC_R_SUCCESS;
		}
		RETERR(result);

		/* Now read the private key. */
		result = dst_key_fromfile(
			dst_key_name(dnskey), dst_key_id(dnskey),
			dst_key_alg(dnskey),
			(DST_TYPE_PUBLIC | DST_TYPE_PRIVATE | DST_TYPE_STATE),
			directory, mctx, &privkey);

		/*
		 * If the key was revoked and the private file
		 * doesn't exist, maybe it was revoked internally
		 * by named.  Try loading the unrevoked version.
		 */
		if (result == ISC_R_FILENOTFOUND) {
			uint32_t flags;
			flags = dst_key_flags(dnskey);
			if ((flags & DNS_KEYFLAG_REVOKE) != 0) {
				dst_key_setflags(dnskey,
						 flags & ~DNS_KEYFLAG_REVOKE);
				result = dst_key_fromfile(
					dst_key_name(dnskey),
					dst_key_id(dnskey), dst_key_alg(dnskey),
					(DST_TYPE_PUBLIC | DST_TYPE_PRIVATE |
					 DST_TYPE_STATE),
					directory, mctx, &privkey);
				if (result == ISC_R_SUCCESS &&
				    dst_key_pubcompare(dnskey, privkey, false))
				{
					dst_key_setflags(privkey, flags);
				}
				dst_key_setflags(dnskey, flags);
			}
		}

		if (result != ISC_R_SUCCESS) {
			char filename[DNS_NAME_FORMATSIZE +
				      DNS_SECALG_FORMATSIZE +
				      sizeof("key file for //65535")];
			isc_result_t result2;
			isc_buffer_t buf;

			isc_buffer_init(&buf, filename, NAME_MAX);
			result2 = dst_key_getfilename(
				dst_key_name(dnskey), dst_key_id(dnskey),
				dst_key_alg(dnskey),
				(DST_TYPE_PUBLIC | DST_TYPE_PRIVATE |
				 DST_TYPE_STATE),
				directory, mctx, &buf);
			if (result2 != ISC_R_SUCCESS) {
				char namebuf[DNS_NAME_FORMATSIZE];
				char algbuf[DNS_SECALG_FORMATSIZE];

				dns_name_format(dst_key_name(dnskey), namebuf,
						sizeof(namebuf));
				dns_secalg_format(dst_key_alg(dnskey), algbuf,
						  sizeof(algbuf));
				snprintf(filename, sizeof(filename) - 1,
					 "key file for %s/%s/%d", namebuf,
					 algbuf, dst_key_id(dnskey));
			}

			isc_log_write(dns_lctx, DNS_LOGCATEGORY_GENERAL,
				      DNS_LOGMODULE_DNSSEC, ISC_LOG_WARNING,
				      "dns_dnssec_keylistfromrdataset: error "
				      "reading %s: %s",
				      filename, isc_result_totext(result));
		}

		if (result == ISC_R_FILENOTFOUND || result == ISC_R_NOPERM) {
			if (pubkey != NULL) {
				RETERR(addkey(keylist, &pubkey, savekeys,
					      mctx));
			} else {
				RETERR(addkey(keylist, &dnskey, savekeys,
					      mctx));
			}
			goto skip;
		}
		RETERR(result);

		/* This should never happen. */
		if ((dst_key_flags(privkey) & DNS_KEYTYPE_NOAUTH) != 0) {
			goto skip;
		}

		/*
		 * Whatever the key's default TTL may have
		 * been, the rdataset TTL takes priority.
		 */
		dst_key_setttl(privkey, dst_key_getttl(dnskey));

		RETERR(addkey(keylist, &privkey, savekeys, mctx));
	skip:
		if (dnskey != NULL) {
			dst_key_free(&dnskey);
		}
		if (pubkey != NULL) {
			dst_key_free(&pubkey);
		}
		if (privkey != NULL) {
			dst_key_free(&privkey);
		}
	}

	if (result != ISC_R_NOMORE) {
		RETERR(result);
	}

	if (keysigs != NULL && dns_rdataset_isassociated(keysigs)) {
		RETERR(mark_active_keys(keylist, keysigs));
	}

	if (soasigs != NULL && dns_rdataset_isassociated(soasigs)) {
		RETERR(mark_active_keys(keylist, soasigs));
	}

	result = ISC_R_SUCCESS;

failure:
	if (dns_rdataset_isassociated(&keys)) {
		dns_rdataset_disassociate(&keys);
	}
	if (dnskey != NULL) {
		dst_key_free(&dnskey);
	}
	if (pubkey != NULL) {
		dst_key_free(&pubkey);
	}
	if (privkey != NULL) {
		dst_key_free(&privkey);
	}
	return (result);
}

static isc_result_t
make_dnskey(dst_key_t *key, unsigned char *buf, int bufsize,
	    dns_rdata_t *target) {
	isc_result_t result;
	isc_buffer_t b;
	isc_region_t r;

	isc_buffer_init(&b, buf, bufsize);
	result = dst_key_todns(key, &b);
	if (result != ISC_R_SUCCESS) {
		return (result);
	}

	dns_rdata_reset(target);
	isc_buffer_usedregion(&b, &r);
	dns_rdata_fromregion(target, dst_key_class(key), dns_rdatatype_dnskey,
			     &r);
	return (ISC_R_SUCCESS);
}

static isc_result_t
addrdata(dns_rdata_t *rdata, dns_diff_t *diff, const dns_name_t *origin,
	 dns_ttl_t ttl, isc_mem_t *mctx) {
	isc_result_t result;
	dns_difftuple_t *tuple = NULL;

	RETERR(dns_difftuple_create(mctx, DNS_DIFFOP_ADD, origin, ttl, rdata,
				    &tuple));
	dns_diff_appendminimal(diff, &tuple);

failure:
	return (result);
}

static isc_result_t
delrdata(dns_rdata_t *rdata, dns_diff_t *diff, const dns_name_t *origin,
	 dns_ttl_t ttl, isc_mem_t *mctx) {
	isc_result_t result;
	dns_difftuple_t *tuple = NULL;

	RETERR(dns_difftuple_create(mctx, DNS_DIFFOP_DEL, origin, ttl, rdata,
				    &tuple));
	dns_diff_appendminimal(diff, &tuple);

failure:
	return (result);
}

static isc_result_t
publish_key(dns_diff_t *diff, dns_dnsseckey_t *key, const dns_name_t *origin,
	    dns_ttl_t ttl, isc_mem_t *mctx,
	    void (*report)(const char *, ...) ISC_FORMAT_PRINTF(1, 2)) {
	isc_result_t result;
	unsigned char buf[DST_KEY_MAXSIZE];
	char keystr[DST_KEY_FORMATSIZE];
	dns_rdata_t dnskey = DNS_RDATA_INIT;

	dns_rdata_reset(&dnskey);
	RETERR(make_dnskey(key->key, buf, sizeof(buf), &dnskey));
	dst_key_format(key->key, keystr, sizeof(keystr));

	report("Fetching %s (%s) from key %s.", keystr,
	       key->ksk ? (key->zsk ? "CSK" : "KSK") : "ZSK",
	       key->source == dns_keysource_user ? "file" : "repository");

	if (key->prepublish && ttl > key->prepublish) {
		isc_stdtime_t now;

		report("Key %s: Delaying activation to match the DNSKEY TTL "
		       "(%u).",
		       keystr, ttl);

		isc_stdtime_get(&now);
		dst_key_settime(key->key, DST_TIME_ACTIVATE, now + ttl);
	}

	/* publish key */
	result = addrdata(&dnskey, diff, origin, ttl, mctx);

failure:
	return (result);
}

static isc_result_t
remove_key(dns_diff_t *diff, dns_dnsseckey_t *key, const dns_name_t *origin,
	   dns_ttl_t ttl, isc_mem_t *mctx, const char *reason,
	   void (*report)(const char *, ...) ISC_FORMAT_PRINTF(1, 2)) {
	isc_result_t result;
	unsigned char buf[DST_KEY_MAXSIZE];
	dns_rdata_t dnskey = DNS_RDATA_INIT;
	char alg[80];
	char namebuf[DNS_NAME_FORMATSIZE];

	dns_secalg_format(dst_key_alg(key->key), alg, sizeof(alg));
	dns_name_format(dst_key_name(key->key), namebuf, sizeof(namebuf));
	report("Removing %s key %s/%d/%s from DNSKEY RRset.", reason, namebuf,
	       dst_key_id(key->key), alg);

	RETERR(make_dnskey(key->key, buf, sizeof(buf), &dnskey));
	result = delrdata(&dnskey, diff, origin, ttl, mctx);

failure:
	return (result);
}

static bool
exists(dns_rdataset_t *rdataset, dns_rdata_t *rdata) {
	isc_result_t result;
	dns_rdataset_t trdataset;

	dns_rdataset_init(&trdataset);
	dns_rdataset_clone(rdataset, &trdataset);
	for (result = dns_rdataset_first(&trdataset); result == ISC_R_SUCCESS;
	     result = dns_rdataset_next(&trdataset))
	{
		dns_rdata_t current = DNS_RDATA_INIT;

		dns_rdataset_current(&trdataset, &current);
		if (dns_rdata_compare(rdata, &current) == 0) {
			dns_rdataset_disassociate(&trdataset);
			return (true);
		}
	}
	dns_rdataset_disassociate(&trdataset);
	return (false);
}

isc_result_t
dns_dnssec_syncupdate(dns_dnsseckeylist_t *keys, dns_dnsseckeylist_t *rmkeys,
		      dns_rdataset_t *cds, dns_rdataset_t *cdnskey,
		      isc_stdtime_t now, dns_ttl_t ttl, dns_diff_t *diff,
		      isc_mem_t *mctx) {
	unsigned char dsbuf1[DNS_DS_BUFFERSIZE];
	unsigned char dsbuf2[DNS_DS_BUFFERSIZE];
	unsigned char keybuf[DST_KEY_MAXSIZE];
	isc_result_t result;
	dns_dnsseckey_t *key;

	for (key = ISC_LIST_HEAD(*keys); key != NULL;
	     key = ISC_LIST_NEXT(key, link))
	{
		dns_rdata_t cds_sha1 = DNS_RDATA_INIT;
		dns_rdata_t cds_sha256 = DNS_RDATA_INIT;
		dns_rdata_t cdnskeyrdata = DNS_RDATA_INIT;
		dns_name_t *origin = dst_key_name(key->key);

		RETERR(make_dnskey(key->key, keybuf, sizeof(keybuf),
				   &cdnskeyrdata));

		/*
		 * We construct the SHA-1 version of the record so we can
		 * delete any old records generated by previous versions of
		 * BIND. We only add SHA-256 records.
		 *
		 * XXXMPA we need to be able to specify the DS algorithms
		 * to be used here and below with rmkeys.
		 */
		RETERR(dns_ds_buildrdata(origin, &cdnskeyrdata,
					 DNS_DSDIGEST_SHA1, dsbuf1, &cds_sha1));
		RETERR(dns_ds_buildrdata(origin, &cdnskeyrdata,
					 DNS_DSDIGEST_SHA256, dsbuf2,
					 &cds_sha256));

		/*
		 * Now that the we have created the DS records convert
		 * the rdata to CDNSKEY and CDS for comparison.
		 */
		cdnskeyrdata.type = dns_rdatatype_cdnskey;
		cds_sha1.type = dns_rdatatype_cds;
		cds_sha256.type = dns_rdatatype_cds;

		if (syncpublish(key->key, now)) {
			char keystr[DST_KEY_FORMATSIZE];
			dst_key_format(key->key, keystr, sizeof(keystr));

			if (!dns_rdataset_isassociated(cdnskey) ||
			    !exists(cdnskey, &cdnskeyrdata))
			{
				isc_log_write(dns_lctx, DNS_LOGCATEGORY_GENERAL,
					      DNS_LOGMODULE_DNSSEC,
					      ISC_LOG_INFO,
					      "CDS for key %s is now published",
					      keystr);
				RETERR(addrdata(&cdnskeyrdata, diff, origin,
						ttl, mctx));
			}
			/* Only publish SHA-256 (SHA-1 is deprecated) */
			if (!dns_rdataset_isassociated(cds) ||
			    !exists(cds, &cds_sha256))
			{
				isc_log_write(
					dns_lctx, DNS_LOGCATEGORY_GENERAL,
					DNS_LOGMODULE_DNSSEC, ISC_LOG_INFO,
					"CDNSKEY for key %s is now published",
					keystr);
				RETERR(addrdata(&cds_sha256, diff, origin, ttl,
						mctx));
			}
		}

		if (syncdelete(key->key, now)) {
			char keystr[DST_KEY_FORMATSIZE];
			dst_key_format(key->key, keystr, sizeof(keystr));

			if (dns_rdataset_isassociated(cds)) {
				/* Delete both SHA-1 and SHA-256 */
				if (exists(cds, &cds_sha1)) {
					isc_log_write(dns_lctx,
						      DNS_LOGCATEGORY_GENERAL,
						      DNS_LOGMODULE_DNSSEC,
						      ISC_LOG_INFO,
						      "CDS (SHA-1) for key %s "
						      "is now deleted",
						      keystr);
					RETERR(delrdata(&cds_sha1, diff, origin,
							cds->ttl, mctx));
				}
				if (exists(cds, &cds_sha256)) {
					isc_log_write(dns_lctx,
						      DNS_LOGCATEGORY_GENERAL,
						      DNS_LOGMODULE_DNSSEC,
						      ISC_LOG_INFO,
						      "CDS (SHA-256) for key "
						      "%s is now deleted",
						      keystr);
					RETERR(delrdata(&cds_sha256, diff,
							origin, cds->ttl,
							mctx));
				}
			}

			if (dns_rdataset_isassociated(cdnskey)) {
				if (exists(cdnskey, &cdnskeyrdata)) {
					isc_log_write(dns_lctx,
						      DNS_LOGCATEGORY_GENERAL,
						      DNS_LOGMODULE_DNSSEC,
						      ISC_LOG_INFO,
						      "CDNSKEY for key %s is "
						      "now deleted",
						      keystr);
					RETERR(delrdata(&cdnskeyrdata, diff,
							origin, cdnskey->ttl,
							mctx));
				}
			}
		}
	}

	if (!dns_rdataset_isassociated(cds) &&
	    !dns_rdataset_isassociated(cdnskey))
	{
		return (ISC_R_SUCCESS);
	}

	/*
	 * Unconditionally remove CDS/DNSKEY records for removed keys.
	 */
	for (key = ISC_LIST_HEAD(*rmkeys); key != NULL;
	     key = ISC_LIST_NEXT(key, link))
	{
		dns_rdata_t cds_sha1 = DNS_RDATA_INIT;
		dns_rdata_t cds_sha256 = DNS_RDATA_INIT;
		dns_rdata_t cdnskeyrdata = DNS_RDATA_INIT;
		dns_name_t *origin = dst_key_name(key->key);

		char keystr[DST_KEY_FORMATSIZE];
		dst_key_format(key->key, keystr, sizeof(keystr));

		RETERR(make_dnskey(key->key, keybuf, sizeof(keybuf),
				   &cdnskeyrdata));

		if (dns_rdataset_isassociated(cds)) {
			RETERR(dns_ds_buildrdata(origin, &cdnskeyrdata,
						 DNS_DSDIGEST_SHA1, dsbuf1,
						 &cds_sha1));
			RETERR(dns_ds_buildrdata(origin, &cdnskeyrdata,
						 DNS_DSDIGEST_SHA256, dsbuf2,
						 &cds_sha256));
			if (exists(cds, &cds_sha1)) {
				isc_log_write(
					dns_lctx, DNS_LOGCATEGORY_GENERAL,
					DNS_LOGMODULE_DNSSEC, ISC_LOG_INFO,
					"CDS (SHA-1) for key %s is now deleted",
					keystr);
				RETERR(delrdata(&cds_sha1, diff, origin,
						cds->ttl, mctx));
			}
			if (exists(cds, &cds_sha256)) {
				isc_log_write(dns_lctx, DNS_LOGCATEGORY_GENERAL,
					      DNS_LOGMODULE_DNSSEC,
					      ISC_LOG_INFO,
					      "CDS (SHA-256) for key %s is now "
					      "deleted",
					      keystr);
				RETERR(delrdata(&cds_sha256, diff, origin,
						cds->ttl, mctx));
			}
		}

		if (dns_rdataset_isassociated(cdnskey)) {
			if (exists(cdnskey, &cdnskeyrdata)) {
				isc_log_write(
					dns_lctx, DNS_LOGCATEGORY_GENERAL,
					DNS_LOGMODULE_DNSSEC, ISC_LOG_INFO,
					"CDNSKEY for key %s is now deleted",
					keystr);
				RETERR(delrdata(&cdnskeyrdata, diff, origin,
						cdnskey->ttl, mctx));
			}
		}
	}

	result = ISC_R_SUCCESS;

failure:
	return (result);
}

isc_result_t
dns_dnssec_syncdelete(dns_rdataset_t *cds, dns_rdataset_t *cdnskey,
		      dns_name_t *origin, dns_rdataclass_t zclass,
		      dns_ttl_t ttl, dns_diff_t *diff, isc_mem_t *mctx,
		      bool expect_cds_delete, bool expect_cdnskey_delete) {
	unsigned char dsbuf[5] = { 0, 0, 0, 0, 0 };  /* CDS DELETE rdata */
	unsigned char keybuf[5] = { 0, 0, 3, 0, 0 }; /* CDNSKEY DELETE rdata */
	char namebuf[DNS_NAME_FORMATSIZE];
	dns_rdata_t cds_delete = DNS_RDATA_INIT;
	dns_rdata_t cdnskey_delete = DNS_RDATA_INIT;
	isc_region_t r;
	isc_result_t result;

	r.base = keybuf;
	r.length = sizeof(keybuf);
	dns_rdata_fromregion(&cdnskey_delete, zclass, dns_rdatatype_cdnskey,
			     &r);

	r.base = dsbuf;
	r.length = sizeof(dsbuf);
	dns_rdata_fromregion(&cds_delete, zclass, dns_rdatatype_cds, &r);

	dns_name_format(origin, namebuf, sizeof(namebuf));

	if (expect_cds_delete) {
		if (!dns_rdataset_isassociated(cds) ||
		    !exists(cds, &cds_delete))
		{
			isc_log_write(dns_lctx, DNS_LOGCATEGORY_GENERAL,
				      DNS_LOGMODULE_DNSSEC, ISC_LOG_INFO,
				      "CDS (DELETE) for zone %s is now "
				      "published",
				      namebuf);
			RETERR(addrdata(&cds_delete, diff, origin, ttl, mctx));
		}
	} else {
		if (dns_rdataset_isassociated(cds) && exists(cds, &cds_delete))
		{
			isc_log_write(dns_lctx, DNS_LOGCATEGORY_GENERAL,
				      DNS_LOGMODULE_DNSSEC, ISC_LOG_INFO,
				      "CDS (DELETE) for zone %s is now "
				      "deleted",
				      namebuf);
			RETERR(delrdata(&cds_delete, diff, origin, cds->ttl,
					mctx));
		}
	}

	if (expect_cdnskey_delete) {
		if (!dns_rdataset_isassociated(cdnskey) ||
		    !exists(cdnskey, &cdnskey_delete))
		{
			isc_log_write(dns_lctx, DNS_LOGCATEGORY_GENERAL,
				      DNS_LOGMODULE_DNSSEC, ISC_LOG_INFO,
				      "CDNSKEY (DELETE) for zone %s is now "
				      "published",
				      namebuf);
			RETERR(addrdata(&cdnskey_delete, diff, origin, ttl,
					mctx));
		}
	} else {
		if (dns_rdataset_isassociated(cdnskey) &&
		    exists(cdnskey, &cdnskey_delete))
		{
			isc_log_write(dns_lctx, DNS_LOGCATEGORY_GENERAL,
				      DNS_LOGMODULE_DNSSEC, ISC_LOG_INFO,
				      "CDNSKEY (DELETE) for zone %s is now "
				      "deleted",
				      namebuf);
			RETERR(delrdata(&cdnskey_delete, diff, origin,
					cdnskey->ttl, mctx));
		}
	}

	result = ISC_R_SUCCESS;

failure:
	return (result);
}

/*
 * Update 'keys' with information from 'newkeys'.
 *
 * If 'removed' is not NULL, any keys that are being removed from
 * the zone will be added to the list for post-removal processing.
 */
isc_result_t
dns_dnssec_updatekeys(dns_dnsseckeylist_t *keys, dns_dnsseckeylist_t *newkeys,
		      dns_dnsseckeylist_t *removed, const dns_name_t *origin,
		      dns_ttl_t hint_ttl, dns_diff_t *diff, isc_mem_t *mctx,
		      void (*report)(const char *, ...)
			      ISC_FORMAT_PRINTF(1, 2)) {
	isc_result_t result;
	dns_dnsseckey_t *key, *key1, *key2, *next;
	bool found_ttl = false;
	dns_ttl_t ttl = hint_ttl;

	/*
	 * First, look through the existing key list to find keys
	 * supplied from the command line which are not in the zone.
	 * Update the zone to include them.
	 *
	 * Also, if there are keys published in the zone already,
	 * use their TTL for all subsequent published keys.
	 */
	for (key = ISC_LIST_HEAD(*keys); key != NULL;
	     key = ISC_LIST_NEXT(key, link))
	{
		if (key->source == dns_keysource_user &&
		    (key->hint_publish || key->force_publish))
		{
			RETERR(publish_key(diff, key, origin, ttl, mctx,
					   report));
		}
		if (key->source == dns_keysource_zoneapex) {
			ttl = dst_key_getttl(key->key);
			found_ttl = true;
		}
	}

	/*
	 * If there were no existing keys, use the smallest nonzero
	 * TTL of the keys found in the repository.
	 */
	if (!found_ttl && !ISC_LIST_EMPTY(*newkeys)) {
		dns_ttl_t shortest = 0;

		for (key = ISC_LIST_HEAD(*newkeys); key != NULL;
		     key = ISC_LIST_NEXT(key, link))
		{
			dns_ttl_t thisttl = dst_key_getttl(key->key);
			if (thisttl != 0 &&
			    (shortest == 0 || thisttl < shortest))
			{
				shortest = thisttl;
			}
		}

		if (shortest != 0) {
			ttl = shortest;
		}
	}

	/*
	 * Second, scan the list of newly found keys looking for matches
	 * with known keys, and update accordingly.
	 */
	for (key1 = ISC_LIST_HEAD(*newkeys); key1 != NULL; key1 = next) {
		bool key_revoked = false;
		char keystr1[DST_KEY_FORMATSIZE];
		char keystr2[DST_KEY_FORMATSIZE];

		next = ISC_LIST_NEXT(key1, link);

		for (key2 = ISC_LIST_HEAD(*keys); key2 != NULL;
		     key2 = ISC_LIST_NEXT(key2, link))
		{
			int f1 = dst_key_flags(key1->key);
			int f2 = dst_key_flags(key2->key);
			int nr1 = f1 & ~DNS_KEYFLAG_REVOKE;
			int nr2 = f2 & ~DNS_KEYFLAG_REVOKE;
			if (nr1 == nr2 &&
			    dst_key_alg(key1->key) == dst_key_alg(key2->key) &&
			    dst_key_pubcompare(key1->key, key2->key, true))
			{
				int r1, r2;
				r1 = dst_key_flags(key1->key) &
				     DNS_KEYFLAG_REVOKE;
				r2 = dst_key_flags(key2->key) &
				     DNS_KEYFLAG_REVOKE;
				key_revoked = (r1 != r2);
				break;
			}
		}

		/* Printable version of key1 (the newly acquired key) */
		dst_key_format(key1->key, keystr1, sizeof(keystr1));

		/* No match found in keys; add the new key. */
		if (key2 == NULL) {
			ISC_LIST_UNLINK(*newkeys, key1, link);
			ISC_LIST_APPEND(*keys, key1, link);

			if (key1->source != dns_keysource_zoneapex &&
			    (key1->hint_publish || key1->force_publish))
			{
				RETERR(publish_key(diff, key1, origin, ttl,
						   mctx, report));
				isc_log_write(
					dns_lctx, DNS_LOGCATEGORY_DNSSEC,
					DNS_LOGMODULE_DNSSEC, ISC_LOG_INFO,
					"DNSKEY %s (%s) is now published",
					keystr1,
					key1->ksk ? (key1->zsk ? "CSK" : "KSK")
						  : "ZSK");
				if (key1->hint_sign || key1->force_sign) {
					key1->first_sign = true;
					isc_log_write(
						dns_lctx,
						DNS_LOGCATEGORY_DNSSEC,
						DNS_LOGMODULE_DNSSEC,
						ISC_LOG_INFO,
						"DNSKEY %s (%s) is now "
						"active",
						keystr1,
						key1->ksk ? (key1->zsk ? "CSK"
								       : "KSK")
							  : "ZSK");
				}
			}

			continue;
		}

		/* Printable version of key2 (the old key, if any) */
		dst_key_format(key2->key, keystr2, sizeof(keystr2));

		/* Copy key metadata. */
		dst_key_copy_metadata(key2->key, key1->key);

		/* Match found: remove or update it as needed */
		if (key1->hint_remove) {
			RETERR(remove_key(diff, key2, origin, ttl, mctx,
					  "expired", report));
			ISC_LIST_UNLINK(*keys, key2, link);

			if (removed != NULL) {
				ISC_LIST_APPEND(*removed, key2, link);
				isc_log_write(
					dns_lctx, DNS_LOGCATEGORY_DNSSEC,
					DNS_LOGMODULE_DNSSEC, ISC_LOG_INFO,
					"DNSKEY %s (%s) is now deleted",
					keystr2,
					key2->ksk ? (key2->zsk ? "CSK" : "KSK")
						  : "ZSK");
			} else {
				dns_dnsseckey_destroy(mctx, &key2);
			}
		} else if (key_revoked &&
			   (dst_key_flags(key1->key) & DNS_KEYFLAG_REVOKE) != 0)
		{
			/*
			 * A previously valid key has been revoked.
			 * We need to remove the old version and pull
			 * in the new one.
			 */
			RETERR(remove_key(diff, key2, origin, ttl, mctx,
					  "revoked", report));
			ISC_LIST_UNLINK(*keys, key2, link);
			if (removed != NULL) {
				ISC_LIST_APPEND(*removed, key2, link);
				isc_log_write(
					dns_lctx, DNS_LOGCATEGORY_DNSSEC,
					DNS_LOGMODULE_DNSSEC, ISC_LOG_INFO,
					"DNSKEY %s (%s) is now revoked; "
					"new ID is %05d",
					keystr2,
					key2->ksk ? (key2->zsk ? "CSK" : "KSK")
						  : "ZSK",
					dst_key_id(key1->key));
			} else {
				dns_dnsseckey_destroy(mctx, &key2);
			}

			RETERR(publish_key(diff, key1, origin, ttl, mctx,
					   report));
			ISC_LIST_UNLINK(*newkeys, key1, link);
			ISC_LIST_APPEND(*keys, key1, link);

			/*
			 * XXX: The revoke flag is only defined for trust
			 * anchors.  Setting the flag on a non-KSK is legal,
			 * but not defined in any RFC.  It seems reasonable
			 * to treat it the same as a KSK: keep it in the
			 * zone, sign the DNSKEY set with it, but not
			 * sign other records with it.
			 */
			key1->ksk = true;
			continue;
		} else {
			if (!key2->is_active &&
			    (key1->hint_sign || key1->force_sign))
			{
				key2->first_sign = true;
				isc_log_write(
					dns_lctx, DNS_LOGCATEGORY_DNSSEC,
					DNS_LOGMODULE_DNSSEC, ISC_LOG_INFO,
					"DNSKEY %s (%s) is now active", keystr1,
					key1->ksk ? (key1->zsk ? "CSK" : "KSK")
						  : "ZSK");
			} else if (key2->is_active && !key1->hint_sign &&
				   !key1->force_sign)
			{
				isc_log_write(
					dns_lctx, DNS_LOGCATEGORY_DNSSEC,
					DNS_LOGMODULE_DNSSEC, ISC_LOG_INFO,
					"DNSKEY %s (%s) is now inactive",
					keystr1,
					key1->ksk ? (key1->zsk ? "CSK" : "KSK")
						  : "ZSK");
			}

			key2->hint_sign = key1->hint_sign;
			key2->hint_publish = key1->hint_publish;
		}
	}

	/* Free any leftover keys in newkeys */
	while (!ISC_LIST_EMPTY(*newkeys)) {
		key1 = ISC_LIST_HEAD(*newkeys);
		ISC_LIST_UNLINK(*newkeys, key1, link);
		dns_dnsseckey_destroy(mctx, &key1);
	}

	result = ISC_R_SUCCESS;

failure:
	return (result);
}

isc_result_t
dns_dnssec_matchdskey(dns_name_t *name, dns_rdata_t *dsrdata,
		      dns_rdataset_t *keyset, dns_rdata_t *keyrdata) {
	isc_result_t result;
	unsigned char buf[DNS_DS_BUFFERSIZE];
	dns_keytag_t keytag;
	dns_rdata_dnskey_t key;
	dns_rdata_ds_t ds;
	isc_region_t r;

	result = dns_rdata_tostruct(dsrdata, &ds, NULL);
	RUNTIME_CHECK(result == ISC_R_SUCCESS);

	for (result = dns_rdataset_first(keyset); result == ISC_R_SUCCESS;
	     result = dns_rdataset_next(keyset))
	{
		dns_rdata_t newdsrdata = DNS_RDATA_INIT;

		dns_rdata_reset(keyrdata);
		dns_rdataset_current(keyset, keyrdata);

		result = dns_rdata_tostruct(keyrdata, &key, NULL);
		RUNTIME_CHECK(result == ISC_R_SUCCESS);

		dns_rdata_toregion(keyrdata, &r);
		keytag = dst_region_computeid(&r);

		if (ds.key_tag != keytag || ds.algorithm != key.algorithm) {
			continue;
		}

		result = dns_ds_buildrdata(name, keyrdata, ds.digest_type, buf,
					   &newdsrdata);
		if (result != ISC_R_SUCCESS) {
			continue;
		}

		if (dns_rdata_compare(dsrdata, &newdsrdata) == 0) {
			break;
		}
	}
	if (result == ISC_R_NOMORE) {
		result = ISC_R_NOTFOUND;
	}

	return (result);
}