cvs updates from Wed Dec 15 17:45:22 EST 2010
[tridge/bind9.git] / lib / dns / tkey.c
1 /*
2  * Copyright (C) 2004-2010  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.96 2010/12/09 00:54:34 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_name_t *name, dns_rdata_tkey_t *tkeyin,
421                 dns_tkeyctx_t *tctx, dns_rdata_tkey_t *tkeyout,
422                 dns_tsig_keyring_t *ring)
423 {
424         isc_result_t result = ISC_R_SUCCESS;
425         dst_key_t *dstkey = NULL;
426         dns_tsigkey_t *tsigkey = NULL;
427         dns_fixedname_t principal;
428         isc_stdtime_t now;
429         isc_region_t intoken;
430         isc_buffer_t *outtoken = NULL;
431         gss_ctx_id_t gss_ctx = NULL;
432
433         if (tctx->gsscred == NULL)
434                 return (ISC_R_NOPERM);
435
436         if (!dns_name_equal(&tkeyin->algorithm, DNS_TSIG_GSSAPI_NAME) &&
437             !dns_name_equal(&tkeyin->algorithm, DNS_TSIG_GSSAPIMS_NAME)) {
438                 tkeyout->error = dns_tsigerror_badalg;
439                 tkey_log("process_gsstkey(): dns_tsigerror_badalg");    /* XXXSRA */
440                 return (ISC_R_SUCCESS);
441         }
442
443         /*
444          * XXXDCL need to check for key expiry per 4.1.1
445          * XXXDCL need a way to check fully established, perhaps w/key_flags
446          */
447
448         intoken.base = tkeyin->key;
449         intoken.length = tkeyin->keylen;
450
451         result = dns_tsigkey_find(&tsigkey, name, &tkeyin->algorithm, ring);
452         if (result == ISC_R_SUCCESS)
453                 gss_ctx = dst_key_getgssctx(tsigkey->key);
454
455         dns_fixedname_init(&principal);
456
457         result = dst_gssapi_acceptctx(tctx->gsscred, &intoken,
458                                       &outtoken, &gss_ctx,
459                                       dns_fixedname_name(&principal),
460                                       tctx->mctx);
461         if (result == DNS_R_INVALIDTKEY) {
462                 if (tsigkey != NULL)
463                         dns_tsigkey_detach(&tsigkey);
464                 tkeyout->error = dns_tsigerror_badkey;
465                 tkey_log("process_gsstkey(): dns_tsigerror_badkey");    /* XXXSRA */
466                 return (ISC_R_SUCCESS);
467         } else if (result == ISC_R_FAILURE)
468                 goto failure;
469         ENSURE(result == DNS_R_CONTINUE || result == ISC_R_SUCCESS);
470         /*
471          * XXXDCL Section 4.1.3: Limit GSS_S_CONTINUE_NEEDED to 10 times.
472          */
473
474         isc_stdtime_get(&now);
475
476         if (tsigkey == NULL) {
477 #ifdef GSSAPI
478                 OM_uint32 gret, minor, lifetime;
479 #endif
480                 isc_uint32_t expire;
481
482                 RETERR(dst_key_fromgssapi(name, gss_ctx, ring->mctx, &dstkey));
483                 /*
484                  * Limit keys to 1 hour or the context's lifetime whichever
485                  * is smaller.
486                  */
487                 expire = now + 3600;
488 #ifdef GSSAPI
489                 gret = gss_context_time(&minor, gss_ctx, &lifetime);
490                 if (gret == GSS_S_COMPLETE && now + lifetime < expire)
491                         expire = now + lifetime;
492 #endif
493                 RETERR(dns_tsigkey_createfromkey(name, &tkeyin->algorithm,
494                                                  dstkey, ISC_TRUE,
495                                                  dns_fixedname_name(&principal),
496                                                  now, expire, ring->mctx, ring,
497                                                  NULL));
498                 dst_key_free(&dstkey);
499                 tkeyout->inception = now;
500                 tkeyout->expire = expire;
501         } else {
502                 tkeyout->inception = tsigkey->inception;
503                 tkeyout->expire = tkeyout->expire;
504                 dns_tsigkey_detach(&tsigkey);
505         }
506
507         if (outtoken) {
508                 tkeyout->key = isc_mem_get(tkeyout->mctx,
509                                            isc_buffer_usedlength(outtoken));
510                 if (tkeyout->key == NULL) {
511                         result = ISC_R_NOMEMORY;
512                         goto failure;
513                 }
514                 tkeyout->keylen = isc_buffer_usedlength(outtoken);
515                 memcpy(tkeyout->key, isc_buffer_base(outtoken),
516                        isc_buffer_usedlength(outtoken));
517                 isc_buffer_free(&outtoken);
518         } else {
519                 tkeyout->key = isc_mem_get(tkeyout->mctx, tkeyin->keylen);
520                 if (tkeyout->key == NULL) {
521                         result = ISC_R_NOMEMORY;
522                         goto failure;
523                 }
524                 tkeyout->keylen = tkeyin->keylen;
525                 memcpy(tkeyout->key, tkeyin->key, tkeyin->keylen);
526         }
527
528         tkeyout->error = dns_rcode_noerror;
529
530         tkey_log("process_gsstkey(): dns_tsigerror_noerror");   /* XXXSRA */
531
532         return (ISC_R_SUCCESS);
533
534 failure:
535         if (tsigkey != NULL)
536                 dns_tsigkey_detach(&tsigkey);
537
538         if (dstkey != NULL)
539                 dst_key_free(&dstkey);
540
541         if (outtoken != NULL)
542                 isc_buffer_free(&outtoken);
543
544         tkey_log("process_gsstkey(): %s",
545                 isc_result_totext(result));     /* XXXSRA */
546
547         return (result);
548 }
549
550 static isc_result_t
551 process_deletetkey(dns_name_t *signer, dns_name_t *name,
552                    dns_rdata_tkey_t *tkeyin, dns_rdata_tkey_t *tkeyout,
553                    dns_tsig_keyring_t *ring)
554 {
555         isc_result_t result;
556         dns_tsigkey_t *tsigkey = NULL;
557         dns_name_t *identity;
558
559         result = dns_tsigkey_find(&tsigkey, name, &tkeyin->algorithm, ring);
560         if (result != ISC_R_SUCCESS) {
561                 tkeyout->error = dns_tsigerror_badname;
562                 return (ISC_R_SUCCESS);
563         }
564
565         /*
566          * Only allow a delete if the identity that created the key is the
567          * same as the identity that signed the message.
568          */
569         identity = dns_tsigkey_identity(tsigkey);
570         if (identity == NULL || !dns_name_equal(identity, signer)) {
571                 dns_tsigkey_detach(&tsigkey);
572                 return (DNS_R_REFUSED);
573         }
574
575         /*
576          * Set the key to be deleted when no references are left.  If the key
577          * was not generated with TKEY and is in the config file, it may be
578          * reloaded later.
579          */
580         dns_tsigkey_setdeleted(tsigkey);
581
582         /* Release the reference */
583         dns_tsigkey_detach(&tsigkey);
584
585         return (ISC_R_SUCCESS);
586 }
587
588 isc_result_t
589 dns_tkey_processquery(dns_message_t *msg, dns_tkeyctx_t *tctx,
590                       dns_tsig_keyring_t *ring)
591 {
592         isc_result_t result = ISC_R_SUCCESS;
593         dns_rdata_tkey_t tkeyin, tkeyout;
594         isc_boolean_t freetkeyin = ISC_FALSE;
595         dns_name_t *qname, *name, *keyname, *signer, tsigner;
596         dns_fixedname_t fkeyname;
597         dns_rdataset_t *tkeyset;
598         dns_rdata_t rdata;
599         dns_namelist_t namelist;
600         char tkeyoutdata[512];
601         isc_buffer_t tkeyoutbuf;
602
603         REQUIRE(msg != NULL);
604         REQUIRE(tctx != NULL);
605         REQUIRE(ring != NULL);
606
607         ISC_LIST_INIT(namelist);
608
609         /*
610          * Interpret the question section.
611          */
612         result = dns_message_firstname(msg, DNS_SECTION_QUESTION);
613         if (result != ISC_R_SUCCESS)
614                 return (DNS_R_FORMERR);
615
616         qname = NULL;
617         dns_message_currentname(msg, DNS_SECTION_QUESTION, &qname);
618
619         /*
620          * Look for a TKEY record that matches the question.
621          */
622         tkeyset = NULL;
623         name = NULL;
624         result = dns_message_findname(msg, DNS_SECTION_ADDITIONAL, qname,
625                                       dns_rdatatype_tkey, 0, &name, &tkeyset);
626         if (result != ISC_R_SUCCESS) {
627                 /*
628                  * Try the answer section, since that's where Win2000
629                  * puts it.
630                  */
631                 if (dns_message_findname(msg, DNS_SECTION_ANSWER, qname,
632                                          dns_rdatatype_tkey, 0, &name,
633                                          &tkeyset) != ISC_R_SUCCESS) {
634                         result = DNS_R_FORMERR;
635                         tkey_log("dns_tkey_processquery: couldn't find a TKEY "
636                                  "matching the question");
637                         goto failure;
638                 }
639         }
640         result = dns_rdataset_first(tkeyset);
641         if (result != ISC_R_SUCCESS) {
642                 result = DNS_R_FORMERR;
643                 goto failure;
644         }
645         dns_rdata_init(&rdata);
646         dns_rdataset_current(tkeyset, &rdata);
647
648         RETERR(dns_rdata_tostruct(&rdata, &tkeyin, NULL));
649         freetkeyin = ISC_TRUE;
650
651         if (tkeyin.error != dns_rcode_noerror) {
652                 result = DNS_R_FORMERR;
653                 goto failure;
654         }
655
656         /*
657          * Before we go any farther, verify that the message was signed.
658          * GSSAPI TKEY doesn't require a signature, the rest do.
659          */
660         dns_name_init(&tsigner, NULL);
661         result = dns_message_signer(msg, &tsigner);
662         if (result != ISC_R_SUCCESS) {
663                 if (tkeyin.mode == DNS_TKEYMODE_GSSAPI &&
664                     result == ISC_R_NOTFOUND)
665                        signer = NULL;
666                 else {
667                         tkey_log("dns_tkey_processquery: query was not "
668                                  "properly signed - rejecting");
669                         result = DNS_R_FORMERR;
670                         goto failure;
671                 }
672         } else
673                 signer = &tsigner;
674
675         tkeyout.common.rdclass = tkeyin.common.rdclass;
676         tkeyout.common.rdtype = tkeyin.common.rdtype;
677         ISC_LINK_INIT(&tkeyout.common, link);
678         tkeyout.mctx = msg->mctx;
679
680         dns_name_init(&tkeyout.algorithm, NULL);
681         dns_name_clone(&tkeyin.algorithm, &tkeyout.algorithm);
682
683         tkeyout.inception = tkeyout.expire = 0;
684         tkeyout.mode = tkeyin.mode;
685         tkeyout.error = 0;
686         tkeyout.keylen = tkeyout.otherlen = 0;
687         tkeyout.key = tkeyout.other = NULL;
688
689         /*
690          * A delete operation must have a fully specified key name.  If this
691          * is not a delete, we do the following:
692          * if (qname != ".")
693          *      keyname = qname + defaultdomain
694          * else
695          *      keyname = <random hex> + defaultdomain
696          */
697         if (tkeyin.mode != DNS_TKEYMODE_DELETE) {
698                 dns_tsigkey_t *tsigkey = NULL;
699
700                 if (tctx->domain == NULL && tkeyin.mode != DNS_TKEYMODE_GSSAPI) {
701                         tkey_log("dns_tkey_processquery: tkey-domain not set");
702                         result = DNS_R_REFUSED;
703                         goto failure;
704                 }
705
706                 dns_fixedname_init(&fkeyname);
707                 keyname = dns_fixedname_name(&fkeyname);
708
709                 if (!dns_name_equal(qname, dns_rootname)) {
710                         unsigned int n = dns_name_countlabels(qname);
711                         RUNTIME_CHECK(dns_name_copy(qname, keyname, NULL)
712                                       == ISC_R_SUCCESS);
713                         dns_name_getlabelsequence(keyname, 0, n - 1, keyname);
714                 } else {
715                         static char hexdigits[16] = {
716                                 '0', '1', '2', '3', '4', '5', '6', '7',
717                                 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
718                         unsigned char randomdata[16];
719                         char randomtext[32];
720                         isc_buffer_t b;
721                         unsigned int i, j;
722
723                         result = isc_entropy_getdata(tctx->ectx,
724                                                      randomdata,
725                                                      sizeof(randomdata),
726                                                      NULL, 0);
727                         if (result != ISC_R_SUCCESS)
728                                 goto failure;
729
730                         for (i = 0, j = 0; i < sizeof(randomdata); i++) {
731                                 unsigned char val = randomdata[i];
732                                 randomtext[j++] = hexdigits[val >> 4];
733                                 randomtext[j++] = hexdigits[val & 0xF];
734                         }
735                         isc_buffer_init(&b, randomtext, sizeof(randomtext));
736                         isc_buffer_add(&b, sizeof(randomtext));
737                         result = dns_name_fromtext(keyname, &b, NULL, 0, NULL);
738                         if (result != ISC_R_SUCCESS)
739                                 goto failure;
740                 }
741
742                 if (tkeyin.mode == DNS_TKEYMODE_GSSAPI) {
743                         /* Yup.  This is a hack */
744                         result = dns_name_concatenate(keyname, dns_rootname,
745                                                       keyname, NULL);
746                         if (result != ISC_R_SUCCESS)
747                                 goto failure;
748                 } else {
749                         result = dns_name_concatenate(keyname, tctx->domain,
750                                                       keyname, NULL);
751                         if (result != ISC_R_SUCCESS)
752                                 goto failure;
753                 }
754
755                 result = dns_tsigkey_find(&tsigkey, keyname, NULL, ring);
756
757                 if (result == ISC_R_SUCCESS) {
758                         tkeyout.error = dns_tsigerror_badname;
759                         dns_tsigkey_detach(&tsigkey);
760                         goto failure_with_tkey;
761                 } else if (result != ISC_R_NOTFOUND)
762                         goto failure;
763         } else
764                 keyname = qname;
765
766         switch (tkeyin.mode) {
767                 case DNS_TKEYMODE_DIFFIEHELLMAN:
768                         tkeyout.error = dns_rcode_noerror;
769                         RETERR(process_dhtkey(msg, signer, keyname, &tkeyin,
770                                               tctx, &tkeyout, ring,
771                                               &namelist));
772                         break;
773                 case DNS_TKEYMODE_GSSAPI:
774                         tkeyout.error = dns_rcode_noerror;
775                         RETERR(process_gsstkey(keyname, &tkeyin, tctx,
776                                                &tkeyout, ring));
777                         break;
778                 case DNS_TKEYMODE_DELETE:
779                         tkeyout.error = dns_rcode_noerror;
780                         RETERR(process_deletetkey(signer, keyname, &tkeyin,
781                                                   &tkeyout, ring));
782                         break;
783                 case DNS_TKEYMODE_SERVERASSIGNED:
784                 case DNS_TKEYMODE_RESOLVERASSIGNED:
785                         result = DNS_R_NOTIMP;
786                         goto failure;
787                 default:
788                         tkeyout.error = dns_tsigerror_badmode;
789         }
790
791  failure_with_tkey:
792         dns_rdata_init(&rdata);
793         isc_buffer_init(&tkeyoutbuf, tkeyoutdata, sizeof(tkeyoutdata));
794         result = dns_rdata_fromstruct(&rdata, tkeyout.common.rdclass,
795                                       tkeyout.common.rdtype, &tkeyout,
796                                       &tkeyoutbuf);
797
798         if (freetkeyin) {
799                 dns_rdata_freestruct(&tkeyin);
800                 freetkeyin = ISC_FALSE;
801         }
802
803         if (tkeyout.key != NULL)
804                 isc_mem_put(tkeyout.mctx, tkeyout.key, tkeyout.keylen);
805         if (tkeyout.other != NULL)
806                 isc_mem_put(tkeyout.mctx, tkeyout.other, tkeyout.otherlen);
807         if (result != ISC_R_SUCCESS)
808                 goto failure;
809
810         RETERR(add_rdata_to_list(msg, keyname, &rdata, 0, &namelist));
811
812         RETERR(dns_message_reply(msg, ISC_TRUE));
813
814         name = ISC_LIST_HEAD(namelist);
815         while (name != NULL) {
816                 dns_name_t *next = ISC_LIST_NEXT(name, link);
817                 ISC_LIST_UNLINK(namelist, name, link);
818                 dns_message_addname(msg, name, DNS_SECTION_ANSWER);
819                 name = next;
820         }
821
822         return (ISC_R_SUCCESS);
823
824  failure:
825         if (freetkeyin)
826                 dns_rdata_freestruct(&tkeyin);
827         if (!ISC_LIST_EMPTY(namelist))
828                 free_namelist(msg, &namelist);
829         return (result);
830 }
831
832 static isc_result_t
833 buildquery(dns_message_t *msg, dns_name_t *name,
834            dns_rdata_tkey_t *tkey, isc_boolean_t win2k)
835 {
836         dns_name_t *qname = NULL, *aname = NULL;
837         dns_rdataset_t *question = NULL, *tkeyset = NULL;
838         dns_rdatalist_t *tkeylist = NULL;
839         dns_rdata_t *rdata = NULL;
840         isc_buffer_t *dynbuf = NULL;
841         isc_result_t result;
842
843         REQUIRE(msg != NULL);
844         REQUIRE(name != NULL);
845         REQUIRE(tkey != NULL);
846
847         RETERR(dns_message_gettempname(msg, &qname));
848         RETERR(dns_message_gettempname(msg, &aname));
849
850         RETERR(dns_message_gettemprdataset(msg, &question));
851         dns_rdataset_init(question);
852         dns_rdataset_makequestion(question, dns_rdataclass_any,
853                                   dns_rdatatype_tkey);
854
855         RETERR(isc_buffer_allocate(msg->mctx, &dynbuf, 4096));
856         RETERR(dns_message_gettemprdata(msg, &rdata));
857
858         RETERR(dns_rdata_fromstruct(rdata, dns_rdataclass_any,
859                                     dns_rdatatype_tkey, tkey, dynbuf));
860         dns_message_takebuffer(msg, &dynbuf);
861
862         RETERR(dns_message_gettemprdatalist(msg, &tkeylist));
863         tkeylist->rdclass = dns_rdataclass_any;
864         tkeylist->type = dns_rdatatype_tkey;
865         tkeylist->covers = 0;
866         tkeylist->ttl = 0;
867         ISC_LIST_INIT(tkeylist->rdata);
868         ISC_LIST_APPEND(tkeylist->rdata, rdata, link);
869
870         RETERR(dns_message_gettemprdataset(msg, &tkeyset));
871         dns_rdataset_init(tkeyset);
872         RETERR(dns_rdatalist_tordataset(tkeylist, tkeyset));
873
874         dns_name_init(qname, NULL);
875         dns_name_clone(name, qname);
876
877         dns_name_init(aname, NULL);
878         dns_name_clone(name, aname);
879
880         ISC_LIST_APPEND(qname->list, question, link);
881         ISC_LIST_APPEND(aname->list, tkeyset, link);
882
883         dns_message_addname(msg, qname, DNS_SECTION_QUESTION);
884
885         /*
886          * Windows 2000 needs this in the answer section, not the additional
887          * section where the RFC specifies.
888          */
889         if (win2k)
890                 dns_message_addname(msg, aname, DNS_SECTION_ANSWER);
891         else
892                 dns_message_addname(msg, aname, DNS_SECTION_ADDITIONAL);
893
894         return (ISC_R_SUCCESS);
895
896  failure:
897         if (qname != NULL)
898                 dns_message_puttempname(msg, &qname);
899         if (aname != NULL)
900                 dns_message_puttempname(msg, &aname);
901         if (question != NULL) {
902                 dns_rdataset_disassociate(question);
903                 dns_message_puttemprdataset(msg, &question);
904         }
905         if (dynbuf != NULL)
906                 isc_buffer_free(&dynbuf);
907         printf("buildquery error\n");
908         return (result);
909 }
910
911 isc_result_t
912 dns_tkey_builddhquery(dns_message_t *msg, dst_key_t *key, dns_name_t *name,
913                       dns_name_t *algorithm, isc_buffer_t *nonce,
914                       isc_uint32_t lifetime)
915 {
916         dns_rdata_tkey_t tkey;
917         dns_rdata_t *rdata = NULL;
918         isc_buffer_t *dynbuf = NULL;
919         isc_region_t r;
920         dns_name_t keyname;
921         dns_namelist_t namelist;
922         isc_result_t result;
923         isc_stdtime_t now;
924
925         REQUIRE(msg != NULL);
926         REQUIRE(key != NULL);
927         REQUIRE(dst_key_alg(key) == DNS_KEYALG_DH);
928         REQUIRE(dst_key_isprivate(key));
929         REQUIRE(name != NULL);
930         REQUIRE(algorithm != NULL);
931
932         tkey.common.rdclass = dns_rdataclass_any;
933         tkey.common.rdtype = dns_rdatatype_tkey;
934         ISC_LINK_INIT(&tkey.common, link);
935         tkey.mctx = msg->mctx;
936         dns_name_init(&tkey.algorithm, NULL);
937         dns_name_clone(algorithm, &tkey.algorithm);
938         isc_stdtime_get(&now);
939         tkey.inception = now;
940         tkey.expire = now + lifetime;
941         tkey.mode = DNS_TKEYMODE_DIFFIEHELLMAN;
942         if (nonce != NULL)
943                 isc_buffer_usedregion(nonce, &r);
944         else {
945                 r.base = isc_mem_get(msg->mctx, 0);
946                 r.length = 0;
947         }
948         tkey.error = 0;
949         tkey.key = r.base;
950         tkey.keylen =  r.length;
951         tkey.other = NULL;
952         tkey.otherlen = 0;
953
954         RETERR(buildquery(msg, name, &tkey, ISC_FALSE));
955
956         if (nonce == NULL)
957                 isc_mem_put(msg->mctx, r.base, 0);
958
959         RETERR(dns_message_gettemprdata(msg, &rdata));
960         RETERR(isc_buffer_allocate(msg->mctx, &dynbuf, 1024));
961         RETERR(dst_key_todns(key, dynbuf));
962         isc_buffer_usedregion(dynbuf, &r);
963         dns_rdata_fromregion(rdata, dns_rdataclass_any,
964                              dns_rdatatype_key, &r);
965         dns_message_takebuffer(msg, &dynbuf);
966
967         dns_name_init(&keyname, NULL);
968         dns_name_clone(dst_key_name(key), &keyname);
969
970         ISC_LIST_INIT(namelist);
971         RETERR(add_rdata_to_list(msg, &keyname, rdata, 0, &namelist));
972         dns_message_addname(msg, ISC_LIST_HEAD(namelist),
973                             DNS_SECTION_ADDITIONAL);
974
975         return (ISC_R_SUCCESS);
976
977  failure:
978
979         if (dynbuf != NULL)
980                 isc_buffer_free(&dynbuf);
981         return (result);
982 }
983
984 isc_result_t
985 dns_tkey_buildgssquery(dns_message_t *msg, dns_name_t *name, dns_name_t *gname,
986                        isc_buffer_t *intoken, isc_uint32_t lifetime,
987                        gss_ctx_id_t *context, isc_boolean_t win2k)
988 {
989         dns_rdata_tkey_t tkey;
990         isc_result_t result;
991         isc_stdtime_t now;
992         isc_buffer_t token;
993         unsigned char array[4096];
994
995         UNUSED(intoken);
996
997         REQUIRE(msg != NULL);
998         REQUIRE(name != NULL);
999         REQUIRE(gname != NULL);
1000         REQUIRE(context != NULL);
1001
1002         isc_buffer_init(&token, array, sizeof(array));
1003         result = dst_gssapi_initctx(gname, NULL, &token, context);
1004         if (result != DNS_R_CONTINUE && result != ISC_R_SUCCESS)
1005                 return (result);
1006
1007         tkey.common.rdclass = dns_rdataclass_any;
1008         tkey.common.rdtype = dns_rdatatype_tkey;
1009         ISC_LINK_INIT(&tkey.common, link);
1010         tkey.mctx = NULL;
1011         dns_name_init(&tkey.algorithm, NULL);
1012
1013         if (win2k)
1014                 dns_name_clone(DNS_TSIG_GSSAPIMS_NAME, &tkey.algorithm);
1015         else
1016                 dns_name_clone(DNS_TSIG_GSSAPI_NAME, &tkey.algorithm);
1017
1018         isc_stdtime_get(&now);
1019         tkey.inception = now;
1020         tkey.expire = now + lifetime;
1021         tkey.mode = DNS_TKEYMODE_GSSAPI;
1022         tkey.error = 0;
1023         tkey.key = isc_buffer_base(&token);
1024         tkey.keylen = isc_buffer_usedlength(&token);
1025         tkey.other = NULL;
1026         tkey.otherlen = 0;
1027
1028         RETERR(buildquery(msg, name, &tkey, win2k));
1029
1030         return (ISC_R_SUCCESS);
1031
1032  failure:
1033         return (result);
1034 }
1035
1036 isc_result_t
1037 dns_tkey_builddeletequery(dns_message_t *msg, dns_tsigkey_t *key) {
1038         dns_rdata_tkey_t tkey;
1039
1040         REQUIRE(msg != NULL);
1041         REQUIRE(key != NULL);
1042
1043         tkey.common.rdclass = dns_rdataclass_any;
1044         tkey.common.rdtype = dns_rdatatype_tkey;
1045         ISC_LINK_INIT(&tkey.common, link);
1046         tkey.mctx = msg->mctx;
1047         dns_name_init(&tkey.algorithm, NULL);
1048         dns_name_clone(key->algorithm, &tkey.algorithm);
1049         tkey.inception = tkey.expire = 0;
1050         tkey.mode = DNS_TKEYMODE_DELETE;
1051         tkey.error = 0;
1052         tkey.keylen = tkey.otherlen = 0;
1053         tkey.key = tkey.other = NULL;
1054
1055         return (buildquery(msg, &key->name, &tkey, ISC_FALSE));
1056 }
1057
1058 static isc_result_t
1059 find_tkey(dns_message_t *msg, dns_name_t **name, dns_rdata_t *rdata,
1060           int section)
1061 {
1062         dns_rdataset_t *tkeyset;
1063         isc_result_t result;
1064
1065         result = dns_message_firstname(msg, section);
1066         while (result == ISC_R_SUCCESS) {
1067                 *name = NULL;
1068                 dns_message_currentname(msg, section, name);
1069                 tkeyset = NULL;
1070                 result = dns_message_findtype(*name, dns_rdatatype_tkey, 0,
1071                                               &tkeyset);
1072                 if (result == ISC_R_SUCCESS) {
1073                         result = dns_rdataset_first(tkeyset);
1074                         if (result != ISC_R_SUCCESS)
1075                                 return (result);
1076                         dns_rdataset_current(tkeyset, rdata);
1077                         return (ISC_R_SUCCESS);
1078                 }
1079                 result = dns_message_nextname(msg, section);
1080         }
1081         if (result == ISC_R_NOMORE)
1082                 return (ISC_R_NOTFOUND);
1083         return (result);
1084 }
1085
1086 isc_result_t
1087 dns_tkey_processdhresponse(dns_message_t *qmsg, dns_message_t *rmsg,
1088                            dst_key_t *key, isc_buffer_t *nonce,
1089                            dns_tsigkey_t **outkey, dns_tsig_keyring_t *ring)
1090 {
1091         dns_rdata_t qtkeyrdata = DNS_RDATA_INIT, rtkeyrdata = DNS_RDATA_INIT;
1092         dns_name_t keyname, *tkeyname, *theirkeyname, *ourkeyname, *tempname;
1093         dns_rdataset_t *theirkeyset = NULL, *ourkeyset = NULL;
1094         dns_rdata_t theirkeyrdata = DNS_RDATA_INIT;
1095         dst_key_t *theirkey = NULL;
1096         dns_rdata_tkey_t qtkey, rtkey;
1097         unsigned char secretdata[256];
1098         unsigned int sharedsize;
1099         isc_buffer_t *shared = NULL, secret;
1100         isc_region_t r, r2;
1101         isc_result_t result;
1102         isc_boolean_t freertkey = ISC_FALSE;
1103
1104         REQUIRE(qmsg != NULL);
1105         REQUIRE(rmsg != NULL);
1106         REQUIRE(key != NULL);
1107         REQUIRE(dst_key_alg(key) == DNS_KEYALG_DH);
1108         REQUIRE(dst_key_isprivate(key));
1109         if (outkey != NULL)
1110                 REQUIRE(*outkey == NULL);
1111
1112         if (rmsg->rcode != dns_rcode_noerror)
1113                 return (ISC_RESULTCLASS_DNSRCODE + rmsg->rcode);
1114         RETERR(find_tkey(rmsg, &tkeyname, &rtkeyrdata, DNS_SECTION_ANSWER));
1115         RETERR(dns_rdata_tostruct(&rtkeyrdata, &rtkey, NULL));
1116         freertkey = ISC_TRUE;
1117
1118         RETERR(find_tkey(qmsg, &tempname, &qtkeyrdata,
1119                          DNS_SECTION_ADDITIONAL));
1120         RETERR(dns_rdata_tostruct(&qtkeyrdata, &qtkey, NULL));
1121
1122         if (rtkey.error != dns_rcode_noerror ||
1123             rtkey.mode != DNS_TKEYMODE_DIFFIEHELLMAN ||
1124             rtkey.mode != qtkey.mode ||
1125             !dns_name_equal(&rtkey.algorithm, &qtkey.algorithm) ||
1126             rmsg->rcode != dns_rcode_noerror) {
1127                 tkey_log("dns_tkey_processdhresponse: tkey mode invalid "
1128                          "or error set(1)");
1129                 result = DNS_R_INVALIDTKEY;
1130                 dns_rdata_freestruct(&qtkey);
1131                 goto failure;
1132         }
1133
1134         dns_rdata_freestruct(&qtkey);
1135
1136         dns_name_init(&keyname, NULL);
1137         dns_name_clone(dst_key_name(key), &keyname);
1138
1139         ourkeyname = NULL;
1140         ourkeyset = NULL;
1141         RETERR(dns_message_findname(rmsg, DNS_SECTION_ANSWER, &keyname,
1142                                     dns_rdatatype_key, 0, &ourkeyname,
1143                                     &ourkeyset));
1144
1145         result = dns_message_firstname(rmsg, DNS_SECTION_ANSWER);
1146         while (result == ISC_R_SUCCESS) {
1147                 theirkeyname = NULL;
1148                 dns_message_currentname(rmsg, DNS_SECTION_ANSWER,
1149                                         &theirkeyname);
1150                 if (dns_name_equal(theirkeyname, ourkeyname))
1151                         goto next;
1152                 theirkeyset = NULL;
1153                 result = dns_message_findtype(theirkeyname, dns_rdatatype_key,
1154                                               0, &theirkeyset);
1155                 if (result == ISC_R_SUCCESS) {
1156                         RETERR(dns_rdataset_first(theirkeyset));
1157                         break;
1158                 }
1159  next:
1160                 result = dns_message_nextname(rmsg, DNS_SECTION_ANSWER);
1161         }
1162
1163         if (theirkeyset == NULL) {
1164                 tkey_log("dns_tkey_processdhresponse: failed to find server "
1165                          "key");
1166                 result = ISC_R_NOTFOUND;
1167                 goto failure;
1168         }
1169
1170         dns_rdataset_current(theirkeyset, &theirkeyrdata);
1171         RETERR(dns_dnssec_keyfromrdata(theirkeyname, &theirkeyrdata,
1172                                        rmsg->mctx, &theirkey));
1173
1174         RETERR(dst_key_secretsize(key, &sharedsize));
1175         RETERR(isc_buffer_allocate(rmsg->mctx, &shared, sharedsize));
1176
1177         RETERR(dst_key_computesecret(theirkey, key, shared));
1178
1179         isc_buffer_init(&secret, secretdata, sizeof(secretdata));
1180
1181         r.base = rtkey.key;
1182         r.length = rtkey.keylen;
1183         if (nonce != NULL)
1184                 isc_buffer_usedregion(nonce, &r2);
1185         else {
1186                 r2.base = isc_mem_get(rmsg->mctx, 0);
1187                 r2.length = 0;
1188         }
1189         RETERR(compute_secret(shared, &r2, &r, &secret));
1190         if (nonce == NULL)
1191                 isc_mem_put(rmsg->mctx, r2.base, 0);
1192
1193         isc_buffer_usedregion(&secret, &r);
1194         result = dns_tsigkey_create(tkeyname, &rtkey.algorithm,
1195                                     r.base, r.length, ISC_TRUE,
1196                                     NULL, rtkey.inception, rtkey.expire,
1197                                     rmsg->mctx, ring, outkey);
1198         isc_buffer_free(&shared);
1199         dns_rdata_freestruct(&rtkey);
1200         dst_key_free(&theirkey);
1201         return (result);
1202
1203  failure:
1204         if (shared != NULL)
1205                 isc_buffer_free(&shared);
1206
1207         if (theirkey != NULL)
1208                 dst_key_free(&theirkey);
1209
1210         if (freertkey)
1211                 dns_rdata_freestruct(&rtkey);
1212
1213         return (result);
1214 }
1215
1216 isc_result_t
1217 dns_tkey_processgssresponse(dns_message_t *qmsg, dns_message_t *rmsg,
1218                             dns_name_t *gname, gss_ctx_id_t *context,
1219                             isc_buffer_t *outtoken, dns_tsigkey_t **outkey,
1220                             dns_tsig_keyring_t *ring)
1221 {
1222         dns_rdata_t rtkeyrdata = DNS_RDATA_INIT, qtkeyrdata = DNS_RDATA_INIT;
1223         dns_name_t *tkeyname;
1224         dns_rdata_tkey_t rtkey, qtkey;
1225         dst_key_t *dstkey = NULL;
1226         isc_buffer_t intoken;
1227         isc_result_t result;
1228         unsigned char array[1024];
1229
1230         REQUIRE(outtoken != NULL);
1231         REQUIRE(qmsg != NULL);
1232         REQUIRE(rmsg != NULL);
1233         REQUIRE(gname != NULL);
1234         if (outkey != NULL)
1235                 REQUIRE(*outkey == NULL);
1236
1237         if (rmsg->rcode != dns_rcode_noerror)
1238                 return (ISC_RESULTCLASS_DNSRCODE + rmsg->rcode);
1239         RETERR(find_tkey(rmsg, &tkeyname, &rtkeyrdata, DNS_SECTION_ANSWER));
1240         RETERR(dns_rdata_tostruct(&rtkeyrdata, &rtkey, NULL));
1241
1242         /*
1243          * Win2k puts the item in the ANSWER section, while the RFC
1244          * specifies it should be in the ADDITIONAL section.  Check first
1245          * where it should be, and then where it may be.
1246          */
1247         result = find_tkey(qmsg, &tkeyname, &qtkeyrdata,
1248                            DNS_SECTION_ADDITIONAL);
1249         if (result == ISC_R_NOTFOUND)
1250                 result = find_tkey(qmsg, &tkeyname, &qtkeyrdata,
1251                                    DNS_SECTION_ANSWER);
1252         if (result != ISC_R_SUCCESS)
1253                 goto failure;
1254
1255         RETERR(dns_rdata_tostruct(&qtkeyrdata, &qtkey, NULL));
1256
1257         if (rtkey.error != dns_rcode_noerror ||
1258             rtkey.mode != DNS_TKEYMODE_GSSAPI ||
1259             !dns_name_equal(&rtkey.algorithm, &qtkey.algorithm)) {
1260                 tkey_log("dns_tkey_processgssresponse: tkey mode invalid "
1261                          "or error set(2) %d", rtkey.error);
1262                 _dns_tkey_dumpmessage(qmsg);
1263                 _dns_tkey_dumpmessage(rmsg);
1264                 result = DNS_R_INVALIDTKEY;
1265                 goto failure;
1266         }
1267
1268         isc_buffer_init(outtoken, array, sizeof(array));
1269         isc_buffer_init(&intoken, rtkey.key, rtkey.keylen);
1270         RETERR(dst_gssapi_initctx(gname, &intoken, outtoken, context));
1271
1272         RETERR(dst_key_fromgssapi(dns_rootname, *context, rmsg->mctx,
1273                                   &dstkey));
1274
1275         RETERR(dns_tsigkey_createfromkey(tkeyname, DNS_TSIG_GSSAPI_NAME,
1276                                          dstkey, ISC_FALSE, NULL,
1277                                          rtkey.inception, rtkey.expire,
1278                                          ring->mctx, ring, outkey));
1279         dst_key_free(&dstkey);
1280         dns_rdata_freestruct(&rtkey);
1281         return (result);
1282
1283  failure:
1284         /*
1285          * XXXSRA This probably leaks memory from rtkey and qtkey.
1286          */
1287         if (dstkey != NULL)
1288                 dst_key_free(&dstkey);
1289         return (result);
1290 }
1291
1292 isc_result_t
1293 dns_tkey_processdeleteresponse(dns_message_t *qmsg, dns_message_t *rmsg,
1294                                dns_tsig_keyring_t *ring)
1295 {
1296         dns_rdata_t qtkeyrdata = DNS_RDATA_INIT, rtkeyrdata = DNS_RDATA_INIT;
1297         dns_name_t *tkeyname, *tempname;
1298         dns_rdata_tkey_t qtkey, rtkey;
1299         dns_tsigkey_t *tsigkey = NULL;
1300         isc_result_t result;
1301
1302         REQUIRE(qmsg != NULL);
1303         REQUIRE(rmsg != NULL);
1304
1305         if (rmsg->rcode != dns_rcode_noerror)
1306                 return(ISC_RESULTCLASS_DNSRCODE + rmsg->rcode);
1307
1308         RETERR(find_tkey(rmsg, &tkeyname, &rtkeyrdata, DNS_SECTION_ANSWER));
1309         RETERR(dns_rdata_tostruct(&rtkeyrdata, &rtkey, NULL));
1310
1311         RETERR(find_tkey(qmsg, &tempname, &qtkeyrdata,
1312                          DNS_SECTION_ADDITIONAL));
1313         RETERR(dns_rdata_tostruct(&qtkeyrdata, &qtkey, NULL));
1314
1315         if (rtkey.error != dns_rcode_noerror ||
1316             rtkey.mode != DNS_TKEYMODE_DELETE ||
1317             rtkey.mode != qtkey.mode ||
1318             !dns_name_equal(&rtkey.algorithm, &qtkey.algorithm) ||
1319             rmsg->rcode != dns_rcode_noerror) {
1320                 tkey_log("dns_tkey_processdeleteresponse: tkey mode invalid "
1321                          "or error set(3)");
1322                 result = DNS_R_INVALIDTKEY;
1323                 dns_rdata_freestruct(&qtkey);
1324                 dns_rdata_freestruct(&rtkey);
1325                 goto failure;
1326         }
1327
1328         dns_rdata_freestruct(&qtkey);
1329
1330         RETERR(dns_tsigkey_find(&tsigkey, tkeyname, &rtkey.algorithm, ring));
1331
1332         dns_rdata_freestruct(&rtkey);
1333
1334         /*
1335          * Mark the key as deleted.
1336          */
1337         dns_tsigkey_setdeleted(tsigkey);
1338         /*
1339          * Release the reference.
1340          */
1341         dns_tsigkey_detach(&tsigkey);
1342
1343  failure:
1344         return (result);
1345 }
1346
1347 isc_result_t
1348 dns_tkey_gssnegotiate(dns_message_t *qmsg, dns_message_t *rmsg,
1349                       dns_name_t *server, gss_ctx_id_t *context,
1350                       dns_tsigkey_t **outkey, dns_tsig_keyring_t *ring,
1351                       isc_boolean_t win2k)
1352 {
1353         dns_rdata_t rtkeyrdata = DNS_RDATA_INIT, qtkeyrdata = DNS_RDATA_INIT;
1354         dns_name_t *tkeyname;
1355         dns_rdata_tkey_t rtkey, qtkey;
1356         isc_buffer_t intoken, outtoken;
1357         dst_key_t *dstkey = NULL;
1358         isc_result_t result;
1359         unsigned char array[1024];
1360
1361         REQUIRE(qmsg != NULL);
1362         REQUIRE(rmsg != NULL);
1363         REQUIRE(server != NULL);
1364         if (outkey != NULL)
1365                 REQUIRE(*outkey == NULL);
1366
1367         if (rmsg->rcode != dns_rcode_noerror)
1368                 return (ISC_RESULTCLASS_DNSRCODE + rmsg->rcode);
1369
1370         RETERR(find_tkey(rmsg, &tkeyname, &rtkeyrdata, DNS_SECTION_ANSWER));
1371         RETERR(dns_rdata_tostruct(&rtkeyrdata, &rtkey, NULL));
1372
1373         if (win2k == ISC_TRUE)
1374                 RETERR(find_tkey(qmsg, &tkeyname, &qtkeyrdata,
1375                                  DNS_SECTION_ANSWER));
1376         else
1377                 RETERR(find_tkey(qmsg, &tkeyname, &qtkeyrdata,
1378                                  DNS_SECTION_ADDITIONAL));
1379
1380         RETERR(dns_rdata_tostruct(&qtkeyrdata, &qtkey, NULL));
1381
1382         if (rtkey.error != dns_rcode_noerror ||
1383             rtkey.mode != DNS_TKEYMODE_GSSAPI ||
1384             !dns_name_equal(&rtkey.algorithm, &qtkey.algorithm))
1385         {
1386                 tkey_log("dns_tkey_processdhresponse: tkey mode invalid "
1387                          "or error set(4)");
1388                 result = DNS_R_INVALIDTKEY;
1389                 goto failure;
1390         }
1391
1392         isc_buffer_init(&intoken, rtkey.key, rtkey.keylen);
1393         isc_buffer_init(&outtoken, array, sizeof(array));
1394
1395         result = dst_gssapi_initctx(server, &intoken, &outtoken, context);
1396         if (result != DNS_R_CONTINUE && result != ISC_R_SUCCESS)
1397                 return (result);
1398
1399         RETERR(dst_key_fromgssapi(dns_rootname, *context, rmsg->mctx,
1400                                   &dstkey));
1401
1402         /*
1403          * XXXSRA This seems confused.  If we got CONTINUE from initctx,
1404          * the GSS negotiation hasn't completed yet, so we can't sign
1405          * anything yet.
1406          */
1407
1408         RETERR(dns_tsigkey_createfromkey(tkeyname,
1409                                          (win2k
1410                                           ? DNS_TSIG_GSSAPIMS_NAME
1411                                           : DNS_TSIG_GSSAPI_NAME),
1412                                          dstkey, ISC_TRUE, NULL,
1413                                          rtkey.inception, rtkey.expire,
1414                                          ring->mctx, ring, outkey));
1415         dst_key_free(&dstkey);
1416         dns_rdata_freestruct(&rtkey);
1417         return (result);
1418
1419  failure:
1420         /*
1421          * XXXSRA This probably leaks memory from qtkey.
1422          */
1423         dns_rdata_freestruct(&rtkey);
1424         if (dstkey != NULL)
1425                 dst_key_free(&dstkey);
1426         return (result);
1427 }