HEIMDAL: move code from source4/heimdal* to third_party/heimdal*
[samba.git] / third_party / heimdal / lib / ntlm / ntlm.c
1 /*
2  * Copyright (c) 2006 - 2008 Kungliga Tekniska Högskolan
3  * (Royal Institute of Technology, Stockholm, Sweden).
4  * All rights reserved.
5  *
6  * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * 3. Neither the name of the Institute nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35
36 #include <config.h>
37
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <assert.h>
41 #include <string.h>
42 #include <ctype.h>
43 #include <errno.h>
44 #include <limits.h>
45
46 #include <roken.h>
47
48 #include <wind.h>
49 #include <parse_units.h>
50 #include <krb5.h>
51
52
53 #define HC_DEPRECATED_CRYPTO
54
55 #include "krb5-types.h"
56 #include "crypto-headers.h"
57
58 #include <heimntlm.h>
59
60 /*! \mainpage Heimdal NTLM library
61  *
62  * \section intro Introduction
63  *
64  * Heimdal libheimntlm library is a implementation of the NTLM
65  * protocol, both version 1 and 2. The GSS-API mech that uses this
66  * library adds support for transport encryption and integrity
67  * checking.
68  *
69  * NTLM is a protocol for mutual authentication, its still used in
70  * many protocol where Kerberos is not support, one example is
71  * EAP/X802.1x mechanism LEAP from Microsoft and Cisco.
72  *
73  * This is a support library for the core protocol, its used in
74  * Heimdal to implement and GSS-API mechanism. There is also support
75  * in the KDC to do remote digest authenticiation, this to allow
76  * services to authenticate users w/o direct access to the users ntlm
77  * hashes (same as Kerberos arcfour enctype keys).
78  *
79  * More information about the NTLM protocol can found here
80  * http://davenport.sourceforge.net/ntlm.html .
81  *
82  * The Heimdal projects web page: http://www.h5l.org/
83  *
84  * @section ntlm_example NTLM Example
85  *
86  * Example to to use @ref test_ntlm.c .
87  *
88  * @example test_ntlm.c
89  *
90  * Example how to use the NTLM primitives.
91  *
92  */
93
94 /** @defgroup ntlm_core Heimdal NTLM library
95  *
96  * The NTLM core functions implement the string2key generation
97  * function, message encode and decode function, and the hash function
98  * functions.
99  */
100
101 struct sec_buffer {
102     uint16_t length;
103     uint16_t allocated;
104     uint32_t offset;
105 };
106
107 static const unsigned char ntlmsigature[8] = "NTLMSSP\x00";
108
109 time_t heim_ntlm_time_skew = 300;
110
111 /*
112  *
113  */
114
115 #define CHECK(f, e)                                                     \
116     do {                                                                \
117         ret = f;                                                        \
118         if (ret != (ssize_t)(e)) {                                      \
119             ret = HNTLM_ERR_DECODE;                                     \
120             goto out;                                                   \
121         }                                                               \
122     } while(/*CONSTCOND*/0)
123
124 #define CHECK_SIZE(f, e)                                                \
125     do {                                                                \
126         ssize_t sret = f;                                               \
127         if (sret != (ssize_t)(e)) {                                     \
128             ret = HNTLM_ERR_DECODE;                                     \
129             goto out;                                                   \
130         }                                                               \
131     } while(/*CONSTCOND*/0)
132
133 #define CHECK_OFFSET(f, e)                                              \
134     do {                                                                \
135         off_t sret = f;                                                 \
136         if (sret != (e)) {                                              \
137             ret = HNTLM_ERR_DECODE;                                     \
138             goto out;                                                   \
139         }                                                               \
140     } while(/*CONSTCOND*/0)
141
142
143 static struct units ntlm_flag_units[] = {
144 #define ntlm_flag(x) { #x, NTLM_##x }
145     ntlm_flag(ENC_56),
146     ntlm_flag(NEG_KEYEX),
147     ntlm_flag(ENC_128),
148     ntlm_flag(MBZ1),
149     ntlm_flag(MBZ2),
150     ntlm_flag(MBZ3),
151     ntlm_flag(NEG_VERSION),
152     ntlm_flag(MBZ4),
153     ntlm_flag(NEG_TARGET_INFO),
154     ntlm_flag(NON_NT_SESSION_KEY),
155     ntlm_flag(MBZ5),
156     ntlm_flag(NEG_IDENTIFY),
157     ntlm_flag(NEG_NTLM2),
158     ntlm_flag(TARGET_SHARE),
159     ntlm_flag(TARGET_SERVER),
160     ntlm_flag(TARGET_DOMAIN),
161     ntlm_flag(NEG_ALWAYS_SIGN),
162     ntlm_flag(MBZ6),
163     ntlm_flag(OEM_SUPPLIED_WORKSTATION),
164     ntlm_flag(OEM_SUPPLIED_DOMAIN),
165     ntlm_flag(NEG_ANONYMOUS),
166     ntlm_flag(NEG_NT_ONLY),
167     ntlm_flag(NEG_NTLM),
168     ntlm_flag(MBZ8),
169     ntlm_flag(NEG_LM_KEY),
170     ntlm_flag(NEG_DATAGRAM),
171     ntlm_flag(NEG_SEAL),
172     ntlm_flag(NEG_SIGN),
173     ntlm_flag(MBZ9),
174     ntlm_flag(NEG_TARGET),
175     ntlm_flag(NEG_OEM),
176     ntlm_flag(NEG_UNICODE),
177 #undef ntlm_flag
178     {NULL, 0}
179 };
180
181 size_t
182 heim_ntlm_unparse_flags(uint32_t flags, char *s, size_t len)
183 {
184     return unparse_flags(flags, ntlm_flag_units, s, len);
185 }
186
187
188 /**
189  * heim_ntlm_free_buf frees the ntlm buffer
190  *
191  * @param p buffer to be freed
192  *
193  * @ingroup ntlm_core
194  */
195
196 void
197 heim_ntlm_free_buf(struct ntlm_buf *p)
198 {
199     if (p->data)
200         free(p->data);
201     p->data = NULL;
202     p->length = 0;
203 }
204
205
206 static int
207 ascii2ucs2le(const char *string, int up, struct ntlm_buf *buf)
208 {
209     uint16_t *data;
210     size_t len, n;
211     uint8_t *p;
212     int ret;
213
214     ret = wind_utf8ucs2_length(string, &len);
215     if (ret)
216         return ret;
217     if (len > UINT_MAX / sizeof(data[0]))
218         return ERANGE;
219
220     data = malloc(len * sizeof(data[0]));
221     if (data == NULL)
222         return ENOMEM;
223
224     ret = wind_utf8ucs2(string, data, &len);
225     if (ret) {
226         free(data);
227         return ret;
228     }
229     
230     if (len == 0) {
231         free(data);
232         buf->data = NULL;
233         buf->length = 0;
234         return 0;
235     }
236
237     /* uppercase string, only handle ascii right now */
238     if (up) {
239         for (n = 0; n < len ; n++) {
240             if (data[n] < 128)
241                 data[n] = toupper((int)data[n]);
242         }
243     }
244
245     buf->length = len * 2;
246     p = buf->data = malloc(buf->length);
247     if (buf->data == NULL && len != 0) {
248         free(data);
249         heim_ntlm_free_buf(buf);
250         return ENOMEM;
251     }
252
253     for (n = 0; n < len ; n++) {
254         p[(n * 2) + 0] = (data[n]     ) & 0xff;
255         p[(n * 2) + 1] = (data[n] >> 8) & 0xff;
256     }
257     memset(data, 0, sizeof(data[0]) * len);
258     free(data);
259
260     return 0;
261 }
262
263 /*
264  * Sizes in bytes
265  */
266
267 #define SIZE_SEC_BUFFER         (2+2+4)
268 #define SIZE_OS_VERSION         (8)
269
270 /*
271  *
272  */
273
274 static krb5_error_code
275 ret_sec_buffer(krb5_storage *sp, struct sec_buffer *buf)
276 {
277     krb5_error_code ret;
278     CHECK(krb5_ret_uint16(sp, &buf->length), 0);
279     CHECK(krb5_ret_uint16(sp, &buf->allocated), 0);
280     CHECK(krb5_ret_uint32(sp, &buf->offset), 0);
281 out:
282     return ret;
283 }
284
285 static krb5_error_code
286 store_sec_buffer(krb5_storage *sp, const struct sec_buffer *buf)
287 {
288     krb5_error_code ret;
289     CHECK(krb5_store_uint16(sp, buf->length), 0);
290     CHECK(krb5_store_uint16(sp, buf->allocated), 0);
291     CHECK(krb5_store_uint32(sp, buf->offset), 0);
292 out:
293     return ret;
294 }
295
296 /*
297  * Strings are either OEM or UNICODE. The later is encoded as ucs2 on
298  * wire, but using utf8 in memory.
299  */
300
301 static size_t
302 len_string(int ucs2, const char *s)
303 {
304     if (ucs2) {
305         size_t len;
306         int ret;
307
308         ret = wind_utf8ucs2_length(s, &len);
309         if (ret == 0)
310             return len * 2;
311         return strlen(s) * 5 * 2;
312     } else {
313         return strlen(s);
314     }
315 }
316
317 /*
318  *
319  */
320
321 static krb5_error_code
322 ret_string(krb5_storage *sp, int ucs2, size_t len, char **s)
323 {
324     krb5_error_code ret;
325     uint16_t *data = NULL;
326
327     *s = malloc(len + 1);
328     if (*s == NULL)
329         return ENOMEM;
330     CHECK_SIZE(krb5_storage_read(sp, *s, len), len);
331
332     (*s)[len] = '\0';
333
334     if (ucs2) {
335         unsigned int flags = WIND_RW_LE;
336         size_t utf16len = len / 2;
337         size_t utf8len;
338
339         data = malloc(utf16len * sizeof(data[0])); 
340         if (data == NULL) {
341             free(*s); *s = NULL;
342             ret = ENOMEM;
343             goto out;
344         }
345
346         ret = wind_ucs2read(*s, len, &flags, data, &utf16len);
347         free(*s); *s = NULL;
348         if (ret) {
349             goto out;
350         }
351
352         CHECK(wind_ucs2utf8_length(data, utf16len, &utf8len), 0);
353
354         utf8len += 1;
355         
356         *s = malloc(utf8len);
357         if (s == NULL) {
358             ret = ENOMEM;
359             goto out;
360         }
361
362         CHECK(wind_ucs2utf8(data, utf16len, *s, &utf8len), 0);
363     }
364     ret = 0;
365  out:
366     if (data)
367         free(data);
368
369     return ret;
370 }
371
372
373
374 static krb5_error_code
375 ret_sec_string(krb5_storage *sp, int ucs2, struct sec_buffer *desc, char **s)
376 {
377     krb5_error_code ret = 0;
378     CHECK_OFFSET(krb5_storage_seek(sp, desc->offset, SEEK_SET), desc->offset);
379     CHECK(ret_string(sp, ucs2, desc->length, s), 0);
380  out:
381     return ret; 
382 }
383
384 static krb5_error_code
385 put_string(krb5_storage *sp, int ucs2, const char *s)
386 {
387     krb5_error_code ret;
388     struct ntlm_buf buf;
389
390     if (ucs2) {
391         ret = ascii2ucs2le(s, 0, &buf);
392         if (ret)
393             return ret;
394     } else {
395         buf.data = rk_UNCONST(s);
396         buf.length = strlen(s);
397     }
398
399     CHECK_SIZE(krb5_storage_write(sp, buf.data, buf.length), buf.length);
400     if (ucs2)
401         heim_ntlm_free_buf(&buf);
402     ret = 0;
403 out:
404     return ret;
405 }
406
407 /*
408  *
409  */
410
411 static krb5_error_code
412 ret_buf(krb5_storage *sp, struct sec_buffer *desc, struct ntlm_buf *buf)
413 {
414     krb5_error_code ret;
415
416     buf->data = malloc(desc->length);
417     buf->length = desc->length;
418     CHECK_OFFSET(krb5_storage_seek(sp, desc->offset, SEEK_SET), desc->offset);
419     CHECK_SIZE(krb5_storage_read(sp, buf->data, buf->length), buf->length);
420     ret = 0;
421 out:
422     return ret;
423 }
424
425 static krb5_error_code
426 put_buf(krb5_storage *sp, const struct ntlm_buf *buf)
427 {
428     krb5_error_code ret;
429     CHECK_SIZE(krb5_storage_write(sp, buf->data, buf->length), buf->length);
430     ret = 0;
431 out:
432     return ret;
433 }
434
435 /**
436  * Frees the ntlm_targetinfo message
437  *
438  * @param ti targetinfo to be freed
439  *
440  * @ingroup ntlm_core
441  */
442
443 void
444 heim_ntlm_free_targetinfo(struct ntlm_targetinfo *ti)
445 {
446     free(ti->servername);
447     free(ti->domainname);
448     free(ti->dnsdomainname);
449     free(ti->dnsservername);
450     free(ti->dnstreename);
451     free(ti->targetname);
452     heim_ntlm_free_buf(&ti->channel_bindings);
453     memset(ti, 0, sizeof(*ti));
454 }
455
456 static int
457 encode_ti_string(krb5_storage *out, uint16_t type, int ucs2, char *s)
458 {
459     krb5_error_code ret;
460     CHECK(krb5_store_uint16(out, type), 0);
461     CHECK(krb5_store_uint16(out, len_string(ucs2, s)), 0);
462     CHECK(put_string(out, ucs2, s), 0);
463 out:
464     return ret;
465 }
466
467 /**
468  * Encodes a ntlm_targetinfo message.
469  *
470  * @param ti the ntlm_targetinfo message to encode.
471  * @param ucs2 ignored
472  * @param data is the return buffer with the encoded message, should be
473  * freed with heim_ntlm_free_buf().
474  *
475  * @return In case of success 0 is return, an errors, a errno in what
476  * went wrong.
477  *
478  * @ingroup ntlm_core
479  */
480
481 int
482 heim_ntlm_encode_targetinfo(const struct ntlm_targetinfo *ti,
483                             int ucs2,
484                             struct ntlm_buf *data)
485 {
486     krb5_error_code ret;
487     krb5_storage *out;
488
489     data->data = NULL;
490     data->length = 0;
491
492     out = krb5_storage_emem();
493     if (out == NULL)
494         return ENOMEM;
495
496     krb5_storage_set_byteorder(out, KRB5_STORAGE_BYTEORDER_LE);
497
498     if (ti->servername)
499         CHECK(encode_ti_string(out, 1, ucs2, ti->servername), 0);
500     if (ti->domainname)
501         CHECK(encode_ti_string(out, 2, ucs2, ti->domainname), 0);
502     if (ti->dnsservername)
503         CHECK(encode_ti_string(out, 3, ucs2, ti->dnsservername), 0);
504     if (ti->dnsdomainname)
505         CHECK(encode_ti_string(out, 4, ucs2, ti->dnsdomainname), 0);
506     if (ti->dnstreename)
507         CHECK(encode_ti_string(out, 5, ucs2, ti->dnstreename), 0);
508     if (ti->avflags) {
509         CHECK(krb5_store_uint16(out, 6), 0);
510         CHECK(krb5_store_uint16(out, 4), 0);
511         CHECK(krb5_store_uint32(out, ti->avflags), 0);
512     }
513     if (ti->timestamp) {
514         CHECK(krb5_store_uint16(out, 7), 0);
515         CHECK(krb5_store_uint16(out, 8), 0);
516         CHECK(krb5_store_uint32(out, ti->timestamp & 0xffffffff), 0);
517         CHECK(krb5_store_uint32(out, (ti->timestamp >> 32) & 0xffffffff), 0);
518     }   
519     if (ti->targetname) {
520         CHECK(encode_ti_string(out, 9, ucs2, ti->targetname), 0);
521     }
522     if (ti->channel_bindings.length) {
523         CHECK(krb5_store_uint16(out, 10), 0);
524         CHECK(krb5_store_uint16(out, ti->channel_bindings.length), 0);
525         CHECK_SIZE(krb5_storage_write(out, ti->channel_bindings.data, ti->channel_bindings.length), ti->channel_bindings.length);
526     }
527
528     /* end tag */
529     CHECK(krb5_store_int16(out, 0), 0);
530     CHECK(krb5_store_int16(out, 0), 0);
531
532     {
533         krb5_data d;
534         ret = krb5_storage_to_data(out, &d);
535         data->data = d.data;
536         data->length = d.length;
537     }
538 out:
539     krb5_storage_free(out);
540     return ret;
541 }
542
543 /**
544  * Decodes an NTLM targetinfo message
545  *
546  * @param data input data buffer with the encode NTLM targetinfo message
547  * @param ucs2 if the strings should be encoded with ucs2 (selected by flag in message).
548  * @param ti the decoded target info, should be freed with heim_ntlm_free_targetinfo().
549  *
550  * @return In case of success 0 is return, an errors, a errno in what
551  * went wrong.
552  *
553  * @ingroup ntlm_core
554  */
555
556 int
557 heim_ntlm_decode_targetinfo(const struct ntlm_buf *data,
558                             int ucs2,
559                             struct ntlm_targetinfo *ti)
560 {
561     uint16_t type, len;
562     krb5_storage *in;
563     int ret = 0, done = 0;
564
565     memset(ti, 0, sizeof(*ti));
566
567     if (data->length == 0)
568         return 0;
569
570     in = krb5_storage_from_readonly_mem(data->data, data->length);
571     if (in == NULL)
572         return ENOMEM;
573     krb5_storage_set_byteorder(in, KRB5_STORAGE_BYTEORDER_LE);
574
575     while (!done) {
576         CHECK(krb5_ret_uint16(in, &type), 0);
577         CHECK(krb5_ret_uint16(in, &len), 0);
578
579         switch (type) {
580         case 0:
581             done = 1;
582             break;
583         case 1:
584             CHECK(ret_string(in, ucs2, len, &ti->servername), 0);
585             break;
586         case 2:
587             CHECK(ret_string(in, ucs2, len, &ti->domainname), 0);
588             break;
589         case 3:
590             CHECK(ret_string(in, ucs2, len, &ti->dnsservername), 0);
591             break;
592         case 4:
593             CHECK(ret_string(in, ucs2, len, &ti->dnsdomainname), 0);
594             break;
595         case 5:
596             CHECK(ret_string(in, ucs2, len, &ti->dnstreename), 0);
597             break;
598         case 6:
599             CHECK(krb5_ret_uint32(in, &ti->avflags), 0);
600             break;
601         case 7: {
602             uint32_t tmp;
603             CHECK(krb5_ret_uint32(in, &tmp), 0);
604             ti->timestamp = tmp;
605             CHECK(krb5_ret_uint32(in, &tmp), 0);
606             ti->timestamp |= ((uint64_t)tmp) << 32;
607             break;
608         }       
609         case 9:
610             CHECK(ret_string(in, 1, len, &ti->targetname), 0);
611             break;
612         case 10:
613             ti->channel_bindings.data = malloc(len);
614             if (ti->channel_bindings.data == NULL) {
615                 ret = ENOMEM;
616                 goto out;
617             }
618             ti->channel_bindings.length = len;
619             CHECK_SIZE(krb5_storage_read(in, ti->channel_bindings.data, len), len);
620             break;
621         default:
622             krb5_storage_seek(in, len, SEEK_CUR);
623             break;
624         }
625     }
626  out:
627     if (in)
628         krb5_storage_free(in);
629     return ret;
630 }
631
632 static krb5_error_code
633 encode_os_version(krb5_storage *out)
634 {
635     krb5_error_code ret;
636     CHECK(krb5_store_uint8(out, 0x06), 0);
637     CHECK(krb5_store_uint8(out, 0x01), 0);
638     CHECK(krb5_store_uint16(out, 0x1db0), 0);
639     CHECK(krb5_store_uint8(out, 0x00), 0);
640     CHECK(krb5_store_uint8(out, 0x00), 0);
641     CHECK(krb5_store_uint8(out, 0x00), 0);
642     CHECK(krb5_store_uint8(out, 0x0f), 0); /* ntlm version 15 */
643  out:
644     return ret;
645 }
646
647 /**
648  * Frees the ntlm_type1 message
649  *
650  * @param data message to be freed
651  *
652  * @ingroup ntlm_core
653  */
654
655 void
656 heim_ntlm_free_type1(struct ntlm_type1 *data)
657 {
658     if (data->domain)
659         free(data->domain);
660     if (data->hostname)
661         free(data->hostname);
662     memset(data, 0, sizeof(*data));
663 }
664
665 int
666 heim_ntlm_decode_type1(const struct ntlm_buf *buf, struct ntlm_type1 *data)
667 {
668     krb5_error_code ret;
669     unsigned char sig[8];
670     uint32_t type;
671     struct sec_buffer domain, hostname;
672     krb5_storage *in;
673     int ucs2;
674
675     memset(data, 0, sizeof(*data));
676
677     in = krb5_storage_from_readonly_mem(buf->data, buf->length);
678     if (in == NULL) {
679         ret = ENOMEM;
680         goto out;
681     }
682     krb5_storage_set_byteorder(in, KRB5_STORAGE_BYTEORDER_LE);
683
684     CHECK_SIZE(krb5_storage_read(in, sig, sizeof(sig)), sizeof(sig));
685     CHECK(memcmp(ntlmsigature, sig, sizeof(ntlmsigature)), 0);
686     CHECK(krb5_ret_uint32(in, &type), 0);
687     CHECK(type, 1);
688     CHECK(krb5_ret_uint32(in, &data->flags), 0);
689
690     ucs2 = !!(data->flags & NTLM_NEG_UNICODE);
691
692     /*
693      * domain and hostname are unconditionally encoded regardless of
694      * NTLMSSP_NEGOTIATE_OEM_{HOSTNAME,WORKSTATION}_SUPPLIED flag
695      */
696     CHECK(ret_sec_buffer(in, &domain), 0);
697     CHECK(ret_sec_buffer(in, &hostname), 0);
698
699     if (data->flags & NTLM_NEG_VERSION) {
700         CHECK(krb5_ret_uint32(in, &data->os[0]), 0);
701         CHECK(krb5_ret_uint32(in, &data->os[1]), 0);
702     }
703
704     if (data->flags & NTLM_OEM_SUPPLIED_DOMAIN)
705         CHECK(ret_sec_string(in, ucs2, &domain, &data->domain), 0);
706     if (data->flags & NTLM_OEM_SUPPLIED_WORKSTATION)
707         CHECK(ret_sec_string(in, ucs2, &hostname, &data->hostname), 0);
708
709 out:
710     if (in)
711         krb5_storage_free(in);
712     if (ret)
713         heim_ntlm_free_type1(data);
714
715     return ret;
716 }
717
718 /**
719  * Encodes an ntlm_type1 message.
720  *
721  * @param type1 the ntlm_type1 message to encode.
722  * @param data is the return buffer with the encoded message, should be
723  * freed with heim_ntlm_free_buf().
724  *
725  * @return In case of success 0 is return, an errors, a errno in what
726  * went wrong.
727  *
728  * @ingroup ntlm_core
729  */
730
731 int
732 heim_ntlm_encode_type1(const struct ntlm_type1 *type1, struct ntlm_buf *data)
733 {
734     krb5_error_code ret;
735     struct sec_buffer domain, hostname;
736     krb5_storage *out;
737     uint32_t base, flags;
738     int ucs2 = 0;
739
740     flags = type1->flags;
741     base = 16;
742
743     if (flags & NTLM_NEG_UNICODE)
744         ucs2 = 1;
745
746     if (type1->domain) {
747         base += SIZE_SEC_BUFFER;
748         flags |= NTLM_OEM_SUPPLIED_DOMAIN;
749     }
750     if (type1->hostname) {
751         base += SIZE_SEC_BUFFER;
752         flags |= NTLM_OEM_SUPPLIED_WORKSTATION;
753     }
754     if (flags & NTLM_NEG_VERSION)
755         base += SIZE_OS_VERSION; /* os */
756
757     if (type1->domain) {
758         domain.offset = base;
759         domain.length = len_string(ucs2, type1->domain);
760         domain.allocated = domain.length;
761     } else {
762         domain.offset = 0;
763         domain.length = 0;
764         domain.allocated = 0;
765     }
766
767     if (type1->hostname) {
768         hostname.offset = domain.allocated + domain.offset;
769         hostname.length = len_string(ucs2, type1->hostname);
770         hostname.allocated = hostname.length;
771     } else {
772         hostname.offset = 0;
773         hostname.length = 0;
774         hostname.allocated = 0;
775     }
776
777     out = krb5_storage_emem();
778     if (out == NULL)
779         return ENOMEM;
780
781     krb5_storage_set_byteorder(out, KRB5_STORAGE_BYTEORDER_LE);
782     CHECK_SIZE(krb5_storage_write(out, ntlmsigature, sizeof(ntlmsigature)),
783           sizeof(ntlmsigature));
784     CHECK(krb5_store_uint32(out, 1), 0);
785     CHECK(krb5_store_uint32(out, flags), 0);
786
787     CHECK(store_sec_buffer(out, &domain), 0);
788     CHECK(store_sec_buffer(out, &hostname), 0);
789
790     if (flags & NTLM_NEG_VERSION) {
791         CHECK(encode_os_version(out), 0);
792     }
793     if (type1->domain)
794         CHECK(put_string(out, ucs2, type1->domain), 0);
795     if (type1->hostname)
796         CHECK(put_string(out, ucs2, type1->hostname), 0);
797
798     {
799         krb5_data d;
800         ret = krb5_storage_to_data(out, &d);
801         data->data = d.data;
802         data->length = d.length;
803     }
804 out:
805     krb5_storage_free(out);
806
807     return ret;
808 }
809
810 /**
811  * Frees the ntlm_type2 message
812  *
813  * @param data message to be freed
814  *
815  * @ingroup ntlm_core
816  */
817
818 void
819 heim_ntlm_free_type2(struct ntlm_type2 *data)
820 {
821     if (data->targetname)
822         free(data->targetname);
823     heim_ntlm_free_buf(&data->targetinfo);
824     memset(data, 0, sizeof(*data));
825 }
826
827 int
828 heim_ntlm_decode_type2(const struct ntlm_buf *buf, struct ntlm_type2 *type2)
829 {
830     krb5_error_code ret;
831     unsigned char sig[8];
832     uint32_t type, ctx[2];
833     struct sec_buffer targetname, targetinfo;
834     krb5_storage *in;
835     int ucs2 = 0;
836
837     memset(type2, 0, sizeof(*type2));
838
839     in = krb5_storage_from_readonly_mem(buf->data, buf->length);
840     if (in == NULL) {
841         ret = ENOMEM;
842         goto out;
843     }
844     krb5_storage_set_byteorder(in, KRB5_STORAGE_BYTEORDER_LE);
845
846     CHECK_SIZE(krb5_storage_read(in, sig, sizeof(sig)), sizeof(sig));
847     CHECK(memcmp(ntlmsigature, sig, sizeof(ntlmsigature)), 0);
848     CHECK(krb5_ret_uint32(in, &type), 0);
849     CHECK(type, 2);
850
851     CHECK(ret_sec_buffer(in, &targetname), 0);
852     CHECK(krb5_ret_uint32(in, &type2->flags), 0);
853     if (type2->flags & NTLM_NEG_UNICODE)
854         ucs2 = 1;
855     CHECK_SIZE(krb5_storage_read(in, type2->challenge, sizeof(type2->challenge)),
856           sizeof(type2->challenge));
857     CHECK(krb5_ret_uint32(in, &ctx[0]), 0); /* context */
858     CHECK(krb5_ret_uint32(in, &ctx[1]), 0);
859     CHECK(ret_sec_buffer(in, &targetinfo), 0);
860     /* os version */
861     if (type2->flags & NTLM_NEG_VERSION) {
862         CHECK(krb5_ret_uint32(in, &type2->os[0]), 0);
863         CHECK(krb5_ret_uint32(in, &type2->os[1]), 0);
864     }
865
866     CHECK(ret_sec_string(in, ucs2, &targetname, &type2->targetname), 0);
867     CHECK(ret_buf(in, &targetinfo, &type2->targetinfo), 0);
868     ret = 0;
869
870 out:
871     if (in)
872         krb5_storage_free(in);
873     if (ret)
874         heim_ntlm_free_type2(type2);
875
876     return ret;
877 }
878
879 /**
880  * Encodes an ntlm_type2 message.
881  *
882  * @param type2 the ntlm_type2 message to encode.
883  * @param data is the return buffer with the encoded message, should be
884  * freed with heim_ntlm_free_buf().
885  *
886  * @return In case of success 0 is return, an errors, a errno in what
887  * went wrong.
888  *
889  * @ingroup ntlm_core
890  */
891
892 int
893 heim_ntlm_encode_type2(const struct ntlm_type2 *type2, struct ntlm_buf *data)
894 {
895     struct sec_buffer targetname, targetinfo;
896     krb5_error_code ret;
897     krb5_storage *out = NULL;
898     uint32_t base;
899     int ucs2 = 0;
900
901     base = 48;
902
903     if (type2->flags & NTLM_NEG_VERSION)
904         base += SIZE_OS_VERSION;
905
906     if (type2->flags & NTLM_NEG_UNICODE)
907         ucs2 = 1;
908
909     targetname.offset = base;
910     targetname.length = len_string(ucs2, type2->targetname);
911     targetname.allocated = targetname.length;
912
913     targetinfo.offset = targetname.allocated + targetname.offset;
914     targetinfo.length = type2->targetinfo.length;
915     targetinfo.allocated = type2->targetinfo.length;
916
917     out = krb5_storage_emem();
918     if (out == NULL)
919         return ENOMEM;
920
921     krb5_storage_set_byteorder(out, KRB5_STORAGE_BYTEORDER_LE);
922     CHECK_SIZE(krb5_storage_write(out, ntlmsigature, sizeof(ntlmsigature)),
923           sizeof(ntlmsigature));
924     CHECK(krb5_store_uint32(out, 2), 0);
925     CHECK(store_sec_buffer(out, &targetname), 0);
926     CHECK(krb5_store_uint32(out, type2->flags), 0);
927     CHECK_SIZE(krb5_storage_write(out, type2->challenge, sizeof(type2->challenge)),
928           sizeof(type2->challenge));
929     CHECK(krb5_store_uint32(out, 0), 0); /* context */
930     CHECK(krb5_store_uint32(out, 0), 0);
931     CHECK(store_sec_buffer(out, &targetinfo), 0);
932     /* os version */
933     if (type2->flags & NTLM_NEG_VERSION) {
934         CHECK(encode_os_version(out), 0);
935     }
936     CHECK(put_string(out, ucs2, type2->targetname), 0);
937     CHECK_SIZE(krb5_storage_write(out, type2->targetinfo.data,
938                              type2->targetinfo.length),
939           type2->targetinfo.length);
940
941     {
942         krb5_data d;
943         ret = krb5_storage_to_data(out, &d);
944         data->data = d.data;
945         data->length = d.length;
946     }
947
948 out:
949     krb5_storage_free(out);
950
951     return ret;
952 }
953
954 /**
955  * Frees the ntlm_type3 message
956  *
957  * @param data message to be freed
958  *
959  * @ingroup ntlm_core
960  */
961
962 void
963 heim_ntlm_free_type3(struct ntlm_type3 *data)
964 {
965     heim_ntlm_free_buf(&data->lm);
966     heim_ntlm_free_buf(&data->ntlm);
967     if (data->targetname)
968         free(data->targetname);
969     if (data->username)
970         free(data->username);
971     if (data->ws)
972         free(data->ws);
973     heim_ntlm_free_buf(&data->sessionkey);
974     memset(data, 0, sizeof(*data));
975 }
976
977 /*
978  *
979  */
980
981 int
982 heim_ntlm_decode_type3(const struct ntlm_buf *buf,
983                        int ucs2,
984                        struct ntlm_type3 *type3)
985 {
986     krb5_error_code ret;
987     unsigned char sig[8];
988     uint32_t type;
989     krb5_storage *in;
990     struct sec_buffer lm, ntlm, target, username, sessionkey, ws;
991     uint32_t min_offset = 0xffffffff;
992
993     memset(type3, 0, sizeof(*type3));
994     memset(&sessionkey, 0, sizeof(sessionkey));
995
996     in = krb5_storage_from_readonly_mem(buf->data, buf->length);
997     if (in == NULL) {
998         ret = ENOMEM;
999         goto out;
1000     }
1001     krb5_storage_set_byteorder(in, KRB5_STORAGE_BYTEORDER_LE);
1002
1003     CHECK_SIZE(krb5_storage_read(in, sig, sizeof(sig)), sizeof(sig));
1004     CHECK(memcmp(ntlmsigature, sig, sizeof(ntlmsigature)), 0);
1005     CHECK(krb5_ret_uint32(in, &type), 0);
1006     CHECK(type, 3);
1007     CHECK(ret_sec_buffer(in, &lm), 0);
1008     if (lm.allocated)
1009         min_offset = min(min_offset, lm.offset);
1010     CHECK(ret_sec_buffer(in, &ntlm), 0);
1011     if (ntlm.allocated)
1012         min_offset = min(min_offset, ntlm.offset);
1013     CHECK(ret_sec_buffer(in, &target), 0);
1014     min_offset = min(min_offset, target.offset);
1015     CHECK(ret_sec_buffer(in, &username), 0);
1016     min_offset = min(min_offset, username.offset);
1017     CHECK(ret_sec_buffer(in, &ws), 0);
1018     if (ws.allocated)
1019         min_offset = min(min_offset, ws.offset);
1020
1021     if (min_offset >= 52) {
1022         CHECK(ret_sec_buffer(in, &sessionkey), 0);
1023         min_offset = min(min_offset, sessionkey.offset);
1024         CHECK(krb5_ret_uint32(in, &type3->flags), 0);
1025     }
1026     if (min_offset >= 52 + SIZE_SEC_BUFFER + 4 + SIZE_OS_VERSION) {
1027         CHECK(krb5_ret_uint32(in, &type3->os[0]), 0);
1028         CHECK(krb5_ret_uint32(in, &type3->os[1]), 0);
1029     }
1030     if (min_offset >= 52 + SIZE_SEC_BUFFER + 4 + SIZE_OS_VERSION + 16) {
1031         type3->mic_offset = 52 + SIZE_SEC_BUFFER + 4 + SIZE_OS_VERSION;
1032         CHECK_SIZE(krb5_storage_read(in, type3->mic, sizeof(type3->mic)), sizeof(type3->mic));
1033     } else
1034         type3->mic_offset = 0;
1035     CHECK(ret_buf(in, &lm, &type3->lm), 0);
1036     CHECK(ret_buf(in, &ntlm, &type3->ntlm), 0);
1037     CHECK(ret_sec_string(in, ucs2, &target, &type3->targetname), 0);
1038     CHECK(ret_sec_string(in, ucs2, &username, &type3->username), 0);
1039     CHECK(ret_sec_string(in, ucs2, &ws, &type3->ws), 0);
1040     if (sessionkey.offset)
1041         CHECK(ret_buf(in, &sessionkey, &type3->sessionkey), 0);
1042
1043 out:
1044     if (in)
1045         krb5_storage_free(in);
1046     if (ret)
1047         heim_ntlm_free_type3(type3);
1048
1049     return ret;
1050 }
1051
1052 /**
1053  * Encodes an ntlm_type3 message.
1054  *
1055  * @param type3 the ntlm_type3 message to encode.
1056  * @param data is the return buffer with the encoded message, should be
1057  * @param[out] mic_offset offset of message integrity code
1058  * freed with heim_ntlm_free_buf().
1059  *
1060  * @return In case of success 0 is return, an errors, a errno in what
1061  * went wrong.
1062  *
1063  * @ingroup ntlm_core
1064  */
1065
1066 int
1067 heim_ntlm_encode_type3(const struct ntlm_type3 *type3, struct ntlm_buf *data, size_t *mic_offset)
1068 {
1069     struct sec_buffer lm, ntlm, target, username, sessionkey, ws;
1070     krb5_error_code ret;
1071     krb5_storage *out = NULL;
1072     uint32_t base;
1073     int ucs2 = 0;
1074
1075     memset(&lm, 0, sizeof(lm));
1076     memset(&ntlm, 0, sizeof(ntlm));
1077     memset(&target, 0, sizeof(target));
1078     memset(&username, 0, sizeof(username));
1079     memset(&ws, 0, sizeof(ws));
1080     memset(&sessionkey, 0, sizeof(sessionkey));
1081
1082     base = 52;
1083
1084     base += 8; /* sessionkey sec buf */
1085     base += 4; /* flags */
1086     if (type3->flags & NTLM_NEG_VERSION)
1087         base += SIZE_OS_VERSION; /* os flags */
1088
1089     if (mic_offset) {
1090         *mic_offset = base;
1091         base += 16;
1092     }
1093
1094     if (type3->flags & NTLM_NEG_UNICODE)
1095         ucs2 = 1;
1096
1097     target.offset = base;
1098     target.length = len_string(ucs2, type3->targetname);
1099     target.allocated = target.length;
1100
1101     username.offset = target.offset + target.allocated;
1102     username.length = len_string(ucs2, type3->username);
1103     username.allocated = username.length;
1104
1105     ws.offset = username.offset + username.allocated;
1106     ws.length = len_string(ucs2, type3->ws);
1107     ws.allocated = ws.length;
1108
1109     lm.offset = ws.offset + ws.allocated;
1110     lm.length = type3->lm.length;
1111     lm.allocated = type3->lm.length;
1112
1113     ntlm.offset = lm.offset + lm.allocated;
1114     ntlm.length = type3->ntlm.length;
1115     ntlm.allocated = ntlm.length;
1116
1117     sessionkey.offset = ntlm.offset + ntlm.allocated;
1118     sessionkey.length = type3->sessionkey.length;
1119     sessionkey.allocated = type3->sessionkey.length;
1120
1121     out = krb5_storage_emem();
1122     if (out == NULL)
1123         return ENOMEM;
1124
1125     krb5_storage_set_byteorder(out, KRB5_STORAGE_BYTEORDER_LE);
1126     CHECK_SIZE(krb5_storage_write(out, ntlmsigature, sizeof(ntlmsigature)),
1127           sizeof(ntlmsigature));
1128     CHECK(krb5_store_uint32(out, 3), 0);
1129
1130     CHECK(store_sec_buffer(out, &lm), 0);
1131     CHECK(store_sec_buffer(out, &ntlm), 0);
1132     CHECK(store_sec_buffer(out, &target), 0);
1133     CHECK(store_sec_buffer(out, &username), 0);
1134     CHECK(store_sec_buffer(out, &ws), 0);
1135     CHECK(store_sec_buffer(out, &sessionkey), 0);
1136     CHECK(krb5_store_uint32(out, type3->flags), 0);
1137
1138     /* os version */
1139     if (type3->flags & NTLM_NEG_VERSION) {
1140         CHECK(encode_os_version(out), 0);
1141     }
1142
1143     if (mic_offset) {
1144         static const uint8_t buf[16] = { 0 };
1145         CHECK_SIZE(krb5_storage_write(out, buf, sizeof(buf)), sizeof(buf));
1146     }
1147
1148     CHECK(put_string(out, ucs2, type3->targetname), 0);
1149     CHECK(put_string(out, ucs2, type3->username), 0);
1150     CHECK(put_string(out, ucs2, type3->ws), 0);
1151     CHECK(put_buf(out, &type3->lm), 0);
1152     CHECK(put_buf(out, &type3->ntlm), 0);
1153     CHECK(put_buf(out, &type3->sessionkey), 0);
1154
1155     {
1156         krb5_data d;
1157         ret = krb5_storage_to_data(out, &d);
1158         data->data = d.data;
1159         data->length = d.length;
1160     }
1161
1162 out:
1163     krb5_storage_free(out);
1164
1165     return ret;
1166 }
1167
1168
1169 /*
1170  *
1171  */
1172
1173 static void
1174 splitandenc(unsigned char *hash,
1175             unsigned char *challenge,
1176             unsigned char *answer)
1177 {
1178     EVP_CIPHER_CTX ctx;
1179     unsigned char key[8];
1180
1181     key[0] =  hash[0];
1182     key[1] = (hash[0] << 7) | (hash[1] >> 1);
1183     key[2] = (hash[1] << 6) | (hash[2] >> 2);
1184     key[3] = (hash[2] << 5) | (hash[3] >> 3);
1185     key[4] = (hash[3] << 4) | (hash[4] >> 4);
1186     key[5] = (hash[4] << 3) | (hash[5] >> 5);
1187     key[6] = (hash[5] << 2) | (hash[6] >> 6);
1188     key[7] = (hash[6] << 1);
1189
1190     EVP_CIPHER_CTX_init(&ctx);
1191
1192     EVP_CipherInit_ex(&ctx, EVP_des_cbc(), NULL, key, NULL, 1);
1193     EVP_Cipher(&ctx, answer, challenge, 8);
1194     EVP_CIPHER_CTX_cleanup(&ctx);
1195     memset_s(key, sizeof(key), 0, sizeof(key));
1196 }
1197
1198 /**
1199  * Calculate the NTLM key, the password is assumed to be in UTF8.
1200  *
1201  * @param password password to calcute the key for.
1202  * @param key calcuted key, should be freed with heim_ntlm_free_buf().
1203  *
1204  * @return In case of success 0 is return, an errors, a errno in what
1205  * went wrong.
1206  *
1207  * @ingroup ntlm_core
1208  */
1209
1210 int
1211 heim_ntlm_nt_key(const char *password, struct ntlm_buf *key)
1212 {
1213     struct ntlm_buf buf;
1214     EVP_MD_CTX *m;
1215     int ret;
1216
1217     key->data = malloc(MD4_DIGEST_LENGTH);
1218     if (key->data == NULL)
1219         return ENOMEM;
1220     key->length = MD4_DIGEST_LENGTH;
1221
1222     ret = ascii2ucs2le(password, 0, &buf);
1223     if (ret) {
1224         heim_ntlm_free_buf(key);
1225         return ret;
1226     }
1227
1228     m = EVP_MD_CTX_create();
1229     if (m == NULL) {
1230         heim_ntlm_free_buf(key);
1231         heim_ntlm_free_buf(&buf);
1232         return ENOMEM;
1233     }
1234
1235     EVP_DigestInit_ex(m, EVP_md4(), NULL);
1236     EVP_DigestUpdate(m, buf.data, buf.length);
1237     EVP_DigestFinal_ex(m, key->data, NULL);
1238     EVP_MD_CTX_destroy(m);
1239
1240     heim_ntlm_free_buf(&buf);
1241     return 0;
1242 }
1243
1244 /**
1245  * Calculate NTLMv1 response hash
1246  *
1247  * @param key the ntlm v1 key
1248  * @param len length of key
1249  * @param challenge sent by the server
1250  * @param answer calculated answer, should be freed with heim_ntlm_free_buf().
1251  *
1252  * @return In case of success 0 is return, an errors, a errno in what
1253  * went wrong.
1254  *
1255  * @ingroup ntlm_core
1256  */
1257
1258 int
1259 heim_ntlm_calculate_ntlm1(void *key, size_t len,
1260                           unsigned char challenge[8],
1261                           struct ntlm_buf *answer)
1262 {
1263     unsigned char res[21];
1264
1265     if (len != MD4_DIGEST_LENGTH)
1266         return HNTLM_ERR_INVALID_LENGTH;
1267
1268     memcpy(res, key, len);
1269     memset(&res[MD4_DIGEST_LENGTH], 0, sizeof(res) - MD4_DIGEST_LENGTH);
1270
1271     answer->data = malloc(24);
1272     if (answer->data == NULL)
1273         return ENOMEM;
1274     answer->length = 24;
1275
1276     splitandenc(&res[0],  challenge, ((unsigned char *)answer->data) + 0);
1277     splitandenc(&res[7],  challenge, ((unsigned char *)answer->data) + 8);
1278     splitandenc(&res[14], challenge, ((unsigned char *)answer->data) + 16);
1279
1280     return 0;
1281 }
1282
1283 int
1284 heim_ntlm_v1_base_session(void *key, size_t len,
1285                           struct ntlm_buf *session)
1286 {
1287     EVP_MD_CTX *m;
1288
1289     session->length = MD4_DIGEST_LENGTH;
1290     session->data = malloc(session->length);
1291     if (session->data == NULL) {
1292         session->length = 0;
1293         return ENOMEM;
1294     }
1295     
1296     m = EVP_MD_CTX_create();
1297     if (m == NULL) {
1298         heim_ntlm_free_buf(session);
1299         return ENOMEM;
1300     }
1301     EVP_DigestInit_ex(m, EVP_md4(), NULL);
1302     EVP_DigestUpdate(m, key, len);
1303     EVP_DigestFinal_ex(m, session->data, NULL);
1304     EVP_MD_CTX_destroy(m);
1305
1306     return 0;
1307 }
1308
1309 int
1310 heim_ntlm_v2_base_session(void *key, size_t len,
1311                           struct ntlm_buf *ntlmResponse,
1312                           struct ntlm_buf *session)
1313 {
1314     unsigned int hmaclen;
1315     HMAC_CTX c;
1316
1317     if (ntlmResponse->length <= 16)
1318         return HNTLM_ERR_INVALID_LENGTH;
1319
1320     session->data = malloc(16);
1321     if (session->data == NULL)
1322         return ENOMEM;
1323     session->length = 16;
1324
1325     /* Note: key is the NTLMv2 key */
1326     HMAC_CTX_init(&c);
1327     HMAC_Init_ex(&c, key, len, EVP_md5(), NULL);
1328     HMAC_Update(&c, ntlmResponse->data, 16);
1329     HMAC_Final(&c, session->data, &hmaclen);
1330     HMAC_CTX_cleanup(&c);
1331
1332     return 0;
1333 }
1334
1335
1336 int
1337 heim_ntlm_keyex_wrap(struct ntlm_buf *base_session,
1338                      struct ntlm_buf *session,
1339                      struct ntlm_buf *encryptedSession)
1340 {
1341     EVP_CIPHER_CTX c;
1342     int ret;
1343
1344     if (base_session->length != MD4_DIGEST_LENGTH)
1345         return HNTLM_ERR_INVALID_LENGTH;
1346
1347     session->length = MD4_DIGEST_LENGTH;
1348     session->data = malloc(session->length);
1349     if (session->data == NULL) {
1350         session->length = 0;
1351         return ENOMEM;
1352     }
1353     encryptedSession->length = MD4_DIGEST_LENGTH;
1354     encryptedSession->data = malloc(encryptedSession->length);
1355     if (encryptedSession->data == NULL) {
1356         heim_ntlm_free_buf(session);
1357         encryptedSession->length = 0;
1358         return ENOMEM;
1359     }
1360
1361     EVP_CIPHER_CTX_init(&c);
1362
1363     ret = EVP_CipherInit_ex(&c, EVP_rc4(), NULL, base_session->data, NULL, 1);
1364     if (ret != 1) {
1365         EVP_CIPHER_CTX_cleanup(&c);
1366         heim_ntlm_free_buf(encryptedSession);
1367         heim_ntlm_free_buf(session);
1368         return HNTLM_ERR_CRYPTO;
1369     }
1370
1371     if (RAND_bytes(session->data, session->length) != 1) {
1372         EVP_CIPHER_CTX_cleanup(&c);
1373         heim_ntlm_free_buf(encryptedSession);
1374         heim_ntlm_free_buf(session);
1375         return HNTLM_ERR_RAND;
1376     }
1377
1378     EVP_Cipher(&c, encryptedSession->data, session->data, encryptedSession->length);
1379     EVP_CIPHER_CTX_cleanup(&c);
1380
1381     return 0;
1382
1383
1384
1385 }
1386
1387 /**
1388  * Generates an NTLMv1 session random with assosited session master key.
1389  *
1390  * @param key the ntlm v1 key
1391  * @param len length of key
1392  * @param session generated session nonce, should be freed with heim_ntlm_free_buf().
1393  * @param master calculated session master key, should be freed with heim_ntlm_free_buf().
1394  *
1395  * @return In case of success 0 is return, an errors, a errno in what
1396  * went wrong.
1397  *
1398  * @ingroup ntlm_core
1399  */
1400
1401 int
1402 heim_ntlm_build_ntlm1_master(void *key, size_t len,
1403                              struct ntlm_buf *session,
1404                              struct ntlm_buf *master)
1405 {
1406     struct ntlm_buf sess;
1407     int ret;
1408
1409     ret = heim_ntlm_v1_base_session(key, len, &sess);
1410     if (ret)
1411         return ret;
1412
1413     ret = heim_ntlm_keyex_wrap(&sess, session, master);
1414     heim_ntlm_free_buf(&sess);
1415
1416     return ret;
1417 }
1418
1419 /**
1420  * Generates an NTLMv2 session random with associated session master key.
1421  *
1422  * @param key the NTLMv2 key
1423  * @param len length of key
1424  * @param blob the NTLMv2 "blob"
1425  * @param session generated session nonce, should be freed with heim_ntlm_free_buf().
1426  * @param master calculated session master key, should be freed with heim_ntlm_free_buf().
1427  *
1428  * @return In case of success 0 is return, an errors, a errno in what
1429  * went wrong.
1430  *
1431  * @ingroup ntlm_core
1432  */
1433
1434
1435 int
1436 heim_ntlm_build_ntlm2_master(void *key, size_t len,
1437                              struct ntlm_buf *blob,
1438                              struct ntlm_buf *session,
1439                              struct ntlm_buf *master)
1440 {
1441     struct ntlm_buf sess;
1442     int ret;
1443
1444     ret = heim_ntlm_v2_base_session(key, len, blob, &sess);
1445     if (ret)
1446         return ret;
1447
1448     ret = heim_ntlm_keyex_wrap(&sess, session, master);
1449     heim_ntlm_free_buf(&sess);
1450
1451     return ret;
1452 }
1453
1454 /**
1455  * Given a key and encrypted session, unwrap the session key
1456  *
1457  * @param baseKey the sessionBaseKey
1458  * @param encryptedSession encrypted session, type3.session field.
1459  * @param session generated session nonce, should be freed with heim_ntlm_free_buf().
1460  *
1461  * @return In case of success 0 is return, an errors, a errno in what
1462  * went wrong.
1463  *
1464  * @ingroup ntlm_core
1465  */
1466
1467 int
1468 heim_ntlm_keyex_unwrap(struct ntlm_buf *baseKey,
1469                        struct ntlm_buf *encryptedSession,
1470                        struct ntlm_buf *session)
1471 {
1472     EVP_CIPHER_CTX c;
1473
1474     memset(session, 0, sizeof(*session));
1475
1476     if (encryptedSession->length != MD4_DIGEST_LENGTH)
1477         return HNTLM_ERR_INVALID_LENGTH;
1478     if (baseKey->length != MD4_DIGEST_LENGTH)
1479         return HNTLM_ERR_INVALID_LENGTH;
1480
1481     session->length = MD4_DIGEST_LENGTH;
1482     session->data = malloc(session->length);
1483     if (session->data == NULL) {
1484         session->length = 0;
1485         return ENOMEM;
1486     }
1487     EVP_CIPHER_CTX_init(&c);
1488
1489     if (EVP_CipherInit_ex(&c, EVP_rc4(), NULL, baseKey->data, NULL, 0) != 1) {
1490         EVP_CIPHER_CTX_cleanup(&c);
1491         heim_ntlm_free_buf(session);
1492         return HNTLM_ERR_CRYPTO;
1493     }
1494
1495     EVP_Cipher(&c, session->data, encryptedSession->data, session->length);
1496     EVP_CIPHER_CTX_cleanup(&c);
1497
1498     return 0;
1499 }
1500
1501
1502 /**
1503  * Generates an NTLMv2 session key.
1504  *
1505  * @param key the ntlm key
1506  * @param len length of key
1507  * @param username name of the user, as sent in the message, assumed to be in UTF8.
1508  * @param target the name of the target, assumed to be in UTF8.
1509  * @param upper_case_target upper case the target, should not be used only for legacy systems
1510  * @param ntlmv2 the ntlmv2 session key
1511  *
1512  * @return 0 on success, or an error code on failure.
1513  *
1514  * @ingroup ntlm_core
1515  */
1516
1517 int
1518 heim_ntlm_ntlmv2_key(const void *key, size_t len,
1519                      const char *username,
1520                      const char *target,
1521                      int upper_case_target,
1522                      unsigned char ntlmv2[16])
1523 {
1524     int ret;
1525     unsigned int hmaclen;
1526     HMAC_CTX c;
1527
1528     HMAC_CTX_init(&c);
1529     HMAC_Init_ex(&c, key, len, EVP_md5(), NULL);
1530     {
1531         struct ntlm_buf buf;
1532         /* uppercase username and turn it into ucs2-le */
1533         ret = ascii2ucs2le(username, 1, &buf);
1534         if (ret)
1535             goto out;
1536         HMAC_Update(&c, buf.data, buf.length);
1537         free(buf.data);
1538         /* turn target into ucs2-le */
1539         ret = ascii2ucs2le(target, upper_case_target, &buf);
1540         if (ret)
1541             goto out;
1542         HMAC_Update(&c, buf.data, buf.length);
1543         free(buf.data);
1544     }
1545     HMAC_Final(&c, ntlmv2, &hmaclen);
1546  out:
1547     HMAC_CTX_cleanup(&c);
1548     memset(&c, 0, sizeof(c));
1549
1550     return ret;
1551 }
1552
1553 /*
1554  *
1555  */
1556
1557 #define NTTIME_EPOCH 0x019DB1DED53E8000LL
1558
1559 uint64_t
1560 heim_ntlm_unix2ts_time(time_t unix_time)
1561 {
1562     long long wt;
1563     wt = unix_time * (uint64_t)10000000 + (uint64_t)NTTIME_EPOCH;
1564     return wt;
1565 }
1566
1567 time_t
1568 heim_ntlm_ts2unixtime(uint64_t t)
1569 {
1570     t = ((t - (uint64_t)NTTIME_EPOCH) / (uint64_t)10000000);
1571     if (t > (((uint64_t)(time_t)(~(uint64_t)0)) >> 1))
1572         return 0;
1573     return (time_t)t;
1574 }
1575
1576 /**
1577  * Calculate LMv2 response
1578  *
1579  * @param key the ntlm key
1580  * @param len length of key
1581  * @param username name of the user, as sent in the message, assumed to be in UTF8.
1582  * @param target the name of the target, assumed to be in UTF8.
1583  * @param serverchallenge challenge as sent by the server in the type2 message.
1584  * @param ntlmv2 calculated session key
1585  * @param answer ntlm response answer, should be freed with heim_ntlm_free_buf().
1586  *
1587  * @return In case of success 0 is return, an errors, a errno in what
1588  * went wrong.
1589  *
1590  * @ingroup ntlm_core
1591  */
1592
1593 int
1594 heim_ntlm_calculate_lm2(const void *key, size_t len,
1595                         const char *username,
1596                         const char *target,
1597                         const unsigned char serverchallenge[8],
1598                         unsigned char ntlmv2[16],
1599                         struct ntlm_buf *answer)
1600 {
1601     unsigned char clientchallenge[8];
1602
1603     if (RAND_bytes(clientchallenge, sizeof(clientchallenge)) != 1)
1604         return HNTLM_ERR_RAND;
1605
1606     /* calculate ntlmv2 key */
1607
1608     heim_ntlm_ntlmv2_key(key, len, username, target, 0, ntlmv2);
1609
1610     answer->data = malloc(24);
1611     if (answer->data == NULL)
1612         return ENOMEM;
1613     answer->length = 24;
1614
1615     heim_ntlm_derive_ntlm2_sess(ntlmv2, clientchallenge, 8,
1616                                 serverchallenge, answer->data);
1617
1618     memcpy(((unsigned char *)answer->data) + 16, clientchallenge, 8);
1619
1620     return 0;
1621 }
1622
1623
1624 /**
1625  * Calculate NTLMv2 response
1626  *
1627  * @param key the ntlm key
1628  * @param len length of key
1629  * @param username name of the user, as sent in the message, assumed to be in UTF8.
1630  * @param target the name of the target, assumed to be in UTF8.
1631  * @param serverchallenge challenge as sent by the server in the type2 message.
1632  * @param infotarget infotarget as sent by the server in the type2 message.
1633  * @param ntlmv2 calculated session key
1634  * @param answer ntlm response answer, should be freed with heim_ntlm_free_buf().
1635  *
1636  * @return In case of success 0 is return, an errors, a errno in what
1637  * went wrong.
1638  *
1639  * @ingroup ntlm_core
1640  */
1641
1642 int
1643 heim_ntlm_calculate_ntlm2(const void *key, size_t len,
1644                           const char *username,
1645                           const char *target,
1646                           const unsigned char serverchallenge[8],
1647                           const struct ntlm_buf *infotarget,
1648                           unsigned char ntlmv2[16],
1649                           struct ntlm_buf *answer)
1650 {
1651     krb5_error_code ret;
1652     krb5_data data;
1653     unsigned char ntlmv2answer[16];
1654     krb5_storage *sp;
1655     unsigned char clientchallenge[8];
1656     uint64_t t;
1657
1658     t = heim_ntlm_unix2ts_time(time(NULL));
1659
1660     if (RAND_bytes(clientchallenge, sizeof(clientchallenge)) != 1)
1661         return HNTLM_ERR_RAND;
1662
1663     /* calculate ntlmv2 key */
1664
1665     heim_ntlm_ntlmv2_key(key, len, username, target, 0, ntlmv2);
1666
1667     /* calculate and build ntlmv2 answer */
1668
1669     sp = krb5_storage_emem();
1670     if (sp == NULL)
1671         return ENOMEM;
1672     krb5_storage_set_flags(sp, KRB5_STORAGE_BYTEORDER_LE);
1673
1674     CHECK(krb5_store_uint32(sp, 0x00000101), 0);
1675     CHECK(krb5_store_uint32(sp, 0), 0);
1676     /* timestamp le 64 bit ts */
1677     CHECK(krb5_store_uint32(sp, t & 0xffffffff), 0);
1678     CHECK(krb5_store_uint32(sp, t >> 32), 0);
1679
1680     CHECK_SIZE(krb5_storage_write(sp, clientchallenge, 8), 8);
1681
1682     CHECK(krb5_store_uint32(sp, 0), 0);  /* Z(4) */
1683     CHECK_SIZE(krb5_storage_write(sp, infotarget->data, infotarget->length),
1684           infotarget->length);
1685
1686     /*
1687      * These last 4 bytes(Z(4)) are not documented by MicroSoft and
1688      * SnowLeopard doesn't send them, Lion expected them to be there,
1689      * so we have to continue to send them. That is ok, since everyone
1690      * else (except Snow) seems to do that too.
1691      */
1692     CHECK(krb5_store_uint32(sp, 0), 0); /* Z(4) */
1693
1694     CHECK(krb5_storage_to_data(sp, &data), 0);
1695     krb5_storage_free(sp);
1696     sp = NULL;
1697
1698     heim_ntlm_derive_ntlm2_sess(ntlmv2, data.data, data.length, serverchallenge, ntlmv2answer);
1699
1700     sp = krb5_storage_emem();
1701     if (sp == NULL) {
1702         krb5_data_free(&data);
1703         return ENOMEM;
1704     }
1705
1706     CHECK_SIZE(krb5_storage_write(sp, ntlmv2answer, 16), 16);
1707     CHECK_SIZE(krb5_storage_write(sp, data.data, data.length), data.length);
1708     krb5_data_free(&data);
1709
1710     CHECK(krb5_storage_to_data(sp, &data), 0);
1711     krb5_storage_free(sp);
1712     sp = NULL;
1713
1714     answer->data = data.data;
1715     answer->length = data.length;
1716
1717     return 0;
1718 out:
1719     if (sp)
1720         krb5_storage_free(sp);
1721     return ret;
1722 }
1723
1724 static const int authtimediff = 3600 * 2; /* 2 hours */
1725
1726 static int
1727 verify_ntlm2(const void *key, size_t len,
1728              const char *username,
1729              const char *target,
1730              int upper_case_target,
1731              time_t now,
1732              const unsigned char serverchallenge[8],
1733              const struct ntlm_buf *answer,
1734              struct ntlm_buf *infotarget,
1735              unsigned char ntlmv2[16])
1736 {
1737     krb5_error_code ret;
1738     unsigned char clientanswer[16];
1739     unsigned char clientnonce[8];
1740     unsigned char serveranswer[16];
1741     krb5_storage *sp;
1742     uint64_t t;
1743     time_t authtime;
1744     uint32_t temp;
1745
1746     infotarget->length = 0;
1747     infotarget->data = NULL;
1748
1749     if (answer->length < 16)
1750         return HNTLM_ERR_INVALID_LENGTH;
1751
1752     if (now == 0)
1753         now = time(NULL);
1754
1755     /* calculate ntlmv2 key */
1756
1757     heim_ntlm_ntlmv2_key(key, len, username, target, upper_case_target, ntlmv2);
1758
1759     /* calculate and build ntlmv2 answer */
1760
1761     sp = krb5_storage_from_readonly_mem(answer->data, answer->length);
1762     if (sp == NULL)
1763         return ENOMEM;
1764     krb5_storage_set_flags(sp, KRB5_STORAGE_BYTEORDER_LE);
1765
1766     CHECK_SIZE(krb5_storage_read(sp, clientanswer, 16), 16);
1767
1768     CHECK(krb5_ret_uint32(sp, &temp), 0);
1769     CHECK(temp, 0x00000101);
1770     CHECK(krb5_ret_uint32(sp, &temp), 0);
1771     CHECK(temp, 0);
1772     /* timestamp le 64 bit ts */
1773     CHECK(krb5_ret_uint32(sp, &temp), 0);
1774     t = temp;
1775     CHECK(krb5_ret_uint32(sp, &temp), 0);
1776     t |= ((uint64_t)temp)<< 32;
1777
1778     authtime = heim_ntlm_ts2unixtime(t);
1779
1780     if (labs((int)(authtime - now)) > authtimediff) {
1781         ret = HNTLM_ERR_TIME_SKEW;
1782         goto out;
1783     }
1784
1785     /* client challenge */
1786     CHECK_SIZE(krb5_storage_read(sp, clientnonce, 8), 8);
1787
1788     CHECK(krb5_ret_uint32(sp, &temp), 0); /* Z(4) */
1789
1790     /* let pick up targetinfo */
1791     infotarget->length = answer->length - (size_t)krb5_storage_seek(sp, 0, SEEK_CUR);
1792     if (infotarget->length < 4) {
1793         ret = HNTLM_ERR_INVALID_LENGTH;
1794         goto out;
1795     }
1796     infotarget->data = malloc(infotarget->length);
1797     if (infotarget->data == NULL) {
1798         ret = ENOMEM;
1799         goto out;
1800     }
1801     CHECK_SIZE(krb5_storage_read(sp, infotarget->data, infotarget->length),
1802           infotarget->length);
1803
1804     krb5_storage_free(sp);
1805     sp = NULL;
1806
1807     if (answer->length < 16) {
1808         ret = HNTLM_ERR_INVALID_LENGTH;
1809         goto out;
1810     }
1811
1812     heim_ntlm_derive_ntlm2_sess(ntlmv2,
1813                                 ((unsigned char *)answer->data) + 16, answer->length - 16,
1814                                 serverchallenge,
1815                                 serveranswer);
1816
1817     if (memcmp(serveranswer, clientanswer, 16) != 0) {
1818         heim_ntlm_free_buf(infotarget);
1819         return HNTLM_ERR_AUTH;
1820     }
1821
1822     return 0;
1823 out:
1824     heim_ntlm_free_buf(infotarget);
1825     if (sp)
1826         krb5_storage_free(sp);
1827     return ret;
1828 }
1829
1830 /**
1831  * Verify NTLMv2 response.
1832  *
1833  * @param key the ntlm key
1834  * @param len length of key
1835  * @param username name of the user, as sent in the message, assumed to be in UTF8.
1836  * @param target the name of the target, assumed to be in UTF8.
1837  * @param now the time now (0 if the library should pick it up itself)
1838  * @param serverchallenge challenge as sent by the server in the type2 message.
1839  * @param answer ntlm response answer, should be freed with heim_ntlm_free_buf().
1840  * @param infotarget infotarget as sent by the server in the type2 message.
1841  * @param ntlmv2 calculated session key
1842  *
1843  * @return In case of success 0 is return, an errors, a errno in what
1844  * went wrong.
1845  *
1846  * @ingroup ntlm_core
1847  */
1848
1849 int
1850 heim_ntlm_verify_ntlm2(const void *key, size_t len,
1851                        const char *username,
1852                        const char *target,
1853                        time_t now,
1854                        const unsigned char serverchallenge[8],
1855                        const struct ntlm_buf *answer,
1856                        struct ntlm_buf *infotarget,
1857                        unsigned char ntlmv2[16])
1858 {
1859     int ret;
1860     
1861     /**
1862      * First check with the domain as the client passed it to the function.
1863      */
1864
1865     ret = verify_ntlm2(key, len, username, target, 0, now,
1866                        serverchallenge, answer, infotarget, ntlmv2);
1867
1868     /**
1869      * Second check with domain uppercased.
1870      */
1871
1872     if (ret)
1873         ret = verify_ntlm2(key, len, username, target, 1, now,
1874                            serverchallenge, answer, infotarget, ntlmv2);
1875
1876     /**
1877      * Third check with empty domain.
1878      */
1879     if (ret)
1880         ret = verify_ntlm2(key, len, username, "", 0, now,
1881                            serverchallenge, answer, infotarget, ntlmv2);
1882     return ret;
1883 }
1884
1885 /*
1886  * Calculate the NTLM2 Session Response
1887  *
1888  * @param clnt_nonce client nonce
1889  * @param svr_chal server challage
1890  * @param ntlm2_hash ntlm hash
1891  * @param lm The LM response, should be freed with heim_ntlm_free_buf().
1892  * @param ntlm The NTLM response, should be freed with heim_ntlm_free_buf().
1893  *
1894  * @return In case of success 0 is return, an errors, a errno in what
1895  * went wrong.
1896  *
1897  * @ingroup ntlm_core
1898  */
1899
1900 int
1901 heim_ntlm_calculate_ntlm2_sess(const unsigned char clnt_nonce[8],
1902                                const unsigned char svr_chal[8],
1903                                const unsigned char ntlm_hash[16],
1904                                struct ntlm_buf *lm,
1905                                struct ntlm_buf *ntlm)
1906 {
1907     unsigned char ntlm2_sess_hash[8];
1908     unsigned char res[21], *resp;
1909     int code;
1910
1911     code = heim_ntlm_calculate_ntlm2_sess_hash(clnt_nonce, svr_chal,
1912                                                ntlm2_sess_hash);
1913     if (code) {
1914         return code;
1915     }
1916
1917     lm->data = malloc(24);
1918     if (lm->data == NULL) {
1919         return ENOMEM;
1920     }
1921     lm->length = 24;
1922
1923     ntlm->data = malloc(24);
1924     if (ntlm->data == NULL) {
1925         free(lm->data);
1926         lm->data = NULL;
1927         return ENOMEM;
1928     }
1929     ntlm->length = 24;
1930
1931     /* first setup the lm resp */
1932     memset(lm->data, 0, 24);
1933     memcpy(lm->data, clnt_nonce, 8);
1934
1935     memset(res, 0, sizeof(res));
1936     memcpy(res, ntlm_hash, 16);
1937
1938     resp = ntlm->data;
1939     splitandenc(&res[0], ntlm2_sess_hash, resp + 0);
1940     splitandenc(&res[7], ntlm2_sess_hash, resp + 8);
1941     splitandenc(&res[14], ntlm2_sess_hash, resp + 16);
1942
1943     return 0;
1944 }
1945
1946
1947 /*
1948  * Calculate the NTLM2 Session "Verifier"
1949  *
1950  * @param clnt_nonce client nonce
1951  * @param svr_chal server challage
1952  * @param hash The NTLM session verifier
1953  *
1954  * @return In case of success 0 is return, an errors, a errno in what
1955  * went wrong.
1956  *
1957  * @ingroup ntlm_core
1958  */
1959
1960 int
1961 heim_ntlm_calculate_ntlm2_sess_hash(const unsigned char clnt_nonce[8],
1962                                     const unsigned char svr_chal[8],
1963                                     unsigned char verifier[8])
1964 {
1965     unsigned char ntlm2_sess_hash[MD5_DIGEST_LENGTH];
1966     EVP_MD_CTX *m;
1967
1968     m = EVP_MD_CTX_create();
1969     if (m == NULL)
1970         return ENOMEM;
1971
1972     EVP_DigestInit_ex(m, EVP_md5(), NULL);
1973     EVP_DigestUpdate(m, svr_chal, 8); /* session nonce part 1 */
1974     EVP_DigestUpdate(m, clnt_nonce, 8); /* session nonce part 2 */
1975     EVP_DigestFinal_ex(m, ntlm2_sess_hash, NULL); /* will only use first 8 bytes */
1976     EVP_MD_CTX_destroy(m);
1977
1978     memcpy(verifier, ntlm2_sess_hash, 8);
1979
1980     return 0;
1981 }
1982
1983
1984 /*
1985  * Derive a NTLM2 session key
1986  *
1987  * @param sessionkey session key from domain controller
1988  * @param clnt_nonce client nonce
1989  * @param svr_chal server challenge
1990  * @param derivedkey salted session key
1991  *
1992  * @return In case of success 0 is return, an errors, a errno in what
1993  * went wrong.
1994  *
1995  * @ingroup ntlm_core
1996  */
1997
1998 void
1999 heim_ntlm_derive_ntlm2_sess(const unsigned char sessionkey[16],
2000                             const unsigned char *clnt_nonce, size_t clnt_nonce_length,
2001                             const unsigned char svr_chal[8],
2002                             unsigned char derivedkey[16])
2003 {
2004     unsigned int hmaclen;
2005     HMAC_CTX c;
2006
2007     /* HMAC(Ksession, serverchallenge || clientchallenge) */
2008     HMAC_CTX_init(&c);
2009     HMAC_Init_ex(&c, sessionkey, 16, EVP_md5(), NULL);
2010     HMAC_Update(&c, svr_chal, 8);
2011     HMAC_Update(&c, clnt_nonce, clnt_nonce_length);
2012     HMAC_Final(&c, derivedkey, &hmaclen);
2013     HMAC_CTX_cleanup(&c);
2014     memset(&c, 0, sizeof(c));
2015 }