Fix for Debian/x86_64 compiler bug
[siplcs.git] / src / core / sip-sec-ntlm.c
blob926eed779ee4b1e18dfafd303df86c109f1734c2
1 /**
2 * @file sip-sec-ntlm.c
4 * pidgin-sipe
6 * Copyright (C) 2009, 2010 pier11 <pier11@operamail.com>
7 * Copyright (C) 2008 Novell, Inc.
8 * Modify 2007, Anibal Avelar <avelar@gmail.com>
9 * Copyright (C) 2005, Thomas Butter <butter@uni-mannheim.de>
11 * Implemented with reference to the follow documentation:
12 * - http://davenport.sourceforge.net/ntlm.html
13 * - MS-NLMP: http://msdn.microsoft.com/en-us/library/cc207842.aspx
14 * - MS-SIP : http://msdn.microsoft.com/en-us/library/cc246115.aspx
16 * This program is free software; you can redistribute it and/or modify
17 * it under the terms of the GNU General Public License as published by
18 * the Free Software Foundation; either version 2 of the License, or
19 * (at your option) any later version.
21 * This program is distributed in the hope that it will be useful,
22 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 * GNU General Public License for more details.
26 * You should have received a copy of the GNU General Public License
27 * along with this program; if not, write to the Free Software
28 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
32 * Byte order policy:
34 * - NTLM messages (byte streams) should be in LE (Little-Endian) byte order.
35 * - internal int16, int32, int64 should contain proper values.
36 * For example: 01 00 00 00 LE should be translated to (int32)1
37 * - When reading/writing from/to NTLM message appropriate conversion should
38 * be taken to properly present integer values. glib's "Byte Order Macros"
39 * should be used for that, for example GUINT32_FROM_LE
41 * NOTE: The Byte Order Macros can have side effects!
42 * Do *NOT* make any calculations inside the macros!
44 * - All calculations should be made in dedicated local variables (system-endian),
45 * not in NTLM (LE) structures.
48 #include <glib.h>
49 #include <glib/gprintf.h>
50 #include <stdio.h>
51 #include <errno.h>
52 #include <string.h>
53 #include <stdlib.h>
54 #include "debug.h"
56 #ifdef _WIN32
57 #include "internal.h"
58 #endif /* _WIN32 */
60 #ifdef HAVE_LANGINFO_CODESET
61 #include <langinfo.h>
62 #endif /* HAVE_LANGINFO_CODESET */
64 #include "util.h"
65 #include "cipher.h"
67 #include "sipe.h"
68 #include "sipe-utils.h"
69 #include "sip-sec-mech.h"
70 #include "sip-sec-ntlm.h"
72 /* [MS-NLMP] */
73 #define NTLMSSP_NEGOTIATE_UNICODE 0x00000001 /* A */
74 #define NTLMSSP_NEGOTIATE_OEM 0x00000002 /* B */
75 #define NTLMSSP_REQUEST_TARGET 0x00000004 /* C */
76 #define r9 0x00000008 /* r9 */
77 #define NTLMSSP_NEGOTIATE_SIGN 0x00000010 /* D */
78 #define NTLMSSP_NEGOTIATE_SEAL 0x00000020 /* E */
79 #define NTLMSSP_NEGOTIATE_DATAGRAM 0x00000040 /* F */
80 #define NTLMSSP_NEGOTIATE_LM_KEY 0x00000080 /* G */
81 #define r8 0x00000100 /* r8 */
82 #define NTLMSSP_NEGOTIATE_NTLM 0x00000200 /* H */
83 #define NTLMSSP_NEGOTIATE_NT_ONLY 0x00000400 /* I */
84 #define anonymous 0x00000800 /* J */
85 #define NTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED 0x00001000 /* K */
86 #define NTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED 0x00002000 /* L */
87 #define r7 0x00004000 /* r7 */
88 #define NTLMSSP_NEGOTIATE_ALWAYS_SIGN 0x00008000 /* M */
89 #define NTLMSSP_TARGET_TYPE_DOMAIN 0x00010000 /* N */
90 #define NTLMSSP_TARGET_TYPE_SERVER 0x00020000 /* O */
91 #define r6 0x00040000 /* r6 */
92 #define NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY 0x00080000 /* P */
93 #define NTLMSSP_NEGOTIATE_IDENTIFY 0x00100000 /* Q */
94 #define r5 0x00200000 /* r5 */
95 #define NTLMSSP_REQUEST_NON_NT_SESSION_KEY 0x00400000 /* R */
96 #define NTLMSSP_NEGOTIATE_TARGET_INFO 0x00800000 /* S */
97 #define r4 0x01000000 /* r4 */
98 #define NTLMSSP_NEGOTIATE_VERSION 0x02000000 /* T */
99 #define r3 0x04000000 /* r3 */
100 #define r2 0x08000000 /* r2 */
101 #define r1 0x10000000 /* r1 */
102 #define NTLMSSP_NEGOTIATE_128 0x20000000 /* U */
103 #define NTLMSSP_NEGOTIATE_KEY_EXCH 0x40000000 /* V */
104 #define NTLMSSP_NEGOTIATE_56 0x80000000 /* W */
106 /* AvId */
107 #define MsvAvEOL 0
108 #define MsvAvNbComputerName 1
109 #define MsvAvNbDomainName 2
110 #define MsvAvDnsComputerName 3
111 #define MsvAvDnsDomainName 4
112 /** @since Windows XP */
113 #define MsvAvDnsTreeName 5
114 /** @since Windows XP */
115 #define MsvAvFlags 6
116 /** @since Windows Vista */
117 #define MsvAvTimestamp 7
118 /** @since Windows Vista */
119 #define MsAvRestrictions 8
120 /** @since Windows 7 */
121 #define MsvAvTargetName 9
122 /** @since Windows 7 */
123 #define MsvChannelBindings 10
125 /* time_t <-> (guint64) time_val conversion */
126 #define TIME_VAL_FACTOR 10000000
127 #define TIME_VAL_OFFSET 116444736000000000LL
128 #define TIME_T_TO_VAL(time_t) (((guint64)(time_t)) * TIME_VAL_FACTOR + TIME_VAL_OFFSET)
129 #define TIME_VAL_TO_T(time_val) ((time_t)((GUINT64_FROM_LE((time_val)) - TIME_VAL_OFFSET) / TIME_VAL_FACTOR))
131 /* 8 bytes */
132 /* LE (Little Endian) byte order */
133 struct version {
134 guint8 product_major_version;
135 guint8 product_minor_version;
136 guint16 product_build;
137 guint8 zero2[3];
138 guint8 ntlm_revision_current;
142 * NTLMv1 is no longer used except in tests. R.I.P.
144 * It remains in this file only for documentary purposes
146 #ifdef _SIPE_COMPILING_TESTS
147 static gboolean use_ntlm_v2 = FALSE;
149 guint64 test_time_val = 0; /* actual time in implementation */
150 guchar test_client_challenge [8]; /* random in implementation */
151 guchar test_random_session_key[16]; /* random in implementation */
152 struct version test_version; /* hard-coded in implementation */
153 #endif
155 /* Minimum set of common features we need to work. */
156 /* we operate in NTLMv2 mode */
157 #define NEGOTIATE_FLAGS_COMMON_MIN \
158 ( NTLMSSP_NEGOTIATE_UNICODE | \
159 NTLMSSP_NEGOTIATE_NTLM | \
160 NTLMSSP_NEGOTIATE_ALWAYS_SIGN | \
161 NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY | \
162 NTLMSSP_NEGOTIATE_TARGET_INFO \
165 /* Negotiate flags for connection-based mode. Nice to have but optional. */
166 #define NEGOTIATE_FLAGS_CONN \
167 ( NEGOTIATE_FLAGS_COMMON_MIN | \
168 NTLMSSP_NEGOTIATE_VERSION | \
169 NTLMSSP_NEGOTIATE_128 | \
170 NTLMSSP_NEGOTIATE_56 | \
171 NTLMSSP_REQUEST_TARGET \
174 /* Extra negotiate flags required in connectionless NTLM */
175 #define NEGOTIATE_FLAGS_CONNLESS_EXTRA \
176 ( NTLMSSP_NEGOTIATE_SIGN | \
177 NTLMSSP_NEGOTIATE_DATAGRAM | \
178 NTLMSSP_NEGOTIATE_IDENTIFY | \
179 NTLMSSP_NEGOTIATE_KEY_EXCH \
182 /* Negotiate flags required in connectionless NTLM */
183 #define NEGOTIATE_FLAGS_CONNLESS \
184 ( NEGOTIATE_FLAGS_CONN | \
185 NEGOTIATE_FLAGS_CONNLESS_EXTRA \
188 #define NTLMSSP_LN_OR_NT_KEY_LEN 16
189 #define NTLMSSP_LM_RESP_LEN 24
190 #define NTLMSSP_SESSION_KEY_LEN 16
191 #define MD4_DIGEST_LEN 16
192 #define MD5_DIGEST_LEN 16
194 #define IS_FLAG(flags, flag) (((flags) & (flag)) == (flag))
196 /* 4 bytes */
197 /* LE (Little Endian) byte order */
198 struct av_pair {
199 guint16 av_id;
200 guint16 av_len;
201 /* value */
204 /* to meet sparc's alignment requirement */
205 #define ALIGN_AV \
206 memcpy(&av_aligned, av, sizeof(av_aligned)); \
207 av_id = GUINT16_FROM_LE(av_aligned.av_id); \
208 av_len = GUINT16_FROM_LE(av_aligned.av_len)
209 #define ALIGN_AV_LOOP_START \
210 struct av_pair av_aligned; \
211 guint16 av_id; \
212 guint16 av_len; \
213 ALIGN_AV; \
214 while (av_id != MsvAvEOL) { \
215 gchar *av_value = ((gchar *)av) + \
216 sizeof(struct av_pair); \
217 switch (av_id)
218 #define ALIGN_AV_LOOP_END \
219 av = av_value + av_len; \
220 ALIGN_AV; \
223 /* 8 bytes */
224 /* LE (Little Endian) byte order */
225 struct smb_header {
226 guint16 len;
227 guint16 maxlen;
228 guint32 offset;
231 /* LE (Little Endian) byte order */
232 struct ntlm_message {
233 guint8 protocol[8]; /* 'N', 'T', 'L', 'M', 'S', 'S', 'P', '\0'*/
234 guint32 type; /* 0x00000003 */
237 /* LE (Little Endian) byte order */
238 struct negotiate_message {
239 guint8 protocol[8]; /* 'N', 'T', 'L', 'M', 'S', 'S', 'P', '\0' */
240 guint32 type; /* 0x00000001 */
241 guint32 flags; /* 0xb203 */
242 struct smb_header domain;
243 struct smb_header host;
244 struct version ver;
245 /* payload
246 * - DomainName (always ASCII)
247 * - WorkstationName (always ASCII)
251 /* LE (Little Endian) byte order */
252 struct challenge_message {
253 guint8 protocol[8]; /* 'N', 'T', 'L', 'M', 'S', 'S', 'P', '\0'*/
254 guint32 type; /* 0x00000002 */
255 struct smb_header target_name;
256 guint32 flags; /* 0x8201 */
257 guint8 nonce[8];
258 guint8 zero1[8];
259 struct smb_header target_info;
260 struct version ver;
261 /* payload
262 * - TargetName (negotiated encoding)
263 * - TargetInfo (a sequence of AV_PAIR structures) (always Unicode)
267 /* LE (Little Endian) byte order */
268 struct authenticate_message {
269 guint8 protocol[8]; /* 'N', 'T', 'L', 'M', 'S', 'S', 'P', '\0'*/
270 guint32 type; /* 0x00000003 */
271 /** LmChallengeResponseFields */
272 struct smb_header lm_resp;
273 /** NtChallengeResponseFields */
274 struct smb_header nt_resp;
275 /** DomainNameFields */
276 struct smb_header domain;
277 /** UserNameFields */
278 struct smb_header user;
279 /** WorkstationFields */
280 struct smb_header host;
281 /** EncryptedRandomSessionKeyFields */
282 struct smb_header session_key;
283 guint32 flags;
284 struct version ver;
285 //guint8 mic[16];
286 /* payload
287 * - LmChallengeResponse
288 * - NtChallengeResponse
289 * - DomainName (negotiated encoding)
290 * - UserName (negotiated encoding)
291 * - Workstation (negotiated encoding)
292 * - EncryptedRandomSessionKey
296 #ifndef HAVE_LANGINFO_CODESET
297 static char SIPE_DEFAULT_CODESET[] = "ANSI_X3.4-1968";
298 #endif
300 /* Private Methods */
302 /* Utility Functions */
303 static GIConv convert_from_utf16le = (GIConv)-1;
304 static GIConv convert_to_utf16le = (GIConv)-1;
306 static gsize
307 unicode_strconvcopy(gchar *dest, const gchar *source, gsize remlen)
309 gsize inbytes = strlen(source);
310 gsize outbytes = remlen;
311 g_iconv(convert_to_utf16le, (gchar **)&source, &inbytes, &dest, &outbytes);
312 return(remlen - outbytes);
315 /* UTF-16LE to native encoding
316 * Must be g_free'd after use */
317 static gchar *
318 unicode_strconvcopy_back(const gchar *source, gsize len)
320 gsize outbytes = 2 * len;
321 gchar *dest = g_new0(gchar, outbytes + 1);
322 gchar *outbuf = dest;
323 g_iconv(convert_from_utf16le, (gchar **)&source, &len, &outbuf, &outbytes);
324 return dest;
327 /* crc32 source copy from gg's common.c */
328 static guint32 crc32_table[256];
329 static int crc32_initialized = 0;
331 static void crc32_make_table()
333 guint32 h = 1;
334 unsigned int i, j;
336 memset(crc32_table, 0, sizeof(crc32_table));
338 for (i = 128; i; i >>= 1) {
339 h = (h >> 1) ^ ((h & 1) ? 0xedb88320L : 0);
341 for (j = 0; j < 256; j += 2 * i)
342 crc32_table[i + j] = crc32_table[j] ^ h;
345 crc32_initialized = 1;
348 static guint32 crc32(guint32 crc, const guint8 *buf, int len)
350 if (!crc32_initialized)
351 crc32_make_table();
353 if (!buf || len < 0)
354 return crc;
356 crc ^= 0xffffffffL;
358 while (len--)
359 crc = (crc >> 8) ^ crc32_table[(crc ^ *buf++) & 0xff];
361 return crc ^ 0xffffffffL;
364 static guint32
365 CRC32 (const char *msg, int len)
367 guint32 crc = 0L;
368 crc = crc32(crc, (guint8 *) msg, len);
369 return crc;
372 /* Cyphers */
374 #ifdef _SIPE_COMPILING_TESTS
375 static void setup_des_key(const unsigned char key_56[], unsigned char *key)
377 key[0] = key_56[0];
378 key[1] = ((key_56[0] << 7) & 0xFF) | (key_56[1] >> 1);
379 key[2] = ((key_56[1] << 6) & 0xFF) | (key_56[2] >> 2);
380 key[3] = ((key_56[2] << 5) & 0xFF) | (key_56[3] >> 3);
381 key[4] = ((key_56[3] << 4) & 0xFF) | (key_56[4] >> 4);
382 key[5] = ((key_56[4] << 3) & 0xFF) | (key_56[5] >> 5);
383 key[6] = ((key_56[5] << 2) & 0xFF) | (key_56[6] >> 6);
384 key[7] = (key_56[6] << 1) & 0xFF;
387 static void des_ecb_encrypt(const unsigned char *plaintext, unsigned char *result, const unsigned char *key)
389 PurpleCipher *cipher;
390 PurpleCipherContext *context;
391 size_t outlen;
393 cipher = purple_ciphers_find_cipher("des");
394 context = purple_cipher_context_new(cipher, NULL);
395 purple_cipher_context_set_key(context, (guchar*)key);
396 purple_cipher_context_encrypt(context, (guchar*)plaintext, 8, (guchar*)result, &outlen);
397 purple_cipher_context_destroy(context);
400 /* (k = 7 byte key, d = 8 byte data) returns 8 bytes in results */
401 static void
402 DES (const unsigned char *k, const unsigned char *d, unsigned char * results)
404 unsigned char key[8];
405 setup_des_key(k, key);
406 des_ecb_encrypt(d, results, key);
409 /* (K = 21 byte key, D = 8 bytes of data) returns 24 bytes in results: */
410 static void
411 DESL (const unsigned char *k, const unsigned char *d, unsigned char * results)
413 unsigned char keys[21];
415 /* Copy the first 16 bytes */
416 memcpy(keys, k, 16);
418 /* Zero out the last 5 bytes of the key */
419 memset(keys + 16, 0, 5);
421 DES(keys, d, results);
422 DES(keys + 7, d, results + 8);
423 DES(keys + 14, d, results + 16);
425 #endif
427 static void
428 RC4K (const unsigned char * k, unsigned long key_len, const unsigned char * d, int len, unsigned char * result)
430 PurpleCipherContext * context = purple_cipher_context_new_by_name("rc4", NULL);
431 purple_cipher_context_set_option(context, "key_len", (gpointer)key_len);
432 purple_cipher_context_set_key(context, k);
433 purple_cipher_context_encrypt(context, (const guchar *)d, len, result, NULL);
434 purple_cipher_context_destroy(context);
437 /* out 16 bytes */
438 static void
439 MD4 (const unsigned char * d, int len, unsigned char * result)
441 PurpleCipher * cipher = purple_ciphers_find_cipher("md4");
442 PurpleCipherContext * context = purple_cipher_context_new(cipher, NULL);
443 purple_cipher_context_append(context, (guchar*)d, len);
444 purple_cipher_context_digest(context, MD4_DIGEST_LEN, (guchar*)result, NULL);
445 purple_cipher_context_destroy(context);
448 /* out 16 bytes */
449 static void
450 MD5 (const unsigned char * d, int len, unsigned char * result)
452 PurpleCipher * cipher = purple_ciphers_find_cipher("md5");
453 PurpleCipherContext * context = purple_cipher_context_new(cipher, NULL);
454 purple_cipher_context_append(context, (guchar*)d, len);
455 purple_cipher_context_digest(context, MD5_DIGEST_LEN, (guchar*)result, NULL);
456 purple_cipher_context_destroy(context);
459 /* out 16 bytes */
461 static void
462 HMACT64 (const unsigned char *key, int key_len, const unsigned char *data, int data_len, unsigned char *result)
464 int i;
465 unsigned char ibuff[64 + data_len];
466 unsigned char obuff[64 + 16];
468 if (key_len > 64)
469 key_len = 64;
471 for (i = 0; i < key_len; i++) {
472 ibuff[i] = key[i] ^ 0x36;
473 obuff[i] = key[i] ^ 0x5c;
475 for (i = key_len; i < 64; i++) {
476 ibuff[i] = 0x36;
477 obuff[i] = 0x5c;
480 memcpy(ibuff+64, data, data_len);
482 MD5 (ibuff, 64 + data_len, obuff+64);
483 MD5 (obuff, 64 + 16, result);
485 #define HMAC_MD5 HMACT64
488 /* out 16 bytes */
489 static void
490 HMAC_MD5 (const unsigned char *key, int key_len, const unsigned char *data, int data_len, unsigned char *result)
492 PurpleCipher *cipher = purple_ciphers_find_cipher("hmac");
493 PurpleCipherContext *context = purple_cipher_context_new(cipher, NULL);
495 purple_cipher_context_set_option(context, "hash", "md5");
496 purple_cipher_context_set_key_with_len(context, (guchar *)key, (key_len));
498 purple_cipher_context_append(context, (guchar *)data, data_len);
499 purple_cipher_context_digest(context, 16, (guchar*)result, NULL);
500 purple_cipher_context_destroy(context);
503 /* NTLM Core Methods */
505 static void
506 NONCE(unsigned char *buffer, int num)
508 int i;
509 for (i = 0; i < num; i++) {
510 buffer[i] = (rand() & 0xff);
514 #ifdef _SIPE_COMPILING_TESTS
515 static void
516 Z(unsigned char *buffer, int num)
518 memset(buffer, 0, num);
521 static void
522 LMOWFv1 (const char *password, SIPE_UNUSED_PARAMETER const char *user, SIPE_UNUSED_PARAMETER const char *domain, unsigned char *result)
524 /* "KGS!@#$%" */
525 unsigned char magic[] = { 0x4B, 0x47, 0x53, 0x21, 0x40, 0x23, 0x24, 0x25 };
526 unsigned char uppercase_password[14];
527 int i;
529 int len = strlen(password);
530 if (len > 14) {
531 len = 14;
534 // Uppercase password
535 for (i = 0; i < len; i++) {
536 uppercase_password[i] = g_ascii_toupper(password[i]);
539 // Zero the rest
540 for (; i < 14; i++) {
541 uppercase_password[i] = 0;
544 DES (uppercase_password, magic, result);
545 DES (uppercase_password + 7, magic, result + 8);
547 #endif
550 Define NTOWFv1(Passwd, User, UserDom) as
551 MD4(UNICODE(Passwd))
552 EndDefine
554 /* out 16 bytes */
555 static void
556 NTOWFv1 (const char* password, SIPE_UNUSED_PARAMETER const char *user, SIPE_UNUSED_PARAMETER const char *domain, unsigned char *result)
558 int len_u = 2 * strlen(password); // utf16 should not be more
559 unsigned char unicode_password[len_u];
561 len_u = unicode_strconvcopy((gchar *)unicode_password, password, len_u);
562 MD4 (unicode_password, len_u, result);
566 Define NTOWFv2(Passwd, User, UserDom) as
567 HMAC_MD5( MD4(UNICODE(Passwd)), ConcatenationOf( Uppercase(User), UserDom ) )
568 EndDefine
570 /* out 16 bytes */
571 void
572 NTOWFv2 (const char* password, const char *user, const char *domain, unsigned char *result)
574 unsigned char response_key_nt_v1 [16];
575 int len_user = user ? strlen(user) : 0;
576 int len_domain = domain ? strlen(domain) : 0;
577 unsigned char user_upper[len_user + 1];
578 int len_user_u = 2 * len_user; // utf16 should not be more
579 int len_domain_u = 2 * len_domain; // utf16 should not be more
580 unsigned char buff[(len_user + len_domain)*2];
581 int i;
583 /* Uppercase user */
584 for (i = 0; i < len_user; i++) {
585 user_upper[i] = g_ascii_toupper(user[i]);
587 user_upper[len_user] = 0;
589 len_user_u = unicode_strconvcopy((gchar *)buff, (gchar *)user_upper, len_user_u);
590 len_domain_u = unicode_strconvcopy((gchar *)(buff+len_user_u), domain ? (gchar *)domain : "", len_domain_u);
592 NTOWFv1(password, user, domain, response_key_nt_v1);
594 HMAC_MD5(response_key_nt_v1, 16, buff, len_user_u + len_domain_u, result);
597 static void
598 compute_response(const guint32 neg_flags,
599 const unsigned char *response_key_nt,
600 const unsigned char *response_key_lm,
601 const guint8 *server_challenge,
602 const guint8 *client_challenge,
603 const guint64 time_val,
604 const guint8 *target_info,
605 int target_info_len,
606 unsigned char *lm_challenge_response,
607 unsigned char *nt_challenge_response,
608 unsigned char *session_base_key)
610 #ifdef _SIPE_COMPILING_TESTS
611 if (use_ntlm_v2)
613 #endif
615 Responserversion - The 1-byte response version. Currently set to 1.
616 HiResponserversion - The 1-byte highest response version understood by the client. Currently set to 1.
617 Time - The 8-byte little-endian time in GMT.
618 ServerName - The TargetInfo field structure of the CHALLENGE_MESSAGE payload.
619 ClientChallenge - The 8-byte challenge message generated by the client.
620 CHALLENGE_MESSAGE.ServerChallenge - The 8-byte challenge message generated by the server.
622 Define ComputeResponse(NegFlg, ResponseKeyNT, ResponseKeyLM, CHALLENGE_MESSAGE.ServerChallenge, ClientChallenge, Time, ServerName) as
623 Set temp to ConcatenationOf(Responserversion, HiResponserversion, Z(6), //8bytes - 0
624 Time, //8bytes - 8
625 ClientChallenge, //8bytes - 16
626 Z(4), //4bytes - 24
627 ServerName, //variable - 28
628 Z(4)) //4bytes - 28+target_info_len
629 Set NTProofStr to HMAC_MD5(ResponseKeyNT, ConcatenationOf(CHALLENGE_MESSAGE.ServerChallenge,temp))
630 Set NtChallengeResponse to ConcatenationOf(NTProofStr, temp)
631 Set LmChallengeResponse to ConcatenationOf(
632 HMAC_MD5(ResponseKeyLM, ConcatenationOf(CHALLENGE_MESSAGE.ServerChallenge, ClientChallenge)),
633 ClientChallenge )
634 Set SessionBaseKey to HMAC_MD5(ResponseKeyNT, NTProofStr)
635 EndDefine
637 guint8 tmp [16];
638 guint8 nt_proof_str [16];
640 /* client_challenge (8) & temp (temp_len) buff */
641 int temp_len = 8+8+8+4+target_info_len+4;
642 guint8 temp2 [8 + temp_len];
643 memset(temp2, 0, 8 + temp_len); /* init to 0 */
644 temp2[8+0] = 1;
645 temp2[8+1] = 1;
646 *((guint64 *)(temp2+8+8)) = GUINT64_TO_LE(time_val); /* should be int64 aligned: OK for sparc */
647 memcpy(temp2+8+16, client_challenge, 8);
648 memcpy(temp2+8+28, target_info, target_info_len);
650 /* NTProofStr */
651 //Set NTProofStr to HMAC_MD5(ResponseKeyNT, ConcatenationOf(CHALLENGE_MESSAGE.ServerChallenge,temp))
652 memcpy(temp2, server_challenge, 8);
653 HMAC_MD5(response_key_nt, 16, temp2, 8+temp_len, nt_proof_str);
655 /* NtChallengeResponse */
656 //Set NtChallengeResponse to ConcatenationOf(NTProofStr, temp)
657 memcpy(nt_challenge_response, nt_proof_str, 16);
658 memcpy(nt_challenge_response+16, temp2+8, temp_len);
660 /* SessionBaseKey */
661 //SessionBaseKey to HMAC_MD5(ResponseKeyNT, NTProofStr)
662 HMAC_MD5(response_key_nt, 16, nt_proof_str, 16, session_base_key);
664 /* lm_challenge_response */
665 memcpy(tmp, server_challenge, 8);
666 memcpy(tmp+8, client_challenge, 8);
667 HMAC_MD5(response_key_lm, 16, tmp, 16, lm_challenge_response);
668 memcpy(lm_challenge_response+16, client_challenge, 8);
670 #ifndef _SIPE_COMPILING_TESTS
671 /* Not used in NTLMv2 */
672 (void)neg_flags;
673 #else
675 else
677 if (IS_FLAG(neg_flags, NTLMSSP_NEGOTIATE_LM_KEY)) {
678 // @TODO do not even reference nt_challenge_response
679 Z (nt_challenge_response, NTLMSSP_LM_RESP_LEN);
680 DESL (response_key_lm, server_challenge, lm_challenge_response);
681 } else if (IS_FLAG(neg_flags, NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY)) {
682 unsigned char prehash [16];
683 unsigned char hash [16];
685 /* nt_challenge_response */
686 memcpy(prehash, server_challenge, 8);
687 memcpy(prehash + 8, client_challenge, 8);
688 MD5 (prehash, 16, hash);
689 DESL (response_key_nt, hash, nt_challenge_response);
691 /* lm_challenge_response */
692 memcpy(lm_challenge_response, client_challenge, 8);
693 Z (lm_challenge_response+8, 16);
694 } else {
695 DESL (response_key_nt, server_challenge, nt_challenge_response);
696 if (IS_FLAG(neg_flags, NTLMSSP_NEGOTIATE_NT_ONLY)) {
697 memcpy(lm_challenge_response, nt_challenge_response, NTLMSSP_LM_RESP_LEN);
698 } else {
699 DESL (response_key_lm, server_challenge, lm_challenge_response);
703 /* Session Key */
704 MD4(response_key_nt, 16, session_base_key); // "User Session Key" -> "master key"
706 #endif
709 static void
710 KXKEY ( guint32 flags,
711 const unsigned char * session_base_key,
712 const unsigned char * lm_challenge_resonse,
713 const guint8 * server_challenge, /* 8-bytes, nonce */
714 unsigned char * key_exchange_key)
716 #ifdef _SIPE_COMPILING_TESTS
717 if (use_ntlm_v2)
719 #else
720 /* Not used in NTLMv2 */
721 (void)flags;
722 (void)lm_challenge_resonse;
723 (void)server_challenge;
724 #endif
725 memcpy(key_exchange_key, session_base_key, 16);
726 #ifdef _SIPE_COMPILING_TESTS
728 else
730 if (IS_FLAG(flags, NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY)) {
731 /* Define KXKEY(SessionBaseKey, LmChallengeResponse, ServerChallenge) as
732 Set KeyExchangeKey to HMAC_MD5(SessionBaseKey, ConcatenationOf(ServerChallenge, LmChallengeResponse [0..7]))
733 EndDefine
735 guint8 tmp[16];
736 memcpy(tmp, server_challenge, 8);
737 memcpy(tmp+8, lm_challenge_resonse, 8);
738 HMAC_MD5(session_base_key, 16, tmp, 16, key_exchange_key);
739 } else {
740 /* Assume v1 and NTLMSSP_REQUEST_NON_NT_SESSION_KEY not set */
741 memcpy(key_exchange_key, session_base_key, 16);
744 #endif
748 If (Mode equals "Client")
749 Set SignKey to MD5(ConcatenationOf(RandomSessionKey,
750 "session key to client-to-server signing key magic constant"))
751 Else
752 Set SignKey to MD5(ConcatenationOf(RandomSessionKey,
753 "session key to server-to-client signing key magic constant"))
754 Endif
756 static void
757 SIGNKEY (const unsigned char * random_session_key, gboolean client, unsigned char * result)
759 char * magic = client
760 ? "session key to client-to-server signing key magic constant"
761 : "session key to server-to-client signing key magic constant";
763 int len = strlen(magic) + 1;
764 unsigned char md5_input [16 + len];
765 memcpy(md5_input, random_session_key, 16);
766 memcpy(md5_input + 16, magic, len);
768 MD5 (md5_input, len + 16, result);
772 Define SEALKEY(NegotiateFlags, RandomSessionKey, Mode) as
773 If (NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY flag is set in NegFlg)
774 If ( NTLMSSP_NEGOTIATE_128 is set in NegFlg)
775 Set SealKey to RandomSessionKey
776 ElseIf ( NTLMSSP_NEGOTIATE_56 flag is set in NegFlg)
777 Set SealKey to RandomSessionKey[0..6]
778 Else
779 Set SealKey to RandomSessionKey[0..4]
780 Endif
782 If (Mode equals "Client")
783 Set SealKey to MD5(ConcatenationOf(SealKey, "session key to client-to-server sealing key magic constant"))
784 Else
785 Set SealKey to MD5(ConcatenationOf(SealKey, "session key to server-to-client sealing key magic constant"))
786 Endif
788 ElseIf (NTLMSSP_NEGOTIATE_56 flag is set in NegFlg)
789 Set SealKey to ConcatenationOf(RandomSessionKey[0..6], 0xA0)
790 Else
791 Set SealKey to ConcatenationOf(RandomSessionKey[0..4], 0xE5, 0x38, 0xB0)
792 Endif
793 EndDefine
795 /* out 16 bytes or 8 bytes depending if Ext.Sess.Sec is negotiated */
796 static void
797 SEALKEY (guint32 flags, const unsigned char * random_session_key, gboolean client, unsigned char * result)
799 if (IS_FLAG(flags, NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY))
801 char * magic = client
802 ? "session key to client-to-server sealing key magic constant"
803 : "session key to server-to-client sealing key magic constant";
805 int len = strlen(magic) + 1;
806 unsigned char md5_input [16 + len];
807 int key_len;
809 if (IS_FLAG(flags, NTLMSSP_NEGOTIATE_128)) {
810 purple_debug_info("sipe", "NTLM SEALKEY(): 128-bit key (Extended session security)\n");
811 key_len = 16;
812 } else if (IS_FLAG(flags, NTLMSSP_NEGOTIATE_56)) {
813 purple_debug_info("sipe", "NTLM SEALKEY(): 56-bit key (Extended session security)\n");
814 key_len = 7;
815 } else {
816 purple_debug_info("sipe", "NTLM SEALKEY(): 40-bit key (Extended session security)\n");
817 key_len = 5;
820 memcpy(md5_input, random_session_key, key_len);
821 memcpy(md5_input + key_len, magic, len);
823 MD5 (md5_input, key_len + len, result);
825 else if (IS_FLAG(flags, NTLMSSP_NEGOTIATE_LM_KEY)) /* http://davenport.sourceforge.net/ntlm.html#ntlm1KeyWeakening */
827 if (IS_FLAG(flags, NTLMSSP_NEGOTIATE_56)) {
828 purple_debug_info("sipe", "NTLM SEALKEY(): 56-bit key\n");
829 memcpy(result, random_session_key, 7);
830 result[7] = 0xA0;
831 } else {
832 purple_debug_info("sipe", "NTLM SEALKEY(): 40-bit key\n");
833 memcpy(result, random_session_key, 5);
834 result[5] = 0xE5;
835 result[6] = 0x38;
836 result[7] = 0xB0;
839 else
841 purple_debug_info("sipe", "NTLM SEALKEY(): 128-bit key\n");
842 memcpy(result, random_session_key, 16);
847 = for Extended Session Security =
848 Version (4 bytes): A 32-bit unsigned integer that contains the signature version. This field MUST be 0x00000001.
849 Checksum (8 bytes): An 8-byte array that contains the checksum for the message.
850 SeqNum (4 bytes): A 32-bit unsigned integer that contains the NTLM sequence number for this application message.
852 = if Extended Session Security is NOT negotiated =
853 Version (4 bytes): A 32-bit unsigned integer that contains the signature version. This field MUST be 0x00000001.
854 RandomPad (4 bytes): A 4-byte array that contains the random pad for the message.
855 Checksum (4 bytes): A 4-byte array that contains the checksum for the message.
856 SeqNum (4 bytes): A 32-bit unsigned integer that contains the NTLM sequence number for this application message.
858 0x00000001, RC4K(RandomPad), RC4K(CRC32(Message)), RC4K(0x00000000) XOR (application supplied SeqNum) -- RC4(X) xor X xor Y = RC4(Y)
860 Version(4), Checksum(8), SeqNum(4) -- for ext.sess.sec.
861 Version(4), RandomPad(4), Checksum(4), SeqNum(4)
863 /** MAC(Handle, SigningKey, SeqNum, Message) */
864 /* out 16 bytes */
865 static void
866 MAC (guint32 flags,
867 const char *buf,
868 int buf_len,
869 unsigned char *sign_key,
870 unsigned long sign_key_len,
871 unsigned char *seal_key,
872 unsigned long seal_key_len,
873 guint32 random_pad,
874 guint32 sequence,
875 unsigned char *result)
877 guint32 *res_ptr;
879 if (IS_FLAG(flags, NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY)) {
881 Define MAC(Handle, SigningKey, SeqNum, Message) as
882 Set NTLMSSP_MESSAGE_SIGNATURE.Version to 0x00000001
883 Set NTLMSSP_MESSAGE_SIGNATURE.Checksum to
884 HMAC_MD5(SigningKey, ConcatenationOf(SeqNum, Message))[0..7]
885 Set NTLMSSP_MESSAGE_SIGNATURE.SeqNum to SeqNum
886 Set SeqNum to SeqNum + 1
887 EndDefine
889 /* If a key exchange key is negotiated
890 Define MAC(Handle, SigningKey, SeqNum, Message) as
891 Set NTLMSSP_MESSAGE_SIGNATURE.Version to 0x00000001
892 Set NTLMSSP_MESSAGE_SIGNATURE.Checksum to RC4(Handle,
893 HMAC_MD5(SigningKey, ConcatenationOf(SeqNum, Message))[0..7])
894 Set NTLMSSP_MESSAGE_SIGNATURE.SeqNum to SeqNum
895 Set SeqNum to SeqNum + 1
896 EndDefine
899 unsigned char seal_key_ [16];
900 guchar hmac[16];
901 guchar tmp[4 + buf_len];
903 /* SealingKey' = MD5(ConcatenationOf(SealingKey, SequenceNumber))
904 RC4Init(Handle, SealingKey')
906 if (IS_FLAG(flags, NTLMSSP_NEGOTIATE_DATAGRAM)) {
907 unsigned char tmp2 [16+4];
909 memcpy(tmp2, seal_key, seal_key_len);
910 *((guint32 *)(tmp2+16)) = GUINT32_TO_LE(sequence);
911 MD5 (tmp2, 16+4, seal_key_);
912 } else {
913 memcpy(seal_key_, seal_key, seal_key_len);
916 purple_debug_info("sipe", "NTLM MAC(): Extented Session Security\n");
918 res_ptr = (guint32 *)result;
919 res_ptr[0] = GUINT32_TO_LE(1); // 4 bytes
920 res_ptr[3] = GUINT32_TO_LE(sequence);
922 res_ptr = (guint32 *)tmp;
923 res_ptr[0] = GUINT32_TO_LE(sequence);
924 memcpy(tmp+4, buf, buf_len);
926 HMAC_MD5(sign_key, sign_key_len, tmp, 4 + buf_len, hmac);
928 if (IS_FLAG(flags, NTLMSSP_NEGOTIATE_KEY_EXCH)) {
929 purple_debug_info("sipe", "NTLM MAC(): Key Exchange\n");
930 RC4K(seal_key_, seal_key_len, hmac, 8, result+4);
931 } else {
932 purple_debug_info("sipe", "NTLM MAC(): *NO* Key Exchange\n");
933 memcpy(result+4, hmac, 8);
935 } else {
936 /* The content of the first 4 bytes is irrelevant */
937 guint32 crc = CRC32(buf, strlen(buf));
938 guint32 plaintext [] = {
939 GUINT32_TO_LE(0),
940 GUINT32_TO_LE(crc),
941 GUINT32_TO_LE(sequence)
942 }; // 4, 4, 4 bytes
944 purple_debug_info("sipe", "NTLM MAC(): *NO* Extented Session Security\n");
946 RC4K(seal_key, seal_key_len, (const guchar *)plaintext, 12, result+4);
948 res_ptr = (guint32 *)result;
949 // Highest four bytes are the Version
950 res_ptr[0] = GUINT32_TO_LE(0x00000001); // 4 bytes
952 // Replace the first four bytes of the ciphertext with the random_pad
953 res_ptr[1] = GUINT32_TO_LE(random_pad); // 4 bytes
957 /* End Core NTLM Methods */
960 * @param flags (out) flags received from server
961 * @param server_challenge must be g_free()'d after use if requested
962 * @param target_info must be g_free()'d after use if requested
964 static void
965 sip_sec_ntlm_parse_challenge(SipSecBuffer in_buff,
966 guint32 *flags,
967 guchar **server_challenge, /* 8 bytes */
968 guint64 *time_val,
969 guchar **target_info,
970 int *target_info_len)
972 struct challenge_message *cmsg = (struct challenge_message*)in_buff.value;
973 guint32 host_flags = GUINT32_FROM_LE(cmsg->flags);
975 /* server challenge (nonce) */
976 if (server_challenge) {
977 *server_challenge = g_memdup(cmsg->nonce, 8);
980 /* flags */
981 if (flags) {
982 *flags = host_flags;
985 /* target_info */
986 if (cmsg->target_info.len && cmsg->target_info.offset) {
987 void *content = (gchar *)cmsg + GUINT32_FROM_LE(cmsg->target_info.offset);
988 void *av = content;
989 guint16 len = GUINT16_FROM_LE(cmsg->target_info.len);
991 ALIGN_AV_LOOP_START
993 /* @since Vista */
994 case MsvAvTimestamp:
995 if (time_val) {
996 guint64 tmp;
998 /* to meet sparc's alignment requirement */
999 memcpy(&tmp, av_value, sizeof(tmp));
1000 *time_val = GUINT64_FROM_LE(tmp);
1002 break;
1004 ALIGN_AV_LOOP_END;
1006 if (target_info_len) {
1007 *target_info_len = len;
1009 if (target_info) {
1010 *target_info = g_memdup(content, len);
1016 * @param client_sign_key (out) must be g_free()'d after use
1017 * @param server_sign_key (out) must be g_free()'d after use
1018 * @param client_seal_key (out) must be g_free()'d after use
1019 * @param server_seal_key (out) must be g_free()'d after use
1020 * @param flags (in, out) negotiated flags
1022 static sip_uint32
1023 sip_sec_ntlm_gen_authenticate(guchar **client_sign_key,
1024 guchar **server_sign_key,
1025 guchar **client_seal_key,
1026 guchar **server_seal_key,
1027 const gchar *user,
1028 const gchar *password,
1029 const gchar *hostname,
1030 const gchar *domain,
1031 const guint8 *server_challenge, /* nonce */
1032 const guint64 time_val,
1033 const guint8 *target_info,
1034 int target_info_len,
1035 gboolean is_connection_based,
1036 SipSecBuffer *out_buff,
1037 guint32 *flags)
1039 guint32 orig_flags = is_connection_based ? NEGOTIATE_FLAGS_CONN : NEGOTIATE_FLAGS_CONNLESS;
1040 guint32 neg_flags = (*flags & orig_flags) | NTLMSSP_REQUEST_TARGET;
1041 int ntlmssp_nt_resp_len =
1042 #ifdef _SIPE_COMPILING_TESTS
1043 use_ntlm_v2 ?
1044 #endif
1045 (16 + (32+target_info_len))
1046 #ifdef _SIPE_COMPILING_TESTS
1047 : NTLMSSP_LM_RESP_LEN
1048 #endif
1050 gsize msglen = sizeof(struct authenticate_message)
1051 + 2*(strlen(domain) + strlen(user)+ strlen(hostname))
1052 + NTLMSSP_LM_RESP_LEN + ntlmssp_nt_resp_len
1053 + (IS_FLAG(neg_flags, NTLMSSP_NEGOTIATE_KEY_EXCH) ? NTLMSSP_SESSION_KEY_LEN : 0);
1054 struct authenticate_message *tmsg;
1055 char *tmp;
1056 guint32 offset;
1057 guint16 len;
1058 unsigned char response_key_lm [NTLMSSP_LN_OR_NT_KEY_LEN]; /* 16 */
1059 unsigned char response_key_nt [NTLMSSP_LN_OR_NT_KEY_LEN]; /* 16 */
1060 unsigned char lm_challenge_response [NTLMSSP_LM_RESP_LEN]; /* 24 */
1061 unsigned char nt_challenge_response [ntlmssp_nt_resp_len]; /* variable or 24 */
1062 unsigned char session_base_key [16];
1063 unsigned char key_exchange_key [16];
1064 unsigned char exported_session_key[16];
1065 unsigned char encrypted_random_session_key [16];
1066 unsigned char key [16];
1067 unsigned char client_challenge [8];
1068 guint64 time_vl = time_val ? time_val : TIME_T_TO_VAL(time(NULL));
1070 if (!IS_FLAG(*flags, NEGOTIATE_FLAGS_COMMON_MIN) ||
1071 !(is_connection_based || IS_FLAG(*flags, NEGOTIATE_FLAGS_CONNLESS_EXTRA)))
1073 purple_debug_info("sipe", "sip_sec_ntlm_gen_authenticate: received incompatible NTLM NegotiateFlags, exiting.");
1074 return SIP_SEC_E_INTERNAL_ERROR;
1077 if (IS_FLAG(neg_flags, NTLMSSP_NEGOTIATE_128)) {
1078 neg_flags = neg_flags & ~NTLMSSP_NEGOTIATE_56;
1081 tmsg = g_malloc0(msglen);
1083 NONCE (client_challenge, 8);
1085 #ifdef _SIPE_COMPILING_TESTS
1086 memcpy(client_challenge, test_client_challenge, 8);
1087 time_vl = test_time_val ? test_time_val : time_vl;
1089 if (use_ntlm_v2) {
1091 #endif
1092 NTOWFv2 (password, user, domain, response_key_nt);
1093 memcpy(response_key_lm, response_key_nt, NTLMSSP_LN_OR_NT_KEY_LEN);
1094 #ifdef _SIPE_COMPILING_TESTS
1095 } else {
1096 NTOWFv1 (password, user, domain, response_key_nt);
1097 LMOWFv1 (password, user, domain, response_key_lm);
1099 #endif
1101 compute_response(neg_flags,
1102 response_key_nt,
1103 response_key_lm,
1104 server_challenge,
1105 client_challenge,
1106 time_vl,
1107 target_info,
1108 target_info_len,
1109 lm_challenge_response, /* out */
1110 nt_challenge_response, /* out */
1111 session_base_key); /* out */
1113 /* same as session_base_key for
1114 * - NTLNv1 w/o Ext.Sess.Sec and
1115 * - NTLMv2
1117 KXKEY(neg_flags, session_base_key, lm_challenge_response, server_challenge, key_exchange_key);
1119 if (IS_FLAG(neg_flags, NTLMSSP_NEGOTIATE_KEY_EXCH)) {
1120 NONCE (exported_session_key, 16); // random master key
1121 #ifdef _SIPE_COMPILING_TESTS
1122 memcpy(exported_session_key, test_random_session_key, 16);
1123 #endif
1124 RC4K (key_exchange_key, 16, exported_session_key, 16, encrypted_random_session_key);
1125 } else {
1126 memcpy(exported_session_key, key_exchange_key, 16);
1129 tmp = buff_to_hex_str(exported_session_key, 16);
1130 purple_debug_info("sipe", "NTLM AUTHENTICATE: exported session key (not encrypted): %s\n", tmp);
1131 g_free(tmp);
1133 if (IS_FLAG(neg_flags, NTLMSSP_NEGOTIATE_SIGN) ||
1134 IS_FLAG(neg_flags, NTLMSSP_NEGOTIATE_SEAL))
1136 /* p.46
1137 Set ClientSigningKey to SIGNKEY(ExportedSessionKey, "Client")
1138 Set ServerSigningKey to SIGNKEY(ExportedSessionKey, "Server")
1140 SIGNKEY(exported_session_key, TRUE, key);
1141 *client_sign_key = (guchar *)g_strndup((gchar *)key, 16);
1142 SIGNKEY(exported_session_key, FALSE, key);
1143 *server_sign_key = (guchar *)g_strndup((gchar *)key, 16);
1144 SEALKEY(neg_flags, exported_session_key, TRUE, key);
1145 *client_seal_key = (guchar *)g_strndup((gchar *)key, 16);
1146 SEALKEY(neg_flags, exported_session_key, FALSE, key);
1147 *server_seal_key = (guchar *)g_strndup((gchar *)key, 16);
1150 /* @TODO: */
1151 /* @since Vista
1152 If the CHALLENGE_MESSAGE TargetInfo field (section 2.2.1.2) has an MsvAvTimestamp present,
1153 the client SHOULD provide a MIC:
1154 - If there is an AV_PAIR structure (section 2.2.2.1) with the AvId field set to MsvAvFlags,
1155 - then in the Value field, set bit 0x2 to 1.
1156 - else add an AV_PAIR structure (section 2.2.2.1) and set the AvId field to MsvAvFlags
1157 and the Value field bit 0x2 to 1.
1158 - Populate the MIC field with the MIC.
1161 /* Connection-oriented:
1162 Set MIC to HMAC_MD5(ExportedSessionKey,
1163 ConcatenationOf( NEGOTIATE_MESSAGE, CHALLENGE_MESSAGE, AUTHENTICATE_MESSAGE_MIC0));
1164 Connectionless:
1165 Set MIC to HMAC_MD5(ExportedSessionKey,
1166 ConcatenationOf( CHALLENGE_MESSAGE, AUTHENTICATE_MESSAGE))
1169 /* on the server-side:
1170 If (NTLMSSP_NEGOTIATE_KEY_EXCH flag is set in NegFlg )
1171 Set ExportedSessionKey to RC4K(KeyExchangeKey, AUTHENTICATE_MESSAGE.EncryptedRandomSessionKey)
1172 Set MIC to HMAC_MD5(ExportedSessionKey,
1173 ConcatenationOf( NEGOTIATE_MESSAGE, CHALLENGE_MESSAGE, AUTHENTICATE_MESSAGE_MIC0))
1174 Else
1175 Set ExportedSessionKey to KeyExchangeKey
1176 Set MIC to HMAC_MD5(KeyExchangeKey,
1177 ConcatenationOf( NEGOTIATE_MESSAGE, CHALLENGE_MESSAGE, AUTHENTICATE_MESSAGE_MIC0)) EndIf
1178 =====
1179 @since Vista
1180 If the AUTHENTICATE_MESSAGE indicates the presence of a MIC field,
1181 then the MIC value computed earlier MUST be compared to the MIC field in the message,
1182 and if the two MIC values are not equal, then an authentication failure MUST be returned.
1183 An AUTHENTICATE_MESSAGE indicates the presence of a MIC field if the TargetInfo field has
1184 an AV_PAIR structure whose two fields:
1185 - AvId == MsvAvFlags
1186 - Value bit 0x2 == 1
1187 @supported NT, 2000, XP
1188 If NTLM v2 authentication is used and the AUTHENTICATE_MESSAGE.NtChallengeResponse.
1189 TimeStamp (section 2.2.2.7) is more than MaxLifetime (section 3.1.1.1) difference from
1190 the server time, then the server SHOULD return a failure.
1192 Connectionless:
1193 Set MIC to HMAC_MD5(ResponseKeyNT,
1194 ConcatenationOf( CHALLENGE_MESSAGE, AUTHENTICATE_MESSAGE_MIC0))
1197 /* authenticate message initialization */
1198 memcpy(tmsg->protocol, "NTLMSSP\0", 8);
1199 tmsg->type = GUINT32_TO_LE(3);
1201 /* Initial offset */
1202 offset = sizeof(struct authenticate_message);
1203 tmp = ((char*) tmsg) + offset;
1205 #define _FILL_SMB_HEADER(header) \
1206 tmsg->header.offset = GUINT32_TO_LE(offset); \
1207 tmsg->header.len = tmsg->header.maxlen = GUINT16_TO_LE(len); \
1208 tmp += len; \
1209 offset += len
1210 #define _APPEND_STRING(header, src) \
1211 len = unicode_strconvcopy(tmp, (src), msglen - offset); \
1212 _FILL_SMB_HEADER(header)
1213 #define _APPEND_DATA(header, src, srclen) \
1214 len = (srclen); \
1215 memcpy(tmp, (src), len); \
1216 _FILL_SMB_HEADER(header)
1218 /* Domain */
1219 _APPEND_STRING(domain, domain);
1221 /* User */
1222 _APPEND_STRING(user, user);
1224 /* Host */
1225 _APPEND_STRING(host, hostname);
1227 /* LM */
1228 /* @since Windows 7
1229 If NTLM v2 authentication is used and the CHALLENGE_MESSAGE contains a TargetInfo field,
1230 the client SHOULD NOT send the LmChallengeResponse and SHOULD set the LmChallengeResponseLen
1231 and LmChallengeResponseMaxLen fields in the AUTHENTICATE_MESSAGE to zero.
1233 _APPEND_DATA(lm_resp, lm_challenge_response, NTLMSSP_LM_RESP_LEN);
1235 /* NT */
1236 _APPEND_DATA(nt_resp, nt_challenge_response, ntlmssp_nt_resp_len);
1238 /* Session Key */
1239 if (IS_FLAG(neg_flags, NTLMSSP_NEGOTIATE_KEY_EXCH))
1241 _APPEND_DATA(session_key, encrypted_random_session_key, NTLMSSP_SESSION_KEY_LEN);
1243 else
1245 tmsg->session_key.offset = GUINT32_TO_LE(offset);
1246 tmsg->session_key.len = tmsg->session_key.maxlen = 0;
1249 /* Version */
1250 #ifdef _SIPE_COMPILING_TESTS
1251 memcpy(&(tmsg->ver), &test_version, sizeof(struct version));
1252 #else
1253 if (IS_FLAG(neg_flags, NTLMSSP_NEGOTIATE_VERSION)) {
1254 tmsg->ver.product_major_version = 5; /* 5.1.2600 (Windows XP SP2) */
1255 tmsg->ver.product_minor_version = 1;
1256 tmsg->ver.product_build = GUINT16_FROM_LE(2600);
1257 tmsg->ver.ntlm_revision_current = 0x0F; /* NTLMSSP_REVISION_W2K3 */
1259 #endif
1261 /* Set Negotiate Flags */
1262 tmsg->flags = GUINT32_TO_LE(neg_flags);
1263 *flags = neg_flags;
1265 out_buff->value = (guint8 *)tmsg;
1266 out_buff->length = msglen;
1268 return SIP_SEC_E_OK;
1272 * Generates Type 1 (Negotiate) message for connection-oriented cases (only)
1274 static void
1275 sip_sec_ntlm_gen_negotiate(SipSecBuffer *out_buff)
1277 guint32 offset;
1278 guint16 len;
1279 int msglen = sizeof(struct negotiate_message);
1280 struct negotiate_message *tmsg = g_malloc0(msglen);
1282 /* negotiate message initialization */
1283 memcpy(tmsg->protocol, "NTLMSSP\0", 8);
1284 tmsg->type = GUINT32_TO_LE(1);
1286 /* Set Negotiate Flags */
1287 tmsg->flags = GUINT32_TO_LE(NEGOTIATE_FLAGS_CONN);
1289 /* Domain */
1290 offset = sizeof(struct negotiate_message);
1291 tmsg->domain.offset = GUINT32_TO_LE(offset);
1292 tmsg->domain.len = tmsg->domain.maxlen = len = 0;
1294 /* Host */
1295 offset += len;
1296 tmsg->host.offset = GUINT32_TO_LE(offset);
1297 tmsg->host.len = tmsg->host.maxlen = len = 0;
1299 /* Version */
1300 tmsg->ver.product_major_version = 5; /* 5.1.2600 (Windows XP SP2) */
1301 tmsg->ver.product_minor_version = 1;
1302 tmsg->ver.product_build = GUINT16_FROM_LE(2600);
1303 tmsg->ver.ntlm_revision_current = 0x0F; /* NTLMSSP_REVISION_W2K3 */
1305 out_buff->value = (guint8 *)tmsg;
1306 out_buff->length = msglen;
1309 static void
1310 sip_sec_ntlm_sipe_signature_make(guint32 flags,
1311 const char *msg,
1312 guint32 random_pad,
1313 unsigned char *sign_key,
1314 unsigned char *seal_key,
1315 unsigned char *result)
1317 char *res;
1319 MAC(flags, msg,strlen(msg), sign_key,16, seal_key,16, random_pad, 100, result);
1321 res = buff_to_hex_str(result, 16);
1322 purple_debug_info("sipe", "NTLM calculated MAC: %s\n", res);
1323 g_free(res);
1327 /* Describe NTLM messages functions */
1329 #define APPEND_NEG_FLAG(str, flags, flag, desc) \
1330 if ((flags & flag) == flag) g_string_append_printf(str, "\t%s\n", desc);
1332 static gchar *
1333 sip_sec_ntlm_negotiate_flags_describe(guint32 flags)
1335 GString* str = g_string_new(NULL);
1337 flags = GUINT32_FROM_LE(flags);
1339 APPEND_NEG_FLAG(str, flags, NTLMSSP_NEGOTIATE_UNICODE, "NTLMSSP_NEGOTIATE_UNICODE");
1340 APPEND_NEG_FLAG(str, flags, NTLMSSP_NEGOTIATE_OEM, "NTLMSSP_NEGOTIATE_OEM");
1341 APPEND_NEG_FLAG(str, flags, NTLMSSP_REQUEST_TARGET, "NTLMSSP_REQUEST_TARGET");
1342 APPEND_NEG_FLAG(str, flags, r9, "r9");
1343 APPEND_NEG_FLAG(str, flags, NTLMSSP_NEGOTIATE_SIGN, "NTLMSSP_NEGOTIATE_SIGN");
1344 APPEND_NEG_FLAG(str, flags, NTLMSSP_NEGOTIATE_SEAL, "NTLMSSP_NEGOTIATE_SEAL");
1345 APPEND_NEG_FLAG(str, flags, NTLMSSP_NEGOTIATE_DATAGRAM, "NTLMSSP_NEGOTIATE_DATAGRAM");
1346 APPEND_NEG_FLAG(str, flags, NTLMSSP_NEGOTIATE_LM_KEY, "NTLMSSP_NEGOTIATE_LM_KEY");
1347 APPEND_NEG_FLAG(str, flags, r8, "r8");
1348 APPEND_NEG_FLAG(str, flags, NTLMSSP_NEGOTIATE_NTLM, "NTLMSSP_NEGOTIATE_NTLM");
1349 APPEND_NEG_FLAG(str, flags, NTLMSSP_NEGOTIATE_NT_ONLY, "NTLMSSP_NEGOTIATE_NT_ONLY");
1350 APPEND_NEG_FLAG(str, flags, anonymous, "anonymous");
1351 APPEND_NEG_FLAG(str, flags, NTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED, "NTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED");
1352 APPEND_NEG_FLAG(str, flags, NTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED, "NTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED");
1353 APPEND_NEG_FLAG(str, flags, r7, "r7");
1354 APPEND_NEG_FLAG(str, flags, NTLMSSP_NEGOTIATE_ALWAYS_SIGN, "NTLMSSP_NEGOTIATE_ALWAYS_SIGN");
1355 APPEND_NEG_FLAG(str, flags, NTLMSSP_TARGET_TYPE_DOMAIN, "NTLMSSP_TARGET_TYPE_DOMAIN");
1356 APPEND_NEG_FLAG(str, flags, NTLMSSP_TARGET_TYPE_SERVER, "NTLMSSP_TARGET_TYPE_SERVER");
1357 APPEND_NEG_FLAG(str, flags, r6, "r6");
1358 APPEND_NEG_FLAG(str, flags, NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY, "NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY");
1359 APPEND_NEG_FLAG(str, flags, NTLMSSP_NEGOTIATE_IDENTIFY, "NTLMSSP_NEGOTIATE_IDENTIFY");
1360 APPEND_NEG_FLAG(str, flags, r5, "r5");
1361 APPEND_NEG_FLAG(str, flags, NTLMSSP_REQUEST_NON_NT_SESSION_KEY, "NTLMSSP_REQUEST_NON_NT_SESSION_KEY");
1362 APPEND_NEG_FLAG(str, flags, NTLMSSP_NEGOTIATE_TARGET_INFO, "NTLMSSP_NEGOTIATE_TARGET_INFO");
1363 APPEND_NEG_FLAG(str, flags, r4, "r4");
1364 APPEND_NEG_FLAG(str, flags, NTLMSSP_NEGOTIATE_VERSION, "NTLMSSP_NEGOTIATE_VERSION");
1365 APPEND_NEG_FLAG(str, flags, r3, "r3");
1366 APPEND_NEG_FLAG(str, flags, r2, "r2");
1367 APPEND_NEG_FLAG(str, flags, r1, "r1");
1368 APPEND_NEG_FLAG(str, flags, NTLMSSP_NEGOTIATE_128, "NTLMSSP_NEGOTIATE_128");
1369 APPEND_NEG_FLAG(str, flags, NTLMSSP_NEGOTIATE_KEY_EXCH, "NTLMSSP_NEGOTIATE_KEY_EXCH");
1370 APPEND_NEG_FLAG(str, flags, NTLMSSP_NEGOTIATE_56, "NTLMSSP_NEGOTIATE_56");
1372 return g_string_free(str, FALSE);
1375 static gchar *
1376 sip_sec_ntlm_describe_version(struct version *ver) {
1377 GString* str = g_string_new(NULL);
1378 gchar *ver_desc = "";
1379 gchar *ntlm_revision_desc = "";
1381 if (ver->product_major_version == 6) {
1382 ver_desc = "Windows Vista, Windows Server 2008, Windows 7 or Windows Server 2008 R2";
1383 } else if (ver->product_major_version == 5 && ver->product_minor_version == 2) {
1384 ver_desc = "Windows Server 2003";
1385 } else if (ver->product_major_version == 5 && ver->product_minor_version == 1) {
1386 ver_desc = "Windows XP SP2";
1389 if (ver->ntlm_revision_current == 0x0F) {
1390 ntlm_revision_desc = "NTLMSSP_REVISION_W2K3";
1391 } else if (ver->ntlm_revision_current == 0x0A) {
1392 ntlm_revision_desc = "NTLMSSP_REVISION_W2K3_RC1";
1395 g_string_append_printf(str, "\tproduct: %d.%d.%d (%s)\n",
1396 ver->product_major_version, ver->product_minor_version, ver->product_build, ver_desc);
1397 g_string_append_printf(str, "\tntlm_revision_current: 0x%02X (%s)\n", ver->ntlm_revision_current, ntlm_revision_desc);
1399 return g_string_free(str, FALSE);
1402 static gchar *
1403 sip_sec_ntlm_describe_smb_header(struct smb_header *header,
1404 const char* name)
1406 GString* str = g_string_new(NULL);
1408 g_string_append_printf(str, "\t%s.len : %d\n", name, GUINT16_FROM_LE(header->len));
1409 g_string_append_printf(str, "\t%s.maxlen: %d\n", name, GUINT16_FROM_LE(header->maxlen));
1410 g_string_append_printf(str, "\t%s.offset: %d\n", name, GUINT32_FROM_LE(header->offset));
1412 return g_string_free(str, FALSE);
1415 static gchar *
1416 sip_sec_ntlm_negotiate_message_describe(struct negotiate_message *cmsg)
1418 GString* str = g_string_new(NULL);
1419 char *tmp;
1421 g_string_append(str, (tmp = sip_sec_ntlm_negotiate_flags_describe(cmsg->flags)));
1422 g_free(tmp);
1424 g_string_append(str, (tmp = sip_sec_ntlm_describe_smb_header(&(cmsg->domain), "domain")));
1425 g_free(tmp);
1427 g_string_append(str, (tmp = sip_sec_ntlm_describe_smb_header(&(cmsg->host), "host")));
1428 g_free(tmp);
1430 tmp = sip_sec_ntlm_describe_version(&(cmsg->ver));
1431 g_string_append(str, tmp);
1432 g_free(tmp);
1434 if (cmsg->domain.len && cmsg->domain.offset) {
1435 gchar *domain = g_strndup(((gchar *)cmsg + GUINT32_FROM_LE(cmsg->domain.offset)), GUINT16_FROM_LE(cmsg->domain.len));
1436 g_string_append_printf(str, "\tdomain: %s\n", domain);
1437 g_free(domain);
1440 if (cmsg->host.len && cmsg->host.offset) {
1441 gchar *host = g_strndup(((gchar *)cmsg + GUINT32_FROM_LE(cmsg->host.offset)), GUINT16_FROM_LE(cmsg->host.len));
1442 g_string_append_printf(str, "\thost: %s\n", host);
1443 g_free(host);
1446 return g_string_free(str, FALSE);
1449 static void
1450 describe_av_pairs(GString* str, const void *av)
1452 #define AV_DESC(av_name) \
1454 gchar *tmp = unicode_strconvcopy_back(av_value, av_len); \
1455 g_string_append_printf(str, "\t%s: %s\n", av_name, tmp); \
1456 g_free(tmp); \
1459 ALIGN_AV_LOOP_START
1461 case MsvAvNbComputerName:
1462 AV_DESC("MsvAvNbComputerName");
1463 break;
1464 case MsvAvNbDomainName:
1465 AV_DESC("MsvAvNbDomainName");
1466 break;
1467 case MsvAvDnsComputerName:
1468 AV_DESC("MsvAvDnsComputerName");
1469 break;
1470 case MsvAvDnsDomainName:
1471 AV_DESC("MsvAvDnsDomainName");
1472 break;
1473 case MsvAvDnsTreeName:
1474 AV_DESC("MsvAvDnsTreeName");
1475 break;
1476 case MsvAvFlags:
1478 guint32 flags;
1480 /* to meet sparc's alignment requirement */
1481 memcpy(&flags, av_value, sizeof(guint32));
1482 g_string_append_printf(str, "\t%s: %d\n", "MsvAvFlags", GUINT32_FROM_LE(flags));
1484 break;
1485 case MsvAvTimestamp:
1487 char *tmp;
1488 guint64 time_val;
1489 time_t time_t_val;
1491 /* to meet sparc's alignment requirement */
1492 memcpy(&time_val, av_value, sizeof(time_val));
1493 time_t_val = TIME_VAL_TO_T(time_val);
1495 g_string_append_printf(str, "\t%s: %s - %s", "MsvAvTimestamp", (tmp = buff_to_hex_str((guint8 *) av_value, 8)),
1496 asctime(gmtime(&time_t_val)));
1497 g_free(tmp);
1499 break;
1500 case MsAvRestrictions:
1501 g_string_append_printf(str, "\t%s\n", "MsAvRestrictions");
1502 break;
1503 case MsvAvTargetName:
1504 AV_DESC("MsvAvTargetName");
1505 break;
1506 case MsvChannelBindings:
1507 g_string_append_printf(str, "\t%s\n", "MsvChannelBindings");
1508 break;
1510 ALIGN_AV_LOOP_END;
1513 static gchar *
1514 sip_sec_ntlm_authenticate_message_describe(struct authenticate_message *cmsg)
1516 GString* str = g_string_new(NULL);
1517 char *tmp;
1518 gsize value_len;
1519 guint8 *value;
1521 g_string_append(str, (tmp = sip_sec_ntlm_negotiate_flags_describe(cmsg->flags)));
1522 g_free(tmp);
1524 g_string_append(str, (tmp = sip_sec_ntlm_describe_smb_header(&(cmsg->lm_resp), "lm_resp")));
1525 g_free(tmp);
1527 g_string_append(str, (tmp = sip_sec_ntlm_describe_smb_header(&(cmsg->nt_resp), "nt_resp")));
1528 g_free(tmp);
1530 g_string_append(str, (tmp = sip_sec_ntlm_describe_smb_header(&(cmsg->domain), "domain")));
1531 g_free(tmp);
1533 g_string_append(str, (tmp = sip_sec_ntlm_describe_smb_header(&(cmsg->user), "user")));
1534 g_free(tmp);
1536 g_string_append(str, (tmp = sip_sec_ntlm_describe_smb_header(&(cmsg->host), "host")));
1537 g_free(tmp);
1539 g_string_append(str, (tmp = sip_sec_ntlm_describe_smb_header(&(cmsg->session_key), "session_key")));
1540 g_free(tmp);
1542 tmp = sip_sec_ntlm_describe_version(&(cmsg->ver));
1543 g_string_append(str, tmp);
1544 g_free(tmp);
1546 /* mic */
1547 //g_string_append_printf(str, "\t%s: %s\n", "mic", (tmp = buff_to_hex_str(cmsg->mic, 16)));
1548 //g_free(tmp);
1550 if (cmsg->lm_resp.len && cmsg->lm_resp.offset) {
1551 value_len = GUINT16_FROM_LE(cmsg->lm_resp.len);
1552 value = (guint8 *)cmsg + GUINT32_FROM_LE(cmsg->lm_resp.offset);
1553 g_string_append_printf(str, "\t%s: %s\n", "lm_resp", (tmp = buff_to_hex_str(value, value_len)));
1554 g_free(tmp);
1557 if (cmsg->nt_resp.len && cmsg->nt_resp.offset) {
1558 guint16 nt_resp_len_full = GUINT16_FROM_LE(cmsg->nt_resp.len);
1559 int nt_resp_len = nt_resp_len_full;
1561 value_len = nt_resp_len_full;
1562 value = (guint8 *)cmsg + GUINT32_FROM_LE(cmsg->nt_resp.offset);
1563 g_string_append_printf(str, "\t%s: %s\n", "nt_resp raw", (tmp = buff_to_hex_str(value, value_len)));
1564 g_free(tmp);
1566 if (nt_resp_len > 24) { /* NTLMv2 */
1567 nt_resp_len = 16;
1570 value_len = nt_resp_len;
1571 value = (guint8 *)cmsg + GUINT32_FROM_LE(cmsg->nt_resp.offset);
1572 g_string_append_printf(str, "\t%s: %s\n", "nt_resp", (tmp = buff_to_hex_str(value, value_len)));
1573 g_free(tmp);
1575 if (nt_resp_len_full > 24) { /* NTLMv2 */
1576 /* Work around Debian/x86_64 compiler bug */
1577 /* const guint8 *temp = (guint8 *)cmsg + GUINT32_FROM_LE(cmsg->nt_resp.offset) + 16; */
1578 const guint offset = GUINT32_FROM_LE(cmsg->nt_resp.offset) + 16;
1579 const guint8 *temp = (guint8 *)cmsg + offset;
1580 const guint response_version = temp[0];
1581 const guint hi_response_version = temp[1];
1582 const guint8 *client_challenge = temp + 16;
1583 const guint8 *target_info = temp + 28;
1584 guint16 target_info_len = nt_resp_len_full - 16 - 32;
1585 guint64 time_val;
1586 time_t time_t_val;
1587 char *tmp;
1589 g_string_append_printf(str, "\t%s: %s\n", "target_info raw",
1590 (tmp = buff_to_hex_str((guint8 *)target_info, target_info_len)));
1591 g_free(tmp);
1593 /* This is not int64 aligned on sparc */
1594 memcpy((gchar *)&time_val, temp+8, sizeof(time_val));
1595 time_t_val = TIME_VAL_TO_T(time_val);
1597 g_string_append_printf(str, "\t%s: %d\n", "response_version", response_version);
1598 g_string_append_printf(str, "\t%s: %d\n", "hi_response_version", hi_response_version);
1600 g_string_append_printf(str, "\t%s: %s - %s", "time", (tmp = buff_to_hex_str((guint8 *)&time_val, 8)),
1601 asctime(gmtime(&time_t_val)));
1602 g_free(tmp);
1604 g_string_append_printf(str, "\t%s: %s\n", "client_challenge", (tmp = buff_to_hex_str((guint8 *)client_challenge, 8)));
1605 g_free(tmp);
1607 describe_av_pairs(str, target_info);
1609 g_string_append_printf(str, "\t%s\n", "----------- end of nt_resp v2 -----------");
1613 if (cmsg->domain.len && cmsg->domain.offset) {
1614 gchar *domain = unicode_strconvcopy_back(((gchar *)cmsg + GUINT32_FROM_LE(cmsg->domain.offset)), GUINT16_FROM_LE(cmsg->domain.len));
1615 g_string_append_printf(str, "\t%s: %s\n", "domain", domain);
1616 g_free(domain);
1619 if (cmsg->user.len && cmsg->user.offset) {
1620 gchar *user = unicode_strconvcopy_back(((gchar *)cmsg + GUINT32_FROM_LE(cmsg->user.offset)), GUINT16_FROM_LE(cmsg->user.len));
1621 g_string_append_printf(str, "\t%s: %s\n", "user", user);
1622 g_free(user);
1625 if (cmsg->host.len && cmsg->host.offset) {
1626 gchar *host = unicode_strconvcopy_back(((gchar *)cmsg + GUINT32_FROM_LE(cmsg->host.offset)), GUINT16_FROM_LE(cmsg->host.len));
1627 g_string_append_printf(str, "\t%s: %s\n", "host", host);
1628 g_free(host);
1631 if (cmsg->session_key.len && cmsg->session_key.offset) {
1632 value_len = GUINT16_FROM_LE(cmsg->session_key.len);
1633 value = (guint8 *)cmsg + GUINT32_FROM_LE(cmsg->session_key.offset);
1634 g_string_append_printf(str, "\t%s: %s\n", "session_key", (tmp = buff_to_hex_str(value, value_len)));
1635 g_free(tmp);
1638 return g_string_free(str, FALSE);
1641 static gchar *
1642 sip_sec_ntlm_challenge_message_describe(struct challenge_message *cmsg)
1644 GString* str = g_string_new(NULL);
1645 char *tmp;
1647 g_string_append(str, (tmp = sip_sec_ntlm_negotiate_flags_describe(cmsg->flags)));
1648 g_free(tmp);
1650 /* nonce (server_challenge) */
1651 g_string_append_printf(str, "\t%s: %s\n", "server_challenge", (tmp = buff_to_hex_str(cmsg->nonce, 8)));
1652 g_free(tmp);
1654 g_string_append(str, (tmp = sip_sec_ntlm_describe_smb_header(&(cmsg->target_name), "target_name")));
1655 g_free(tmp);
1657 g_string_append(str, (tmp = sip_sec_ntlm_describe_smb_header(&(cmsg->target_info), "target_info")));
1658 g_free(tmp);
1660 g_string_append(str, (tmp = sip_sec_ntlm_describe_version(&(cmsg->ver))));
1661 g_free(tmp);
1663 if (cmsg->target_name.len && cmsg->target_name.offset) {
1664 gchar *target_name = unicode_strconvcopy_back(((gchar *)cmsg + GUINT32_FROM_LE(cmsg->target_name.offset)), GUINT16_FROM_LE(cmsg->target_name.len));
1665 g_string_append_printf(str, "\ttarget_name: %s\n", target_name);
1666 g_free(target_name);
1669 if (cmsg->target_info.len && cmsg->target_info.offset) {
1670 guint8 *target_info = (guint8 *)cmsg + GUINT32_FROM_LE(cmsg->target_info.offset);
1671 guint16 target_info_len = GUINT16_FROM_LE(cmsg->target_info.len);
1673 g_string_append_printf(str, "\t%s: %s\n", "target_info raw", (tmp = buff_to_hex_str(target_info, target_info_len)));
1674 g_free(tmp);
1676 describe_av_pairs(str, target_info);
1679 return g_string_free(str, FALSE);
1682 gchar *
1683 sip_sec_ntlm_message_describe(SipSecBuffer buff)
1685 struct ntlm_message *msg;
1686 gchar *res = NULL;
1688 if (buff.length == 0 || buff.value == NULL || buff.length < 12) return NULL;
1690 msg = (struct ntlm_message *)buff.value;
1691 if(!sipe_strequal("NTLMSSP", (char*)msg)) return NULL;
1693 switch (GUINT32_FROM_LE(msg->type)) {
1694 case 1: res = sip_sec_ntlm_negotiate_message_describe((struct negotiate_message *)msg);
1695 break;
1696 case 2: res = sip_sec_ntlm_challenge_message_describe((struct challenge_message *)msg);
1697 break;
1698 case 3: res = sip_sec_ntlm_authenticate_message_describe((struct authenticate_message *)msg);
1699 break;
1702 return res;
1705 /* sip-sec-mech.h API implementation for NTLM */
1707 /* Security context for NTLM */
1708 typedef struct _context_ntlm {
1709 struct sip_sec_context common;
1710 char* domain;
1711 char *username;
1712 char *password;
1713 int step;
1714 guchar *client_sign_key;
1715 guchar *server_sign_key;
1716 guchar *client_seal_key;
1717 guchar *server_seal_key;
1718 guint32 flags;
1719 } *context_ntlm;
1722 static sip_uint32
1723 sip_sec_acquire_cred__ntlm(SipSecContext context,
1724 const char *domain,
1725 const char *username,
1726 const char *password)
1728 context_ntlm ctx = (context_ntlm)context;
1730 /* NTLM requires a domain, username & password */
1731 if (!domain || !username || !password)
1732 return SIP_SEC_E_INTERNAL_ERROR;
1734 ctx->domain = g_strdup(domain);
1735 ctx->username = g_strdup(username);
1736 ctx->password = g_strdup(password);
1738 return SIP_SEC_E_OK;
1741 static sip_uint32
1742 sip_sec_init_sec_context__ntlm(SipSecContext context,
1743 SipSecBuffer in_buff,
1744 SipSecBuffer *out_buff,
1745 SIPE_UNUSED_PARAMETER const char *service_name)
1747 context_ntlm ctx = (context_ntlm) context;
1749 purple_debug_info("sipe", "sip_sec_init_sec_context__ntlm: in use\n");
1751 ctx->step++;
1752 if (ctx->step == 1) {
1753 if (!context->is_connection_based) {
1754 out_buff->length = 0;
1755 out_buff->value = NULL;
1756 } else {
1757 sip_sec_ntlm_gen_negotiate(out_buff);
1759 return SIP_SEC_I_CONTINUE_NEEDED;
1761 } else {
1762 sip_uint32 res;
1763 guchar *client_sign_key = NULL;
1764 guchar *server_sign_key = NULL;
1765 guchar *client_seal_key = NULL;
1766 guchar *server_seal_key = NULL;
1767 guchar *server_challenge = NULL;
1768 guint64 time_val = 0;
1769 guchar *target_info = NULL;
1770 int target_info_len = 0;
1771 guint32 flags;
1772 gchar *tmp;
1774 if (!in_buff.value || !in_buff.length) {
1775 return SIP_SEC_E_INTERNAL_ERROR;
1778 sip_sec_ntlm_parse_challenge(in_buff,
1779 &flags,
1780 &server_challenge, /* 8 bytes */
1781 &time_val,
1782 &target_info,
1783 &target_info_len);
1785 res = sip_sec_ntlm_gen_authenticate(
1786 &client_sign_key,
1787 &server_sign_key,
1788 &client_seal_key,
1789 &server_seal_key,
1790 ctx->username,
1791 ctx->password,
1792 (tmp = g_ascii_strup(sipe_get_host_name(), -1)),
1793 ctx->domain,
1794 server_challenge,
1795 time_val,
1796 target_info,
1797 target_info_len,
1798 context->is_connection_based,
1799 out_buff,
1800 &flags);
1801 g_free(server_challenge);
1802 g_free(target_info);
1803 g_free(tmp);
1805 if (res != SIP_SEC_E_OK) {
1806 g_free(client_sign_key);
1807 g_free(server_sign_key);
1808 g_free(client_seal_key);
1809 g_free(server_seal_key);
1810 return res;
1813 g_free(ctx->client_sign_key);
1814 ctx->client_sign_key = client_sign_key;
1816 g_free(ctx->server_sign_key);
1817 ctx->server_sign_key = server_sign_key;
1819 g_free(ctx->client_seal_key);
1820 ctx->client_seal_key = client_seal_key;
1822 g_free(ctx->server_seal_key);
1823 ctx->server_seal_key = server_seal_key;
1825 ctx->flags = flags;
1826 return SIP_SEC_E_OK;
1831 * @param message a NULL terminated string to sign
1834 static sip_uint32
1835 sip_sec_make_signature__ntlm(SipSecContext context,
1836 const char *message,
1837 SipSecBuffer *signature)
1839 signature->length = 16;
1840 signature->value = g_malloc0(16);
1842 /* FIXME? We always use a random_pad of 0 */
1843 sip_sec_ntlm_sipe_signature_make(((context_ntlm) context)->flags,
1844 message,
1846 ((context_ntlm) context)->client_sign_key,
1847 ((context_ntlm) context)->client_seal_key,
1848 signature->value);
1849 return SIP_SEC_E_OK;
1853 * @param message a NULL terminated string to check signature of
1854 * @return SIP_SEC_E_OK on success
1856 static sip_uint32
1857 sip_sec_verify_signature__ntlm(SipSecContext context,
1858 const char *message,
1859 SipSecBuffer signature)
1861 guint8 mac[16];
1862 guint32 random_pad = GUINT32_FROM_LE(((guint32 *) signature.value)[1]);
1864 sip_sec_ntlm_sipe_signature_make(((context_ntlm) context)->flags,
1865 message,
1866 random_pad,
1867 ((context_ntlm) context)->server_sign_key,
1868 ((context_ntlm) context)->server_seal_key,
1869 mac);
1870 return(memcmp(signature.value, mac, 16) ?
1871 SIP_SEC_E_INTERNAL_ERROR :
1872 SIP_SEC_E_OK);
1875 static void
1876 sip_sec_destroy_sec_context__ntlm(SipSecContext context)
1878 context_ntlm ctx = (context_ntlm) context;
1880 g_free(ctx->domain);
1881 g_free(ctx->username);
1882 g_free(ctx->password);
1883 g_free(ctx->client_sign_key);
1884 g_free(ctx->server_sign_key);
1885 g_free(ctx->client_seal_key);
1886 g_free(ctx->server_seal_key);
1887 g_free(ctx);
1890 SipSecContext
1891 sip_sec_create_context__ntlm(SIPE_UNUSED_PARAMETER SipSecAuthType type)
1893 context_ntlm context = g_malloc0(sizeof(struct _context_ntlm));
1894 if (!context) return(NULL);
1896 context->common.acquire_cred_func = sip_sec_acquire_cred__ntlm;
1897 context->common.init_context_func = sip_sec_init_sec_context__ntlm;
1898 context->common.destroy_context_func = sip_sec_destroy_sec_context__ntlm;
1899 context->common.make_signature_func = sip_sec_make_signature__ntlm;
1900 context->common.verify_signature_func = sip_sec_verify_signature__ntlm;
1902 return((SipSecContext) context);
1905 void sip_sec_init__ntlm(void)
1907 #ifdef HAVE_LANGINFO_CODESET
1908 const char *sys_cp = nl_langinfo(CODESET);
1909 #else
1910 const char *sys_cp = SIPE_DEFAULT_CODESET;
1911 #endif /* HAVE_LANGINFO_CODESET */
1913 /* fall back to utf-8 */
1914 if (!sys_cp) sys_cp = "UTF-8";
1916 convert_from_utf16le = g_iconv_open(sys_cp, "UTF-16LE");
1917 if (convert_from_utf16le == (GIConv)-1) {
1918 purple_debug_error("sipe", "g_iconv_open from UTF-16LE to %s failed\n",
1919 sys_cp);
1922 convert_to_utf16le = g_iconv_open("UTF-16LE", sys_cp);
1923 if (convert_from_utf16le == (GIConv)-1) {
1924 purple_debug_error("sipe", "g_iconv_open from %s to UTF-16LE failed\n",
1925 sys_cp);
1929 void sip_sec_destroy__ntlm(void)
1931 g_iconv_close(convert_to_utf16le);
1932 g_iconv_close(convert_from_utf16le);
1936 Local Variables:
1937 mode: c
1938 c-file-style: "bsd"
1939 indent-tabs-mode: t
1940 tab-width: 8
1941 End: