secur32: Downgrade WARN to TRACE, fix another TRACE.
[wine.git] / dlls / secur32 / ntlm.c
blob4c7f3b46228ed796333ad494095bd746d57757f5
1 /*
2 * Copyright 2005, 2006 Kai Blin
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
18 * This file implements the NTLM security provider.
21 #include <assert.h>
22 #include <stdarg.h>
23 #include <stdio.h>
24 #include "windef.h"
25 #include "winbase.h"
26 #include "winnls.h"
27 #include "rpc.h"
28 #include "sspi.h"
29 #include "lm.h"
30 #include "secur32_priv.h"
31 #include "hmac_md5.h"
32 #include "wine/debug.h"
34 WINE_DEFAULT_DEBUG_CHANNEL(ntlm);
36 #define NTLM_MAX_BUF 1904
37 #define MIN_NTLM_AUTH_MAJOR_VERSION 3
38 #define MIN_NTLM_AUTH_MINOR_VERSION 0
39 #define MIN_NTLM_AUTH_MICRO_VERSION 25
41 static CHAR ntlm_auth[] = "ntlm_auth";
43 /***********************************************************************
44 * QueryCredentialsAttributesA
46 static SECURITY_STATUS SEC_ENTRY ntlm_QueryCredentialsAttributesA(
47 PCredHandle phCredential, ULONG ulAttribute, PVOID pBuffer)
49 SECURITY_STATUS ret;
51 TRACE("(%p, %d, %p)\n", phCredential, ulAttribute, pBuffer);
53 if(ulAttribute == SECPKG_ATTR_NAMES)
55 FIXME("SECPKG_CRED_ATTR_NAMES: stub\n");
56 ret = SEC_E_UNSUPPORTED_FUNCTION;
58 else
59 ret = SEC_E_UNSUPPORTED_FUNCTION;
61 return ret;
64 /***********************************************************************
65 * QueryCredentialsAttributesW
67 static SECURITY_STATUS SEC_ENTRY ntlm_QueryCredentialsAttributesW(
68 PCredHandle phCredential, ULONG ulAttribute, PVOID pBuffer)
70 SECURITY_STATUS ret;
72 TRACE("(%p, %d, %p)\n", phCredential, ulAttribute, pBuffer);
74 if(ulAttribute == SECPKG_ATTR_NAMES)
76 FIXME("SECPKG_CRED_ATTR_NAMES: stub\n");
77 ret = SEC_E_UNSUPPORTED_FUNCTION;
79 else
80 ret = SEC_E_UNSUPPORTED_FUNCTION;
82 return ret;
85 /***********************************************************************
86 * AcquireCredentialsHandleW
88 static SECURITY_STATUS SEC_ENTRY ntlm_AcquireCredentialsHandleW(
89 SEC_WCHAR *pszPrincipal, SEC_WCHAR *pszPackage, ULONG fCredentialUse,
90 PLUID pLogonID, PVOID pAuthData, SEC_GET_KEY_FN pGetKeyFn,
91 PVOID pGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
93 SECURITY_STATUS ret;
94 PNegoHelper helper = NULL;
95 static CHAR server_helper_protocol[] = "--helper-protocol=squid-2.5-ntlmssp",
96 credentials_argv[] = "--use-cached-creds";
98 SEC_CHAR *client_user_arg = NULL;
99 SEC_CHAR *client_domain_arg = NULL;
100 SEC_WCHAR *username = NULL, *domain = NULL;
102 SEC_CHAR *client_argv[6];
103 SEC_CHAR *server_argv[] = { ntlm_auth,
104 server_helper_protocol,
105 NULL };
107 TRACE("(%s, %s, 0x%08x, %p, %p, %p, %p, %p, %p)\n",
108 debugstr_w(pszPrincipal), debugstr_w(pszPackage), fCredentialUse,
109 pLogonID, pAuthData, pGetKeyFn, pGetKeyArgument, phCredential, ptsExpiry);
112 switch(fCredentialUse)
114 case SECPKG_CRED_INBOUND:
115 if( (ret = fork_helper(&helper, ntlm_auth, server_argv)) !=
116 SEC_E_OK)
118 phCredential = NULL;
119 break;
121 else
123 helper->mode = NTLM_SERVER;
124 phCredential->dwUpper = fCredentialUse;
125 phCredential->dwLower = (ULONG_PTR)helper;
127 ret = SEC_E_OK;
128 break;
129 case SECPKG_CRED_OUTBOUND:
131 static const char username_arg[] = "--username=";
132 static const char domain_arg[] = "--domain=";
133 static char helper_protocol[] = "--helper-protocol=ntlmssp-client-1";
134 int unixcp_size;
136 if(pAuthData == NULL)
138 LPWKSTA_USER_INFO_1 ui = NULL;
139 NET_API_STATUS status;
141 status = NetWkstaUserGetInfo(NULL, 1, (LPBYTE *)&ui);
142 if (status != NERR_Success || ui == NULL)
144 ret = SEC_E_NO_CREDENTIALS;
145 phCredential = NULL;
146 break;
149 username = HeapAlloc(GetProcessHeap(), 0,
150 (lstrlenW(ui->wkui1_username)+1) *
151 sizeof(SEC_WCHAR));
152 lstrcpyW(username, ui->wkui1_username);
154 /* same for the domain */
155 domain = HeapAlloc(GetProcessHeap(), 0,
156 (lstrlenW(ui->wkui1_logon_domain)+1) *
157 sizeof(SEC_WCHAR));
158 lstrcpyW(domain, ui->wkui1_logon_domain);
159 NetApiBufferFree(ui);
161 else
163 PSEC_WINNT_AUTH_IDENTITY_W auth_data =
164 (PSEC_WINNT_AUTH_IDENTITY_W)pAuthData;
166 /* Get username and domain from pAuthData */
167 username = HeapAlloc(GetProcessHeap(), 0,
168 (auth_data->UserLength + 1) * sizeof(SEC_WCHAR));
169 memcpy(username, auth_data->User,
170 auth_data->UserLength * sizeof(SEC_WCHAR));
171 username[auth_data->UserLength] = '\0';
173 domain = HeapAlloc(GetProcessHeap(), 0,
174 (auth_data->DomainLength + 1) * sizeof(SEC_WCHAR));
175 memcpy(domain, auth_data->Domain,
176 auth_data->DomainLength * sizeof(SEC_WCHAR));
177 domain[auth_data->DomainLength] = '\0';
179 TRACE("Username is %s\n", debugstr_w(username));
180 unixcp_size = WideCharToMultiByte(CP_UNIXCP, WC_NO_BEST_FIT_CHARS,
181 username, -1, NULL, 0, NULL, NULL) + sizeof(username_arg);
182 client_user_arg = HeapAlloc(GetProcessHeap(), 0, unixcp_size);
183 lstrcpyA(client_user_arg, username_arg);
184 WideCharToMultiByte(CP_UNIXCP, WC_NO_BEST_FIT_CHARS, username, -1,
185 client_user_arg + sizeof(username_arg) - 1,
186 unixcp_size - sizeof(username_arg) + 1, NULL, NULL);
188 TRACE("Domain name is %s\n", debugstr_w(domain));
189 unixcp_size = WideCharToMultiByte(CP_UNIXCP, WC_NO_BEST_FIT_CHARS,
190 domain, -1, NULL, 0, NULL, NULL) + sizeof(domain_arg);
191 client_domain_arg = HeapAlloc(GetProcessHeap(), 0, unixcp_size);
192 lstrcpyA(client_domain_arg, domain_arg);
193 WideCharToMultiByte(CP_UNIXCP, WC_NO_BEST_FIT_CHARS, domain,
194 -1, client_domain_arg + sizeof(domain_arg) - 1,
195 unixcp_size - sizeof(domain) + 1, NULL, NULL);
197 client_argv[0] = ntlm_auth;
198 client_argv[1] = helper_protocol;
199 client_argv[2] = client_user_arg;
200 client_argv[3] = client_domain_arg;
201 client_argv[4] = credentials_argv;
202 client_argv[5] = NULL;
204 if((ret = fork_helper(&helper, ntlm_auth, client_argv)) !=
205 SEC_E_OK)
207 phCredential = NULL;
208 break;
210 else
212 helper->mode = NTLM_CLIENT;
214 if(pAuthData != NULL)
216 PSEC_WINNT_AUTH_IDENTITY_W auth_data =
217 (PSEC_WINNT_AUTH_IDENTITY_W)pAuthData;
219 if(auth_data->PasswordLength != 0)
221 helper->pwlen = WideCharToMultiByte(CP_UNIXCP,
222 WC_NO_BEST_FIT_CHARS, auth_data->Password,
223 auth_data->PasswordLength, NULL, 0, NULL,
224 NULL);
226 helper->password = HeapAlloc(GetProcessHeap(), 0,
227 helper->pwlen);
229 WideCharToMultiByte(CP_UNIXCP, WC_NO_BEST_FIT_CHARS,
230 auth_data->Password, auth_data->PasswordLength,
231 helper->password, helper->pwlen, NULL, NULL);
235 phCredential->dwUpper = fCredentialUse;
236 phCredential->dwLower = (ULONG_PTR)helper;
237 TRACE("ACH phCredential->dwUpper: 0x%08lx, dwLower: 0x%08lx\n",
238 phCredential->dwUpper, phCredential->dwLower);
240 ret = SEC_E_OK;
241 break;
243 case SECPKG_CRED_BOTH:
244 FIXME("AcquireCredentialsHandle: SECPKG_CRED_BOTH stub\n");
245 ret = SEC_E_UNSUPPORTED_FUNCTION;
246 phCredential = NULL;
247 break;
248 default:
249 phCredential = NULL;
250 ret = SEC_E_UNKNOWN_CREDENTIALS;
254 HeapFree(GetProcessHeap(), 0, client_user_arg);
255 HeapFree(GetProcessHeap(), 0, client_domain_arg);
256 HeapFree(GetProcessHeap(), 0, username);
257 HeapFree(GetProcessHeap(), 0, domain);
259 return ret;
262 /***********************************************************************
263 * AcquireCredentialsHandleA
265 static SECURITY_STATUS SEC_ENTRY ntlm_AcquireCredentialsHandleA(
266 SEC_CHAR *pszPrincipal, SEC_CHAR *pszPackage, ULONG fCredentialUse,
267 PLUID pLogonID, PVOID pAuthData, SEC_GET_KEY_FN pGetKeyFn,
268 PVOID pGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
270 SECURITY_STATUS ret;
271 int user_sizeW, domain_sizeW, passwd_sizeW;
273 SEC_WCHAR *user = NULL, *domain = NULL, *passwd = NULL, *package = NULL;
275 PSEC_WINNT_AUTH_IDENTITY_W pAuthDataW = NULL;
276 PSEC_WINNT_AUTH_IDENTITY_A identity = NULL;
278 TRACE("(%s, %s, 0x%08x, %p, %p, %p, %p, %p, %p)\n",
279 debugstr_a(pszPrincipal), debugstr_a(pszPackage), fCredentialUse,
280 pLogonID, pAuthData, pGetKeyFn, pGetKeyArgument, phCredential, ptsExpiry);
282 if(pszPackage != NULL)
284 int package_sizeW = MultiByteToWideChar(CP_ACP, 0, pszPackage, -1,
285 NULL, 0);
287 package = HeapAlloc(GetProcessHeap(), 0, package_sizeW *
288 sizeof(SEC_WCHAR));
289 MultiByteToWideChar(CP_ACP, 0, pszPackage, -1, package, package_sizeW);
293 if(pAuthData != NULL)
295 identity = (PSEC_WINNT_AUTH_IDENTITY_A)pAuthData;
297 if(identity->Flags == SEC_WINNT_AUTH_IDENTITY_ANSI)
299 pAuthDataW = HeapAlloc(GetProcessHeap(), 0,
300 sizeof(SEC_WINNT_AUTH_IDENTITY_W));
302 if(identity->UserLength != 0)
304 user_sizeW = MultiByteToWideChar(CP_ACP, 0,
305 (LPCSTR)identity->User, identity->UserLength, NULL, 0);
306 user = HeapAlloc(GetProcessHeap(), 0, user_sizeW *
307 sizeof(SEC_WCHAR));
308 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)identity->User,
309 identity->UserLength, user, user_sizeW);
311 else
313 user_sizeW = 0;
316 if(identity->DomainLength != 0)
318 domain_sizeW = MultiByteToWideChar(CP_ACP, 0,
319 (LPCSTR)identity->Domain, identity->DomainLength, NULL, 0);
320 domain = HeapAlloc(GetProcessHeap(), 0, domain_sizeW
321 * sizeof(SEC_WCHAR));
322 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)identity->Domain,
323 identity->DomainLength, domain, domain_sizeW);
325 else
327 domain_sizeW = 0;
330 if(identity->PasswordLength != 0)
332 passwd_sizeW = MultiByteToWideChar(CP_ACP, 0,
333 (LPCSTR)identity->Password, identity->PasswordLength,
334 NULL, 0);
335 passwd = HeapAlloc(GetProcessHeap(), 0, passwd_sizeW
336 * sizeof(SEC_WCHAR));
337 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)identity->Password,
338 identity->PasswordLength, passwd, passwd_sizeW);
340 else
342 passwd_sizeW = 0;
345 pAuthDataW->Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
346 pAuthDataW->User = user;
347 pAuthDataW->UserLength = user_sizeW;
348 pAuthDataW->Domain = domain;
349 pAuthDataW->DomainLength = domain_sizeW;
350 pAuthDataW->Password = passwd;
351 pAuthDataW->PasswordLength = passwd_sizeW;
353 else
355 pAuthDataW = (PSEC_WINNT_AUTH_IDENTITY_W)identity;
359 ret = ntlm_AcquireCredentialsHandleW(NULL, package, fCredentialUse,
360 pLogonID, pAuthDataW, pGetKeyFn, pGetKeyArgument, phCredential,
361 ptsExpiry);
363 HeapFree(GetProcessHeap(), 0, package);
364 HeapFree(GetProcessHeap(), 0, user);
365 HeapFree(GetProcessHeap(), 0, domain);
366 HeapFree(GetProcessHeap(), 0, passwd);
367 if(pAuthDataW != (PSEC_WINNT_AUTH_IDENTITY_W)identity)
368 HeapFree(GetProcessHeap(), 0, pAuthDataW);
370 return ret;
373 /*************************************************************************
374 * ntlm_GetTokenBufferIndex
375 * Calculates the index of the secbuffer with BufferType == SECBUFFER_TOKEN
376 * Returns index if found or -1 if not found.
378 static int ntlm_GetTokenBufferIndex(PSecBufferDesc pMessage)
380 UINT i;
382 TRACE("%p\n", pMessage);
384 for( i = 0; i < pMessage->cBuffers; ++i )
386 if(pMessage->pBuffers[i].BufferType == SECBUFFER_TOKEN)
387 return i;
390 return -1;
393 /***********************************************************************
394 * InitializeSecurityContextW
396 static SECURITY_STATUS SEC_ENTRY ntlm_InitializeSecurityContextW(
397 PCredHandle phCredential, PCtxtHandle phContext, SEC_WCHAR *pszTargetName,
398 ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep,
399 PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext,
400 PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
402 SECURITY_STATUS ret;
403 PNegoHelper helper;
404 ULONG ctxt_attr = 0;
405 char* buffer, *want_flags = NULL;
406 PBYTE bin;
407 int buffer_len, bin_len, max_len = NTLM_MAX_BUF;
408 int token_idx;
410 TRACE("%p %p %s %d %d %d %p %d %p %p %p %p\n", phCredential, phContext,
411 debugstr_w(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
412 Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
414 /****************************************
415 * When communicating with the client, there can be the
416 * following reply packets:
417 * YR <base64 blob> should be sent to the server
418 * PW should be sent back to helper with
419 * base64 encoded password
420 * AF <base64 blob> client is done, blob should be
421 * sent to server with KK prefixed
422 * GF <string list> A string list of negotiated flags
423 * GK <base64 blob> base64 encoded session key
424 * BH <char reason> something broke
426 /* The squid cache size is 2010 chars, and that's what ntlm_auth uses */
428 if (pszTargetName)
430 TRACE("According to a MS whitepaper pszTargetName is ignored.\n");
433 if(TargetDataRep == SECURITY_NETWORK_DREP){
434 TRACE("Setting SECURITY_NETWORK_DREP\n");
437 buffer = HeapAlloc(GetProcessHeap(), 0, sizeof(char) * NTLM_MAX_BUF);
438 bin = HeapAlloc(GetProcessHeap(), 0, sizeof(BYTE) * NTLM_MAX_BUF);
440 if((phContext == NULL) && (pInput == NULL))
442 TRACE("First time in ISC()\n");
444 if(!phCredential)
445 return SEC_E_INVALID_HANDLE;
447 /* As the server side of sspi never calls this, make sure that
448 * the handler is a client handler.
450 helper = (PNegoHelper)phCredential->dwLower;
451 if(helper->mode != NTLM_CLIENT)
453 TRACE("Helper mode = %d\n", helper->mode);
454 return SEC_E_INVALID_HANDLE;
457 /* Allocate space for a maximal string of
458 * "SF NTLMSSP_FEATURE_SIGN NTLMSSP_FEATURE_SEAL
459 * NTLMSSP_FEATURE_SESSION_KEY"
461 want_flags = HeapAlloc(GetProcessHeap(), 0, 73);
462 if(want_flags == NULL)
464 ret = SEC_E_INSUFFICIENT_MEMORY;
465 goto isc_end;
467 lstrcpyA(want_flags, "SF");
468 if(fContextReq & ISC_REQ_CONFIDENTIALITY)
470 char *ptr;
471 if((ptr = strstr(want_flags, "NTLMSSP_FEATURE_SEAL")) == NULL)
472 lstrcatA(want_flags, " NTLMSSP_FEATURE_SEAL");
474 if(fContextReq & ISC_REQ_CONNECTION)
475 ctxt_attr |= ISC_RET_CONNECTION;
476 if(fContextReq & ISC_REQ_EXTENDED_ERROR)
477 ctxt_attr |= ISC_RET_EXTENDED_ERROR;
478 if(fContextReq & ISC_REQ_INTEGRITY)
480 char *ptr;
481 if((ptr = strstr(want_flags, "NTLMSSP_FEATURE_SIGN")) == NULL)
482 lstrcatA(want_flags, " NTLMSSP_FEATURE_SIGN");
484 if(fContextReq & ISC_REQ_MUTUAL_AUTH)
485 ctxt_attr |= ISC_RET_MUTUAL_AUTH;
486 if(fContextReq & ISC_REQ_REPLAY_DETECT)
488 char *ptr;
489 if((ptr = strstr(want_flags, "NTLMSSP_FEATURE_SIGN")) == NULL)
490 lstrcatA(want_flags, " NTLMSSP_FEATURE_SIGN");
492 if(fContextReq & ISC_REQ_SEQUENCE_DETECT)
494 char *ptr;
495 if((ptr = strstr(want_flags, "NTLMSSP_FEATURE_SIGN")) == NULL)
496 lstrcatA(want_flags, " NTLMSSP_FEATURE_SIGN");
498 if(fContextReq & ISC_REQ_STREAM)
499 FIXME("ISC_REQ_STREAM\n");
500 if(fContextReq & ISC_REQ_USE_DCE_STYLE)
501 ctxt_attr |= ISC_RET_USED_DCE_STYLE;
502 if(fContextReq & ISC_REQ_DELEGATE)
503 ctxt_attr |= ISC_RET_DELEGATE;
505 /* If no password is given, try to use cached credentials. Fall back to an empty
506 * password if this failed. */
507 if(helper->password == NULL)
509 lstrcpynA(buffer, "OK", max_len-1);
510 if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
511 goto isc_end;
512 /* If the helper replied with "PW", using cached credentials failed */
513 if(!strncmp(buffer, "PW", 2))
515 TRACE("Using cached credentials failed. Using empty password.\n");
516 lstrcpynA(buffer, "PW AA==", max_len-1);
518 else /* Just do a noop on the next run */
519 lstrcpynA(buffer, "OK", max_len-1);
521 else
523 lstrcpynA(buffer, "PW ", max_len-1);
524 if((ret = encodeBase64((unsigned char*)helper->password,
525 helper->pwlen, buffer+3,
526 max_len-3, &buffer_len)) != SEC_E_OK)
528 TRACE("Deleting password!\n");
529 memset(helper->password, 0, helper->pwlen);
530 HeapFree(GetProcessHeap(), 0, helper->password);
531 goto isc_end;
536 TRACE("Sending to helper: %s\n", debugstr_a(buffer));
537 if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
538 goto isc_end;
540 TRACE("Helper returned %s\n", debugstr_a(buffer));
542 if(lstrlenA(want_flags) > 2)
544 TRACE("Want flags are %s\n", debugstr_a(want_flags));
545 lstrcpynA(buffer, want_flags, max_len-1);
546 if((ret = run_helper(helper, buffer, max_len, &buffer_len))
547 != SEC_E_OK)
548 goto isc_end;
549 if(!strncmp(buffer, "BH", 2))
550 ERR("Helper doesn't understand new command set. Expect more things to fail.\n");
553 lstrcpynA(buffer, "YR", max_len-1);
555 if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
556 goto isc_end;
558 TRACE("%s\n", buffer);
560 if(strncmp(buffer, "YR ", 3) != 0)
562 /* Something borked */
563 TRACE("Helper returned %c%c\n", buffer[0], buffer[1]);
564 ret = SEC_E_INTERNAL_ERROR;
565 goto isc_end;
567 if((ret = decodeBase64(buffer+3, buffer_len-3, bin,
568 max_len-1, &bin_len)) != SEC_E_OK)
569 goto isc_end;
571 /* put the decoded client blob into the out buffer */
573 phNewContext->dwUpper = ctxt_attr;
574 phNewContext->dwLower = (ULONG_PTR)helper;
576 ret = SEC_I_CONTINUE_NEEDED;
578 else
580 int input_token_idx;
582 /* handle second call here */
583 /* encode server data to base64 */
584 if (!pInput || ((input_token_idx = ntlm_GetTokenBufferIndex(pInput)) == -1))
586 ret = SEC_E_INVALID_TOKEN;
587 goto isc_end;
590 if(!phContext)
591 return SEC_E_INVALID_HANDLE;
593 /* As the server side of sspi never calls this, make sure that
594 * the handler is a client handler.
596 helper = (PNegoHelper)phContext->dwLower;
597 if(helper->mode != NTLM_CLIENT)
599 TRACE("Helper mode = %d\n", helper->mode);
600 return SEC_E_INVALID_HANDLE;
603 if (!pInput->pBuffers[input_token_idx].pvBuffer)
605 ret = SEC_E_INTERNAL_ERROR;
606 goto isc_end;
609 if(pInput->pBuffers[input_token_idx].cbBuffer > max_len)
611 TRACE("pInput->pBuffers[%d].cbBuffer is: %ld\n",
612 input_token_idx,
613 pInput->pBuffers[input_token_idx].cbBuffer);
614 ret = SEC_E_INVALID_TOKEN;
615 goto isc_end;
617 else
618 bin_len = pInput->pBuffers[input_token_idx].cbBuffer;
620 memcpy(bin, pInput->pBuffers[input_token_idx].pvBuffer, bin_len);
622 lstrcpynA(buffer, "TT ", max_len-1);
624 if((ret = encodeBase64(bin, bin_len, buffer+3,
625 max_len-3, &buffer_len)) != SEC_E_OK)
626 goto isc_end;
628 TRACE("Server sent: %s\n", debugstr_a(buffer));
630 /* send TT base64 blob to ntlm_auth */
631 if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
632 goto isc_end;
634 TRACE("Helper replied: %s\n", debugstr_a(buffer));
636 if( (strncmp(buffer, "KK ", 3) != 0) &&
637 (strncmp(buffer, "AF ", 3) !=0))
639 TRACE("Helper returned %c%c\n", buffer[0], buffer[1]);
640 ret = SEC_E_INVALID_TOKEN;
641 goto isc_end;
644 /* decode the blob and send it to server */
645 if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len,
646 &bin_len)) != SEC_E_OK)
648 goto isc_end;
651 phNewContext->dwUpper = ctxt_attr;
652 phNewContext->dwLower = (ULONG_PTR)helper;
654 ret = SEC_E_OK;
657 /* put the decoded client blob into the out buffer */
659 if (!pOutput || ((token_idx = ntlm_GetTokenBufferIndex(pOutput)) == -1))
661 TRACE("no SECBUFFER_TOKEN buffer could be found\n");
662 ret = SEC_E_BUFFER_TOO_SMALL;
663 goto isc_end;
666 if (fContextReq & ISC_REQ_ALLOCATE_MEMORY)
668 pOutput->pBuffers[token_idx].pvBuffer = SECUR32_ALLOC(bin_len);
669 pOutput->pBuffers[token_idx].cbBuffer = bin_len;
671 else if (pOutput->pBuffers[token_idx].cbBuffer < bin_len)
673 TRACE("out buffer is NULL or has not enough space\n");
674 ret = SEC_E_BUFFER_TOO_SMALL;
675 goto isc_end;
678 if (!pOutput->pBuffers[token_idx].pvBuffer)
680 TRACE("out buffer is NULL\n");
681 ret = SEC_E_INTERNAL_ERROR;
682 goto isc_end;
685 pOutput->pBuffers[token_idx].cbBuffer = bin_len;
686 memcpy(pOutput->pBuffers[token_idx].pvBuffer, bin, bin_len);
688 if(ret == SEC_E_OK)
690 TRACE("Getting negotiated flags\n");
691 lstrcpynA(buffer, "GF", max_len - 1);
692 if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
693 goto isc_end;
695 if(buffer_len < 3)
697 TRACE("No flags negotiated.\n");
698 helper->neg_flags = 0l;
700 else
702 TRACE("Negotiated %s\n", debugstr_a(buffer));
703 sscanf(buffer + 3, "%lx", &(helper->neg_flags));
704 TRACE("Stored 0x%08lx as flags\n", helper->neg_flags);
707 TRACE("Getting session key\n");
708 lstrcpynA(buffer, "GK", max_len - 1);
709 if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
710 goto isc_end;
712 if(strncmp(buffer, "BH", 2) == 0)
714 TRACE("No key negotiated.\n");
715 helper->valid_session_key = FALSE;
716 helper->session_key = HeapAlloc(GetProcessHeap(), 0, 16);
717 /*Generate the dummy session key = MD4(MD4(password))*/
718 if(helper->password)
720 SEC_WCHAR *unicode_password;
721 int passwd_lenW;
723 TRACE("Converting password to unicode.\n");
724 passwd_lenW = MultiByteToWideChar(CP_ACP, 0,
725 (LPCSTR)helper->password, helper->pwlen,
726 NULL, 0);
727 unicode_password = HeapAlloc(GetProcessHeap(), 0,
728 passwd_lenW * sizeof(SEC_WCHAR));
729 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)helper->password,
730 helper->pwlen, unicode_password, passwd_lenW);
732 SECUR32_CreateNTLMv1SessionKey((PBYTE)unicode_password,
733 passwd_lenW * sizeof(SEC_WCHAR), helper->session_key);
735 HeapFree(GetProcessHeap(), 0, unicode_password);
737 else
738 memset(helper->session_key, 0, 16);
740 else if(strncmp(buffer, "GK ", 3) == 0)
742 if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len,
743 &bin_len)) != SEC_E_OK)
745 TRACE("Failed to decode session key\n");
747 TRACE("Session key is %s\n", debugstr_a(buffer+3));
748 helper->valid_session_key = TRUE;
749 helper->session_key = HeapAlloc(GetProcessHeap(), 0, bin_len);
750 if(!helper->session_key)
752 TRACE("Failed to allocate memory for session key\n");
753 ret = SEC_E_INTERNAL_ERROR;
754 goto isc_end;
756 memcpy(helper->session_key, bin, bin_len);
759 helper->crypt.ntlm.a4i = SECUR32_arc4Alloc();
760 SECUR32_arc4Init(helper->crypt.ntlm.a4i, helper->session_key, 16);
761 helper->crypt.ntlm.seq_num = 0l;
762 SECUR32_CreateNTLMv2SubKeys(helper);
763 helper->crypt.ntlm2.send_a4i = SECUR32_arc4Alloc();
764 helper->crypt.ntlm2.recv_a4i = SECUR32_arc4Alloc();
765 SECUR32_arc4Init(helper->crypt.ntlm2.send_a4i,
766 (BYTE *)helper->crypt.ntlm2.send_seal_key, 16);
767 SECUR32_arc4Init(helper->crypt.ntlm2.recv_a4i,
768 (BYTE *)helper->crypt.ntlm2.recv_seal_key, 16);
769 helper->crypt.ntlm2.send_seq_no = 0l;
770 helper->crypt.ntlm2.recv_seq_no = 0l;
773 if(ret != SEC_I_CONTINUE_NEEDED)
775 TRACE("Deleting password!\n");
776 if(helper->password)
777 memset(helper->password, 0, helper->pwlen);
778 HeapFree(GetProcessHeap(), 0, helper->password);
780 isc_end:
781 HeapFree(GetProcessHeap(), 0, want_flags);
782 HeapFree(GetProcessHeap(), 0, buffer);
783 HeapFree(GetProcessHeap(), 0, bin);
784 return ret;
787 /***********************************************************************
788 * InitializeSecurityContextA
790 static SECURITY_STATUS SEC_ENTRY ntlm_InitializeSecurityContextA(
791 PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR *pszTargetName,
792 ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep,
793 PSecBufferDesc pInput,ULONG Reserved2, PCtxtHandle phNewContext,
794 PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
796 SECURITY_STATUS ret;
797 SEC_WCHAR *target = NULL;
799 TRACE("%p %p %s %d %d %d %p %d %p %p %p %p\n", phCredential, phContext,
800 debugstr_a(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
801 Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
803 if(pszTargetName != NULL)
805 int target_size = MultiByteToWideChar(CP_ACP, 0, pszTargetName,
806 strlen(pszTargetName)+1, NULL, 0);
807 target = HeapAlloc(GetProcessHeap(), 0, target_size *
808 sizeof(SEC_WCHAR));
809 MultiByteToWideChar(CP_ACP, 0, pszTargetName, strlen(pszTargetName)+1,
810 target, target_size);
813 ret = ntlm_InitializeSecurityContextW(phCredential, phContext, target,
814 fContextReq, Reserved1, TargetDataRep, pInput, Reserved2,
815 phNewContext, pOutput, pfContextAttr, ptsExpiry);
817 HeapFree(GetProcessHeap(), 0, target);
818 return ret;
821 /***********************************************************************
822 * AcceptSecurityContext
824 static SECURITY_STATUS SEC_ENTRY ntlm_AcceptSecurityContext(
825 PCredHandle phCredential, PCtxtHandle phContext, PSecBufferDesc pInput,
826 ULONG fContextReq, ULONG TargetDataRep, PCtxtHandle phNewContext,
827 PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
829 SECURITY_STATUS ret;
830 char *buffer, *want_flags = NULL;
831 PBYTE bin;
832 int buffer_len, bin_len, max_len = NTLM_MAX_BUF;
833 ULONG ctxt_attr = 0;
834 PNegoHelper helper;
836 TRACE("%p %p %p %d %d %p %p %p %p\n", phCredential, phContext, pInput,
837 fContextReq, TargetDataRep, phNewContext, pOutput, pfContextAttr,
838 ptsExpiry);
840 if (!phCredential)
841 return SEC_E_INVALID_HANDLE;
843 helper = (PNegoHelper)phCredential->dwLower;
845 buffer = HeapAlloc(GetProcessHeap(), 0, sizeof(char) * NTLM_MAX_BUF);
846 bin = HeapAlloc(GetProcessHeap(),0, sizeof(BYTE) * NTLM_MAX_BUF);
848 if(helper->mode != NTLM_SERVER)
850 ret = SEC_E_INVALID_HANDLE;
851 goto asc_end;
854 if(TargetDataRep == SECURITY_NETWORK_DREP){
855 TRACE("Using SECURITY_NETWORK_DREP\n");
858 if(phContext == NULL)
860 /* This is the first call to AcceptSecurityHandle */
861 if(pInput == NULL)
863 ret = SEC_E_INCOMPLETE_MESSAGE;
864 goto asc_end;
867 if(pInput->cBuffers < 1)
869 ret = SEC_E_INCOMPLETE_MESSAGE;
870 goto asc_end;
873 if(pInput->pBuffers[0].cbBuffer > max_len)
875 ret = SEC_E_INVALID_TOKEN;
876 goto asc_end;
878 else
879 bin_len = pInput->pBuffers[0].cbBuffer;
881 /* Handle all the flags */
882 want_flags = HeapAlloc(GetProcessHeap(), 0, 73);
883 if(want_flags == NULL)
885 TRACE("Failed to allocate memory for the want_flags!\n");
886 ret = SEC_E_INSUFFICIENT_MEMORY;
887 goto asc_end;
889 lstrcpyA(want_flags, "SF");
890 if(fContextReq & ASC_REQ_ALLOCATE_MEMORY)
892 FIXME("ASC_REQ_ALLOCATE_MEMORY stub\n");
894 if(fContextReq & ASC_REQ_CONFIDENTIALITY)
896 lstrcatA(want_flags, " NTLMSSP_FEATURE_SEAL");
898 if(fContextReq & ASC_REQ_CONNECTION)
900 /* This is default, so we'll enable it */
901 lstrcatA(want_flags, " NTLMSSP_FEATURE_SESSION_KEY");
902 ctxt_attr |= ASC_RET_CONNECTION;
904 if(fContextReq & ASC_REQ_EXTENDED_ERROR)
906 FIXME("ASC_REQ_EXTENDED_ERROR stub\n");
908 if(fContextReq & ASC_REQ_INTEGRITY)
910 lstrcatA(want_flags, " NTLMSSP_FEATURE_SIGN");
912 if(fContextReq & ASC_REQ_MUTUAL_AUTH)
914 FIXME("ASC_REQ_MUTUAL_AUTH stub\n");
916 if(fContextReq & ASC_REQ_REPLAY_DETECT)
918 FIXME("ASC_REQ_REPLAY_DETECT stub\n");
920 if(fContextReq & ISC_REQ_SEQUENCE_DETECT)
922 FIXME("ASC_REQ_SEQUENCE_DETECT stub\n");
924 if(fContextReq & ISC_REQ_STREAM)
926 FIXME("ASC_REQ_STREAM stub\n");
928 /* Done with the flags */
930 if(lstrlenA(want_flags) > 3)
932 TRACE("Server set want_flags: %s\n", debugstr_a(want_flags));
933 lstrcpynA(buffer, want_flags, max_len - 1);
934 if((ret = run_helper(helper, buffer, max_len, &buffer_len)) !=
935 SEC_E_OK)
936 goto asc_end;
937 if(!strncmp(buffer, "BH", 2))
938 TRACE("Helper doesn't understand new command set\n");
941 /* This is the YR request from the client, encode to base64 */
943 memcpy(bin, pInput->pBuffers[0].pvBuffer, bin_len);
945 lstrcpynA(buffer, "YR ", max_len-1);
947 if((ret = encodeBase64(bin, bin_len, buffer+3, max_len-3,
948 &buffer_len)) != SEC_E_OK)
950 goto asc_end;
953 TRACE("Client sent: %s\n", debugstr_a(buffer));
955 if((ret = run_helper(helper, buffer, max_len, &buffer_len)) !=
956 SEC_E_OK)
958 goto asc_end;
961 TRACE("Reply from ntlm_auth: %s\n", debugstr_a(buffer));
962 /* The expected answer is TT <base64 blob> */
964 if(strncmp(buffer, "TT ", 3) != 0)
966 ret = SEC_E_INTERNAL_ERROR;
967 goto asc_end;
970 if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len,
971 &bin_len)) != SEC_E_OK)
973 goto asc_end;
976 /* send this to the client */
977 if(pOutput == NULL)
979 ret = SEC_E_INSUFFICIENT_MEMORY;
980 goto asc_end;
983 if(pOutput->cBuffers < 1)
985 ret = SEC_E_INSUFFICIENT_MEMORY;
986 goto asc_end;
989 pOutput->pBuffers[0].cbBuffer = bin_len;
990 pOutput->pBuffers[0].BufferType = SECBUFFER_DATA;
991 memcpy(pOutput->pBuffers[0].pvBuffer, bin, bin_len);
992 ret = SEC_I_CONTINUE_NEEDED;
995 else
997 /* we expect a KK request from client */
998 if(pInput == NULL)
1000 ret = SEC_E_INCOMPLETE_MESSAGE;
1001 goto asc_end;
1004 if(pInput->cBuffers < 1)
1006 ret = SEC_E_INCOMPLETE_MESSAGE;
1007 goto asc_end;
1010 if(pInput->pBuffers[0].cbBuffer > max_len)
1012 ret = SEC_E_INVALID_TOKEN;
1013 goto asc_end;
1015 else
1016 bin_len = pInput->pBuffers[0].cbBuffer;
1018 memcpy(bin, pInput->pBuffers[0].pvBuffer, bin_len);
1020 lstrcpynA(buffer, "KK ", max_len-1);
1022 if((ret = encodeBase64(bin, bin_len, buffer+3, max_len-3,
1023 &buffer_len)) != SEC_E_OK)
1025 goto asc_end;
1028 TRACE("Client sent: %s\n", debugstr_a(buffer));
1030 if((ret = run_helper(helper, buffer, max_len, &buffer_len)) !=
1031 SEC_E_OK)
1033 goto asc_end;
1036 TRACE("Reply from ntlm_auth: %s\n", debugstr_a(buffer));
1038 if(strncmp(buffer, "AF ", 3) != 0)
1040 if(strncmp(buffer, "NA ", 3) == 0)
1042 ret = SEC_E_LOGON_DENIED;
1043 goto asc_end;
1045 else
1047 ret = SEC_E_INTERNAL_ERROR;
1048 goto asc_end;
1051 pOutput->pBuffers[0].cbBuffer = 0;
1052 ret = SEC_E_OK;
1054 TRACE("Getting negotiated flags\n");
1055 lstrcpynA(buffer, "GF", max_len - 1);
1056 if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
1057 goto asc_end;
1059 if(buffer_len < 3)
1061 TRACE("No flags negotiated, or helper does not support GF command\n");
1063 else
1065 TRACE("Negotiated %s\n", debugstr_a(buffer));
1066 sscanf(buffer + 3, "%lx", &(helper->neg_flags));
1067 TRACE("Stored 0x%08lx as flags\n", helper->neg_flags);
1070 TRACE("Getting session key\n");
1071 lstrcpynA(buffer, "GK", max_len - 1);
1072 if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
1073 goto asc_end;
1075 if(buffer_len < 3)
1076 TRACE("Helper does not support GK command\n");
1077 else
1079 if(strncmp(buffer, "BH ", 3) == 0)
1081 TRACE("Helper sent %s\n", debugstr_a(buffer+3));
1082 helper->valid_session_key = FALSE;
1083 helper->session_key = HeapAlloc(GetProcessHeap(), 0, 16);
1084 /*FIXME: Generate the dummy session key = MD4(MD4(password))*/
1085 memset(helper->session_key, 0 , 16);
1087 else if(strncmp(buffer, "GK ", 3) == 0)
1089 if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len,
1090 &bin_len)) != SEC_E_OK)
1092 TRACE("Failed to decode session key\n");
1094 TRACE("Session key is %s\n", debugstr_a(buffer+3));
1095 helper->valid_session_key = TRUE;
1096 helper->session_key = HeapAlloc(GetProcessHeap(), 0, 16);
1097 if(!helper->session_key)
1099 TRACE("Failed to allocate memory for session key\n");
1100 ret = SEC_E_INTERNAL_ERROR;
1101 goto asc_end;
1103 memcpy(helper->session_key, bin, 16);
1106 helper->crypt.ntlm.a4i = SECUR32_arc4Alloc();
1107 SECUR32_arc4Init(helper->crypt.ntlm.a4i, helper->session_key, 16);
1108 helper->crypt.ntlm.seq_num = 0l;
1111 phNewContext->dwUpper = ctxt_attr;
1112 phNewContext->dwLower = (ULONG_PTR)helper;
1114 asc_end:
1115 HeapFree(GetProcessHeap(), 0, want_flags);
1116 HeapFree(GetProcessHeap(), 0, buffer);
1117 HeapFree(GetProcessHeap(), 0, bin);
1118 return ret;
1121 /***********************************************************************
1122 * CompleteAuthToken
1124 static SECURITY_STATUS SEC_ENTRY ntlm_CompleteAuthToken(PCtxtHandle phContext,
1125 PSecBufferDesc pToken)
1127 /* We never need to call CompleteAuthToken anyway */
1128 TRACE("%p %p\n", phContext, pToken);
1129 if (!phContext)
1130 return SEC_E_INVALID_HANDLE;
1132 return SEC_E_OK;
1135 /***********************************************************************
1136 * DeleteSecurityContext
1138 static SECURITY_STATUS SEC_ENTRY ntlm_DeleteSecurityContext(PCtxtHandle phContext)
1140 PNegoHelper helper;
1142 TRACE("%p\n", phContext);
1143 if (!phContext)
1144 return SEC_E_INVALID_HANDLE;
1146 helper = (PNegoHelper)phContext->dwLower;
1148 phContext->dwUpper = 0;
1149 phContext->dwLower = 0;
1151 SECUR32_arc4Cleanup(helper->crypt.ntlm.a4i);
1152 HeapFree(GetProcessHeap(), 0, helper->session_key);
1153 helper->valid_session_key = FALSE;
1154 SECUR32_arc4Cleanup(helper->crypt.ntlm2.send_a4i);
1155 SECUR32_arc4Cleanup(helper->crypt.ntlm2.recv_a4i);
1156 HeapFree(GetProcessHeap(), 0, helper->crypt.ntlm2.send_sign_key);
1157 HeapFree(GetProcessHeap(), 0, helper->crypt.ntlm2.send_seal_key);
1158 HeapFree(GetProcessHeap(), 0, helper->crypt.ntlm2.recv_sign_key);
1159 HeapFree(GetProcessHeap(), 0, helper->crypt.ntlm2.recv_seal_key);
1161 return SEC_E_OK;
1164 /***********************************************************************
1165 * QueryContextAttributesW
1167 static SECURITY_STATUS SEC_ENTRY ntlm_QueryContextAttributesW(PCtxtHandle phContext,
1168 ULONG ulAttribute, void *pBuffer)
1170 TRACE("%p %d %p\n", phContext, ulAttribute, pBuffer);
1171 if (!phContext)
1172 return SEC_E_INVALID_HANDLE;
1174 switch(ulAttribute)
1176 #define _x(x) case (x) : FIXME(#x" stub\n"); break
1177 _x(SECPKG_ATTR_ACCESS_TOKEN);
1178 _x(SECPKG_ATTR_AUTHORITY);
1179 _x(SECPKG_ATTR_DCE_INFO);
1180 case SECPKG_ATTR_FLAGS:
1182 PSecPkgContext_Flags spcf = (PSecPkgContext_Flags)pBuffer;
1183 PNegoHelper helper = (PNegoHelper)phContext->dwLower;
1185 spcf->Flags = 0;
1186 if(helper->neg_flags & NTLMSSP_NEGOTIATE_SIGN)
1187 spcf->Flags |= ISC_RET_INTEGRITY;
1188 if(helper->neg_flags & NTLMSSP_NEGOTIATE_SEAL)
1189 spcf->Flags |= ISC_RET_CONFIDENTIALITY;
1190 return SEC_E_OK;
1192 _x(SECPKG_ATTR_KEY_INFO);
1193 _x(SECPKG_ATTR_LIFESPAN);
1194 _x(SECPKG_ATTR_NAMES);
1195 _x(SECPKG_ATTR_NATIVE_NAMES);
1196 _x(SECPKG_ATTR_NEGOTIATION_INFO);
1197 _x(SECPKG_ATTR_PACKAGE_INFO);
1198 _x(SECPKG_ATTR_PASSWORD_EXPIRY);
1199 _x(SECPKG_ATTR_SESSION_KEY);
1200 case SECPKG_ATTR_SIZES:
1202 PSecPkgContext_Sizes spcs = (PSecPkgContext_Sizes)pBuffer;
1203 spcs->cbMaxToken = NTLM_MAX_BUF;
1204 spcs->cbMaxSignature = 16;
1205 spcs->cbBlockSize = 0;
1206 spcs->cbSecurityTrailer = 16;
1207 return SEC_E_OK;
1209 _x(SECPKG_ATTR_STREAM_SIZES);
1210 _x(SECPKG_ATTR_TARGET_INFORMATION);
1211 #undef _x
1212 default:
1213 TRACE("Unknown value %d passed for ulAttribute\n", ulAttribute);
1216 return SEC_E_UNSUPPORTED_FUNCTION;
1219 /***********************************************************************
1220 * QueryContextAttributesA
1222 static SECURITY_STATUS SEC_ENTRY ntlm_QueryContextAttributesA(PCtxtHandle phContext,
1223 ULONG ulAttribute, void *pBuffer)
1225 return ntlm_QueryContextAttributesW(phContext, ulAttribute, pBuffer);
1228 /***********************************************************************
1229 * ImpersonateSecurityContext
1231 static SECURITY_STATUS SEC_ENTRY ntlm_ImpersonateSecurityContext(PCtxtHandle phContext)
1233 SECURITY_STATUS ret;
1235 TRACE("%p\n", phContext);
1236 if (phContext)
1238 ret = SEC_E_UNSUPPORTED_FUNCTION;
1240 else
1242 ret = SEC_E_INVALID_HANDLE;
1244 return ret;
1247 /***********************************************************************
1248 * RevertSecurityContext
1250 static SECURITY_STATUS SEC_ENTRY ntlm_RevertSecurityContext(PCtxtHandle phContext)
1252 SECURITY_STATUS ret;
1254 TRACE("%p\n", phContext);
1255 if (phContext)
1257 ret = SEC_E_UNSUPPORTED_FUNCTION;
1259 else
1261 ret = SEC_E_INVALID_HANDLE;
1263 return ret;
1266 /***********************************************************************
1267 * ntlm_CreateSignature
1268 * As both MakeSignature and VerifySignature need this, but different keys
1269 * are needed for NTLMv2, the logic goes into a helper function.
1270 * To ensure maximal reusability, we can specify the direction as NTLM_SEND for
1271 * signing/encrypting and NTLM_RECV for verfying/decrypting. When encrypting,
1272 * the signature is encrypted after the message was encrypted, so
1273 * CreateSignature shouldn't do it. In this case, encrypt_sig can be set to
1274 * false.
1276 static SECURITY_STATUS ntlm_CreateSignature(PNegoHelper helper, PSecBufferDesc pMessage,
1277 int token_idx, SignDirection direction, BOOL encrypt_sig)
1279 ULONG sign_version = 1;
1280 UINT i;
1281 PBYTE sig;
1282 TRACE("%p, %p, %d, %d, %d\n", helper, pMessage, token_idx, direction,
1283 encrypt_sig);
1285 sig = pMessage->pBuffers[token_idx].pvBuffer;
1287 if(helper->neg_flags & NTLMSSP_NEGOTIATE_NTLM2 &&
1288 helper->neg_flags & NTLMSSP_NEGOTIATE_SIGN)
1290 BYTE digest[16];
1291 BYTE seq_no[4];
1292 HMAC_MD5_CTX hmac_md5_ctx;
1294 TRACE("Signing NTLM2 style\n");
1296 if(direction == NTLM_SEND)
1298 seq_no[0] = (helper->crypt.ntlm2.send_seq_no >> 0) & 0xff;
1299 seq_no[1] = (helper->crypt.ntlm2.send_seq_no >> 8) & 0xff;
1300 seq_no[2] = (helper->crypt.ntlm2.send_seq_no >> 16) & 0xff;
1301 seq_no[3] = (helper->crypt.ntlm2.send_seq_no >> 24) & 0xff;
1303 ++(helper->crypt.ntlm2.send_seq_no);
1305 HMACMD5Init(&hmac_md5_ctx, helper->crypt.ntlm2.send_sign_key, 16);
1307 else
1309 seq_no[0] = (helper->crypt.ntlm2.recv_seq_no >> 0) & 0xff;
1310 seq_no[1] = (helper->crypt.ntlm2.recv_seq_no >> 8) & 0xff;
1311 seq_no[2] = (helper->crypt.ntlm2.recv_seq_no >> 16) & 0xff;
1312 seq_no[3] = (helper->crypt.ntlm2.recv_seq_no >> 24) & 0xff;
1314 ++(helper->crypt.ntlm2.recv_seq_no);
1316 HMACMD5Init(&hmac_md5_ctx, helper->crypt.ntlm2.recv_sign_key, 16);
1319 HMACMD5Update(&hmac_md5_ctx, seq_no, 4);
1320 for( i = 0; i < pMessage->cBuffers; ++i )
1322 if(pMessage->pBuffers[i].BufferType & SECBUFFER_DATA)
1323 HMACMD5Update(&hmac_md5_ctx, (BYTE *)pMessage->pBuffers[i].pvBuffer,
1324 pMessage->pBuffers[i].cbBuffer);
1327 HMACMD5Final(&hmac_md5_ctx, digest);
1329 if(encrypt_sig && helper->neg_flags & NTLMSSP_NEGOTIATE_KEY_EXCHANGE)
1331 if(direction == NTLM_SEND)
1332 SECUR32_arc4Process(helper->crypt.ntlm2.send_a4i, digest, 8);
1333 else
1334 SECUR32_arc4Process(helper->crypt.ntlm2.recv_a4i, digest, 8);
1337 /* The NTLM2 signature is the sign version */
1338 sig[ 0] = (sign_version >> 0) & 0xff;
1339 sig[ 1] = (sign_version >> 8) & 0xff;
1340 sig[ 2] = (sign_version >> 16) & 0xff;
1341 sig[ 3] = (sign_version >> 24) & 0xff;
1342 /* The first 8 bytes of the digest */
1343 memcpy(sig+4, digest, 8);
1344 /* And the sequence number */
1345 memcpy(sig+12, seq_no, 4);
1347 pMessage->pBuffers[token_idx].cbBuffer = 16;
1349 return SEC_E_OK;
1351 if(helper->neg_flags & NTLMSSP_NEGOTIATE_SIGN)
1353 ULONG crc = 0U;
1354 TRACE("Signing NTLM1 style\n");
1356 for(i=0; i < pMessage->cBuffers; ++i)
1358 if(pMessage->pBuffers[i].BufferType & SECBUFFER_DATA)
1360 crc = ComputeCrc32(pMessage->pBuffers[i].pvBuffer,
1361 pMessage->pBuffers[i].cbBuffer, crc);
1365 sig[ 0] = (sign_version >> 0) & 0xff;
1366 sig[ 1] = (sign_version >> 8) & 0xff;
1367 sig[ 2] = (sign_version >> 16) & 0xff;
1368 sig[ 3] = (sign_version >> 24) & 0xff;
1369 memset(sig+4, 0, 4);
1370 sig[ 8] = (crc >> 0) & 0xff;
1371 sig[ 9] = (crc >> 8) & 0xff;
1372 sig[10] = (crc >> 16) & 0xff;
1373 sig[11] = (crc >> 24) & 0xff;
1374 sig[12] = (helper->crypt.ntlm.seq_num >> 0) & 0xff;
1375 sig[13] = (helper->crypt.ntlm.seq_num >> 8) & 0xff;
1376 sig[14] = (helper->crypt.ntlm.seq_num >> 16) & 0xff;
1377 sig[15] = (helper->crypt.ntlm.seq_num >> 24) & 0xff;
1379 ++(helper->crypt.ntlm.seq_num);
1381 if(encrypt_sig)
1382 SECUR32_arc4Process(helper->crypt.ntlm.a4i, sig+4, 12);
1383 return SEC_E_OK;
1386 if(helper->neg_flags & NTLMSSP_NEGOTIATE_ALWAYS_SIGN || helper->neg_flags == 0)
1388 TRACE("Creating a dummy signature.\n");
1389 /* A dummy signature is 0x01 followed by 15 bytes of 0x00 */
1390 memset(pMessage->pBuffers[token_idx].pvBuffer, 0, 16);
1391 memset(pMessage->pBuffers[token_idx].pvBuffer, 0x01, 1);
1392 pMessage->pBuffers[token_idx].cbBuffer = 16;
1393 return SEC_E_OK;
1396 return SEC_E_UNSUPPORTED_FUNCTION;
1399 /***********************************************************************
1400 * MakeSignature
1402 static SECURITY_STATUS SEC_ENTRY ntlm_MakeSignature(PCtxtHandle phContext, ULONG fQOP,
1403 PSecBufferDesc pMessage, ULONG MessageSeqNo)
1405 PNegoHelper helper;
1406 int token_idx;
1408 TRACE("%p %d %p %d\n", phContext, fQOP, pMessage, MessageSeqNo);
1409 if (!phContext)
1410 return SEC_E_INVALID_HANDLE;
1412 if(fQOP)
1413 FIXME("Ignoring fQOP 0x%08x\n", fQOP);
1415 if(MessageSeqNo)
1416 FIXME("Ignoring MessageSeqNo\n");
1418 if(!pMessage || !pMessage->pBuffers || pMessage->cBuffers < 2)
1419 return SEC_E_INVALID_TOKEN;
1421 /* If we didn't find a SECBUFFER_TOKEN type buffer */
1422 if((token_idx = ntlm_GetTokenBufferIndex(pMessage)) == -1)
1423 return SEC_E_INVALID_TOKEN;
1425 if(pMessage->pBuffers[token_idx].cbBuffer < 16)
1426 return SEC_E_BUFFER_TOO_SMALL;
1428 helper = (PNegoHelper)phContext->dwLower;
1429 TRACE("Negotiated flags are: 0x%08lx\n", helper->neg_flags);
1431 return ntlm_CreateSignature(helper, pMessage, token_idx, NTLM_SEND, TRUE);
1434 /***********************************************************************
1435 * VerifySignature
1437 static SECURITY_STATUS SEC_ENTRY ntlm_VerifySignature(PCtxtHandle phContext,
1438 PSecBufferDesc pMessage, ULONG MessageSeqNo, PULONG pfQOP)
1440 PNegoHelper helper;
1441 ULONG fQOP = 0;
1442 UINT i;
1443 int token_idx;
1444 SECURITY_STATUS ret;
1445 SecBufferDesc local_desc;
1446 PSecBuffer local_buff;
1447 BYTE local_sig[16];
1449 TRACE("%p %p %d %p\n", phContext, pMessage, MessageSeqNo, pfQOP);
1450 if(!phContext)
1451 return SEC_E_INVALID_HANDLE;
1453 if(!pMessage || !pMessage->pBuffers || pMessage->cBuffers < 2)
1454 return SEC_E_INVALID_TOKEN;
1456 if((token_idx = ntlm_GetTokenBufferIndex(pMessage)) == -1)
1457 return SEC_E_INVALID_TOKEN;
1459 if(pMessage->pBuffers[token_idx].cbBuffer < 16)
1460 return SEC_E_BUFFER_TOO_SMALL;
1462 if(MessageSeqNo)
1463 FIXME("Ignoring MessageSeqNo\n");
1465 helper = (PNegoHelper)phContext->dwLower;
1466 TRACE("Negotiated flags: 0x%08lx\n", helper->neg_flags);
1468 local_buff = HeapAlloc(GetProcessHeap(), 0, pMessage->cBuffers * sizeof(SecBuffer));
1470 local_desc.ulVersion = SECBUFFER_VERSION;
1471 local_desc.cBuffers = pMessage->cBuffers;
1472 local_desc.pBuffers = local_buff;
1474 for(i=0; i < pMessage->cBuffers; ++i)
1476 if(pMessage->pBuffers[i].BufferType == SECBUFFER_TOKEN)
1478 local_buff[i].BufferType = SECBUFFER_TOKEN;
1479 local_buff[i].cbBuffer = 16;
1480 local_buff[i].pvBuffer = local_sig;
1482 else
1484 local_buff[i].BufferType = pMessage->pBuffers[i].BufferType;
1485 local_buff[i].cbBuffer = pMessage->pBuffers[i].cbBuffer;
1486 local_buff[i].pvBuffer = pMessage->pBuffers[i].pvBuffer;
1490 if((ret = ntlm_CreateSignature(helper, &local_desc, token_idx, NTLM_RECV, TRUE)) != SEC_E_OK)
1491 return ret;
1493 if(memcmp(((PBYTE)local_buff[token_idx].pvBuffer) + 8,
1494 ((PBYTE)pMessage->pBuffers[token_idx].pvBuffer) + 8, 8))
1495 ret = SEC_E_MESSAGE_ALTERED;
1496 else
1497 ret = SEC_E_OK;
1499 HeapFree(GetProcessHeap(), 0, local_buff);
1500 pfQOP = &fQOP;
1502 return ret;
1506 /***********************************************************************
1507 * FreeCredentialsHandle
1509 static SECURITY_STATUS SEC_ENTRY ntlm_FreeCredentialsHandle(
1510 PCredHandle phCredential)
1512 SECURITY_STATUS ret;
1514 if(phCredential){
1515 PNegoHelper helper = (PNegoHelper) phCredential->dwLower;
1516 phCredential->dwUpper = 0;
1517 phCredential->dwLower = 0;
1518 cleanup_helper(helper);
1519 ret = SEC_E_OK;
1521 else
1522 ret = SEC_E_OK;
1524 return ret;
1527 /***********************************************************************
1528 * EncryptMessage
1530 static SECURITY_STATUS SEC_ENTRY ntlm_EncryptMessage(PCtxtHandle phContext,
1531 ULONG fQOP, PSecBufferDesc pMessage, ULONG MessageSeqNo)
1533 PNegoHelper helper;
1534 int token_idx;
1536 TRACE("(%p %d %p %d)\n", phContext, fQOP, pMessage, MessageSeqNo);
1538 if(!phContext)
1539 return SEC_E_INVALID_HANDLE;
1541 if(fQOP)
1542 FIXME("Ignoring fQOP\n");
1544 if(MessageSeqNo)
1545 FIXME("Ignoring MessageSeqNo\n");
1547 if(!pMessage || !pMessage->pBuffers || pMessage->cBuffers < 2)
1548 return SEC_E_INVALID_TOKEN;
1550 if((token_idx = ntlm_GetTokenBufferIndex(pMessage)) == -1)
1551 return SEC_E_INVALID_TOKEN;
1553 if(pMessage->pBuffers[token_idx].cbBuffer < 16)
1554 return SEC_E_BUFFER_TOO_SMALL;
1556 helper = (PNegoHelper) phContext->dwLower;
1558 if(helper->neg_flags & NTLMSSP_NEGOTIATE_NTLM2 &&
1559 helper->neg_flags & NTLMSSP_NEGOTIATE_SEAL)
1561 ntlm_CreateSignature(helper, pMessage, token_idx, NTLM_SEND, FALSE);
1562 SECUR32_arc4Process(helper->crypt.ntlm2.send_a4i,
1563 (BYTE *)pMessage->pBuffers[1].pvBuffer,
1564 pMessage->pBuffers[1].cbBuffer);
1566 if(helper->neg_flags & NTLMSSP_NEGOTIATE_KEY_EXCHANGE)
1567 SECUR32_arc4Process(helper->crypt.ntlm2.send_a4i,
1568 ((BYTE *)pMessage->pBuffers[token_idx].pvBuffer)+4, 8);
1571 return SEC_E_OK;
1573 else
1575 PBYTE sig;
1576 ULONG save_flags;
1578 /* EncryptMessage always produces real signatures, so make sure
1579 * NTLMSSP_NEGOTIATE_SIGN is set*/
1580 save_flags = helper->neg_flags;
1581 helper->neg_flags |= NTLMSSP_NEGOTIATE_SIGN;
1582 ntlm_CreateSignature(helper, pMessage, token_idx, NTLM_SEND, FALSE);
1583 helper->neg_flags = save_flags;
1585 sig = pMessage->pBuffers[token_idx].pvBuffer;
1587 SECUR32_arc4Process(helper->crypt.ntlm.a4i, pMessage->pBuffers[1].pvBuffer,
1588 pMessage->pBuffers[1].cbBuffer);
1589 SECUR32_arc4Process(helper->crypt.ntlm.a4i, sig+4, 12);
1591 if(helper->neg_flags & NTLMSSP_NEGOTIATE_ALWAYS_SIGN || helper->neg_flags == 0)
1592 memset(sig+4, 0, 4);
1596 return SEC_E_OK;
1599 /***********************************************************************
1600 * DecryptMessage
1602 static SECURITY_STATUS SEC_ENTRY ntlm_DecryptMessage(PCtxtHandle phContext,
1603 PSecBufferDesc pMessage, ULONG MessageSeqNo, PULONG pfQOP)
1605 SECURITY_STATUS ret;
1606 ULONG ntlmssp_flags_save;
1607 PNegoHelper helper;
1608 int token_idx;
1609 TRACE("(%p %p %d %p)\n", phContext, pMessage, MessageSeqNo, pfQOP);
1611 if(!phContext)
1612 return SEC_E_INVALID_HANDLE;
1614 if(MessageSeqNo)
1615 FIXME("Ignoring MessageSeqNo\n");
1617 if(!pMessage || !pMessage->pBuffers || pMessage->cBuffers < 2)
1618 return SEC_E_INVALID_TOKEN;
1620 if((token_idx = ntlm_GetTokenBufferIndex(pMessage)) == -1)
1621 return SEC_E_INVALID_TOKEN;
1623 if(pMessage->pBuffers[token_idx].cbBuffer < 16)
1624 return SEC_E_BUFFER_TOO_SMALL;
1626 helper = (PNegoHelper) phContext->dwLower;
1628 if(helper->neg_flags & NTLMSSP_NEGOTIATE_NTLM2 && helper->neg_flags & NTLMSSP_NEGOTIATE_SEAL)
1630 SECUR32_arc4Process(helper->crypt.ntlm2.recv_a4i,
1631 pMessage->pBuffers[1].pvBuffer, pMessage->pBuffers[1].cbBuffer);
1633 else
1635 SECUR32_arc4Process(helper->crypt.ntlm.a4i,
1636 pMessage->pBuffers[1].pvBuffer, pMessage->pBuffers[1].cbBuffer);
1639 /* Make sure we use a session key for the signature check, EncryptMessage
1640 * always does that, even in the dummy case */
1641 ntlmssp_flags_save = helper->neg_flags;
1643 helper->neg_flags |= NTLMSSP_NEGOTIATE_SIGN;
1644 ret = ntlm_VerifySignature(phContext, pMessage, MessageSeqNo, pfQOP);
1646 helper->neg_flags = ntlmssp_flags_save;
1648 return ret;
1651 static const SecurityFunctionTableA ntlmTableA = {
1653 NULL, /* EnumerateSecurityPackagesA */
1654 ntlm_QueryCredentialsAttributesA, /* QueryCredentialsAttributesA */
1655 ntlm_AcquireCredentialsHandleA, /* AcquireCredentialsHandleA */
1656 ntlm_FreeCredentialsHandle, /* FreeCredentialsHandle */
1657 NULL, /* Reserved2 */
1658 ntlm_InitializeSecurityContextA, /* InitializeSecurityContextA */
1659 ntlm_AcceptSecurityContext, /* AcceptSecurityContext */
1660 ntlm_CompleteAuthToken, /* CompleteAuthToken */
1661 ntlm_DeleteSecurityContext, /* DeleteSecurityContext */
1662 NULL, /* ApplyControlToken */
1663 ntlm_QueryContextAttributesA, /* QueryContextAttributesA */
1664 ntlm_ImpersonateSecurityContext, /* ImpersonateSecurityContext */
1665 ntlm_RevertSecurityContext, /* RevertSecurityContext */
1666 ntlm_MakeSignature, /* MakeSignature */
1667 ntlm_VerifySignature, /* VerifySignature */
1668 FreeContextBuffer, /* FreeContextBuffer */
1669 NULL, /* QuerySecurityPackageInfoA */
1670 NULL, /* Reserved3 */
1671 NULL, /* Reserved4 */
1672 NULL, /* ExportSecurityContext */
1673 NULL, /* ImportSecurityContextA */
1674 NULL, /* AddCredentialsA */
1675 NULL, /* Reserved8 */
1676 NULL, /* QuerySecurityContextToken */
1677 ntlm_EncryptMessage, /* EncryptMessage */
1678 ntlm_DecryptMessage, /* DecryptMessage */
1679 NULL, /* SetContextAttributesA */
1682 static const SecurityFunctionTableW ntlmTableW = {
1684 NULL, /* EnumerateSecurityPackagesW */
1685 ntlm_QueryCredentialsAttributesW, /* QueryCredentialsAttributesW */
1686 ntlm_AcquireCredentialsHandleW, /* AcquireCredentialsHandleW */
1687 ntlm_FreeCredentialsHandle, /* FreeCredentialsHandle */
1688 NULL, /* Reserved2 */
1689 ntlm_InitializeSecurityContextW, /* InitializeSecurityContextW */
1690 ntlm_AcceptSecurityContext, /* AcceptSecurityContext */
1691 ntlm_CompleteAuthToken, /* CompleteAuthToken */
1692 ntlm_DeleteSecurityContext, /* DeleteSecurityContext */
1693 NULL, /* ApplyControlToken */
1694 ntlm_QueryContextAttributesW, /* QueryContextAttributesW */
1695 ntlm_ImpersonateSecurityContext, /* ImpersonateSecurityContext */
1696 ntlm_RevertSecurityContext, /* RevertSecurityContext */
1697 ntlm_MakeSignature, /* MakeSignature */
1698 ntlm_VerifySignature, /* VerifySignature */
1699 FreeContextBuffer, /* FreeContextBuffer */
1700 NULL, /* QuerySecurityPackageInfoW */
1701 NULL, /* Reserved3 */
1702 NULL, /* Reserved4 */
1703 NULL, /* ExportSecurityContext */
1704 NULL, /* ImportSecurityContextW */
1705 NULL, /* AddCredentialsW */
1706 NULL, /* Reserved8 */
1707 NULL, /* QuerySecurityContextToken */
1708 ntlm_EncryptMessage, /* EncryptMessage */
1709 ntlm_DecryptMessage, /* DecryptMessage */
1710 NULL, /* SetContextAttributesW */
1713 #define NTLM_COMMENT \
1714 { 'N', 'T', 'L', 'M', ' ', \
1715 'S', 'e', 'c', 'u', 'r', 'i', 't', 'y', ' ', \
1716 'P', 'a', 'c', 'k', 'a', 'g', 'e', 0}
1718 static CHAR ntlm_comment_A[] = NTLM_COMMENT;
1719 static WCHAR ntlm_comment_W[] = NTLM_COMMENT;
1721 #define NTLM_NAME {'N', 'T', 'L', 'M', 0}
1723 static char ntlm_name_A[] = NTLM_NAME;
1724 static WCHAR ntlm_name_W[] = NTLM_NAME;
1726 /* According to Windows, NTLM has the following capabilities. */
1727 #define CAPS ( \
1728 SECPKG_FLAG_INTEGRITY | \
1729 SECPKG_FLAG_PRIVACY | \
1730 SECPKG_FLAG_TOKEN_ONLY | \
1731 SECPKG_FLAG_CONNECTION | \
1732 SECPKG_FLAG_MULTI_REQUIRED | \
1733 SECPKG_FLAG_IMPERSONATION | \
1734 SECPKG_FLAG_ACCEPT_WIN32_NAME | \
1735 SECPKG_FLAG_READONLY_WITH_CHECKSUM)
1737 static const SecPkgInfoW infoW = {
1738 CAPS,
1740 RPC_C_AUTHN_WINNT,
1741 NTLM_MAX_BUF,
1742 ntlm_name_W,
1743 ntlm_comment_W
1746 static const SecPkgInfoA infoA = {
1747 CAPS,
1749 RPC_C_AUTHN_WINNT,
1750 NTLM_MAX_BUF,
1751 ntlm_name_A,
1752 ntlm_comment_A
1755 void SECUR32_initNTLMSP(void)
1757 SECURITY_STATUS ret;
1758 PNegoHelper helper;
1759 static CHAR version[] = "--version";
1761 SEC_CHAR *args[] = {
1762 ntlm_auth,
1763 version,
1764 NULL };
1766 if((ret = fork_helper(&helper, ntlm_auth, args)) != SEC_E_OK)
1768 /* Cheat and allocate a helper anyway, so cleanup later will work. */
1769 helper = HeapAlloc(GetProcessHeap(),0, sizeof(PNegoHelper));
1770 helper->major = helper->minor = helper->micro = -1;
1772 else
1773 check_version(helper);
1775 if( (helper->major > MIN_NTLM_AUTH_MAJOR_VERSION) ||
1776 (helper->major == MIN_NTLM_AUTH_MAJOR_VERSION &&
1777 helper->minor > MIN_NTLM_AUTH_MINOR_VERSION) ||
1778 (helper->major == MIN_NTLM_AUTH_MAJOR_VERSION &&
1779 helper->minor == MIN_NTLM_AUTH_MINOR_VERSION &&
1780 helper->micro >= MIN_NTLM_AUTH_MICRO_VERSION) )
1782 SecureProvider *provider = SECUR32_addProvider(&ntlmTableA, &ntlmTableW, NULL);
1783 SECUR32_addPackages(provider, 1L, &infoA, &infoW);
1785 else
1787 ERR("%s was not found or is outdated. "
1788 "Make sure that ntlm_auth >= %d.%d.%d is in your path.\n",
1789 ntlm_auth,
1790 MIN_NTLM_AUTH_MAJOR_VERSION,
1791 MIN_NTLM_AUTH_MINOR_VERSION,
1792 MIN_NTLM_AUTH_MICRO_VERSION);
1794 cleanup_helper(helper);