r20640: Commit part 2/2
[tprouty/samba.git] / source4 / heimdal / kdc / digest.c
1 /*
2  * Copyright (c) 2006 Kungliga Tekniska Högskolan
3  * (Royal Institute of Technology, Stockholm, Sweden). 
4  * All rights reserved. 
5  *
6  * Redistribution and use in source and binary forms, with or without 
7  * modification, are permitted provided that the following conditions 
8  * are met: 
9  *
10  * 1. Redistributions of source code must retain the above copyright 
11  *    notice, this list of conditions and the following disclaimer. 
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright 
14  *    notice, this list of conditions and the following disclaimer in the 
15  *    documentation and/or other materials provided with the distribution. 
16  *
17  * 3. Neither the name of the Institute nor the names of its contributors 
18  *    may be used to endorse or promote products derived from this software 
19  *    without specific prior written permission. 
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND 
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE 
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 
31  * SUCH DAMAGE. 
32  */
33
34 #include "kdc_locl.h"
35 #include <hex.h>
36
37 RCSID("$Id: digest.c,v 1.19 2006/12/28 17:03:51 lha Exp $");
38
39 #define CHAP_MD5        0x10
40 #define DIGEST_MD5      0x08
41 #define NTLM_V2         0x04
42 #define NTLM_V1_SESSION 0x02
43 #define NTLM_V1         0x01
44
45 const struct units _kdc_digestunits[] = {
46         {"chap-md5",            1U << 4},
47         {"digest-md5",          1U << 3},
48         {"ntlm-v2",             1U << 2},
49         {"ntlm-v1-session",     1U << 1},
50         {"ntlm-v1",             1U << 0},
51         {NULL,  0}
52 };
53
54
55 static krb5_error_code
56 get_digest_key(krb5_context context,
57                krb5_kdc_configuration *config,
58                hdb_entry_ex *server,
59                krb5_crypto *crypto)
60 {
61     krb5_error_code ret;
62     krb5_enctype enctype;
63     Key *key;
64     
65     ret = _kdc_get_preferred_key(context,
66                                  config,
67                                  server,
68                                  "digest-service",
69                                  &enctype,
70                                  &key);
71     if (ret)
72         return ret;
73     return krb5_crypto_init(context, &key->key, 0, crypto);
74 }
75
76 /*
77  *
78  */
79
80 static char *
81 get_ntlm_targetname(krb5_context context,
82                     hdb_entry_ex *client)
83 {
84     char *targetname, *p;
85
86     targetname = strdup(krb5_principal_get_realm(context,
87                                                  client->entry.principal));
88     if (targetname == NULL)
89         return NULL;
90
91     p = strchr(targetname, '.');
92     if (p)
93         *p = '\0';
94
95     strupr(targetname);
96     return targetname;
97 }
98
99 static krb5_error_code
100 fill_targetinfo(krb5_context context,
101                 char *targetname,
102                 hdb_entry_ex *client,
103                 krb5_data *data)
104 {
105     struct ntlm_targetinfo ti;
106     krb5_error_code ret;
107     struct ntlm_buf d;
108     krb5_principal p;
109     const char *str;
110
111     memset(&ti, 0, sizeof(ti));
112
113     ti.domainname = targetname;
114     p = client->entry.principal;
115     str = krb5_principal_get_comp_string(context, p, 0);
116     if (str != NULL && 
117         (strcmp("host", str) == 0 || 
118          strcmp("ftp", str) == 0 ||
119          strcmp("imap", str) == 0 ||
120          strcmp("pop", str) == 0 ||
121          strcmp("smtp", str)))
122     {
123         str = krb5_principal_get_comp_string(context, p, 1);
124         ti.dnsservername = rk_UNCONST(str);
125     }
126     
127     ret = heim_ntlm_encode_targetinfo(&ti, 1, &d);
128     if (ret)
129         return ret;
130
131     data->data = d.data;
132     data->length = d.length;
133
134     return 0;
135 }
136
137
138 /*
139  *
140  */
141
142 krb5_error_code
143 _kdc_do_digest(krb5_context context, 
144                krb5_kdc_configuration *config,
145                const DigestREQ *req, krb5_data *reply,
146                const char *from, struct sockaddr *addr)
147 {
148     krb5_error_code ret = 0;
149     krb5_ticket *ticket = NULL;
150     krb5_auth_context ac = NULL;
151     krb5_keytab id = NULL;
152     krb5_crypto crypto = NULL;
153     DigestReqInner ireq;
154     DigestRepInner r;
155     DigestREP rep;
156     krb5_flags ap_req_options;
157     krb5_data buf;
158     size_t size;
159     krb5_storage *sp = NULL;
160     Checksum res;
161     hdb_entry_ex *server = NULL, *user = NULL;
162     hdb_entry_ex *client = NULL;
163     char *client_name = NULL, *password = NULL;
164     krb5_data serverNonce;
165
166     if(!config->enable_digest) {
167         kdc_log(context, config, 0, 
168                 "Rejected digest request (disabled) from %s", from);
169         return KRB5KDC_ERR_POLICY;
170     }
171
172     krb5_data_zero(&buf);
173     krb5_data_zero(reply);
174     krb5_data_zero(&serverNonce);
175     memset(&ireq, 0, sizeof(ireq));
176     memset(&r, 0, sizeof(r));
177     memset(&rep, 0, sizeof(rep));
178
179     kdc_log(context, config, 0, "Digest request from %s", from);
180
181     ret = krb5_kt_resolve(context, "HDB:", &id);
182     if (ret) {
183         kdc_log(context, config, 0, "Can't open database for digest");
184         goto out;
185     }
186
187     ret = krb5_rd_req(context, 
188                       &ac,
189                       &req->apReq,
190                       NULL,
191                       id,
192                       &ap_req_options,
193                       &ticket);
194     if (ret)
195         goto out;
196
197     /* check the server principal in the ticket matches digest/R@R */
198     {
199         krb5_principal principal = NULL;
200         const char *p, *r;
201
202         ret = krb5_ticket_get_server(context, ticket, &principal);
203         if (ret)
204             goto out;
205
206         ret = EINVAL;
207         krb5_set_error_string(context, "Wrong digest server principal used");
208         p = krb5_principal_get_comp_string(context, principal, 0);
209         if (p == NULL) {
210             krb5_free_principal(context, principal);
211             goto out;
212         }
213         if (strcmp(p, KRB5_DIGEST_NAME) != 0) {
214             krb5_free_principal(context, principal);
215             goto out;
216         }
217
218         p = krb5_principal_get_comp_string(context, principal, 1);
219         if (p == NULL) {
220             krb5_free_principal(context, principal);
221             goto out;
222         }
223         r = krb5_principal_get_realm(context, principal);
224         if (r == NULL) {
225             krb5_free_principal(context, principal);
226             goto out;
227         }
228         if (strcmp(p, r) != 0) {
229             krb5_free_principal(context, principal);
230             goto out;
231         }
232         krb5_clear_error_string(context);
233
234         ret = _kdc_db_fetch(context, config, principal,
235                             HDB_F_GET_SERVER, NULL, &server);
236         if (ret)
237             goto out;
238
239         krb5_free_principal(context, principal);
240     }
241
242     /* check the client is allowed to do digest auth */
243     {
244         krb5_principal principal = NULL;
245
246         ret = krb5_ticket_get_client(context, ticket, &principal);
247         if (ret)
248             goto out;
249
250         ret = krb5_unparse_name(context, principal, &client_name);
251         if (ret) {
252             krb5_free_principal(context, principal);
253             goto out;
254         }
255
256         ret = _kdc_db_fetch(context, config, principal,
257                             HDB_F_GET_CLIENT, NULL, &client);
258         krb5_free_principal(context, principal);
259         if (ret)
260             goto out;
261
262         if (client->entry.flags.allow_digest == 0) {
263             kdc_log(context, config, 0, 
264                     "Client %s tried to use digest "
265                     "but is not allowed to", 
266                     client_name);
267             krb5_set_error_string(context, 
268                                   "Client is not permitted to use digest");
269             ret = KRB5KDC_ERR_POLICY;
270             goto out;
271         }
272     }
273
274     /* unpack request */
275     {
276         krb5_keyblock *key;
277
278         ret = krb5_auth_con_getremotesubkey(context, ac, &key);
279         if (ret)
280             goto out;
281         if (key == NULL) {
282             krb5_set_error_string(context, "digest: remote subkey not found");
283             ret = EINVAL;
284             goto out;
285         }
286
287         ret = krb5_crypto_init(context, key, 0, &crypto);
288         krb5_free_keyblock (context, key);
289         if (ret)
290             goto out;
291     }
292
293     ret = krb5_decrypt_EncryptedData(context, crypto, KRB5_KU_DIGEST_ENCRYPT,
294                                      &req->innerReq, &buf);
295     krb5_crypto_destroy(context, crypto);
296     crypto = NULL;
297     if (ret)
298         goto out;
299            
300     ret = decode_DigestReqInner(buf.data, buf.length, &ireq, NULL);
301     krb5_data_free(&buf);
302     if (ret) {
303         krb5_set_error_string(context, "Failed to decode digest inner request");
304         goto out;
305     }
306
307     kdc_log(context, config, 0, "Valid digest request from %s (%s)", 
308             client_name, from);
309
310     /*
311      * Process the inner request
312      */
313
314     switch (ireq.element) {
315     case choice_DigestReqInner_init: {
316         unsigned char server_nonce[16], identifier;
317
318         RAND_pseudo_bytes(&identifier, sizeof(identifier));
319         RAND_pseudo_bytes(server_nonce, sizeof(server_nonce));
320
321         server_nonce[0] = kdc_time & 0xff;
322         server_nonce[1] = (kdc_time >> 8) & 0xff;
323         server_nonce[2] = (kdc_time >> 16) & 0xff;
324         server_nonce[3] = (kdc_time >> 24) & 0xff;
325
326         r.element = choice_DigestRepInner_initReply;
327
328         hex_encode(server_nonce, sizeof(server_nonce), &r.u.initReply.nonce);
329         if (r.u.initReply.nonce == NULL) {
330             krb5_set_error_string(context, "Failed to decode server nonce");
331             ret = ENOMEM;
332             goto out;
333         }
334
335         sp = krb5_storage_emem();
336         if (sp == NULL) {
337             ret = ENOMEM;
338             krb5_set_error_string(context, "out of memory");
339             goto out;
340         }
341         ret = krb5_store_stringz(sp, ireq.u.init.type);
342         if (ret) {
343             krb5_clear_error_string(context);
344             goto out;
345         }
346
347         if (ireq.u.init.channel) {
348             char *s;
349
350             asprintf(&s, "%s-%s:%s", r.u.initReply.nonce,
351                      ireq.u.init.channel->cb_type,
352                      ireq.u.init.channel->cb_binding);
353             if (s == NULL) {
354                 krb5_set_error_string(context, "Failed to allocate "
355                                       "channel binding");
356                 ret = ENOMEM;
357                 goto out;
358             }
359             free(r.u.initReply.nonce);
360             r.u.initReply.nonce = s;
361         }
362         
363         ret = krb5_store_stringz(sp, r.u.initReply.nonce);
364         if (ret) {
365             krb5_clear_error_string(context);
366             goto out;
367         }
368
369         if (strcasecmp(ireq.u.init.type, "CHAP") == 0) {
370             r.u.initReply.identifier = 
371                 malloc(sizeof(*r.u.initReply.identifier));
372             if (r.u.initReply.identifier == NULL) {
373                 krb5_set_error_string(context, "out of memory");
374                 ret = ENOMEM;
375                 goto out;
376             }
377
378             asprintf(r.u.initReply.identifier, "%02X", identifier & 0xff);
379             if (*r.u.initReply.identifier == NULL) {
380                 krb5_set_error_string(context, "out of memory");
381                 ret = ENOMEM;
382                 goto out;
383             }
384
385             ret = krb5_store_stringz(sp, *r.u.initReply.identifier);
386             if (ret) {
387                 krb5_clear_error_string(context);
388                 goto out;
389             }
390         } else
391             r.u.initReply.identifier = NULL;
392
393         if (ireq.u.init.hostname) {
394             ret = krb5_store_stringz(sp, *ireq.u.init.hostname);
395             if (ret) {
396                 krb5_clear_error_string(context);
397                 goto out;
398             }
399         }
400
401         ret = krb5_storage_to_data(sp, &buf);
402         if (ret) {
403             krb5_clear_error_string(context);
404             goto out;
405         }
406
407         ret = get_digest_key(context, config, server, &crypto);
408         if (ret)
409             goto out;
410
411         ret = krb5_create_checksum(context,
412                                    crypto,
413                                    KRB5_KU_DIGEST_OPAQUE,
414                                    0,
415                                    buf.data,
416                                    buf.length,
417                                    &res);
418         krb5_crypto_destroy(context, crypto);
419         crypto = NULL;
420         krb5_data_free(&buf);
421         if (ret)
422             goto out;
423         
424         ASN1_MALLOC_ENCODE(Checksum, buf.data, buf.length, &res, &size, ret);
425         free_Checksum(&res);
426         if (ret) {
427             krb5_set_error_string(context, "Failed to encode "
428                                   "checksum in digest request");
429             goto out;
430         }
431         if (size != buf.length)
432             krb5_abortx(context, "ASN1 internal error");
433
434         hex_encode(buf.data, buf.length, &r.u.initReply.opaque);
435         free(buf.data);
436         if (r.u.initReply.opaque == NULL) {
437             krb5_clear_error_string(context);
438             ret = ENOMEM;
439             goto out;
440         }
441
442         kdc_log(context, config, 0, "Digest %s init request successful from %s",
443                 ireq.u.init.type, from);
444
445         break;
446     }
447     case choice_DigestReqInner_digestRequest: {
448         krb5_principal clientprincipal;
449         HDB *db;
450
451         sp = krb5_storage_emem();
452         if (sp == NULL) {
453             ret = ENOMEM;
454             krb5_set_error_string(context, "out of memory");
455             goto out;
456         }
457         ret = krb5_store_stringz(sp, ireq.u.digestRequest.type);
458         if (ret) {
459             krb5_clear_error_string(context);
460             goto out;
461         }
462
463         krb5_store_stringz(sp, ireq.u.digestRequest.serverNonce);
464         if (ireq.u.digestRequest.identifier) {
465             ret = krb5_store_stringz(sp, *ireq.u.digestRequest.identifier);
466             if (ret) {
467                 krb5_clear_error_string(context);
468                 goto out;
469             }
470         }
471         if (ireq.u.digestRequest.hostname) {
472             ret = krb5_store_stringz(sp, *ireq.u.digestRequest.hostname);
473             if (ret) {
474                 krb5_clear_error_string(context);
475                 goto out;
476             }
477         }
478
479         buf.length = strlen(ireq.u.digestRequest.opaque);
480         buf.data = malloc(buf.length);
481         if (buf.data == NULL) {
482             krb5_set_error_string(context, "out of memory");
483             ret = ENOMEM;
484             goto out;
485         }
486
487         ret = hex_decode(ireq.u.digestRequest.opaque, buf.data, buf.length);
488         if (ret <= 0) {
489             krb5_set_error_string(context, "Failed to decode opaque");
490             ret = ENOMEM;
491             goto out;
492         }
493         buf.length = ret;
494
495         ret = decode_Checksum(buf.data, buf.length, &res, NULL);
496         free(buf.data);
497         if (ret) {
498             krb5_set_error_string(context, "Failed to decode digest Checksum");
499             goto out;
500         }
501         
502         ret = krb5_storage_to_data(sp, &buf);
503         if (ret) {
504             krb5_clear_error_string(context);
505             goto out;
506         }
507
508         serverNonce.length = strlen(ireq.u.digestRequest.serverNonce);
509         serverNonce.data = malloc(serverNonce.length);
510         if (serverNonce.data == NULL) {
511             krb5_set_error_string(context, "out of memory");
512             ret = ENOMEM;
513             goto out;
514         }
515             
516         /*
517          * CHAP does the checksum of the raw nonce, but do it for all
518          * types, since we need to check the timestamp.
519          */
520         {
521             ssize_t ssize;
522             
523             ssize = hex_decode(ireq.u.digestRequest.serverNonce, 
524                                serverNonce.data, serverNonce.length);
525             if (ssize <= 0) {
526                 krb5_set_error_string(context, "Failed to decode serverNonce");
527                 ret = ENOMEM;
528                 goto out;
529             }
530             serverNonce.length = ssize;
531         }
532
533         ret = get_digest_key(context, config, server, &crypto);
534         if (ret)
535             goto out;
536
537         ret = krb5_verify_checksum(context, crypto, 
538                                    KRB5_KU_DIGEST_OPAQUE,
539                                    buf.data, buf.length, &res);
540         krb5_crypto_destroy(context, crypto);
541         crypto = NULL;
542         if (ret)
543             goto out;
544
545         /* verify time */
546         {
547             unsigned char *p = serverNonce.data;
548             uint32_t t;
549             
550             if (serverNonce.length < 4) {
551                 krb5_set_error_string(context, "server nonce too short");
552                 ret = EINVAL;
553                 goto out;
554             }
555             t = p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
556
557             if (abs((kdc_time & 0xffffffff) - t) > context->max_skew) {
558                 krb5_set_error_string(context, "time screw in server nonce ");
559                 ret = EINVAL;
560                 goto out;
561             }
562         }
563
564         /* get username */
565         ret = krb5_parse_name(context,
566                               ireq.u.digestRequest.username,
567                               &clientprincipal);
568         if (ret)
569             goto out;
570
571         ret = _kdc_db_fetch(context, config, clientprincipal,
572                             HDB_F_GET_CLIENT, &db, &user);
573
574         krb5_free_principal(context, clientprincipal);
575         if (ret)
576             goto out;
577
578         ret = hdb_entry_get_password(context, db, &user->entry, &password);
579         if (ret || password == NULL) {
580             if (ret == 0) {
581                 ret = EINVAL;
582                 krb5_set_error_string(context, "password missing");
583             }
584             goto out;
585         }
586
587         if (strcasecmp(ireq.u.digestRequest.type, "CHAP") == 0) {
588             MD5_CTX ctx;
589             unsigned char md[MD5_DIGEST_LENGTH];
590             char id;
591
592             if ((config->digests_allowed & CHAP_MD5) == 0) {
593                 kdc_log(context, config, 0, "Digest CHAP MD5 not allowed");
594                 goto out;
595             }
596
597             if (ireq.u.digestRequest.identifier == NULL) {
598                 krb5_set_error_string(context, "Identifier missing "
599                                       "from CHAP request");
600                 ret = EINVAL;
601                 goto out;
602             }
603             
604             if (hex_decode(*ireq.u.digestRequest.identifier, &id, 1) != 1) {
605                 krb5_set_error_string(context, "failed to decode identifier");
606                 ret = EINVAL;
607                 goto out;
608             }
609             
610             MD5_Init(&ctx);
611             MD5_Update(&ctx, &id, 1);
612             MD5_Update(&ctx, password, strlen(password));
613             MD5_Update(&ctx, serverNonce.data, serverNonce.length);
614             MD5_Final(md, &ctx);
615
616             r.element = choice_DigestRepInner_response;
617             hex_encode(md, sizeof(md), &r.u.response.responseData);
618             if (r.u.response.responseData == NULL) {
619                 krb5_clear_error_string(context);
620                 ret = ENOMEM;
621                 goto out;
622             }
623         } else if (strcasecmp(ireq.u.digestRequest.type, "SASL-DIGEST-MD5") == 0) {
624             MD5_CTX ctx;
625             unsigned char md[MD5_DIGEST_LENGTH];
626             char *A1, *A2;
627
628             if ((config->digests_allowed & DIGEST_MD5) == 0) {
629                 kdc_log(context, config, 0, "Digest SASL MD5 not allowed");
630                 goto out;
631             }
632
633             if (ireq.u.digestRequest.nonceCount == NULL) 
634                 goto out;
635             if (ireq.u.digestRequest.clientNonce == NULL) 
636                 goto out;
637             if (ireq.u.digestRequest.qop == NULL) 
638                 goto out;
639             if (ireq.u.digestRequest.realm == NULL) 
640                 goto out;
641             
642             MD5_Init(&ctx);
643             MD5_Update(&ctx, ireq.u.digestRequest.username,
644                        strlen(ireq.u.digestRequest.username));
645             MD5_Update(&ctx, ":", 1);
646             MD5_Update(&ctx, *ireq.u.digestRequest.realm,
647                        strlen(*ireq.u.digestRequest.realm));
648             MD5_Update(&ctx, ":", 1);
649             MD5_Update(&ctx, password, strlen(password));
650             MD5_Final(md, &ctx);
651             
652             MD5_Init(&ctx);
653             MD5_Update(&ctx, md, sizeof(md));
654             MD5_Update(&ctx, ":", 1);
655             MD5_Update(&ctx, ireq.u.digestRequest.serverNonce,
656                        strlen(ireq.u.digestRequest.serverNonce));
657             MD5_Update(&ctx, ":", 1);
658             MD5_Update(&ctx, *ireq.u.digestRequest.nonceCount,
659                        strlen(*ireq.u.digestRequest.nonceCount));
660             if (ireq.u.digestRequest.authid) {
661                 MD5_Update(&ctx, ":", 1);
662                 MD5_Update(&ctx, *ireq.u.digestRequest.authid,
663                            strlen(*ireq.u.digestRequest.authid));
664             }
665             MD5_Final(md, &ctx);
666             hex_encode(md, sizeof(md), &A1);
667             if (A1 == NULL) {
668                 krb5_set_error_string(context, "out of memory");
669                 ret = ENOMEM;
670                 goto out;
671             }
672             
673             MD5_Init(&ctx);
674             MD5_Update(&ctx, "AUTHENTICATE:", sizeof("AUTHENTICATE:") - 1);
675             MD5_Update(&ctx, *ireq.u.digestRequest.uri,
676                        strlen(*ireq.u.digestRequest.uri));
677         
678             /* conf|int */
679             if (strcmp(ireq.u.digestRequest.digest, "clear") != 0) {
680                 static char conf_zeros[] = ":00000000000000000000000000000000";
681                 MD5_Update(&ctx, conf_zeros, sizeof(conf_zeros) - 1);
682             }
683             
684             MD5_Final(md, &ctx);
685             hex_encode(md, sizeof(md), &A2);
686             if (A2 == NULL) {
687                 krb5_set_error_string(context, "out of memory");
688                 ret = ENOMEM;
689                 free(A1);
690                 goto out;
691             }
692
693             MD5_Init(&ctx);
694             MD5_Update(&ctx, A1, strlen(A2));
695             MD5_Update(&ctx, ":", 1);
696             MD5_Update(&ctx, ireq.u.digestRequest.serverNonce,
697                        strlen(ireq.u.digestRequest.serverNonce));
698             MD5_Update(&ctx, ":", 1);
699             MD5_Update(&ctx, *ireq.u.digestRequest.nonceCount,
700                        strlen(*ireq.u.digestRequest.nonceCount));
701             MD5_Update(&ctx, ":", 1);
702             MD5_Update(&ctx, *ireq.u.digestRequest.clientNonce,
703                        strlen(*ireq.u.digestRequest.clientNonce));
704             MD5_Update(&ctx, ":", 1);
705             MD5_Update(&ctx, *ireq.u.digestRequest.qop,
706                        strlen(*ireq.u.digestRequest.qop));
707             MD5_Update(&ctx, ":", 1);
708             MD5_Update(&ctx, A2, strlen(A2));
709
710             MD5_Final(md, &ctx);
711
712             r.element = choice_DigestRepInner_response;
713             hex_encode(md, sizeof(md), &r.u.response.responseData);
714
715             free(A1);
716             free(A2);
717
718             if (r.u.response.responseData == NULL) {
719                 krb5_set_error_string(context, "out of memory");
720                 ret = ENOMEM;
721                 goto out;
722             }
723
724         } else {
725             r.element = choice_DigestRepInner_error;
726             asprintf(&r.u.error.reason, "unsupported digest type %s", 
727                      ireq.u.digestRequest.type);
728             if (r.u.error.reason == NULL) {
729                 krb5_set_error_string(context, "out of memory");
730                 ret = ENOMEM;
731                 goto out;
732             }
733             r.u.error.code = EINVAL;
734         }
735
736         kdc_log(context, config, 0, "Digest %s request successful %s",
737                 ireq.u.digestRequest.type, from);
738
739         break;
740     }
741     case choice_DigestReqInner_ntlmInit:
742
743         if ((config->digests_allowed & (NTLM_V1|NTLM_V1_SESSION|NTLM_V2)) == 0) {
744             kdc_log(context, config, 0, "NTLM not allowed");
745             goto out;
746         }
747
748
749         r.element = choice_DigestRepInner_ntlmInitReply;
750
751         r.u.ntlmInitReply.flags = NTLM_NEG_UNICODE;
752
753         if ((ireq.u.ntlmInit.flags & NTLM_NEG_UNICODE) == 0) {
754             kdc_log(context, config, 0, "NTLM client have no unicode");
755             goto out;
756         }
757
758         if (ireq.u.ntlmInit.flags & NTLM_NEG_NTLM)
759             r.u.ntlmInitReply.flags |= NTLM_NEG_NTLM;
760         else {
761             kdc_log(context, config, 0, "NTLM client doesn't support NTLM");
762             goto out;
763         }
764
765         r.u.ntlmInitReply.flags |= 
766             NTLM_NEG_TARGET_DOMAIN |
767             NTLM_ENC_128;
768
769 #define ALL \
770         NTLM_NEG_SIGN| \
771         NTLM_NEG_SEAL| \
772         NTLM_NEG_ALWAYS_SIGN| \
773         NTLM_NEG_NTLM2_SESSION| \
774         NTLM_NEG_KEYEX
775
776         r.u.ntlmInitReply.flags |= (ireq.u.ntlmInit.flags & (ALL));
777
778 #undef ALL
779
780         r.u.ntlmInitReply.targetname = 
781             get_ntlm_targetname(context, client);
782         if (r.u.ntlmInitReply.targetname == NULL) {
783             krb5_set_error_string(context, "out of memory");
784             ret = ENOMEM;
785             goto out;
786         }
787         r.u.ntlmInitReply.challange.data = malloc(8);
788         if (r.u.ntlmInitReply.challange.data == NULL) {
789             krb5_set_error_string(context, "out of memory");
790             ret = ENOMEM;
791             goto out;
792         }
793         r.u.ntlmInitReply.challange.length = 8;
794         if (RAND_bytes(r.u.ntlmInitReply.challange.data,
795                        r.u.ntlmInitReply.challange.length) != 1) 
796         {
797             krb5_set_error_string(context, "out of random error");
798             ret = ENOMEM;
799             goto out;
800         }
801         /* XXX fix targetinfo */
802         ALLOC(r.u.ntlmInitReply.targetinfo);
803         if (r.u.ntlmInitReply.targetinfo == NULL) {
804             krb5_set_error_string(context, "out of memory");
805             ret = ENOMEM;
806             goto out;
807         }
808
809         ret = fill_targetinfo(context,
810                               r.u.ntlmInitReply.targetname,
811                               client,
812                               r.u.ntlmInitReply.targetinfo);
813         if (ret) {
814             krb5_set_error_string(context, "out of memory");
815             ret = ENOMEM;
816             goto out;
817         }
818
819         /* 
820          * Save data encryted in opaque for the second part of the
821          * ntlm authentication
822          */
823         sp = krb5_storage_emem();
824         if (sp == NULL) {
825             ret = ENOMEM;
826             krb5_set_error_string(context, "out of memory");
827             goto out;
828         }
829         
830         ret = krb5_storage_write(sp, r.u.ntlmInitReply.challange.data, 8);
831         if (ret != 8) {
832             ret = ENOMEM;
833             krb5_set_error_string(context, "storage write challange");
834             goto out;
835         }
836         ret = krb5_store_uint32(sp, r.u.ntlmInitReply.flags);
837         if (ret) {
838             krb5_clear_error_string(context);
839             goto out;
840         }
841
842         ret = krb5_storage_to_data(sp, &buf);
843         if (ret) {
844             krb5_clear_error_string(context);
845             goto out;
846         }
847
848         ret = get_digest_key(context, config, server, &crypto);
849         if (ret)
850             goto out;
851
852         ret = krb5_encrypt(context, crypto, KRB5_KU_DIGEST_OPAQUE,
853                            buf.data, buf.length, &r.u.ntlmInitReply.opaque);
854         krb5_data_free(&buf);
855         krb5_crypto_destroy(context, crypto);
856         crypto = NULL;
857         if (ret)
858             goto out;
859
860         kdc_log(context, config, 0, "NTLM init from %s", from);
861
862         break;
863
864     case choice_DigestReqInner_ntlmRequest: {
865         krb5_principal clientprincipal;
866         unsigned char sessionkey[16];
867         unsigned char challange[8];
868         uint32_t flags;
869         Key *key = NULL;
870         int version;
871             
872         r.element = choice_DigestRepInner_ntlmResponse;
873         r.u.ntlmResponse.success = 0;
874         r.u.ntlmResponse.flags = 0;
875         r.u.ntlmResponse.sessionkey = NULL;
876         r.u.ntlmResponse.tickets = NULL;
877
878         /* get username */
879         ret = krb5_parse_name(context,
880                               ireq.u.ntlmRequest.username,
881                               &clientprincipal);
882         if (ret)
883             goto out;
884
885         ret = _kdc_db_fetch(context, config, clientprincipal,
886                             HDB_F_GET_CLIENT, NULL, &user);
887         krb5_free_principal(context, clientprincipal);
888         if (ret) {
889             krb5_set_error_string(context, "NTLM user %s not in database",
890                                   ireq.u.ntlmRequest.username);
891             goto out;
892         }
893
894         ret = get_digest_key(context, config, server, &crypto);
895         if (ret)
896             goto out;
897
898         ret = krb5_decrypt(context, crypto, KRB5_KU_DIGEST_OPAQUE,
899                            ireq.u.ntlmRequest.opaque.data,
900                            ireq.u.ntlmRequest.opaque.length, &buf);
901         krb5_crypto_destroy(context, crypto);
902         crypto = NULL;
903         if (ret)
904             goto out;
905
906         sp = krb5_storage_from_data(&buf);
907         if (sp == NULL) {
908             ret = ENOMEM;
909             krb5_set_error_string(context, "out of memory");
910             goto out;
911         }
912         
913         ret = krb5_storage_read(sp, challange, sizeof(challange));
914         if (ret != sizeof(challange)) {
915             krb5_set_error_string(context, "NTLM storage read challange");
916             ret = ENOMEM;
917             goto out;
918         }
919         ret = krb5_ret_uint32(sp, &flags);
920         if (ret) {
921             krb5_set_error_string(context, "NTLM storage read flags");
922             goto out;
923         }
924         krb5_data_free(&buf);
925
926         if ((flags & NTLM_NEG_NTLM) == 0) {
927             ret = EINVAL;
928             krb5_set_error_string(context, "NTLM not negotiated");
929             goto out;
930         }
931
932         ret = hdb_enctype2key(context, &user->entry, 
933                               ETYPE_ARCFOUR_HMAC_MD5, &key);
934         if (ret) {
935             krb5_set_error_string(context, "NTLM missing arcfour key");
936             goto out;
937         }
938
939         /* check if this is NTLMv2 */
940         if (ireq.u.ntlmRequest.ntlm.length != 24) {
941             struct ntlm_buf infotarget, answer;
942             char *targetname;
943
944             if ((config->digests_allowed & NTLM_V2) == 0) {
945                 kdc_log(context, config, 0, "NTLM v2 not allowed");
946                 goto out;
947             }
948
949             version = 2;
950
951             targetname = get_ntlm_targetname(context, client);
952             if (targetname == NULL) {
953                 krb5_set_error_string(context, "out of memory");
954                 ret = ENOMEM;
955                 goto out;
956             }
957
958             answer.length = ireq.u.ntlmRequest.ntlm.length;
959             answer.data = ireq.u.ntlmRequest.ntlm.data;
960
961             ret = heim_ntlm_verify_ntlm2(key->key.keyvalue.data,
962                                          key->key.keyvalue.length,
963                                          ireq.u.ntlmRequest.username,
964                                          targetname,
965                                          0,
966                                          challange,
967                                          &answer,
968                                          &infotarget,
969                                          sessionkey);
970             free(targetname);
971             if (ret) {
972                 krb5_set_error_string(context, "NTLM v2 verify failed");
973                 goto out;
974             }
975
976             /* XXX verify infotarget matches client (checksum ?) */
977
978             free(infotarget.data);
979             /* */
980
981         } else {
982             struct ntlm_buf answer;
983
984             version = 1;
985
986             if (flags & NTLM_NEG_NTLM2_SESSION) {
987                 char sessionhash[MD5_DIGEST_LENGTH];
988                 MD5_CTX md5ctx;
989                 
990                 if ((config->digests_allowed & NTLM_V1_SESSION) == 0) {
991                     kdc_log(context, config, 0, "NTLM v1-session not allowed");
992                     goto out;
993                 }
994
995                 if (ireq.u.ntlmRequest.lm.length != 24) {
996                     krb5_set_error_string(context, "LM hash have wrong length "
997                                           "for NTLM session key");
998                     ret = EINVAL;
999                     goto out;
1000                 }
1001                 
1002                 MD5_Init(&md5ctx);
1003                 MD5_Update(&md5ctx, challange, sizeof(challange));
1004                 MD5_Update(&md5ctx, ireq.u.ntlmRequest.lm.data, 8);
1005                 MD5_Final(sessionhash, &md5ctx);
1006                 memcpy(challange, sessionhash, sizeof(challange));
1007             } else {
1008                 if ((config->digests_allowed & NTLM_V1) == 0) {
1009                     kdc_log(context, config, 0, "NTLM v1 not allowed");
1010                     goto out;
1011                 }
1012             }
1013             
1014             ret = heim_ntlm_calculate_ntlm1(key->key.keyvalue.data,
1015                                             key->key.keyvalue.length,
1016                                             challange, &answer);
1017             if (ret) {
1018                 krb5_set_error_string(context, "NTLM missing arcfour key");
1019                 goto out;
1020             }
1021             
1022             if (ireq.u.ntlmRequest.ntlm.length != answer.length ||
1023                 memcmp(ireq.u.ntlmRequest.ntlm.data, answer.data, answer.length) != 0)
1024             {
1025                 free(answer.data);
1026                 ret = EINVAL;
1027                 krb5_set_error_string(context, "NTLM hash mismatch");
1028                 goto out;
1029             }
1030             free(answer.data);
1031
1032             {
1033                 MD4_CTX ctx;
1034
1035                 MD4_Init(&ctx);
1036                 MD4_Update(&ctx, 
1037                            key->key.keyvalue.data, key->key.keyvalue.length);
1038                 MD4_Final(sessionkey, &ctx);
1039             }
1040         }
1041
1042         if (ireq.u.ntlmRequest.sessionkey) {
1043             unsigned char masterkey[MD4_DIGEST_LENGTH];
1044             RC4_KEY rc4;
1045             size_t len;
1046             
1047             if ((flags & NTLM_NEG_KEYEX) == 0) {
1048                 krb5_set_error_string(context,
1049                                       "NTLM client failed to neg key "
1050                                       "exchange but still sent key");
1051                 goto out;
1052             }
1053             
1054             len = ireq.u.ntlmRequest.sessionkey->length;
1055             if (len != sizeof(masterkey)){
1056                 krb5_set_error_string(context,
1057                                       "NTLM master key wrong length: %lu",
1058                                       (unsigned long)len);
1059                 goto out;
1060             }
1061             
1062             RC4_set_key(&rc4, sizeof(sessionkey), sessionkey);
1063             
1064             RC4(&rc4, sizeof(masterkey),
1065                 ireq.u.ntlmRequest.sessionkey->data, 
1066                 masterkey);
1067             memset(&rc4, 0, sizeof(rc4));
1068             
1069             r.u.ntlmResponse.sessionkey = 
1070                 malloc(sizeof(*r.u.ntlmResponse.sessionkey));
1071             if (r.u.ntlmResponse.sessionkey == NULL) {
1072                 krb5_set_error_string(context, "out of memory");
1073                 goto out;
1074             }
1075             
1076             ret = krb5_data_copy(r.u.ntlmResponse.sessionkey,
1077                                  masterkey, sizeof(masterkey));
1078             if (ret) {
1079                 krb5_set_error_string(context, "out of memory");
1080                 goto out;
1081             }
1082         }
1083
1084         r.u.ntlmResponse.success = 1;
1085         kdc_log(context, config, 0, "NTLM version %d successful for %s",
1086                 version, ireq.u.ntlmRequest.username);
1087
1088         break;
1089     }
1090     default:
1091         r.element = choice_DigestRepInner_error;
1092         r.u.error.reason = strdup("unknown operation");
1093         if (r.u.error.reason == NULL) {
1094             krb5_set_error_string(context, "out of memory");
1095             ret = ENOMEM;
1096             goto out;
1097         }
1098         r.u.error.code = EINVAL;
1099         break;
1100     }
1101
1102     ASN1_MALLOC_ENCODE(DigestRepInner, buf.data, buf.length, &r, &size, ret);
1103     if (ret) {
1104         krb5_set_error_string(context, "Failed to encode inner digest reply");
1105         goto out;
1106     }
1107     if (size != buf.length)
1108         krb5_abortx(context, "ASN1 internal error");
1109
1110     krb5_auth_con_addflags(context, ac, KRB5_AUTH_CONTEXT_USE_SUBKEY, NULL);
1111
1112     ret = krb5_mk_rep (context, ac, &rep.apRep);
1113     if (ret)
1114         goto out;
1115
1116     {
1117         krb5_keyblock *key;
1118
1119         ret = krb5_auth_con_getlocalsubkey(context, ac, &key);
1120         if (ret)
1121             goto out;
1122
1123         ret = krb5_crypto_init(context, key, 0, &crypto);
1124         krb5_free_keyblock (context, key);
1125         if (ret)
1126             goto out;
1127     }
1128
1129     ret = krb5_encrypt_EncryptedData(context, crypto, KRB5_KU_DIGEST_ENCRYPT, 
1130                                      buf.data, buf.length, 0,
1131                                      &rep.innerRep);
1132     
1133     ASN1_MALLOC_ENCODE(DigestREP, reply->data, reply->length, &rep, &size, ret);
1134     if (ret) {
1135         krb5_set_error_string(context, "Failed to encode digest reply");
1136         goto out;
1137     }
1138     if (size != reply->length)
1139         krb5_abortx(context, "ASN1 internal error");
1140
1141     
1142 out:
1143     if (ac)
1144         krb5_auth_con_free(context, ac);
1145     if (ret)
1146         krb5_warn(context, ret, "Digest request from %s failed", from);
1147     if (ticket)
1148         krb5_free_ticket(context, ticket);
1149     if (id)
1150         krb5_kt_close(context, id);
1151     if (crypto)
1152         krb5_crypto_destroy(context, crypto);
1153     if (sp)
1154         krb5_storage_free(sp);
1155     if (user)
1156         _kdc_free_ent (context, user);
1157     if (server)
1158         _kdc_free_ent (context, server);
1159     if (client)
1160         _kdc_free_ent (context, client);
1161     if (password) {
1162         memset(password, 0, strlen(password));
1163         free (password);
1164     }
1165     if (client_name)
1166         free (client_name);
1167     krb5_data_free(&buf);
1168     krb5_data_free(&serverNonce);
1169     free_DigestREP(&rep);
1170     free_DigestRepInner(&r);
1171     free_DigestReqInner(&ireq);
1172
1173     return ret;
1174 }