Detect FPU by checking CPUID features.
[dragonfly.git] / contrib / bind-9.5.2 / lib / dns / tkey.c
1 /*
2  * Copyright (C) 2004-2008  Internet Systems Consortium, Inc. ("ISC")
3  * Copyright (C) 1999-2001, 2003  Internet Software Consortium.
4  *
5  * Permission to use, copy, modify, and/or distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
10  * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11  * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
12  * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
14  * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15  * PERFORMANCE OF THIS SOFTWARE.
16  */
17
18 /*
19  * $Id: tkey.c,v 1.87.2.3 2008/04/03 00:47:46 marka Exp $
20  */
21 /*! \file */
22 #include <config.h>
23
24 #include <isc/buffer.h>
25 #include <isc/entropy.h>
26 #include <isc/md5.h>
27 #include <isc/mem.h>
28 #include <isc/string.h>
29 #include <isc/util.h>
30
31 #include <dns/dnssec.h>
32 #include <dns/fixedname.h>
33 #include <dns/keyvalues.h>
34 #include <dns/log.h>
35 #include <dns/message.h>
36 #include <dns/name.h>
37 #include <dns/rdata.h>
38 #include <dns/rdatalist.h>
39 #include <dns/rdataset.h>
40 #include <dns/rdatastruct.h>
41 #include <dns/result.h>
42 #include <dns/tkey.h>
43 #include <dns/tsig.h>
44
45 #include <dst/dst.h>
46 #include <dst/gssapi.h>
47
48 #define TKEY_RANDOM_AMOUNT 16
49
50 #define RETERR(x) do { \
51         result = (x); \
52         if (result != ISC_R_SUCCESS) \
53                 goto failure; \
54         } while (0)
55
56 static void
57 tkey_log(const char *fmt, ...) ISC_FORMAT_PRINTF(1, 2);
58
59 static void
60 tkey_log(const char *fmt, ...) {
61         va_list ap;
62
63         va_start(ap, fmt);
64         isc_log_vwrite(dns_lctx, DNS_LOGCATEGORY_GENERAL,
65                        DNS_LOGMODULE_REQUEST, ISC_LOG_DEBUG(4), fmt, ap);
66         va_end(ap);
67 }
68
69 static void
70 _dns_tkey_dumpmessage(dns_message_t *msg) {
71         isc_buffer_t outbuf;
72         unsigned char output[4096];
73         isc_result_t result;
74
75         isc_buffer_init(&outbuf, output, sizeof(output));
76         result = dns_message_totext(msg, &dns_master_style_debug, 0,
77                                     &outbuf);
78         /* XXXMLG ignore result */
79         fprintf(stderr, "%.*s\n", (int)isc_buffer_usedlength(&outbuf),
80                 (char *)isc_buffer_base(&outbuf));
81 }
82
83 isc_result_t
84 dns_tkeyctx_create(isc_mem_t *mctx, isc_entropy_t *ectx, dns_tkeyctx_t **tctxp)
85 {
86         dns_tkeyctx_t *tctx;
87
88         REQUIRE(mctx != NULL);
89         REQUIRE(ectx != NULL);
90         REQUIRE(tctxp != NULL && *tctxp == NULL);
91
92         tctx = isc_mem_get(mctx, sizeof(dns_tkeyctx_t));
93         if (tctx == NULL)
94                 return (ISC_R_NOMEMORY);
95         tctx->mctx = NULL;
96         isc_mem_attach(mctx, &tctx->mctx);
97         tctx->ectx = NULL;
98         isc_entropy_attach(ectx, &tctx->ectx);
99         tctx->dhkey = NULL;
100         tctx->domain = NULL;
101         tctx->gsscred = NULL;
102
103         *tctxp = tctx;
104         return (ISC_R_SUCCESS);
105 }
106
107 void
108 dns_tkeyctx_destroy(dns_tkeyctx_t **tctxp) {
109         isc_mem_t *mctx;
110         dns_tkeyctx_t *tctx;
111
112         REQUIRE(tctxp != NULL && *tctxp != NULL);
113
114         tctx = *tctxp;
115         mctx = tctx->mctx;
116
117         if (tctx->dhkey != NULL)
118                 dst_key_free(&tctx->dhkey);
119         if (tctx->domain != NULL) {
120                 if (dns_name_dynamic(tctx->domain))
121                         dns_name_free(tctx->domain, mctx);
122                 isc_mem_put(mctx, tctx->domain, sizeof(dns_name_t));
123         }
124         if (tctx->gsscred != NULL)
125                 dst_gssapi_releasecred(&tctx->gsscred);
126         isc_entropy_detach(&tctx->ectx);
127         isc_mem_put(mctx, tctx, sizeof(dns_tkeyctx_t));
128         isc_mem_detach(&mctx);
129         *tctxp = NULL;
130 }
131
132 static isc_result_t
133 add_rdata_to_list(dns_message_t *msg, dns_name_t *name, dns_rdata_t *rdata,
134                 isc_uint32_t ttl, dns_namelist_t *namelist)
135 {
136         isc_result_t result;
137         isc_region_t r, newr;
138         dns_rdata_t *newrdata = NULL;
139         dns_name_t *newname = NULL;
140         dns_rdatalist_t *newlist = NULL;
141         dns_rdataset_t *newset = NULL;
142         isc_buffer_t *tmprdatabuf = NULL;
143
144         RETERR(dns_message_gettemprdata(msg, &newrdata));
145
146         dns_rdata_toregion(rdata, &r);
147         RETERR(isc_buffer_allocate(msg->mctx, &tmprdatabuf, r.length));
148         isc_buffer_availableregion(tmprdatabuf, &newr);
149         memcpy(newr.base, r.base, r.length);
150         dns_rdata_fromregion(newrdata, rdata->rdclass, rdata->type, &newr);
151         dns_message_takebuffer(msg, &tmprdatabuf);
152
153         RETERR(dns_message_gettempname(msg, &newname));
154         dns_name_init(newname, NULL);
155         RETERR(dns_name_dup(name, msg->mctx, newname));
156
157         RETERR(dns_message_gettemprdatalist(msg, &newlist));
158         newlist->rdclass = newrdata->rdclass;
159         newlist->type = newrdata->type;
160         newlist->covers = 0;
161         newlist->ttl = ttl;
162         ISC_LIST_INIT(newlist->rdata);
163         ISC_LIST_APPEND(newlist->rdata, newrdata, link);
164
165         RETERR(dns_message_gettemprdataset(msg, &newset));
166         dns_rdataset_init(newset);
167         RETERR(dns_rdatalist_tordataset(newlist, newset));
168
169         ISC_LIST_INIT(newname->list);
170         ISC_LIST_APPEND(newname->list, newset, link);
171
172         ISC_LIST_APPEND(*namelist, newname, link);
173
174         return (ISC_R_SUCCESS);
175
176  failure:
177         if (newrdata != NULL) {
178                 if (ISC_LINK_LINKED(newrdata, link))
179                         ISC_LIST_UNLINK(newlist->rdata, newrdata, link);
180                 dns_message_puttemprdata(msg, &newrdata);
181         }
182         if (newname != NULL)
183                 dns_message_puttempname(msg, &newname);
184         if (newset != NULL) {
185                 dns_rdataset_disassociate(newset);
186                 dns_message_puttemprdataset(msg, &newset);
187         }
188         if (newlist != NULL)
189                 dns_message_puttemprdatalist(msg, &newlist);
190         return (result);
191 }
192
193 static void
194 free_namelist(dns_message_t *msg, dns_namelist_t *namelist) {
195         dns_name_t *name;
196         dns_rdataset_t *set;
197
198         while (!ISC_LIST_EMPTY(*namelist)) {
199                 name = ISC_LIST_HEAD(*namelist);
200                 ISC_LIST_UNLINK(*namelist, name, link);
201                 while (!ISC_LIST_EMPTY(name->list)) {
202                         set = ISC_LIST_HEAD(name->list);
203                         ISC_LIST_UNLINK(name->list, set, link);
204                         dns_message_puttemprdataset(msg, &set);
205                 }
206                 dns_message_puttempname(msg, &name);
207         }
208 }
209
210 static isc_result_t
211 compute_secret(isc_buffer_t *shared, isc_region_t *queryrandomness,
212                isc_region_t *serverrandomness, isc_buffer_t *secret)
213 {
214         isc_md5_t md5ctx;
215         isc_region_t r, r2;
216         unsigned char digests[32];
217         unsigned int i;
218
219         isc_buffer_usedregion(shared, &r);
220
221         /*
222          * MD5 ( query data | DH value ).
223          */
224         isc_md5_init(&md5ctx);
225         isc_md5_update(&md5ctx, queryrandomness->base,
226                        queryrandomness->length);
227         isc_md5_update(&md5ctx, r.base, r.length);
228         isc_md5_final(&md5ctx, digests);
229
230         /*
231          * MD5 ( server data | DH value ).
232          */
233         isc_md5_init(&md5ctx);
234         isc_md5_update(&md5ctx, serverrandomness->base,
235                        serverrandomness->length);
236         isc_md5_update(&md5ctx, r.base, r.length);
237         isc_md5_final(&md5ctx, &digests[ISC_MD5_DIGESTLENGTH]);
238
239         /*
240          * XOR ( DH value, MD5-1 | MD5-2).
241          */
242         isc_buffer_availableregion(secret, &r);
243         isc_buffer_usedregion(shared, &r2);
244         if (r.length < sizeof(digests) || r.length < r2.length)
245                 return (ISC_R_NOSPACE);
246         if (r2.length > sizeof(digests)) {
247                 memcpy(r.base, r2.base, r2.length);
248                 for (i = 0; i < sizeof(digests); i++)
249                         r.base[i] ^= digests[i];
250                 isc_buffer_add(secret, r2.length);
251         } else {
252                 memcpy(r.base, digests, sizeof(digests));
253                 for (i = 0; i < r2.length; i++)
254                         r.base[i] ^= r2.base[i];
255                 isc_buffer_add(secret, sizeof(digests));
256         }
257         return (ISC_R_SUCCESS);
258
259 }
260
261 static isc_result_t
262 process_dhtkey(dns_message_t *msg, dns_name_t *signer, dns_name_t *name,
263                dns_rdata_tkey_t *tkeyin, dns_tkeyctx_t *tctx,
264                dns_rdata_tkey_t *tkeyout,
265                dns_tsig_keyring_t *ring, dns_namelist_t *namelist)
266 {
267         isc_result_t result = ISC_R_SUCCESS;
268         dns_name_t *keyname, ourname;
269         dns_rdataset_t *keyset = NULL;
270         dns_rdata_t keyrdata = DNS_RDATA_INIT, ourkeyrdata = DNS_RDATA_INIT;
271         isc_boolean_t found_key = ISC_FALSE, found_incompatible = ISC_FALSE;
272         dst_key_t *pubkey = NULL;
273         isc_buffer_t ourkeybuf, *shared = NULL;
274         isc_region_t r, r2, ourkeyr;
275         unsigned char keydata[DST_KEY_MAXSIZE];
276         unsigned int sharedsize;
277         isc_buffer_t secret;
278         unsigned char *randomdata = NULL, secretdata[256];
279         dns_ttl_t ttl = 0;
280
281         if (tctx->dhkey == NULL) {
282                 tkey_log("process_dhtkey: tkey-dhkey not defined");
283                 tkeyout->error = dns_tsigerror_badalg;
284                 return (DNS_R_REFUSED);
285         }
286
287         if (!dns_name_equal(&tkeyin->algorithm, DNS_TSIG_HMACMD5_NAME)) {
288                 tkey_log("process_dhtkey: algorithms other than "
289                          "hmac-md5 are not supported");
290                 tkeyout->error = dns_tsigerror_badalg;
291                 return (ISC_R_SUCCESS);
292         }
293
294         /*
295          * Look for a DH KEY record that will work with ours.
296          */
297         for (result = dns_message_firstname(msg, DNS_SECTION_ADDITIONAL);
298              result == ISC_R_SUCCESS && !found_key;
299              result = dns_message_nextname(msg, DNS_SECTION_ADDITIONAL)) {
300                 keyname = NULL;
301                 dns_message_currentname(msg, DNS_SECTION_ADDITIONAL, &keyname);
302                 keyset = NULL;
303                 result = dns_message_findtype(keyname, dns_rdatatype_key, 0,
304                                               &keyset);
305                 if (result != ISC_R_SUCCESS)
306                         continue;
307
308                 for (result = dns_rdataset_first(keyset);
309                      result == ISC_R_SUCCESS && !found_key;
310                      result = dns_rdataset_next(keyset)) {
311                         dns_rdataset_current(keyset, &keyrdata);
312                         pubkey = NULL;
313                         result = dns_dnssec_keyfromrdata(keyname, &keyrdata,
314                                                          msg->mctx, &pubkey);
315                         if (result != ISC_R_SUCCESS) {
316                                 dns_rdata_reset(&keyrdata);
317                                 continue;
318                         }
319                         if (dst_key_alg(pubkey) == DNS_KEYALG_DH) {
320                                 if (dst_key_paramcompare(pubkey, tctx->dhkey))
321                                 {
322                                         found_key = ISC_TRUE;
323                                         ttl = keyset->ttl;
324                                         break;
325                                 } else
326                                         found_incompatible = ISC_TRUE;
327                         }
328                         dst_key_free(&pubkey);
329                         dns_rdata_reset(&keyrdata);
330                 }
331         }
332
333         if (!found_key) {
334                 if (found_incompatible) {
335                         tkey_log("process_dhtkey: found an incompatible key");
336                         tkeyout->error = dns_tsigerror_badkey;
337                         return (ISC_R_SUCCESS);
338                 } else {
339                         tkey_log("process_dhtkey: failed to find a key");
340                         return (DNS_R_FORMERR);
341                 }
342         }
343
344         RETERR(add_rdata_to_list(msg, keyname, &keyrdata, ttl, namelist));
345
346         isc_buffer_init(&ourkeybuf, keydata, sizeof(keydata));
347         RETERR(dst_key_todns(tctx->dhkey, &ourkeybuf));
348         isc_buffer_usedregion(&ourkeybuf, &ourkeyr);
349         dns_rdata_fromregion(&ourkeyrdata, dns_rdataclass_any,
350                              dns_rdatatype_key, &ourkeyr);
351
352         dns_name_init(&ourname, NULL);
353         dns_name_clone(dst_key_name(tctx->dhkey), &ourname);
354
355         /*
356          * XXXBEW The TTL should be obtained from the database, if it exists.
357          */
358         RETERR(add_rdata_to_list(msg, &ourname, &ourkeyrdata, 0, namelist));
359
360         RETERR(dst_key_secretsize(tctx->dhkey, &sharedsize));
361         RETERR(isc_buffer_allocate(msg->mctx, &shared, sharedsize));
362
363         result = dst_key_computesecret(pubkey, tctx->dhkey, shared);
364         if (result != ISC_R_SUCCESS) {
365                 tkey_log("process_dhtkey: failed to compute shared secret: %s",
366                          isc_result_totext(result));
367                 goto failure;
368         }
369         dst_key_free(&pubkey);
370
371         isc_buffer_init(&secret, secretdata, sizeof(secretdata));
372
373         randomdata = isc_mem_get(tkeyout->mctx, TKEY_RANDOM_AMOUNT);
374         if (randomdata == NULL)
375                 goto failure;
376
377         result = isc_entropy_getdata(tctx->ectx, randomdata,
378                                      TKEY_RANDOM_AMOUNT, NULL, 0);
379         if (result != ISC_R_SUCCESS) {
380                 tkey_log("process_dhtkey: failed to obtain entropy: %s",
381                          isc_result_totext(result));
382                 goto failure;
383         }
384
385         r.base = randomdata;
386         r.length = TKEY_RANDOM_AMOUNT;
387         r2.base = tkeyin->key;
388         r2.length = tkeyin->keylen;
389         RETERR(compute_secret(shared, &r2, &r, &secret));
390         isc_buffer_free(&shared);
391
392         RETERR(dns_tsigkey_create(name, &tkeyin->algorithm,
393                                   isc_buffer_base(&secret),
394                                   isc_buffer_usedlength(&secret),
395                                   ISC_TRUE, signer, tkeyin->inception,
396                                   tkeyin->expire, ring->mctx, ring, NULL));
397
398         /* This key is good for a long time */
399         tkeyout->inception = tkeyin->inception;
400         tkeyout->expire = tkeyin->expire;
401
402         tkeyout->key = randomdata;
403         tkeyout->keylen = TKEY_RANDOM_AMOUNT;
404
405         return (ISC_R_SUCCESS);
406
407  failure:
408         if (!ISC_LIST_EMPTY(*namelist))
409                 free_namelist(msg, namelist);
410         if (shared != NULL)
411                 isc_buffer_free(&shared);
412         if (pubkey != NULL)
413                 dst_key_free(&pubkey);
414         if (randomdata != NULL)
415                 isc_mem_put(tkeyout->mctx, randomdata, TKEY_RANDOM_AMOUNT);
416         return (result);
417 }
418
419 static isc_result_t
420 process_gsstkey(dns_message_t *msg, dns_name_t *signer, dns_name_t *name,
421                 dns_rdata_tkey_t *tkeyin, dns_tkeyctx_t *tctx,
422                 dns_rdata_tkey_t *tkeyout,
423                 dns_tsig_keyring_t *ring, dns_namelist_t *namelist)
424 {
425         isc_result_t result = ISC_R_SUCCESS;
426         dst_key_t *dstkey = NULL;
427         dns_tsigkey_t *tsigkey = NULL;
428         dns_fixedname_t principal;
429         isc_stdtime_t now;
430         isc_region_t intoken;
431         isc_buffer_t *outtoken = NULL;
432         gss_ctx_id_t gss_ctx = NULL;
433
434         UNUSED(namelist);
435         UNUSED(signer);
436
437         if (tctx->gsscred == NULL)
438                 return (ISC_R_NOPERM);
439
440         if (!dns_name_equal(&tkeyin->algorithm, DNS_TSIG_GSSAPI_NAME) &&
441             !dns_name_equal(&tkeyin->algorithm, DNS_TSIG_GSSAPIMS_NAME)) {
442                 tkeyout->error = dns_tsigerror_badalg;
443                 tkey_log("process_gsstkey(): dns_tsigerror_badalg");    /* XXXSRA */
444                 return (ISC_R_SUCCESS);
445         }
446
447         /*
448          * XXXDCL need to check for key expiry per 4.1.1
449          * XXXDCL need a way to check fully established, perhaps w/key_flags
450          */
451
452         intoken.base = tkeyin->key;
453         intoken.length = tkeyin->keylen;
454
455         result = dns_tsigkey_find(&tsigkey, name, &tkeyin->algorithm, ring);
456         if (result == ISC_R_SUCCESS)
457                 gss_ctx = dst_key_getgssctx(tsigkey->key);
458
459
460         dns_fixedname_init(&principal);
461
462         result = dst_gssapi_acceptctx(tctx->gsscred, &intoken,
463                                       &outtoken, &gss_ctx,
464                                       dns_fixedname_name(&principal),
465                                       tctx->mctx);
466
467         if (tsigkey != NULL)
468                 dns_tsigkey_detach(&tsigkey);
469
470         if (result == DNS_R_INVALIDTKEY) {
471                 tkeyout->error = dns_tsigerror_badkey;
472                 tkey_log("process_gsstkey(): dns_tsigerror_badkey");    /* XXXSRA */
473                 return (ISC_R_SUCCESS);
474         } else if (result == ISC_R_FAILURE)
475                 goto failure;
476         ENSURE(result == DNS_R_CONTINUE || result == ISC_R_SUCCESS);
477         /*
478          * XXXDCL Section 4.1.3: Limit GSS_S_CONTINUE_NEEDED to 10 times.
479          */
480
481         if (tsigkey == NULL) {
482                 RETERR(dst_key_fromgssapi(name, gss_ctx, msg->mctx, &dstkey));
483                 RETERR(dns_tsigkey_createfromkey(name, &tkeyin->algorithm,
484                                                  dstkey, ISC_TRUE,
485                                                  dns_fixedname_name(&principal),
486                                                  tkeyin->inception,
487                                                  tkeyin->expire,
488                                                  ring->mctx, ring, NULL));
489         }
490
491         isc_stdtime_get(&now);
492         tkeyout->inception = tkeyin->inception;
493         tkeyout->expire = tkeyin->expire;
494
495         if (outtoken) {
496                 tkeyout->key = isc_mem_get(tkeyout->mctx,
497                                            isc_buffer_usedlength(outtoken));
498                 if (tkeyout->key == NULL) {
499                         result = ISC_R_NOMEMORY;
500                         goto failure;
501                 }
502                 tkeyout->keylen = isc_buffer_usedlength(outtoken);
503                 memcpy(tkeyout->key, isc_buffer_base(outtoken),
504                        isc_buffer_usedlength(outtoken));
505                 isc_buffer_free(&outtoken);
506         } else {
507                 tkeyout->key = isc_mem_get(tkeyout->mctx, tkeyin->keylen);
508                 if (tkeyout->key == NULL) {
509                         result = ISC_R_NOMEMORY;
510                         goto failure;
511                 }
512                 tkeyout->keylen = tkeyin->keylen;
513                 memcpy(tkeyout->key, tkeyin->key, tkeyin->keylen);
514         }
515
516         tkeyout->error = dns_rcode_noerror;
517
518         tkey_log("process_gsstkey(): dns_tsigerror_noerror");   /* XXXSRA */
519
520         return (ISC_R_SUCCESS);
521
522 failure:
523         if (dstkey != NULL)
524                 dst_key_free(&dstkey);
525
526         if (outtoken != NULL)
527                 isc_buffer_free(&outtoken);
528
529         tkey_log("process_gsstkey(): %s",
530                 isc_result_totext(result));     /* XXXSRA */
531
532         return (result);
533 }
534
535 static isc_result_t
536 process_deletetkey(dns_message_t *msg, dns_name_t *signer, dns_name_t *name,
537                    dns_rdata_tkey_t *tkeyin,
538                    dns_rdata_tkey_t *tkeyout,
539                    dns_tsig_keyring_t *ring,
540                    dns_namelist_t *namelist)
541 {
542         isc_result_t result;
543         dns_tsigkey_t *tsigkey = NULL;
544         dns_name_t *identity;
545
546         UNUSED(msg);
547         UNUSED(namelist);
548
549         result = dns_tsigkey_find(&tsigkey, name, &tkeyin->algorithm, ring);
550         if (result != ISC_R_SUCCESS) {
551                 tkeyout->error = dns_tsigerror_badname;
552                 return (ISC_R_SUCCESS);
553         }
554
555         /*
556          * Only allow a delete if the identity that created the key is the
557          * same as the identity that signed the message.
558          */
559         identity = dns_tsigkey_identity(tsigkey);
560         if (identity == NULL || !dns_name_equal(identity, signer)) {
561                 dns_tsigkey_detach(&tsigkey);
562                 return (DNS_R_REFUSED);
563         }
564
565         /*
566          * Set the key to be deleted when no references are left.  If the key
567          * was not generated with TKEY and is in the config file, it may be
568          * reloaded later.
569          */
570         dns_tsigkey_setdeleted(tsigkey);
571
572         /* Release the reference */
573         dns_tsigkey_detach(&tsigkey);
574
575         return (ISC_R_SUCCESS);
576 }
577
578 isc_result_t
579 dns_tkey_processquery(dns_message_t *msg, dns_tkeyctx_t *tctx,
580                       dns_tsig_keyring_t *ring)
581 {
582         isc_result_t result = ISC_R_SUCCESS;
583         dns_rdata_tkey_t tkeyin, tkeyout;
584         isc_boolean_t freetkeyin = ISC_FALSE;
585         dns_name_t *qname, *name, *keyname, *signer, tsigner;
586         dns_fixedname_t fkeyname;
587         dns_rdataset_t *tkeyset;
588         dns_rdata_t rdata;
589         dns_namelist_t namelist;
590         char tkeyoutdata[512];
591         isc_buffer_t tkeyoutbuf;
592
593         REQUIRE(msg != NULL);
594         REQUIRE(tctx != NULL);
595         REQUIRE(ring != NULL);
596
597         ISC_LIST_INIT(namelist);
598
599         /*
600          * Interpret the question section.
601          */
602         result = dns_message_firstname(msg, DNS_SECTION_QUESTION);
603         if (result != ISC_R_SUCCESS)
604                 return (DNS_R_FORMERR);
605
606         qname = NULL;
607         dns_message_currentname(msg, DNS_SECTION_QUESTION, &qname);
608
609         /*
610          * Look for a TKEY record that matches the question.
611          */
612         tkeyset = NULL;
613         name = NULL;
614         result = dns_message_findname(msg, DNS_SECTION_ADDITIONAL, qname,
615                                       dns_rdatatype_tkey, 0, &name, &tkeyset);
616         if (result != ISC_R_SUCCESS) {
617                 /*
618                  * Try the answer section, since that's where Win2000
619                  * puts it.
620                  */
621                 if (dns_message_findname(msg, DNS_SECTION_ANSWER, qname,
622                                          dns_rdatatype_tkey, 0, &name,
623                                          &tkeyset) != ISC_R_SUCCESS) {
624                         result = DNS_R_FORMERR;
625                         tkey_log("dns_tkey_processquery: couldn't find a TKEY "
626                                  "matching the question");
627                         goto failure;
628                 }
629         }
630         result = dns_rdataset_first(tkeyset);
631         if (result != ISC_R_SUCCESS) {
632                 result = DNS_R_FORMERR;
633                 goto failure;
634         }
635         dns_rdata_init(&rdata);
636         dns_rdataset_current(tkeyset, &rdata);
637
638         RETERR(dns_rdata_tostruct(&rdata, &tkeyin, NULL));
639         freetkeyin = ISC_TRUE;
640
641         if (tkeyin.error != dns_rcode_noerror) {
642                 result = DNS_R_FORMERR;
643                 goto failure;
644         }
645
646         /*
647          * Before we go any farther, verify that the message was signed.
648          * GSSAPI TKEY doesn't require a signature, the rest do.
649          */
650         dns_name_init(&tsigner, NULL);
651         result = dns_message_signer(msg, &tsigner);
652         if (result != ISC_R_SUCCESS) {
653                 if (tkeyin.mode == DNS_TKEYMODE_GSSAPI &&
654                     result == ISC_R_NOTFOUND)
655                        signer = NULL;
656                 else {
657                         tkey_log("dns_tkey_processquery: query was not "
658                                  "properly signed - rejecting");
659                         result = DNS_R_FORMERR;
660                         goto failure;
661                 }
662         } else
663                 signer = &tsigner;
664
665         tkeyout.common.rdclass = tkeyin.common.rdclass;
666         tkeyout.common.rdtype = tkeyin.common.rdtype;
667         ISC_LINK_INIT(&tkeyout.common, link);
668         tkeyout.mctx = msg->mctx;
669
670         dns_name_init(&tkeyout.algorithm, NULL);
671         dns_name_clone(&tkeyin.algorithm, &tkeyout.algorithm);
672
673         tkeyout.inception = tkeyout.expire = 0;
674         tkeyout.mode = tkeyin.mode;
675         tkeyout.error = 0;
676         tkeyout.keylen = tkeyout.otherlen = 0;
677         tkeyout.key = tkeyout.other = NULL;
678
679         /*
680          * A delete operation must have a fully specified key name.  If this
681          * is not a delete, we do the following:
682          * if (qname != ".")
683          *      keyname = qname + defaultdomain
684          * else
685          *      keyname = <random hex> + defaultdomain
686          */
687         if (tkeyin.mode != DNS_TKEYMODE_DELETE) {
688                 dns_tsigkey_t *tsigkey = NULL;
689
690                 if (tctx->domain == NULL && tkeyin.mode != DNS_TKEYMODE_GSSAPI) {
691                         tkey_log("dns_tkey_processquery: tkey-domain not set");
692                         result = DNS_R_REFUSED;
693                         goto failure;
694                 }
695
696                 dns_fixedname_init(&fkeyname);
697                 keyname = dns_fixedname_name(&fkeyname);
698
699                 if (!dns_name_equal(qname, dns_rootname)) {
700                         unsigned int n = dns_name_countlabels(qname);
701                         RUNTIME_CHECK(dns_name_copy(qname, keyname, NULL)
702                                       == ISC_R_SUCCESS);
703                         dns_name_getlabelsequence(keyname, 0, n - 1, keyname);
704                 } else {
705                         static char hexdigits[16] = {
706                                 '0', '1', '2', '3', '4', '5', '6', '7',
707                                 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
708                         unsigned char randomdata[16];
709                         char randomtext[32];
710                         isc_buffer_t b;
711                         unsigned int i, j;
712
713                         result = isc_entropy_getdata(tctx->ectx,
714                                                      randomdata,
715                                                      sizeof(randomdata),
716                                                      NULL, 0);
717                         if (result != ISC_R_SUCCESS)
718                                 goto failure;
719
720                         for (i = 0, j = 0; i < sizeof(randomdata); i++) {
721                                 unsigned char val = randomdata[i];
722                                 randomtext[j++] = hexdigits[val >> 4];
723                                 randomtext[j++] = hexdigits[val & 0xF];
724                         }
725                         isc_buffer_init(&b, randomtext, sizeof(randomtext));
726                         isc_buffer_add(&b, sizeof(randomtext));
727                         result = dns_name_fromtext(keyname, &b, NULL,
728                                                    ISC_FALSE, NULL);
729                         if (result != ISC_R_SUCCESS)
730                                 goto failure;
731                 }
732
733                 if (tkeyin.mode == DNS_TKEYMODE_GSSAPI) {
734                         /* Yup.  This is a hack */
735                         result = dns_name_concatenate(keyname, dns_rootname,
736                                                       keyname, NULL);
737                         if (result != ISC_R_SUCCESS)
738                                 goto failure;
739                 } else {
740                         result = dns_name_concatenate(keyname, tctx->domain,
741                                                       keyname, NULL);
742                         if (result != ISC_R_SUCCESS)
743                                 goto failure;
744                 }
745
746                 result = dns_tsigkey_find(&tsigkey, keyname, NULL, ring);
747
748                 if (result == ISC_R_SUCCESS) {
749                         tkeyout.error = dns_tsigerror_badname;
750                         dns_tsigkey_detach(&tsigkey);
751                         goto failure_with_tkey;
752                 } else if (result != ISC_R_NOTFOUND)
753                         goto failure;
754         } else
755                 keyname = qname;
756
757         switch (tkeyin.mode) {
758                 case DNS_TKEYMODE_DIFFIEHELLMAN:
759                         tkeyout.error = dns_rcode_noerror;
760                         RETERR(process_dhtkey(msg, signer, keyname, &tkeyin,
761                                               tctx, &tkeyout, ring,
762                                               &namelist));
763                         break;
764                 case DNS_TKEYMODE_GSSAPI:
765                         tkeyout.error = dns_rcode_noerror;
766                         RETERR(process_gsstkey(msg, signer, keyname, &tkeyin,
767                                                tctx, &tkeyout, ring,
768                                                &namelist));
769
770                         break;
771                 case DNS_TKEYMODE_DELETE:
772                         tkeyout.error = dns_rcode_noerror;
773                         RETERR(process_deletetkey(msg, signer, keyname,
774                                                   &tkeyin, &tkeyout,
775                                                   ring, &namelist));
776                         break;
777                 case DNS_TKEYMODE_SERVERASSIGNED:
778                 case DNS_TKEYMODE_RESOLVERASSIGNED:
779                         result = DNS_R_NOTIMP;
780                         goto failure;
781                 default:
782                         tkeyout.error = dns_tsigerror_badmode;
783         }
784
785  failure_with_tkey:
786         dns_rdata_init(&rdata);
787         isc_buffer_init(&tkeyoutbuf, tkeyoutdata, sizeof(tkeyoutdata));
788         result = dns_rdata_fromstruct(&rdata, tkeyout.common.rdclass,
789                                       tkeyout.common.rdtype, &tkeyout,
790                                       &tkeyoutbuf);
791
792         if (freetkeyin) {
793                 dns_rdata_freestruct(&tkeyin);
794                 freetkeyin = ISC_FALSE;
795         }
796
797         if (tkeyout.key != NULL)
798                 isc_mem_put(tkeyout.mctx, tkeyout.key, tkeyout.keylen);
799         if (tkeyout.other != NULL)
800                 isc_mem_put(tkeyout.mctx, tkeyout.other, tkeyout.otherlen);
801         if (result != ISC_R_SUCCESS)
802                 goto failure;
803
804         RETERR(add_rdata_to_list(msg, keyname, &rdata, 0, &namelist));
805
806         RETERR(dns_message_reply(msg, ISC_TRUE));
807
808         name = ISC_LIST_HEAD(namelist);
809         while (name != NULL) {
810                 dns_name_t *next = ISC_LIST_NEXT(name, link);
811                 ISC_LIST_UNLINK(namelist, name, link);
812                 dns_message_addname(msg, name, DNS_SECTION_ANSWER);
813                 name = next;
814         }
815
816         return (ISC_R_SUCCESS);
817
818  failure:
819         if (freetkeyin)
820                 dns_rdata_freestruct(&tkeyin);
821         if (!ISC_LIST_EMPTY(namelist))
822                 free_namelist(msg, &namelist);
823         return (result);
824 }
825
826 static isc_result_t
827 buildquery(dns_message_t *msg, dns_name_t *name,
828            dns_rdata_tkey_t *tkey, isc_boolean_t win2k)
829 {
830         dns_name_t *qname = NULL, *aname = NULL;
831         dns_rdataset_t *question = NULL, *tkeyset = NULL;
832         dns_rdatalist_t *tkeylist = NULL;
833         dns_rdata_t *rdata = NULL;
834         isc_buffer_t *dynbuf = NULL;
835         isc_result_t result;
836
837         REQUIRE(msg != NULL);
838         REQUIRE(name != NULL);
839         REQUIRE(tkey != NULL);
840
841         RETERR(dns_message_gettempname(msg, &qname));
842         RETERR(dns_message_gettempname(msg, &aname));
843
844         RETERR(dns_message_gettemprdataset(msg, &question));
845         dns_rdataset_init(question);
846         dns_rdataset_makequestion(question, dns_rdataclass_any,
847                                   dns_rdatatype_tkey);
848
849         RETERR(isc_buffer_allocate(msg->mctx, &dynbuf, 4096));
850         RETERR(dns_message_gettemprdata(msg, &rdata));
851
852         RETERR(dns_rdata_fromstruct(rdata, dns_rdataclass_any,
853                                     dns_rdatatype_tkey, tkey, dynbuf));
854         dns_message_takebuffer(msg, &dynbuf);
855
856         RETERR(dns_message_gettemprdatalist(msg, &tkeylist));
857         tkeylist->rdclass = dns_rdataclass_any;
858         tkeylist->type = dns_rdatatype_tkey;
859         tkeylist->covers = 0;
860         tkeylist->ttl = 0;
861         ISC_LIST_INIT(tkeylist->rdata);
862         ISC_LIST_APPEND(tkeylist->rdata, rdata, link);
863
864         RETERR(dns_message_gettemprdataset(msg, &tkeyset));
865         dns_rdataset_init(tkeyset);
866         RETERR(dns_rdatalist_tordataset(tkeylist, tkeyset));
867
868         dns_name_init(qname, NULL);
869         dns_name_clone(name, qname);
870
871         dns_name_init(aname, NULL);
872         dns_name_clone(name, aname);
873
874         ISC_LIST_APPEND(qname->list, question, link);
875         ISC_LIST_APPEND(aname->list, tkeyset, link);
876
877         dns_message_addname(msg, qname, DNS_SECTION_QUESTION);
878
879         /*
880          * Windows 2000 needs this in the answer section, not the additional
881          * section where the RFC specifies.
882          */
883         if (win2k)
884                 dns_message_addname(msg, aname, DNS_SECTION_ANSWER);
885         else
886                 dns_message_addname(msg, aname, DNS_SECTION_ADDITIONAL);
887
888         return (ISC_R_SUCCESS);
889
890  failure:
891         if (qname != NULL)
892                 dns_message_puttempname(msg, &qname);
893         if (aname != NULL)
894                 dns_message_puttempname(msg, &aname);
895         if (question != NULL) {
896                 dns_rdataset_disassociate(question);
897                 dns_message_puttemprdataset(msg, &question);
898         }
899         if (dynbuf != NULL)
900                 isc_buffer_free(&dynbuf);
901         printf("buildquery error\n");
902         return (result);
903 }
904
905 isc_result_t
906 dns_tkey_builddhquery(dns_message_t *msg, dst_key_t *key, dns_name_t *name,
907                       dns_name_t *algorithm, isc_buffer_t *nonce,
908                       isc_uint32_t lifetime)
909 {
910         dns_rdata_tkey_t tkey;
911         dns_rdata_t *rdata = NULL;
912         isc_buffer_t *dynbuf = NULL;
913         isc_region_t r;
914         dns_name_t keyname;
915         dns_namelist_t namelist;
916         isc_result_t result;
917         isc_stdtime_t now;
918
919         REQUIRE(msg != NULL);
920         REQUIRE(key != NULL);
921         REQUIRE(dst_key_alg(key) == DNS_KEYALG_DH);
922         REQUIRE(dst_key_isprivate(key));
923         REQUIRE(name != NULL);
924         REQUIRE(algorithm != NULL);
925
926         tkey.common.rdclass = dns_rdataclass_any;
927         tkey.common.rdtype = dns_rdatatype_tkey;
928         ISC_LINK_INIT(&tkey.common, link);
929         tkey.mctx = msg->mctx;
930         dns_name_init(&tkey.algorithm, NULL);
931         dns_name_clone(algorithm, &tkey.algorithm);
932         isc_stdtime_get(&now);
933         tkey.inception = now;
934         tkey.expire = now + lifetime;
935         tkey.mode = DNS_TKEYMODE_DIFFIEHELLMAN;
936         if (nonce != NULL)
937                 isc_buffer_usedregion(nonce, &r);
938         else {
939                 r.base = isc_mem_get(msg->mctx, 0);
940                 r.length = 0;
941         }
942         tkey.error = 0;
943         tkey.key = r.base;
944         tkey.keylen =  r.length;
945         tkey.other = NULL;
946         tkey.otherlen = 0;
947
948         RETERR(buildquery(msg, name, &tkey, ISC_FALSE));
949
950         if (nonce == NULL)
951                 isc_mem_put(msg->mctx, r.base, 0);
952
953         RETERR(dns_message_gettemprdata(msg, &rdata));
954         RETERR(isc_buffer_allocate(msg->mctx, &dynbuf, 1024));
955         RETERR(dst_key_todns(key, dynbuf));
956         isc_buffer_usedregion(dynbuf, &r);
957         dns_rdata_fromregion(rdata, dns_rdataclass_any,
958                              dns_rdatatype_key, &r);
959         dns_message_takebuffer(msg, &dynbuf);
960
961         dns_name_init(&keyname, NULL);
962         dns_name_clone(dst_key_name(key), &keyname);
963
964         ISC_LIST_INIT(namelist);
965         RETERR(add_rdata_to_list(msg, &keyname, rdata, 0, &namelist));
966         dns_message_addname(msg, ISC_LIST_HEAD(namelist),
967                             DNS_SECTION_ADDITIONAL);
968
969         return (ISC_R_SUCCESS);
970
971  failure:
972
973         if (dynbuf != NULL)
974                 isc_buffer_free(&dynbuf);
975         return (result);
976 }
977
978 isc_result_t
979 dns_tkey_buildgssquery(dns_message_t *msg, dns_name_t *name, dns_name_t *gname,
980                        isc_buffer_t *intoken, isc_uint32_t lifetime,
981                        gss_ctx_id_t *context, isc_boolean_t win2k)
982 {
983         dns_rdata_tkey_t tkey;
984         isc_result_t result;
985         isc_stdtime_t now;
986         isc_buffer_t token;
987         unsigned char array[4096];
988
989         UNUSED(intoken);
990
991         REQUIRE(msg != NULL);
992         REQUIRE(name != NULL);
993         REQUIRE(gname != NULL);
994         REQUIRE(context != NULL);
995
996         isc_buffer_init(&token, array, sizeof(array));
997         result = dst_gssapi_initctx(gname, NULL, &token, context);
998         if (result != DNS_R_CONTINUE && result != ISC_R_SUCCESS)
999                 return (result);
1000
1001         tkey.common.rdclass = dns_rdataclass_any;
1002         tkey.common.rdtype = dns_rdatatype_tkey;
1003         ISC_LINK_INIT(&tkey.common, link);
1004         tkey.mctx = NULL;
1005         dns_name_init(&tkey.algorithm, NULL);
1006
1007         if (win2k)
1008                 dns_name_clone(DNS_TSIG_GSSAPIMS_NAME, &tkey.algorithm);
1009         else
1010                 dns_name_clone(DNS_TSIG_GSSAPI_NAME, &tkey.algorithm);
1011
1012         isc_stdtime_get(&now);
1013         tkey.inception = now;
1014         tkey.expire = now + lifetime;
1015         tkey.mode = DNS_TKEYMODE_GSSAPI;
1016         tkey.error = 0;
1017         tkey.key = isc_buffer_base(&token);
1018         tkey.keylen = isc_buffer_usedlength(&token);
1019         tkey.other = NULL;
1020         tkey.otherlen = 0;
1021
1022         RETERR(buildquery(msg, name, &tkey, win2k));
1023
1024         return (ISC_R_SUCCESS);
1025
1026  failure:
1027         return (result);
1028 }
1029
1030 isc_result_t
1031 dns_tkey_builddeletequery(dns_message_t *msg, dns_tsigkey_t *key) {
1032         dns_rdata_tkey_t tkey;
1033
1034         REQUIRE(msg != NULL);
1035         REQUIRE(key != NULL);
1036
1037         tkey.common.rdclass = dns_rdataclass_any;
1038         tkey.common.rdtype = dns_rdatatype_tkey;
1039         ISC_LINK_INIT(&tkey.common, link);
1040         tkey.mctx = msg->mctx;
1041         dns_name_init(&tkey.algorithm, NULL);
1042         dns_name_clone(key->algorithm, &tkey.algorithm);
1043         tkey.inception = tkey.expire = 0;
1044         tkey.mode = DNS_TKEYMODE_DELETE;
1045         tkey.error = 0;
1046         tkey.keylen = tkey.otherlen = 0;
1047         tkey.key = tkey.other = NULL;
1048
1049         return (buildquery(msg, &key->name, &tkey, ISC_FALSE));
1050 }
1051
1052 static isc_result_t
1053 find_tkey(dns_message_t *msg, dns_name_t **name, dns_rdata_t *rdata,
1054           int section)
1055 {
1056         dns_rdataset_t *tkeyset;
1057         isc_result_t result;
1058
1059         result = dns_message_firstname(msg, section);
1060         while (result == ISC_R_SUCCESS) {
1061                 *name = NULL;
1062                 dns_message_currentname(msg, section, name);
1063                 tkeyset = NULL;
1064                 result = dns_message_findtype(*name, dns_rdatatype_tkey, 0,
1065                                               &tkeyset);
1066                 if (result == ISC_R_SUCCESS) {
1067                         result = dns_rdataset_first(tkeyset);
1068                         if (result != ISC_R_SUCCESS)
1069                                 return (result);
1070                         dns_rdataset_current(tkeyset, rdata);
1071                         return (ISC_R_SUCCESS);
1072                 }
1073                 result = dns_message_nextname(msg, section);
1074         }
1075         if (result == ISC_R_NOMORE)
1076                 return (ISC_R_NOTFOUND);
1077         return (result);
1078 }
1079
1080 isc_result_t
1081 dns_tkey_processdhresponse(dns_message_t *qmsg, dns_message_t *rmsg,
1082                            dst_key_t *key, isc_buffer_t *nonce,
1083                            dns_tsigkey_t **outkey, dns_tsig_keyring_t *ring)
1084 {
1085         dns_rdata_t qtkeyrdata = DNS_RDATA_INIT, rtkeyrdata = DNS_RDATA_INIT;
1086         dns_name_t keyname, *tkeyname, *theirkeyname, *ourkeyname, *tempname;
1087         dns_rdataset_t *theirkeyset = NULL, *ourkeyset = NULL;
1088         dns_rdata_t theirkeyrdata = DNS_RDATA_INIT;
1089         dst_key_t *theirkey = NULL;
1090         dns_rdata_tkey_t qtkey, rtkey;
1091         unsigned char secretdata[256];
1092         unsigned int sharedsize;
1093         isc_buffer_t *shared = NULL, secret;
1094         isc_region_t r, r2;
1095         isc_result_t result;
1096         isc_boolean_t freertkey = ISC_FALSE;
1097
1098         REQUIRE(qmsg != NULL);
1099         REQUIRE(rmsg != NULL);
1100         REQUIRE(key != NULL);
1101         REQUIRE(dst_key_alg(key) == DNS_KEYALG_DH);
1102         REQUIRE(dst_key_isprivate(key));
1103         if (outkey != NULL)
1104                 REQUIRE(*outkey == NULL);
1105
1106         if (rmsg->rcode != dns_rcode_noerror)
1107                 return (ISC_RESULTCLASS_DNSRCODE + rmsg->rcode);
1108         RETERR(find_tkey(rmsg, &tkeyname, &rtkeyrdata, DNS_SECTION_ANSWER));
1109         RETERR(dns_rdata_tostruct(&rtkeyrdata, &rtkey, NULL));
1110         freertkey = ISC_TRUE;
1111
1112         RETERR(find_tkey(qmsg, &tempname, &qtkeyrdata,
1113                          DNS_SECTION_ADDITIONAL));
1114         RETERR(dns_rdata_tostruct(&qtkeyrdata, &qtkey, NULL));
1115
1116         if (rtkey.error != dns_rcode_noerror ||
1117             rtkey.mode != DNS_TKEYMODE_DIFFIEHELLMAN ||
1118             rtkey.mode != qtkey.mode ||
1119             !dns_name_equal(&rtkey.algorithm, &qtkey.algorithm) ||
1120             rmsg->rcode != dns_rcode_noerror) {
1121                 tkey_log("dns_tkey_processdhresponse: tkey mode invalid "
1122                          "or error set(1)");
1123                 result = DNS_R_INVALIDTKEY;
1124                 dns_rdata_freestruct(&qtkey);
1125                 goto failure;
1126         }
1127
1128         dns_rdata_freestruct(&qtkey);
1129
1130         dns_name_init(&keyname, NULL);
1131         dns_name_clone(dst_key_name(key), &keyname);
1132
1133         ourkeyname = NULL;
1134         ourkeyset = NULL;
1135         RETERR(dns_message_findname(rmsg, DNS_SECTION_ANSWER, &keyname,
1136                                     dns_rdatatype_key, 0, &ourkeyname,
1137                                     &ourkeyset));
1138
1139         result = dns_message_firstname(rmsg, DNS_SECTION_ANSWER);
1140         while (result == ISC_R_SUCCESS) {
1141                 theirkeyname = NULL;
1142                 dns_message_currentname(rmsg, DNS_SECTION_ANSWER,
1143                                         &theirkeyname);
1144                 if (dns_name_equal(theirkeyname, ourkeyname))
1145                         goto next;
1146                 theirkeyset = NULL;
1147                 result = dns_message_findtype(theirkeyname, dns_rdatatype_key,
1148                                               0, &theirkeyset);
1149                 if (result == ISC_R_SUCCESS) {
1150                         RETERR(dns_rdataset_first(theirkeyset));
1151                         break;
1152                 }
1153  next:
1154                 result = dns_message_nextname(rmsg, DNS_SECTION_ANSWER);
1155         }
1156
1157         if (theirkeyset == NULL) {
1158                 tkey_log("dns_tkey_processdhresponse: failed to find server "
1159                          "key");
1160                 result = ISC_R_NOTFOUND;
1161                 goto failure;
1162         }
1163
1164         dns_rdataset_current(theirkeyset, &theirkeyrdata);
1165         RETERR(dns_dnssec_keyfromrdata(theirkeyname, &theirkeyrdata,
1166                                        rmsg->mctx, &theirkey));
1167
1168         RETERR(dst_key_secretsize(key, &sharedsize));
1169         RETERR(isc_buffer_allocate(rmsg->mctx, &shared, sharedsize));
1170
1171         RETERR(dst_key_computesecret(theirkey, key, shared));
1172
1173         isc_buffer_init(&secret, secretdata, sizeof(secretdata));
1174
1175         r.base = rtkey.key;
1176         r.length = rtkey.keylen;
1177         if (nonce != NULL)
1178                 isc_buffer_usedregion(nonce, &r2);
1179         else {
1180                 r2.base = isc_mem_get(rmsg->mctx, 0);
1181                 r2.length = 0;
1182         }
1183         RETERR(compute_secret(shared, &r2, &r, &secret));
1184         if (nonce == NULL)
1185                 isc_mem_put(rmsg->mctx, r2.base, 0);
1186
1187         isc_buffer_usedregion(&secret, &r);
1188         result = dns_tsigkey_create(tkeyname, &rtkey.algorithm,
1189                                     r.base, r.length, ISC_TRUE,
1190                                     NULL, rtkey.inception, rtkey.expire,
1191                                     rmsg->mctx, ring, outkey);
1192         isc_buffer_free(&shared);
1193         dns_rdata_freestruct(&rtkey);
1194         dst_key_free(&theirkey);
1195         return (result);
1196
1197  failure:
1198         if (shared != NULL)
1199                 isc_buffer_free(&shared);
1200
1201         if (theirkey != NULL)
1202                 dst_key_free(&theirkey);
1203
1204         if (freertkey)
1205                 dns_rdata_freestruct(&rtkey);
1206
1207         return (result);
1208 }
1209
1210 isc_result_t
1211 dns_tkey_processgssresponse(dns_message_t *qmsg, dns_message_t *rmsg,
1212                             dns_name_t *gname, gss_ctx_id_t *context,
1213                             isc_buffer_t *outtoken, dns_tsigkey_t **outkey,
1214                             dns_tsig_keyring_t *ring)
1215 {
1216         dns_rdata_t rtkeyrdata = DNS_RDATA_INIT, qtkeyrdata = DNS_RDATA_INIT;
1217         dns_name_t *tkeyname;
1218         dns_rdata_tkey_t rtkey, qtkey;
1219         dst_key_t *dstkey = NULL;
1220         isc_buffer_t intoken;
1221         isc_result_t result;
1222         unsigned char array[1024];
1223
1224         REQUIRE(outtoken != NULL);
1225         REQUIRE(qmsg != NULL);
1226         REQUIRE(rmsg != NULL);
1227         REQUIRE(gname != NULL);
1228         if (outkey != NULL)
1229                 REQUIRE(*outkey == NULL);
1230
1231         if (rmsg->rcode != dns_rcode_noerror)
1232                 return (ISC_RESULTCLASS_DNSRCODE + rmsg->rcode);
1233         RETERR(find_tkey(rmsg, &tkeyname, &rtkeyrdata, DNS_SECTION_ANSWER));
1234         RETERR(dns_rdata_tostruct(&rtkeyrdata, &rtkey, NULL));
1235
1236         /*
1237          * Win2k puts the item in the ANSWER section, while the RFC
1238          * specifies it should be in the ADDITIONAL section.  Check first
1239          * where it should be, and then where it may be.
1240          */
1241         result = find_tkey(qmsg, &tkeyname, &qtkeyrdata,
1242                            DNS_SECTION_ADDITIONAL);
1243         if (result == ISC_R_NOTFOUND)
1244                 result = find_tkey(qmsg, &tkeyname, &qtkeyrdata,
1245                                    DNS_SECTION_ANSWER);
1246         if (result != ISC_R_SUCCESS)
1247                 goto failure;
1248
1249         RETERR(dns_rdata_tostruct(&qtkeyrdata, &qtkey, NULL));
1250
1251         if (rtkey.error != dns_rcode_noerror ||
1252             rtkey.mode != DNS_TKEYMODE_GSSAPI ||
1253             !dns_name_equal(&rtkey.algorithm, &qtkey.algorithm)) {
1254                 tkey_log("dns_tkey_processgssresponse: tkey mode invalid "
1255                          "or error set(2) %d", rtkey.error);
1256                 _dns_tkey_dumpmessage(qmsg);
1257                 _dns_tkey_dumpmessage(rmsg);
1258                 result = DNS_R_INVALIDTKEY;
1259                 goto failure;
1260         }
1261
1262         isc_buffer_init(outtoken, array, sizeof(array));
1263         isc_buffer_init(&intoken, rtkey.key, rtkey.keylen);
1264         RETERR(dst_gssapi_initctx(gname, &intoken, outtoken, context));
1265
1266         dstkey = NULL;
1267         RETERR(dst_key_fromgssapi(dns_rootname, *context, rmsg->mctx,
1268                                   &dstkey));
1269
1270         RETERR(dns_tsigkey_createfromkey(tkeyname, DNS_TSIG_GSSAPI_NAME,
1271                                          dstkey, ISC_FALSE, NULL,
1272                                          rtkey.inception, rtkey.expire,
1273                                          ring->mctx, ring, outkey));
1274
1275         dns_rdata_freestruct(&rtkey);
1276         return (result);
1277
1278  failure:
1279         /*
1280          * XXXSRA This probably leaks memory from rtkey and qtkey.
1281          */
1282         return (result);
1283 }
1284
1285 isc_result_t
1286 dns_tkey_processdeleteresponse(dns_message_t *qmsg, dns_message_t *rmsg,
1287                                dns_tsig_keyring_t *ring)
1288 {
1289         dns_rdata_t qtkeyrdata = DNS_RDATA_INIT, rtkeyrdata = DNS_RDATA_INIT;
1290         dns_name_t *tkeyname, *tempname;
1291         dns_rdata_tkey_t qtkey, rtkey;
1292         dns_tsigkey_t *tsigkey = NULL;
1293         isc_result_t result;
1294
1295         REQUIRE(qmsg != NULL);
1296         REQUIRE(rmsg != NULL);
1297
1298         if (rmsg->rcode != dns_rcode_noerror)
1299                 return(ISC_RESULTCLASS_DNSRCODE + rmsg->rcode);
1300
1301         RETERR(find_tkey(rmsg, &tkeyname, &rtkeyrdata, DNS_SECTION_ANSWER));
1302         RETERR(dns_rdata_tostruct(&rtkeyrdata, &rtkey, NULL));
1303
1304         RETERR(find_tkey(qmsg, &tempname, &qtkeyrdata,
1305                          DNS_SECTION_ADDITIONAL));
1306         RETERR(dns_rdata_tostruct(&qtkeyrdata, &qtkey, NULL));
1307
1308         if (rtkey.error != dns_rcode_noerror ||
1309             rtkey.mode != DNS_TKEYMODE_DELETE ||
1310             rtkey.mode != qtkey.mode ||
1311             !dns_name_equal(&rtkey.algorithm, &qtkey.algorithm) ||
1312             rmsg->rcode != dns_rcode_noerror) {
1313                 tkey_log("dns_tkey_processdeleteresponse: tkey mode invalid "
1314                          "or error set(3)");
1315                 result = DNS_R_INVALIDTKEY;
1316                 dns_rdata_freestruct(&qtkey);
1317                 dns_rdata_freestruct(&rtkey);
1318                 goto failure;
1319         }
1320
1321         dns_rdata_freestruct(&qtkey);
1322
1323         RETERR(dns_tsigkey_find(&tsigkey, tkeyname, &rtkey.algorithm, ring));
1324
1325         dns_rdata_freestruct(&rtkey);
1326
1327         /*
1328          * Mark the key as deleted.
1329          */
1330         dns_tsigkey_setdeleted(tsigkey);
1331         /*
1332          * Release the reference.
1333          */
1334         dns_tsigkey_detach(&tsigkey);
1335
1336  failure:
1337         return (result);
1338 }
1339
1340 isc_result_t
1341 dns_tkey_gssnegotiate(dns_message_t *qmsg, dns_message_t *rmsg,
1342                       dns_name_t *server, gss_ctx_id_t *context,
1343                       dns_tsigkey_t **outkey, dns_tsig_keyring_t *ring,
1344                       isc_boolean_t win2k)
1345 {
1346         dns_rdata_t rtkeyrdata = DNS_RDATA_INIT, qtkeyrdata = DNS_RDATA_INIT;
1347         dns_name_t *tkeyname;
1348         dns_rdata_tkey_t rtkey, qtkey;
1349         isc_buffer_t intoken, outtoken;
1350         dst_key_t *dstkey = NULL;
1351         isc_result_t result;
1352         unsigned char array[1024];
1353
1354         REQUIRE(qmsg != NULL);
1355         REQUIRE(rmsg != NULL);
1356         REQUIRE(server != NULL);
1357         if (outkey != NULL)
1358                 REQUIRE(*outkey == NULL);
1359
1360         if (rmsg->rcode != dns_rcode_noerror)
1361                 return (ISC_RESULTCLASS_DNSRCODE + rmsg->rcode);
1362
1363         RETERR(find_tkey(rmsg, &tkeyname, &rtkeyrdata, DNS_SECTION_ANSWER));
1364         RETERR(dns_rdata_tostruct(&rtkeyrdata, &rtkey, NULL));
1365
1366         if (win2k == ISC_TRUE)
1367                 RETERR(find_tkey(qmsg, &tkeyname, &qtkeyrdata,
1368                          DNS_SECTION_ANSWER));
1369         else
1370                 RETERR(find_tkey(qmsg, &tkeyname, &qtkeyrdata,
1371                          DNS_SECTION_ADDITIONAL));
1372
1373         RETERR(dns_rdata_tostruct(&qtkeyrdata, &qtkey, NULL));
1374
1375         if (rtkey.error != dns_rcode_noerror ||
1376             rtkey.mode != DNS_TKEYMODE_GSSAPI ||
1377             !dns_name_equal(&rtkey.algorithm, &qtkey.algorithm))
1378         {
1379                 tkey_log("dns_tkey_processdhresponse: tkey mode invalid "
1380                          "or error set(4)");
1381                 result = DNS_R_INVALIDTKEY;
1382                 goto failure;
1383         }
1384
1385         isc_buffer_init(&intoken, rtkey.key, rtkey.keylen);
1386         isc_buffer_init(&outtoken, array, sizeof(array));
1387
1388         result = dst_gssapi_initctx(server, &intoken, &outtoken, context);
1389         if (result != DNS_R_CONTINUE && result != ISC_R_SUCCESS)
1390                 return (result);
1391
1392         dstkey = NULL;
1393         RETERR(dst_key_fromgssapi(dns_rootname, *context, rmsg->mctx,
1394                                   &dstkey));
1395
1396         /*
1397          * XXXSRA This seems confused.  If we got CONTINUE from initctx,
1398          * the GSS negotiation hasn't completed yet, so we can't sign
1399          * anything yet.
1400          */
1401
1402         RETERR(dns_tsigkey_createfromkey(tkeyname,
1403                                          (win2k
1404                                           ? DNS_TSIG_GSSAPIMS_NAME
1405                                           : DNS_TSIG_GSSAPI_NAME),
1406                                          dstkey, ISC_TRUE, NULL,
1407                                          rtkey.inception, rtkey.expire,
1408                                          ring->mctx, ring, outkey));
1409
1410         dns_rdata_freestruct(&rtkey);
1411         return (result);
1412
1413  failure:
1414         /*
1415          * XXXSRA This probably leaks memory from qtkey.
1416          */
1417         dns_rdata_freestruct(&rtkey);
1418         return (result);
1419 }