heimdal: import heimdal's trunk svn rev 23697 + lorikeet-heimdal patches
[metze/samba/wip.git] / source / 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  * 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 <config.h>
35
36 RCSID("$Id$");
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 <krb5.h>
47 #include <roken.h>
48
49 #define HC_DEPRECATED_CRYPTO
50
51 #include "krb5-types.h"
52 #include "crypto-headers.h"
53
54 #include <heimntlm.h>
55
56 /*! \mainpage Heimdal NTLM library
57  *
58  * \section intro Introduction
59  *
60  * Heimdal libheimntlm library is a implementation of the NTLM
61  * protocol, both version 1 and 2. The GSS-API mech that uses this
62  * library adds support for transport encryption and integrity
63  * checking.
64  * 
65  * NTLM is a protocol for mutual authentication, its still used in
66  * many protocol where Kerberos is not support, one example is
67  * EAP/X802.1x mechanism LEAP from Microsoft and Cisco.
68  *
69  * This is a support library for the core protocol, its used in
70  * Heimdal to implement and GSS-API mechanism. There is also support
71  * in the KDC to do remote digest authenticiation, this to allow
72  * services to authenticate users w/o direct access to the users ntlm
73  * hashes (same as Kerberos arcfour enctype keys).
74  *
75  * More information about the NTLM protocol can found here
76  * http://davenport.sourceforge.net/ntlm.html .
77  * 
78  * The Heimdal projects web page: http://www.h5l.org/
79  */
80
81 /** @defgroup ntlm_core Heimdal NTLM library 
82  * 
83  * The NTLM core functions implement the string2key generation
84  * function, message encode and decode function, and the hash function
85  * functions.
86  */
87
88 struct sec_buffer {
89     uint16_t length;
90     uint16_t allocated;
91     uint32_t offset;
92 };
93
94 static const unsigned char ntlmsigature[8] = "NTLMSSP\x00";
95
96 /*
97  *
98  */
99
100 #define CHECK(f, e)                                                     \
101     do { ret = f ; if (ret != (e)) { ret = EINVAL; goto out; } } while(0)
102
103 /**
104  * heim_ntlm_free_buf frees the ntlm buffer
105  *
106  * @param p buffer to be freed
107  *
108  * @ingroup ntlm_core
109  */
110
111 void
112 heim_ntlm_free_buf(struct ntlm_buf *p)
113 {
114     if (p->data)
115         free(p->data);
116     p->data = NULL;
117     p->length = 0;
118 }
119     
120
121 static int
122 ascii2ucs2le(const char *string, int up, struct ntlm_buf *buf)
123 {
124     unsigned char *p;
125     size_t len, i;
126
127     len = strlen(string);
128     if (len / 2 > UINT_MAX)
129         return ERANGE;
130
131     buf->length = len * 2;
132     buf->data = malloc(buf->length);
133     if (buf->data == NULL && len != 0) {
134         heim_ntlm_free_buf(buf);
135         return ENOMEM;
136     }
137
138     p = buf->data;
139     for (i = 0; i < len; i++) {
140         unsigned char t = (unsigned char)string[i];
141         if (t & 0x80) {
142             heim_ntlm_free_buf(buf);
143             return EINVAL;
144         }
145         if (up)
146             t = toupper(t);
147         p[(i * 2) + 0] = t;
148         p[(i * 2) + 1] = 0;
149     }
150     return 0;
151 }
152
153 /*
154  *
155  */
156
157 static krb5_error_code
158 ret_sec_buffer(krb5_storage *sp, struct sec_buffer *buf)
159 {
160     krb5_error_code ret;
161     CHECK(krb5_ret_uint16(sp, &buf->length), 0);
162     CHECK(krb5_ret_uint16(sp, &buf->allocated), 0);
163     CHECK(krb5_ret_uint32(sp, &buf->offset), 0);
164 out:
165     return ret;
166 }
167
168 static krb5_error_code
169 store_sec_buffer(krb5_storage *sp, const struct sec_buffer *buf)
170 {
171     krb5_error_code ret;
172     CHECK(krb5_store_uint16(sp, buf->length), 0);
173     CHECK(krb5_store_uint16(sp, buf->allocated), 0);
174     CHECK(krb5_store_uint32(sp, buf->offset), 0);
175 out:
176     return ret;
177 }
178
179 /*
180  * Strings are either OEM or UNICODE. The later is encoded as ucs2 on
181  * wire, but using utf8 in memory.
182  */
183
184 static krb5_error_code
185 len_string(int ucs2, const char *s)
186 {
187     size_t len = strlen(s);
188     if (ucs2)
189         len *= 2;
190     return len;
191 }
192
193 static krb5_error_code
194 ret_string(krb5_storage *sp, int ucs2, struct sec_buffer *desc, char **s)
195 {
196     krb5_error_code ret;
197
198     *s = malloc(desc->length + 1);
199     CHECK(krb5_storage_seek(sp, desc->offset, SEEK_SET), desc->offset);
200     CHECK(krb5_storage_read(sp, *s, desc->length), desc->length);
201     (*s)[desc->length] = '\0';
202
203     if (ucs2) {
204         size_t i;
205         for (i = 0; i < desc->length / 2; i++) {
206             (*s)[i] = (*s)[i * 2];
207             if ((*s)[i * 2 + 1]) {
208                 free(*s);
209                 *s = NULL;
210                 return EINVAL;
211             }
212         }
213         (*s)[i] = '\0';
214     }
215     ret = 0;
216 out:
217     return ret;
218
219     return 0;
220 }
221
222 static krb5_error_code
223 put_string(krb5_storage *sp, int ucs2, const char *s)
224 {
225     krb5_error_code ret;
226     struct ntlm_buf buf;
227
228     if (ucs2) {
229         ret = ascii2ucs2le(s, 0, &buf);
230         if (ret)
231             return ret;
232     } else {
233         buf.data = rk_UNCONST(s);
234         buf.length = strlen(s);
235     }
236
237     CHECK(krb5_storage_write(sp, buf.data, buf.length), buf.length);
238     if (ucs2)
239         heim_ntlm_free_buf(&buf);
240     ret = 0;
241 out:
242     return ret;
243 }
244
245 /*
246  *
247  */
248
249 static krb5_error_code
250 ret_buf(krb5_storage *sp, struct sec_buffer *desc, struct ntlm_buf *buf)
251 {
252     krb5_error_code ret;
253
254     buf->data = malloc(desc->length);
255     buf->length = desc->length;
256     CHECK(krb5_storage_seek(sp, desc->offset, SEEK_SET), desc->offset);
257     CHECK(krb5_storage_read(sp, buf->data, buf->length), buf->length);
258     ret = 0;
259 out:
260     return ret;
261 }
262
263 static krb5_error_code
264 put_buf(krb5_storage *sp, const struct ntlm_buf *buf)
265 {
266     krb5_error_code ret;
267     CHECK(krb5_storage_write(sp, buf->data, buf->length), buf->length);
268     ret = 0;
269 out:
270     return ret;
271 }
272
273 /**
274  * Frees the ntlm_targetinfo message
275  *
276  * @param ti targetinfo to be freed
277  *
278  * @ingroup ntlm_core
279  */
280
281 void
282 heim_ntlm_free_targetinfo(struct ntlm_targetinfo *ti)
283 {
284     free(ti->servername);
285     free(ti->domainname);
286     free(ti->dnsdomainname);
287     free(ti->dnsservername);
288     memset(ti, 0, sizeof(*ti));
289 }
290
291 static int
292 encode_ti_blob(krb5_storage *out, uint16_t type, int ucs2, char *s)
293 {
294     krb5_error_code ret;
295     CHECK(krb5_store_uint16(out, type), 0);
296     CHECK(krb5_store_uint16(out, len_string(ucs2, s)), 0);
297     CHECK(put_string(out, ucs2, s), 0);
298 out:
299     return ret;
300 }
301
302 /**
303  * Encodes a ntlm_targetinfo message.
304  *
305  * @param ti the ntlm_targetinfo message to encode.
306  * @param ucs2 if the strings should be encoded with ucs2 (selected by flag in message).
307  * @param data is the return buffer with the encoded message, should be
308  * freed with heim_ntlm_free_buf().
309  *
310  * @return In case of success 0 is return, an errors, a errno in what
311  * went wrong.
312  *
313  * @ingroup ntlm_core
314  */
315
316 int
317 heim_ntlm_encode_targetinfo(const struct ntlm_targetinfo *ti,
318                             int ucs2, 
319                             struct ntlm_buf *data)
320 {
321     krb5_error_code ret;
322     krb5_storage *out;
323
324     data->data = NULL;
325     data->length = 0;
326
327     out = krb5_storage_emem();
328     if (out == NULL)
329         return ENOMEM;
330
331     if (ti->servername)
332         CHECK(encode_ti_blob(out, 1, ucs2, ti->servername), 0);
333     if (ti->domainname)
334         CHECK(encode_ti_blob(out, 2, ucs2, ti->domainname), 0);
335     if (ti->dnsservername)
336         CHECK(encode_ti_blob(out, 3, ucs2, ti->dnsservername), 0);
337     if (ti->dnsdomainname)
338         CHECK(encode_ti_blob(out, 4, ucs2, ti->dnsdomainname), 0);
339
340     /* end tag */
341     CHECK(krb5_store_int16(out, 0), 0);
342     CHECK(krb5_store_int16(out, 0), 0);
343
344     {
345         krb5_data d;
346         ret = krb5_storage_to_data(out, &d);
347         data->data = d.data;
348         data->length = d.length;
349     }
350 out:
351     krb5_storage_free(out);
352     return ret;
353 }
354
355 /**
356  * Decodes an NTLM targetinfo message
357  *
358  * @param data input data buffer with the encode NTLM targetinfo message
359  * @param ucs2 if the strings should be encoded with ucs2 (selected by flag in message).
360  * @param ti the decoded target info, should be freed with heim_ntlm_free_targetinfo().
361  *
362  * @return In case of success 0 is return, an errors, a errno in what
363  * went wrong.
364  *
365  * @ingroup ntlm_core
366  */
367
368 int
369 heim_ntlm_decode_targetinfo(const struct ntlm_buf *data,
370                             int ucs2,
371                             struct ntlm_targetinfo *ti)
372 {
373     memset(ti, 0, sizeof(*ti));
374     return 0;
375 }
376
377 /**
378  * Frees the ntlm_type1 message
379  *
380  * @param data message to be freed
381  *
382  * @ingroup ntlm_core
383  */
384
385 void
386 heim_ntlm_free_type1(struct ntlm_type1 *data)
387 {
388     if (data->domain)
389         free(data->domain);
390     if (data->hostname)
391         free(data->hostname);
392     memset(data, 0, sizeof(*data));
393 }
394
395 int
396 heim_ntlm_decode_type1(const struct ntlm_buf *buf, struct ntlm_type1 *data)
397 {
398     krb5_error_code ret;
399     unsigned char sig[8];
400     uint32_t type;
401     struct sec_buffer domain, hostname;
402     krb5_storage *in;
403     
404     memset(data, 0, sizeof(*data));
405
406     in = krb5_storage_from_readonly_mem(buf->data, buf->length);
407     if (in == NULL) {
408         ret = EINVAL;
409         goto out;
410     }
411     krb5_storage_set_byteorder(in, KRB5_STORAGE_BYTEORDER_LE);
412
413     CHECK(krb5_storage_read(in, sig, sizeof(sig)), sizeof(sig));
414     CHECK(memcmp(ntlmsigature, sig, sizeof(ntlmsigature)), 0);
415     CHECK(krb5_ret_uint32(in, &type), 0);
416     CHECK(type, 1);
417     CHECK(krb5_ret_uint32(in, &data->flags), 0);
418     if (data->flags & NTLM_SUPPLIED_DOMAIN)
419         CHECK(ret_sec_buffer(in, &domain), 0);
420     if (data->flags & NTLM_SUPPLIED_WORKSTAION)
421         CHECK(ret_sec_buffer(in, &hostname), 0);
422 #if 0
423     if (domain.offset > 32) {
424         CHECK(krb5_ret_uint32(in, &data->os[0]), 0);
425         CHECK(krb5_ret_uint32(in, &data->os[1]), 0);
426     }
427 #endif
428     if (data->flags & NTLM_SUPPLIED_DOMAIN)
429         CHECK(ret_string(in, 0, &domain, &data->domain), 0);
430     if (data->flags & NTLM_SUPPLIED_WORKSTAION)
431         CHECK(ret_string(in, 0, &hostname, &data->hostname), 0);
432
433 out:
434     krb5_storage_free(in);
435     if (ret)
436         heim_ntlm_free_type1(data);
437
438     return ret;
439 }
440
441 /**
442  * Encodes an ntlm_type1 message.
443  *
444  * @param type1 the ntlm_type1 message to encode.
445  * @param data is the return buffer with the encoded message, should be
446  * freed with heim_ntlm_free_buf().
447  *
448  * @return In case of success 0 is return, an errors, a errno in what
449  * went wrong.
450  *
451  * @ingroup ntlm_core
452  */
453
454 int
455 heim_ntlm_encode_type1(const struct ntlm_type1 *type1, struct ntlm_buf *data)
456 {
457     krb5_error_code ret;
458     struct sec_buffer domain, hostname;
459     krb5_storage *out;
460     uint32_t base, flags;
461     
462     flags = type1->flags;
463     base = 16;
464
465     if (type1->domain) {
466         base += 8;
467         flags |= NTLM_SUPPLIED_DOMAIN;
468     }
469     if (type1->hostname) {
470         base += 8;
471         flags |= NTLM_SUPPLIED_WORKSTAION;
472     }
473     if (type1->os[0])
474         base += 8;
475
476     if (type1->domain) {
477         domain.offset = base;
478         domain.length = len_string(0, type1->domain);
479         domain.allocated = domain.length;
480     }
481     if (type1->hostname) {
482         hostname.offset = domain.allocated + domain.offset;
483         hostname.length = len_string(0, type1->hostname);
484         hostname.allocated = hostname.length;
485     }
486
487     out = krb5_storage_emem();
488     if (out == NULL)
489         return ENOMEM;
490
491     krb5_storage_set_byteorder(out, KRB5_STORAGE_BYTEORDER_LE);
492     CHECK(krb5_storage_write(out, ntlmsigature, sizeof(ntlmsigature)), 
493           sizeof(ntlmsigature));
494     CHECK(krb5_store_uint32(out, 1), 0);
495     CHECK(krb5_store_uint32(out, flags), 0);
496     
497     if (type1->domain)
498         CHECK(store_sec_buffer(out, &domain), 0);
499     if (type1->hostname)
500         CHECK(store_sec_buffer(out, &hostname), 0);
501     if (type1->os[0]) {
502         CHECK(krb5_store_uint32(out, type1->os[0]), 0);
503         CHECK(krb5_store_uint32(out, type1->os[1]), 0);
504     }
505     if (type1->domain)
506         CHECK(put_string(out, 0, type1->domain), 0);
507     if (type1->hostname)
508         CHECK(put_string(out, 0, type1->hostname), 0);
509
510     {
511         krb5_data d;
512         ret = krb5_storage_to_data(out, &d);
513         data->data = d.data;
514         data->length = d.length;
515     }
516 out:
517     krb5_storage_free(out);
518
519     return ret;
520 }
521
522 /**
523  * Frees the ntlm_type2 message
524  *
525  * @param data message to be freed
526  *
527  * @ingroup ntlm_core
528  */
529
530 void
531 heim_ntlm_free_type2(struct ntlm_type2 *data)
532 {
533     if (data->targetname)
534         free(data->targetname);
535     heim_ntlm_free_buf(&data->targetinfo);
536     memset(data, 0, sizeof(*data));
537 }
538
539 int
540 heim_ntlm_decode_type2(const struct ntlm_buf *buf, struct ntlm_type2 *type2)
541 {
542     krb5_error_code ret;
543     unsigned char sig[8];
544     uint32_t type, ctx[2];
545     struct sec_buffer targetname, targetinfo;
546     krb5_storage *in;
547     int ucs2 = 0;
548     
549     memset(type2, 0, sizeof(*type2));
550
551     in = krb5_storage_from_readonly_mem(buf->data, buf->length);
552     if (in == NULL) {
553         ret = EINVAL;
554         goto out;
555     }
556     krb5_storage_set_byteorder(in, KRB5_STORAGE_BYTEORDER_LE);
557
558     CHECK(krb5_storage_read(in, sig, sizeof(sig)), sizeof(sig));
559     CHECK(memcmp(ntlmsigature, sig, sizeof(ntlmsigature)), 0);
560     CHECK(krb5_ret_uint32(in, &type), 0);
561     CHECK(type, 2);
562
563     CHECK(ret_sec_buffer(in, &targetname), 0);
564     CHECK(krb5_ret_uint32(in, &type2->flags), 0);
565     if (type2->flags & NTLM_NEG_UNICODE)
566         ucs2 = 1;
567     CHECK(krb5_storage_read(in, type2->challange, sizeof(type2->challange)),
568           sizeof(type2->challange));
569     CHECK(krb5_ret_uint32(in, &ctx[0]), 0); /* context */
570     CHECK(krb5_ret_uint32(in, &ctx[1]), 0);
571     CHECK(ret_sec_buffer(in, &targetinfo), 0);
572     /* os version */
573 #if 0
574     CHECK(krb5_ret_uint32(in, &type2->os[0]), 0);
575     CHECK(krb5_ret_uint32(in, &type2->os[1]), 0);
576 #endif
577
578     CHECK(ret_string(in, ucs2, &targetname, &type2->targetname), 0);
579     CHECK(ret_buf(in, &targetinfo, &type2->targetinfo), 0);
580     ret = 0;
581
582 out:
583     krb5_storage_free(in);
584     if (ret)
585         heim_ntlm_free_type2(type2);
586
587     return ret;
588 }
589
590 /**
591  * Encodes an ntlm_type2 message.
592  *
593  * @param type2 the ntlm_type2 message to encode.
594  * @param data is the return buffer with the encoded message, should be
595  * freed with heim_ntlm_free_buf().
596  *
597  * @return In case of success 0 is return, an errors, a errno in what
598  * went wrong.
599  *
600  * @ingroup ntlm_core
601  */
602
603 int
604 heim_ntlm_encode_type2(const struct ntlm_type2 *type2, struct ntlm_buf *data)
605 {
606     struct sec_buffer targetname, targetinfo;
607     krb5_error_code ret;
608     krb5_storage *out = NULL;
609     uint32_t base;
610     int ucs2 = 0;
611
612     if (type2->os[0])
613         base = 56;
614     else
615         base = 48;
616
617     if (type2->flags & NTLM_NEG_UNICODE)
618         ucs2 = 1;
619
620     targetname.offset = base;
621     targetname.length = len_string(ucs2, type2->targetname);
622     targetname.allocated = targetname.length;
623
624     targetinfo.offset = targetname.allocated + targetname.offset;
625     targetinfo.length = type2->targetinfo.length;
626     targetinfo.allocated = type2->targetinfo.length;
627
628     out = krb5_storage_emem();
629     if (out == NULL)
630         return ENOMEM;
631
632     krb5_storage_set_byteorder(out, KRB5_STORAGE_BYTEORDER_LE);
633     CHECK(krb5_storage_write(out, ntlmsigature, sizeof(ntlmsigature)), 
634           sizeof(ntlmsigature));
635     CHECK(krb5_store_uint32(out, 2), 0);
636     CHECK(store_sec_buffer(out, &targetname), 0);
637     CHECK(krb5_store_uint32(out, type2->flags), 0);
638     CHECK(krb5_storage_write(out, type2->challange, sizeof(type2->challange)),
639           sizeof(type2->challange));
640     CHECK(krb5_store_uint32(out, 0), 0); /* context */
641     CHECK(krb5_store_uint32(out, 0), 0);
642     CHECK(store_sec_buffer(out, &targetinfo), 0);
643     /* os version */
644     if (type2->os[0]) {
645         CHECK(krb5_store_uint32(out, type2->os[0]), 0);
646         CHECK(krb5_store_uint32(out, type2->os[1]), 0);
647     }
648     CHECK(put_string(out, ucs2, type2->targetname), 0);
649     CHECK(krb5_storage_write(out, type2->targetinfo.data, 
650                              type2->targetinfo.length),
651           type2->targetinfo.length);
652     
653     {
654         krb5_data d;
655         ret = krb5_storage_to_data(out, &d);
656         data->data = d.data;
657         data->length = d.length;
658     }
659
660 out:
661     krb5_storage_free(out);
662
663     return ret;
664 }
665
666 /**
667  * Frees the ntlm_type3 message
668  *
669  * @param data message to be freed
670  *
671  * @ingroup ntlm_core
672  */
673
674 void
675 heim_ntlm_free_type3(struct ntlm_type3 *data)
676 {
677     heim_ntlm_free_buf(&data->lm);
678     heim_ntlm_free_buf(&data->ntlm);
679     if (data->targetname)
680         free(data->targetname);
681     if (data->username)
682         free(data->username);
683     if (data->ws)
684         free(data->ws);
685     heim_ntlm_free_buf(&data->sessionkey);
686     memset(data, 0, sizeof(*data));
687 }
688
689 /*
690  *
691  */
692
693 int
694 heim_ntlm_decode_type3(const struct ntlm_buf *buf,
695                        int ucs2,
696                        struct ntlm_type3 *type3)
697 {
698     krb5_error_code ret;
699     unsigned char sig[8];
700     uint32_t type;
701     krb5_storage *in;
702     struct sec_buffer lm, ntlm, target, username, sessionkey, ws;
703
704     memset(type3, 0, sizeof(*type3));
705     memset(&sessionkey, 0, sizeof(sessionkey));
706
707     in = krb5_storage_from_readonly_mem(buf->data, buf->length);
708     if (in == NULL) {
709         ret = EINVAL;
710         goto out;
711     }
712     krb5_storage_set_byteorder(in, KRB5_STORAGE_BYTEORDER_LE);
713
714     CHECK(krb5_storage_read(in, sig, sizeof(sig)), sizeof(sig));
715     CHECK(memcmp(ntlmsigature, sig, sizeof(ntlmsigature)), 0);
716     CHECK(krb5_ret_uint32(in, &type), 0);
717     CHECK(type, 3);
718     CHECK(ret_sec_buffer(in, &lm), 0);
719     CHECK(ret_sec_buffer(in, &ntlm), 0);
720     CHECK(ret_sec_buffer(in, &target), 0);
721     CHECK(ret_sec_buffer(in, &username), 0);
722     CHECK(ret_sec_buffer(in, &ws), 0);
723     if (lm.offset >= 60) {
724         CHECK(ret_sec_buffer(in, &sessionkey), 0);
725     }
726     if (lm.offset >= 64) {
727         CHECK(krb5_ret_uint32(in, &type3->flags), 0);
728     }
729     if (lm.offset >= 72) {
730         CHECK(krb5_ret_uint32(in, &type3->os[0]), 0);
731         CHECK(krb5_ret_uint32(in, &type3->os[1]), 0);
732     }
733     CHECK(ret_buf(in, &lm, &type3->lm), 0);
734     CHECK(ret_buf(in, &ntlm, &type3->ntlm), 0);
735     CHECK(ret_string(in, ucs2, &target, &type3->targetname), 0);
736     CHECK(ret_string(in, ucs2, &username, &type3->username), 0);
737     CHECK(ret_string(in, ucs2, &ws, &type3->ws), 0);
738     if (sessionkey.offset)
739         CHECK(ret_buf(in, &sessionkey, &type3->sessionkey), 0);
740
741 out:
742     krb5_storage_free(in);
743     if (ret)
744         heim_ntlm_free_type3(type3);
745
746     return ret;
747 }
748
749 /**
750  * Encodes an ntlm_type3 message.
751  *
752  * @param type3 the ntlm_type3 message to encode.
753  * @param data is the return buffer with the encoded message, should be
754  * freed with heim_ntlm_free_buf().
755  *
756  * @return In case of success 0 is return, an errors, a errno in what
757  * went wrong.
758  *
759  * @ingroup ntlm_core
760  */
761
762 int
763 heim_ntlm_encode_type3(const struct ntlm_type3 *type3, struct ntlm_buf *data)
764 {
765     struct sec_buffer lm, ntlm, target, username, sessionkey, ws;
766     krb5_error_code ret;
767     krb5_storage *out = NULL;
768     uint32_t base;
769     int ucs2 = 0;
770
771     memset(&lm, 0, sizeof(lm));
772     memset(&ntlm, 0, sizeof(ntlm));
773     memset(&target, 0, sizeof(target));
774     memset(&username, 0, sizeof(username));
775     memset(&ws, 0, sizeof(ws));
776     memset(&sessionkey, 0, sizeof(sessionkey));
777
778     base = 52;
779     if (type3->sessionkey.length) {
780         base += 8; /* sessionkey sec buf */
781         base += 4; /* flags */
782     }
783     if (type3->os[0]) {
784         base += 8;
785     }
786
787     if (type3->flags & NTLM_NEG_UNICODE)
788         ucs2 = 1;
789
790     lm.offset = base;
791     lm.length = type3->lm.length;
792     lm.allocated = type3->lm.length;
793
794     ntlm.offset = lm.offset + lm.allocated;
795     ntlm.length = type3->ntlm.length;
796     ntlm.allocated = ntlm.length;
797
798     target.offset = ntlm.offset + ntlm.allocated;
799     target.length = len_string(ucs2, type3->targetname);
800     target.allocated = target.length;
801
802     username.offset = target.offset + target.allocated;
803     username.length = len_string(ucs2, type3->username);
804     username.allocated = username.length;
805
806     ws.offset = username.offset + username.allocated;
807     ws.length = len_string(ucs2, type3->ws);
808     ws.allocated = ws.length;
809
810     sessionkey.offset = ws.offset + ws.allocated;
811     sessionkey.length = type3->sessionkey.length;
812     sessionkey.allocated = type3->sessionkey.length;
813
814     out = krb5_storage_emem();
815     if (out == NULL)
816         return ENOMEM;
817
818     krb5_storage_set_byteorder(out, KRB5_STORAGE_BYTEORDER_LE);
819     CHECK(krb5_storage_write(out, ntlmsigature, sizeof(ntlmsigature)), 
820           sizeof(ntlmsigature));
821     CHECK(krb5_store_uint32(out, 3), 0);
822
823     CHECK(store_sec_buffer(out, &lm), 0);
824     CHECK(store_sec_buffer(out, &ntlm), 0);
825     CHECK(store_sec_buffer(out, &target), 0);
826     CHECK(store_sec_buffer(out, &username), 0);
827     CHECK(store_sec_buffer(out, &ws), 0);
828     /* optional */
829     if (type3->sessionkey.length) {
830         CHECK(store_sec_buffer(out, &sessionkey), 0);
831         CHECK(krb5_store_uint32(out, type3->flags), 0);
832     }
833 #if 0
834     CHECK(krb5_store_uint32(out, 0), 0); /* os0 */
835     CHECK(krb5_store_uint32(out, 0), 0); /* os1 */
836 #endif
837
838     CHECK(put_buf(out, &type3->lm), 0);
839     CHECK(put_buf(out, &type3->ntlm), 0);
840     CHECK(put_string(out, ucs2, type3->targetname), 0);
841     CHECK(put_string(out, ucs2, type3->username), 0);
842     CHECK(put_string(out, ucs2, type3->ws), 0);
843     CHECK(put_buf(out, &type3->sessionkey), 0);
844     
845     {
846         krb5_data d;
847         ret = krb5_storage_to_data(out, &d);
848         data->data = d.data;
849         data->length = d.length;
850     }
851
852 out:
853     krb5_storage_free(out);
854
855     return ret;
856 }
857
858
859 /*
860  *
861  */
862
863 static void
864 splitandenc(unsigned char *hash, 
865             unsigned char *challange,
866             unsigned char *answer)
867 {
868     DES_cblock key;
869     DES_key_schedule sched;
870
871     ((unsigned char*)key)[0] =  hash[0];
872     ((unsigned char*)key)[1] = (hash[0] << 7) | (hash[1] >> 1);
873     ((unsigned char*)key)[2] = (hash[1] << 6) | (hash[2] >> 2);
874     ((unsigned char*)key)[3] = (hash[2] << 5) | (hash[3] >> 3);
875     ((unsigned char*)key)[4] = (hash[3] << 4) | (hash[4] >> 4);
876     ((unsigned char*)key)[5] = (hash[4] << 3) | (hash[5] >> 5);
877     ((unsigned char*)key)[6] = (hash[5] << 2) | (hash[6] >> 6);
878     ((unsigned char*)key)[7] = (hash[6] << 1);
879
880     DES_set_odd_parity(&key);
881     DES_set_key_unchecked(&key, &sched);
882     DES_ecb_encrypt((DES_cblock *)challange, (DES_cblock *)answer, &sched, 1);
883     memset(&sched, 0, sizeof(sched));
884     memset(key, 0, sizeof(key));
885 }
886
887 /**
888  * Calculate the NTLM key, the password is assumed to be in UTF8.
889  *
890  * @param password password to calcute the key for.
891  * @param key calcuted key, should be freed with heim_ntlm_free_buf().
892  *
893  * @return In case of success 0 is return, an errors, a errno in what
894  * went wrong.
895  *
896  * @ingroup ntlm_core
897  */
898
899 int
900 heim_ntlm_nt_key(const char *password, struct ntlm_buf *key)
901 {
902     struct ntlm_buf buf;
903     MD4_CTX ctx;
904     int ret;
905
906     key->data = malloc(MD5_DIGEST_LENGTH);
907     if (key->data == NULL)
908         return ENOMEM;
909     key->length = MD5_DIGEST_LENGTH;
910
911     ret = ascii2ucs2le(password, 0, &buf);
912     if (ret) {
913         heim_ntlm_free_buf(key);
914         return ret;
915     }
916     MD4_Init(&ctx);
917     MD4_Update(&ctx, buf.data, buf.length);
918     MD4_Final(key->data, &ctx);
919     heim_ntlm_free_buf(&buf);
920     return 0;
921 }
922
923 /**
924  * Calculate NTLMv1 response hash
925  *
926  * @param key the ntlm v1 key
927  * @param len length of key
928  * @param challange sent by the server
929  * @param answer calculated answer, should be freed with heim_ntlm_free_buf().
930  *
931  * @return In case of success 0 is return, an errors, a errno in what
932  * went wrong.
933  *
934  * @ingroup ntlm_core
935  */
936
937 int
938 heim_ntlm_calculate_ntlm1(void *key, size_t len,
939                           unsigned char challange[8],
940                           struct ntlm_buf *answer)
941 {
942     unsigned char res[21];
943
944     if (len != MD4_DIGEST_LENGTH)
945         return EINVAL;
946
947     memcpy(res, key, len);
948     memset(&res[MD4_DIGEST_LENGTH], 0, sizeof(res) - MD4_DIGEST_LENGTH);
949
950     answer->data = malloc(24);
951     if (answer->data == NULL)
952         return ENOMEM;
953     answer->length = 24;
954
955     splitandenc(&res[0],  challange, ((unsigned char *)answer->data) + 0);
956     splitandenc(&res[7],  challange, ((unsigned char *)answer->data) + 8);
957     splitandenc(&res[14], challange, ((unsigned char *)answer->data) + 16);
958
959     return 0;
960 }
961
962 /**
963  * Generates an NTLMv1 session random with assosited session master key.
964  *
965  * @param key the ntlm v1 key
966  * @param len length of key
967  * @param session generated session nonce, should be freed with heim_ntlm_free_buf().
968  * @param master calculated session master key, should be freed with heim_ntlm_free_buf().
969  *
970  * @return In case of success 0 is return, an errors, a errno in what
971  * went wrong.
972  *
973  * @ingroup ntlm_core
974  */
975
976 int
977 heim_ntlm_build_ntlm1_master(void *key, size_t len,
978                              struct ntlm_buf *session,
979                              struct ntlm_buf *master)
980 {
981     RC4_KEY rc4;
982
983     memset(master, 0, sizeof(*master));
984     memset(session, 0, sizeof(*session));
985
986     if (len != MD4_DIGEST_LENGTH)
987         return EINVAL;
988     
989     session->length = MD4_DIGEST_LENGTH;
990     session->data = malloc(session->length);
991     if (session->data == NULL) {
992         session->length = 0;
993         return EINVAL;
994     }    
995     master->length = MD4_DIGEST_LENGTH;
996     master->data = malloc(master->length);
997     if (master->data == NULL) {
998         heim_ntlm_free_buf(master);
999         heim_ntlm_free_buf(session);
1000         return EINVAL;
1001     }
1002     
1003     {
1004         unsigned char sessionkey[MD4_DIGEST_LENGTH];
1005         MD4_CTX ctx;
1006     
1007         MD4_Init(&ctx);
1008         MD4_Update(&ctx, key, len);
1009         MD4_Final(sessionkey, &ctx);
1010         
1011         RC4_set_key(&rc4, sizeof(sessionkey), sessionkey);
1012     }
1013     
1014     if (RAND_bytes(session->data, session->length) != 1) {
1015         heim_ntlm_free_buf(master);
1016         heim_ntlm_free_buf(session);
1017         return EINVAL;
1018     }
1019     
1020     RC4(&rc4, master->length, session->data, master->data);
1021     memset(&rc4, 0, sizeof(rc4));
1022     
1023     return 0;
1024 }
1025
1026 /**
1027  * Generates an NTLMv2 session key.
1028  *
1029  * @param key the ntlm key
1030  * @param len length of key
1031  * @param username name of the user, as sent in the message, assumed to be in UTF8.
1032  * @param target the name of the target, assumed to be in UTF8.
1033  * @param ntlmv2 the ntlmv2 session key
1034  *
1035  * @ingroup ntlm_core
1036  */
1037
1038 void
1039 heim_ntlm_ntlmv2_key(const void *key, size_t len,
1040                      const char *username,
1041                      const char *target,
1042                      unsigned char ntlmv2[16])
1043 {
1044     unsigned int hmaclen;
1045     HMAC_CTX c;
1046
1047     HMAC_CTX_init(&c);
1048     HMAC_Init_ex(&c, key, len, EVP_md5(), NULL);
1049     {
1050         struct ntlm_buf buf;
1051         /* uppercase username and turn it into ucs2-le */
1052         ascii2ucs2le(username, 1, &buf);
1053         HMAC_Update(&c, buf.data, buf.length);
1054         free(buf.data);
1055         /* uppercase target and turn into ucs2-le */
1056         ascii2ucs2le(target, 1, &buf);
1057         HMAC_Update(&c, buf.data, buf.length);
1058         free(buf.data);
1059     }
1060     HMAC_Final(&c, ntlmv2, &hmaclen);
1061     HMAC_CTX_cleanup(&c);
1062
1063 }
1064
1065 /*
1066  *
1067  */
1068
1069 #define NTTIME_EPOCH 0x019DB1DED53E8000LL
1070
1071 static uint64_t
1072 unix2nttime(time_t unix_time)
1073 {
1074     long long wt;
1075     wt = unix_time * (uint64_t)10000000 + (uint64_t)NTTIME_EPOCH;
1076     return wt;
1077 }
1078
1079 static time_t
1080 nt2unixtime(uint64_t t)
1081 {
1082     t = ((t - (uint64_t)NTTIME_EPOCH) / (uint64_t)10000000);
1083     if (t > (((time_t)(~(uint64_t)0)) >> 1))
1084         return 0;
1085     return (time_t)t;
1086 }
1087
1088
1089 /**
1090  * Calculate NTLMv2 response
1091  *
1092  * @param key the ntlm key
1093  * @param len length of key
1094  * @param username name of the user, as sent in the message, assumed to be in UTF8.
1095  * @param target the name of the target, assumed to be in UTF8.
1096  * @param serverchallange challange as sent by the server in the type2 message.
1097  * @param infotarget infotarget as sent by the server in the type2 message.
1098  * @param ntlmv2 calculated session key
1099  * @param answer ntlm response answer, should be freed with heim_ntlm_free_buf().
1100  *
1101  * @return In case of success 0 is return, an errors, a errno in what
1102  * went wrong.
1103  *
1104  * @ingroup ntlm_core
1105  */
1106
1107 int
1108 heim_ntlm_calculate_ntlm2(const void *key, size_t len,
1109                           const char *username,
1110                           const char *target,
1111                           const unsigned char serverchallange[8],
1112                           const struct ntlm_buf *infotarget,
1113                           unsigned char ntlmv2[16],
1114                           struct ntlm_buf *answer)
1115 {
1116     krb5_error_code ret;
1117     krb5_data data;
1118     unsigned int hmaclen;
1119     unsigned char ntlmv2answer[16];
1120     krb5_storage *sp;
1121     unsigned char clientchallange[8];
1122     HMAC_CTX c;
1123     uint64_t t;
1124     
1125     t = unix2nttime(time(NULL));
1126
1127     if (RAND_bytes(clientchallange, sizeof(clientchallange)) != 1)
1128         return EINVAL;
1129     
1130     /* calculate ntlmv2 key */
1131
1132     heim_ntlm_ntlmv2_key(key, len, username, target, ntlmv2);
1133
1134     /* calculate and build ntlmv2 answer */
1135
1136     sp = krb5_storage_emem();
1137     if (sp == NULL)
1138         return ENOMEM;
1139     krb5_storage_set_flags(sp, KRB5_STORAGE_BYTEORDER_LE);
1140
1141     CHECK(krb5_store_uint32(sp, 0x00000101), 0);
1142     CHECK(krb5_store_uint32(sp, 0), 0);
1143     /* timestamp le 64 bit ts */
1144     CHECK(krb5_store_uint32(sp, t & 0xffffffff), 0);
1145     CHECK(krb5_store_uint32(sp, t >> 32), 0);
1146
1147     CHECK(krb5_storage_write(sp, clientchallange, 8), 8);
1148
1149     CHECK(krb5_store_uint32(sp, 0), 0);  /* unknown but zero will work */
1150     CHECK(krb5_storage_write(sp, infotarget->data, infotarget->length), 
1151           infotarget->length);
1152     CHECK(krb5_store_uint32(sp, 0), 0); /* unknown but zero will work */
1153     
1154     CHECK(krb5_storage_to_data(sp, &data), 0);
1155     krb5_storage_free(sp);
1156     sp = NULL;
1157
1158     HMAC_CTX_init(&c);
1159     HMAC_Init_ex(&c, ntlmv2, 16, EVP_md5(), NULL);
1160     HMAC_Update(&c, serverchallange, 8);
1161     HMAC_Update(&c, data.data, data.length);
1162     HMAC_Final(&c, ntlmv2answer, &hmaclen);
1163     HMAC_CTX_cleanup(&c);
1164
1165     sp = krb5_storage_emem();
1166     if (sp == NULL) {
1167         krb5_data_free(&data);
1168         return ENOMEM;
1169     }
1170
1171     CHECK(krb5_storage_write(sp, ntlmv2answer, 16), 16);
1172     CHECK(krb5_storage_write(sp, data.data, data.length), data.length);
1173     krb5_data_free(&data);
1174     
1175     CHECK(krb5_storage_to_data(sp, &data), 0);
1176     krb5_storage_free(sp);
1177     sp = NULL;
1178
1179     answer->data = data.data;
1180     answer->length = data.length;
1181
1182     return 0;
1183 out:
1184     if (sp)
1185         krb5_storage_free(sp);
1186     return ret;
1187 }
1188
1189 static const int authtimediff = 3600 * 2; /* 2 hours */
1190
1191 /**
1192  * Verify NTLMv2 response.
1193  *
1194  * @param key the ntlm key
1195  * @param len length of key
1196  * @param username name of the user, as sent in the message, assumed to be in UTF8.
1197  * @param target the name of the target, assumed to be in UTF8.
1198  * @param now the time now (0 if the library should pick it up itself)
1199  * @param serverchallange challange as sent by the server in the type2 message.
1200  * @param answer ntlm response answer, should be freed with heim_ntlm_free_buf().
1201  * @param infotarget infotarget as sent by the server in the type2 message.
1202  * @param ntlmv2 calculated session key
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_verify_ntlm2(const void *key, size_t len,
1212                        const char *username,
1213                        const char *target,
1214                        time_t now,
1215                        const unsigned char serverchallange[8],
1216                        const struct ntlm_buf *answer,
1217                        struct ntlm_buf *infotarget,
1218                        unsigned char ntlmv2[16])
1219 {
1220     krb5_error_code ret;
1221     unsigned int hmaclen;
1222     unsigned char clientanswer[16];
1223     unsigned char clientnonce[8];
1224     unsigned char serveranswer[16];
1225     krb5_storage *sp;
1226     HMAC_CTX c;
1227     uint64_t t;
1228     time_t authtime;
1229     uint32_t temp;
1230
1231     infotarget->length = 0;    
1232     infotarget->data = NULL;    
1233
1234     if (answer->length < 16)
1235         return EINVAL;
1236
1237     if (now == 0)
1238         now = time(NULL);
1239
1240     /* calculate ntlmv2 key */
1241
1242     heim_ntlm_ntlmv2_key(key, len, username, target, ntlmv2);
1243
1244     /* calculate and build ntlmv2 answer */
1245
1246     sp = krb5_storage_from_readonly_mem(answer->data, answer->length);
1247     if (sp == NULL)
1248         return ENOMEM;
1249     krb5_storage_set_flags(sp, KRB5_STORAGE_BYTEORDER_LE);
1250
1251     CHECK(krb5_storage_read(sp, clientanswer, 16), 16);
1252
1253     CHECK(krb5_ret_uint32(sp, &temp), 0);
1254     CHECK(temp, 0x00000101);
1255     CHECK(krb5_ret_uint32(sp, &temp), 0);
1256     CHECK(temp, 0);
1257     /* timestamp le 64 bit ts */
1258     CHECK(krb5_ret_uint32(sp, &temp), 0);
1259     t = temp;
1260     CHECK(krb5_ret_uint32(sp, &temp), 0);
1261     t |= ((uint64_t)temp)<< 32;
1262
1263     authtime = nt2unixtime(t);
1264
1265     if (abs((int)(authtime - now)) > authtimediff) {
1266         ret = EINVAL;
1267         goto out;
1268     }
1269
1270     /* client challange */
1271     CHECK(krb5_storage_read(sp, clientnonce, 8), 8);
1272
1273     CHECK(krb5_ret_uint32(sp, &temp), 0); /* unknown */
1274
1275     /* should really unparse the infotarget, but lets pick up everything */
1276     infotarget->length = answer->length - krb5_storage_seek(sp, 0, SEEK_CUR);
1277     infotarget->data = malloc(infotarget->length);
1278     if (infotarget->data == NULL) {
1279         ret = ENOMEM;
1280         goto out;
1281     }
1282     CHECK(krb5_storage_read(sp, infotarget->data, infotarget->length), 
1283           infotarget->length);
1284     /* XXX remove the unknown ?? */
1285     krb5_storage_free(sp);
1286     sp = NULL;
1287
1288     HMAC_CTX_init(&c);
1289     HMAC_Init_ex(&c, ntlmv2, 16, EVP_md5(), NULL);
1290     HMAC_Update(&c, serverchallange, 8);
1291     HMAC_Update(&c, ((unsigned char *)answer->data) + 16, answer->length - 16);
1292     HMAC_Final(&c, serveranswer, &hmaclen);
1293     HMAC_CTX_cleanup(&c);
1294
1295     if (memcmp(serveranswer, clientanswer, 16) != 0) {
1296         heim_ntlm_free_buf(infotarget);
1297         return EINVAL;
1298     }
1299
1300     return 0;
1301 out:
1302     heim_ntlm_free_buf(infotarget);
1303     if (sp)
1304         krb5_storage_free(sp);
1305     return ret;
1306 }
1307
1308
1309 /*
1310  * Calculate the NTLM2 Session Response
1311  *
1312  * @param clnt_nonce client nonce
1313  * @param svr_chal server challage
1314  * @param ntlm2_hash ntlm hash
1315  * @param lm The LM response, should be freed with heim_ntlm_free_buf().
1316  * @param ntlm The NTLM response, should be freed with heim_ntlm_free_buf().
1317  *
1318  * @return In case of success 0 is return, an errors, a errno in what
1319  * went wrong.
1320  *
1321  * @ingroup ntlm_core
1322  */
1323
1324 int
1325 heim_ntlm_calculate_ntlm2_sess(const unsigned char clnt_nonce[8],
1326                                const unsigned char svr_chal[8],
1327                                const unsigned char ntlm_hash[16],
1328                                struct ntlm_buf *lm,
1329                                struct ntlm_buf *ntlm)
1330 {
1331     unsigned char ntlm2_sess_hash[MD5_DIGEST_LENGTH];
1332     unsigned char res[21], *resp;
1333     MD5_CTX md5;
1334
1335     lm->data = malloc(24);
1336     if (lm->data == NULL)
1337         return ENOMEM;
1338     lm->length = 24;
1339
1340     ntlm->data = malloc(24);
1341     if (ntlm->data == NULL) {
1342         free(lm->data);
1343         lm->data = NULL;
1344         return ENOMEM;
1345     }
1346     ntlm->length = 24;
1347
1348     /* first setup the lm resp */
1349     memset(lm->data, 0, 24);
1350     memcpy(lm->data, clnt_nonce, 8);
1351
1352     MD5_Init(&md5);
1353     MD5_Update(&md5, svr_chal, 8); /* session nonce part 1 */
1354     MD5_Update(&md5, clnt_nonce, 8); /* session nonce part 2 */
1355     MD5_Final(ntlm2_sess_hash, &md5); /* will only use first 8 bytes */
1356
1357     memset(res, 0, sizeof(res));
1358     memcpy(res, ntlm_hash, 16);
1359
1360     resp = ntlm->data;
1361     splitandenc(&res[0], ntlm2_sess_hash, resp + 0);
1362     splitandenc(&res[7], ntlm2_sess_hash, resp + 8);
1363     splitandenc(&res[14], ntlm2_sess_hash, resp + 16);
1364
1365     return 0;
1366 }