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.
30 #include "secur32_priv.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 typedef struct _NtlmCredentials
47 /* these are all in the Unix codepage */
50 char *password; /* not nul-terminated */
52 } NtlmCredentials, *PNtlmCredentials;
54 /***********************************************************************
55 * QueryCredentialsAttributesA
57 static SECURITY_STATUS SEC_ENTRY ntlm_QueryCredentialsAttributesA(
58 PCredHandle phCredential, ULONG ulAttribute, PVOID pBuffer)
62 TRACE("(%p, %d, %p)\n", phCredential, ulAttribute, pBuffer);
64 if(ulAttribute == SECPKG_ATTR_NAMES)
66 FIXME("SECPKG_CRED_ATTR_NAMES: stub\n");
67 ret = SEC_E_UNSUPPORTED_FUNCTION;
70 ret = SEC_E_UNSUPPORTED_FUNCTION;
75 /***********************************************************************
76 * QueryCredentialsAttributesW
78 static SECURITY_STATUS SEC_ENTRY ntlm_QueryCredentialsAttributesW(
79 PCredHandle phCredential, ULONG ulAttribute, PVOID pBuffer)
83 TRACE("(%p, %d, %p)\n", phCredential, ulAttribute, pBuffer);
85 if(ulAttribute == SECPKG_ATTR_NAMES)
87 FIXME("SECPKG_CRED_ATTR_NAMES: stub\n");
88 ret = SEC_E_UNSUPPORTED_FUNCTION;
91 ret = SEC_E_UNSUPPORTED_FUNCTION;
96 /***********************************************************************
97 * AcquireCredentialsHandleW
99 static SECURITY_STATUS SEC_ENTRY ntlm_AcquireCredentialsHandleW(
100 SEC_WCHAR *pszPrincipal, SEC_WCHAR *pszPackage, ULONG fCredentialUse,
101 PLUID pLogonID, PVOID pAuthData, SEC_GET_KEY_FN pGetKeyFn,
102 PVOID pGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
105 PNtlmCredentials ntlm_cred = NULL;
106 SEC_WCHAR *username = NULL, *domain = NULL;
108 TRACE("(%s, %s, 0x%08x, %p, %p, %p, %p, %p, %p)\n",
109 debugstr_w(pszPrincipal), debugstr_w(pszPackage), fCredentialUse,
110 pLogonID, pAuthData, pGetKeyFn, pGetKeyArgument, phCredential, ptsExpiry);
112 switch(fCredentialUse)
114 case SECPKG_CRED_INBOUND:
115 ntlm_cred = HeapAlloc(GetProcessHeap(), 0, sizeof(*ntlm_cred));
117 ret = SEC_E_INSUFFICIENT_MEMORY;
120 ntlm_cred->mode = NTLM_SERVER;
121 ntlm_cred->username_arg = NULL;
122 ntlm_cred->domain_arg = NULL;
123 ntlm_cred->password = NULL;
124 ntlm_cred->pwlen = 0;
125 phCredential->dwUpper = fCredentialUse;
126 phCredential->dwLower = (ULONG_PTR)ntlm_cred;
130 case SECPKG_CRED_OUTBOUND:
132 static const char username_arg[] = "--username=";
133 static const char domain_arg[] = "--domain=";
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;
149 username = HeapAlloc(GetProcessHeap(), 0,
150 (lstrlenW(ui->wkui1_username)+1) *
152 lstrcpyW(username, ui->wkui1_username);
154 /* same for the domain */
155 domain = HeapAlloc(GetProcessHeap(), 0,
156 (lstrlenW(ui->wkui1_logon_domain)+1) *
158 lstrcpyW(domain, ui->wkui1_logon_domain);
159 NetApiBufferFree(ui);
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';
180 ntlm_cred = HeapAlloc(GetProcessHeap(), 0, sizeof(*ntlm_cred));
183 ret = SEC_E_INSUFFICIENT_MEMORY;
186 ntlm_cred->mode = NTLM_CLIENT;
187 ntlm_cred->password = NULL;
188 ntlm_cred->pwlen = 0;
190 TRACE("Username is %s\n", debugstr_w(username));
191 unixcp_size = WideCharToMultiByte(CP_UNIXCP, WC_NO_BEST_FIT_CHARS,
192 username, -1, NULL, 0, NULL, NULL) + sizeof(username_arg);
193 ntlm_cred->username_arg = HeapAlloc(GetProcessHeap(), 0, unixcp_size);
194 memcpy(ntlm_cred->username_arg, username_arg, sizeof(username_arg) - 1);
195 WideCharToMultiByte(CP_UNIXCP, WC_NO_BEST_FIT_CHARS, username, -1,
196 ntlm_cred->username_arg + sizeof(username_arg) - 1,
197 unixcp_size - sizeof(username_arg) + 1, NULL, NULL);
199 TRACE("Domain name is %s\n", debugstr_w(domain));
200 unixcp_size = WideCharToMultiByte(CP_UNIXCP, WC_NO_BEST_FIT_CHARS,
201 domain, -1, NULL, 0, NULL, NULL) + sizeof(domain_arg);
202 ntlm_cred->domain_arg = HeapAlloc(GetProcessHeap(), 0, unixcp_size);
203 memcpy(ntlm_cred->domain_arg, domain_arg, sizeof(domain_arg) - 1);
204 WideCharToMultiByte(CP_UNIXCP, WC_NO_BEST_FIT_CHARS, domain,
205 -1, ntlm_cred->domain_arg + sizeof(domain_arg) - 1,
206 unixcp_size - sizeof(domain) + 1, NULL, NULL);
208 if(pAuthData != NULL)
210 PSEC_WINNT_AUTH_IDENTITY_W auth_data =
211 (PSEC_WINNT_AUTH_IDENTITY_W)pAuthData;
213 if(auth_data->PasswordLength != 0)
215 ntlm_cred->pwlen = WideCharToMultiByte(CP_UNIXCP,
216 WC_NO_BEST_FIT_CHARS, auth_data->Password,
217 auth_data->PasswordLength, NULL, 0, NULL,
220 ntlm_cred->password = HeapAlloc(GetProcessHeap(), 0,
223 WideCharToMultiByte(CP_UNIXCP, WC_NO_BEST_FIT_CHARS,
224 auth_data->Password, auth_data->PasswordLength,
225 ntlm_cred->password, ntlm_cred->pwlen, NULL, NULL);
229 phCredential->dwUpper = fCredentialUse;
230 phCredential->dwLower = (ULONG_PTR)ntlm_cred;
231 TRACE("ACH phCredential->dwUpper: 0x%08lx, dwLower: 0x%08lx\n",
232 phCredential->dwUpper, phCredential->dwLower);
236 case SECPKG_CRED_BOTH:
237 FIXME("AcquireCredentialsHandle: SECPKG_CRED_BOTH stub\n");
238 ret = SEC_E_UNSUPPORTED_FUNCTION;
243 ret = SEC_E_UNKNOWN_CREDENTIALS;
246 HeapFree(GetProcessHeap(), 0, username);
247 HeapFree(GetProcessHeap(), 0, domain);
252 /***********************************************************************
253 * AcquireCredentialsHandleA
255 static SECURITY_STATUS SEC_ENTRY ntlm_AcquireCredentialsHandleA(
256 SEC_CHAR *pszPrincipal, SEC_CHAR *pszPackage, ULONG fCredentialUse,
257 PLUID pLogonID, PVOID pAuthData, SEC_GET_KEY_FN pGetKeyFn,
258 PVOID pGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
261 int user_sizeW, domain_sizeW, passwd_sizeW;
263 SEC_WCHAR *user = NULL, *domain = NULL, *passwd = NULL, *package = NULL;
265 PSEC_WINNT_AUTH_IDENTITY_W pAuthDataW = NULL;
266 PSEC_WINNT_AUTH_IDENTITY_A identity = NULL;
268 TRACE("(%s, %s, 0x%08x, %p, %p, %p, %p, %p, %p)\n",
269 debugstr_a(pszPrincipal), debugstr_a(pszPackage), fCredentialUse,
270 pLogonID, pAuthData, pGetKeyFn, pGetKeyArgument, phCredential, ptsExpiry);
272 if(pszPackage != NULL)
274 int package_sizeW = MultiByteToWideChar(CP_ACP, 0, pszPackage, -1,
277 package = HeapAlloc(GetProcessHeap(), 0, package_sizeW *
279 MultiByteToWideChar(CP_ACP, 0, pszPackage, -1, package, package_sizeW);
283 if(pAuthData != NULL)
285 identity = (PSEC_WINNT_AUTH_IDENTITY_A)pAuthData;
287 if(identity->Flags == SEC_WINNT_AUTH_IDENTITY_ANSI)
289 pAuthDataW = HeapAlloc(GetProcessHeap(), 0,
290 sizeof(SEC_WINNT_AUTH_IDENTITY_W));
292 if(identity->UserLength != 0)
294 user_sizeW = MultiByteToWideChar(CP_ACP, 0,
295 (LPCSTR)identity->User, identity->UserLength, NULL, 0);
296 user = HeapAlloc(GetProcessHeap(), 0, user_sizeW *
298 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)identity->User,
299 identity->UserLength, user, user_sizeW);
306 if(identity->DomainLength != 0)
308 domain_sizeW = MultiByteToWideChar(CP_ACP, 0,
309 (LPCSTR)identity->Domain, identity->DomainLength, NULL, 0);
310 domain = HeapAlloc(GetProcessHeap(), 0, domain_sizeW
311 * sizeof(SEC_WCHAR));
312 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)identity->Domain,
313 identity->DomainLength, domain, domain_sizeW);
320 if(identity->PasswordLength != 0)
322 passwd_sizeW = MultiByteToWideChar(CP_ACP, 0,
323 (LPCSTR)identity->Password, identity->PasswordLength,
325 passwd = HeapAlloc(GetProcessHeap(), 0, passwd_sizeW
326 * sizeof(SEC_WCHAR));
327 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)identity->Password,
328 identity->PasswordLength, passwd, passwd_sizeW);
335 pAuthDataW->Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
336 pAuthDataW->User = user;
337 pAuthDataW->UserLength = user_sizeW;
338 pAuthDataW->Domain = domain;
339 pAuthDataW->DomainLength = domain_sizeW;
340 pAuthDataW->Password = passwd;
341 pAuthDataW->PasswordLength = passwd_sizeW;
345 pAuthDataW = (PSEC_WINNT_AUTH_IDENTITY_W)identity;
349 ret = ntlm_AcquireCredentialsHandleW(NULL, package, fCredentialUse,
350 pLogonID, pAuthDataW, pGetKeyFn, pGetKeyArgument, phCredential,
353 HeapFree(GetProcessHeap(), 0, package);
354 HeapFree(GetProcessHeap(), 0, user);
355 HeapFree(GetProcessHeap(), 0, domain);
356 HeapFree(GetProcessHeap(), 0, passwd);
357 if(pAuthDataW != (PSEC_WINNT_AUTH_IDENTITY_W)identity)
358 HeapFree(GetProcessHeap(), 0, pAuthDataW);
363 /*************************************************************************
364 * ntlm_GetTokenBufferIndex
365 * Calculates the index of the secbuffer with BufferType == SECBUFFER_TOKEN
366 * Returns index if found or -1 if not found.
368 static int ntlm_GetTokenBufferIndex(PSecBufferDesc pMessage)
372 TRACE("%p\n", pMessage);
374 for( i = 0; i < pMessage->cBuffers; ++i )
376 if(pMessage->pBuffers[i].BufferType == SECBUFFER_TOKEN)
383 /*************************************************************************
384 * ntlm_GetDataBufferIndex
385 * Calculates the index of the first secbuffer with BufferType == SECBUFFER_DATA
386 * Returns index if found or -1 if not found.
388 static int ntlm_GetDataBufferIndex(PSecBufferDesc pMessage)
392 TRACE("%p\n", pMessage);
394 for( i = 0; i < pMessage->cBuffers; ++i )
396 if(pMessage->pBuffers[i].BufferType == SECBUFFER_DATA)
403 /***********************************************************************
404 * InitializeSecurityContextW
406 static SECURITY_STATUS SEC_ENTRY ntlm_InitializeSecurityContextW(
407 PCredHandle phCredential, PCtxtHandle phContext, SEC_WCHAR *pszTargetName,
408 ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep,
409 PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext,
410 PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
413 PNtlmCredentials ntlm_cred = NULL;
414 PNegoHelper helper = NULL;
416 char* buffer, *want_flags = NULL;
418 int buffer_len, bin_len, max_len = NTLM_MAX_BUF;
421 TRACE("%p %p %s %d %d %d %p %d %p %p %p %p\n", phCredential, phContext,
422 debugstr_w(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
423 Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
425 /****************************************
426 * When communicating with the client, there can be the
427 * following reply packets:
428 * YR <base64 blob> should be sent to the server
429 * PW should be sent back to helper with
430 * base64 encoded password
431 * AF <base64 blob> client is done, blob should be
432 * sent to server with KK prefixed
433 * GF <string list> A string list of negotiated flags
434 * GK <base64 blob> base64 encoded session key
435 * BH <char reason> something broke
437 /* The squid cache size is 2010 chars, and that's what ntlm_auth uses */
441 TRACE("According to a MS whitepaper pszTargetName is ignored.\n");
444 if(TargetDataRep == SECURITY_NETWORK_DREP){
445 TRACE("Setting SECURITY_NETWORK_DREP\n");
448 buffer = HeapAlloc(GetProcessHeap(), 0, sizeof(char) * NTLM_MAX_BUF);
449 bin = HeapAlloc(GetProcessHeap(), 0, sizeof(BYTE) * NTLM_MAX_BUF);
451 if((phContext == NULL) && (pInput == NULL))
453 static char helper_protocol[] = "--helper-protocol=ntlmssp-client-1";
454 static CHAR credentials_argv[] = "--use-cached-creds";
455 SEC_CHAR *client_argv[6];
457 TRACE("First time in ISC()\n");
461 ret = SEC_E_INVALID_HANDLE;
465 /* As the server side of sspi never calls this, make sure that
466 * the handler is a client handler.
468 ntlm_cred = (PNtlmCredentials)phCredential->dwLower;
469 if(ntlm_cred->mode != NTLM_CLIENT)
471 TRACE("Cred mode = %d\n", ntlm_cred->mode);
472 ret = SEC_E_INVALID_HANDLE;
476 client_argv[0] = ntlm_auth;
477 client_argv[1] = helper_protocol;
478 client_argv[2] = ntlm_cred->username_arg;
479 client_argv[3] = ntlm_cred->domain_arg;
480 client_argv[4] = credentials_argv;
481 client_argv[5] = NULL;
483 if((ret = fork_helper(&helper, ntlm_auth, client_argv)) != SEC_E_OK)
486 helper->mode = NTLM_CLIENT;
487 helper->session_key = HeapAlloc(GetProcessHeap(), 0, 16);
488 if (!helper->session_key)
490 cleanup_helper(helper);
491 ret = SEC_E_INSUFFICIENT_MEMORY;
495 /* Generate the dummy session key = MD4(MD4(password))*/
496 if(ntlm_cred->password)
498 SEC_WCHAR *unicode_password;
501 TRACE("Converting password to unicode.\n");
502 passwd_lenW = MultiByteToWideChar(CP_ACP, 0,
503 (LPCSTR)ntlm_cred->password, ntlm_cred->pwlen,
505 unicode_password = HeapAlloc(GetProcessHeap(), 0,
506 passwd_lenW * sizeof(SEC_WCHAR));
507 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)ntlm_cred->password,
508 ntlm_cred->pwlen, unicode_password, passwd_lenW);
510 SECUR32_CreateNTLMv1SessionKey((PBYTE)unicode_password,
511 passwd_lenW * sizeof(SEC_WCHAR), helper->session_key);
513 HeapFree(GetProcessHeap(), 0, unicode_password);
516 memset(helper->session_key, 0, 16);
518 /* Allocate space for a maximal string of
519 * "SF NTLMSSP_FEATURE_SIGN NTLMSSP_FEATURE_SEAL
520 * NTLMSSP_FEATURE_SESSION_KEY"
522 want_flags = HeapAlloc(GetProcessHeap(), 0, 73);
523 if(want_flags == NULL)
525 cleanup_helper(helper);
526 ret = SEC_E_INSUFFICIENT_MEMORY;
529 lstrcpyA(want_flags, "SF");
530 if(fContextReq & ISC_REQ_CONFIDENTIALITY)
533 if((ptr = strstr(want_flags, "NTLMSSP_FEATURE_SEAL")) == NULL)
534 lstrcatA(want_flags, " NTLMSSP_FEATURE_SEAL");
536 if(fContextReq & ISC_REQ_CONNECTION)
537 ctxt_attr |= ISC_RET_CONNECTION;
538 if(fContextReq & ISC_REQ_EXTENDED_ERROR)
539 ctxt_attr |= ISC_RET_EXTENDED_ERROR;
540 if(fContextReq & ISC_REQ_INTEGRITY)
543 if((ptr = strstr(want_flags, "NTLMSSP_FEATURE_SIGN")) == NULL)
544 lstrcatA(want_flags, " NTLMSSP_FEATURE_SIGN");
546 if(fContextReq & ISC_REQ_MUTUAL_AUTH)
547 ctxt_attr |= ISC_RET_MUTUAL_AUTH;
548 if(fContextReq & ISC_REQ_REPLAY_DETECT)
551 if((ptr = strstr(want_flags, "NTLMSSP_FEATURE_SIGN")) == NULL)
552 lstrcatA(want_flags, " NTLMSSP_FEATURE_SIGN");
554 if(fContextReq & ISC_REQ_SEQUENCE_DETECT)
557 if((ptr = strstr(want_flags, "NTLMSSP_FEATURE_SIGN")) == NULL)
558 lstrcatA(want_flags, " NTLMSSP_FEATURE_SIGN");
560 if(fContextReq & ISC_REQ_STREAM)
561 FIXME("ISC_REQ_STREAM\n");
562 if(fContextReq & ISC_REQ_USE_DCE_STYLE)
563 ctxt_attr |= ISC_RET_USED_DCE_STYLE;
564 if(fContextReq & ISC_REQ_DELEGATE)
565 ctxt_attr |= ISC_RET_DELEGATE;
567 /* If no password is given, try to use cached credentials. Fall back to an empty
568 * password if this failed. */
569 if(ntlm_cred->password == NULL)
571 lstrcpynA(buffer, "OK", max_len-1);
572 if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
574 cleanup_helper(helper);
577 /* If the helper replied with "PW", using cached credentials failed */
578 if(!strncmp(buffer, "PW", 2))
580 TRACE("Using cached credentials failed. Using empty password.\n");
581 lstrcpynA(buffer, "PW AA==", max_len-1);
583 else /* Just do a noop on the next run */
584 lstrcpynA(buffer, "OK", max_len-1);
588 lstrcpynA(buffer, "PW ", max_len-1);
589 if((ret = encodeBase64((unsigned char*)ntlm_cred->password,
590 ntlm_cred->pwlen, buffer+3,
591 max_len-3, &buffer_len)) != SEC_E_OK)
593 cleanup_helper(helper);
599 TRACE("Sending to helper: %s\n", debugstr_a(buffer));
600 if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
602 cleanup_helper(helper);
606 TRACE("Helper returned %s\n", debugstr_a(buffer));
608 if(lstrlenA(want_flags) > 2)
610 TRACE("Want flags are %s\n", debugstr_a(want_flags));
611 lstrcpynA(buffer, want_flags, max_len-1);
612 if((ret = run_helper(helper, buffer, max_len, &buffer_len))
615 if(!strncmp(buffer, "BH", 2))
616 ERR("Helper doesn't understand new command set. Expect more things to fail.\n");
619 lstrcpynA(buffer, "YR", max_len-1);
621 if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
623 cleanup_helper(helper);
627 TRACE("%s\n", buffer);
629 if(strncmp(buffer, "YR ", 3) != 0)
631 /* Something borked */
632 TRACE("Helper returned %c%c\n", buffer[0], buffer[1]);
633 ret = SEC_E_INTERNAL_ERROR;
634 cleanup_helper(helper);
637 if((ret = decodeBase64(buffer+3, buffer_len-3, bin,
638 max_len-1, &bin_len)) != SEC_E_OK)
640 cleanup_helper(helper);
644 /* put the decoded client blob into the out buffer */
646 phNewContext->dwUpper = ctxt_attr;
647 phNewContext->dwLower = (ULONG_PTR)helper;
649 ret = SEC_I_CONTINUE_NEEDED;
655 /* handle second call here */
656 /* encode server data to base64 */
657 if (!pInput || ((input_token_idx = ntlm_GetTokenBufferIndex(pInput)) == -1))
659 ret = SEC_E_INVALID_TOKEN;
665 ret = SEC_E_INVALID_HANDLE;
669 /* As the server side of sspi never calls this, make sure that
670 * the handler is a client handler.
672 helper = (PNegoHelper)phContext->dwLower;
673 if(helper->mode != NTLM_CLIENT)
675 TRACE("Helper mode = %d\n", helper->mode);
676 ret = SEC_E_INVALID_HANDLE;
680 if (!pInput->pBuffers[input_token_idx].pvBuffer)
682 ret = SEC_E_INTERNAL_ERROR;
686 if(pInput->pBuffers[input_token_idx].cbBuffer > max_len)
688 TRACE("pInput->pBuffers[%d].cbBuffer is: %ld\n",
690 pInput->pBuffers[input_token_idx].cbBuffer);
691 ret = SEC_E_INVALID_TOKEN;
695 bin_len = pInput->pBuffers[input_token_idx].cbBuffer;
697 memcpy(bin, pInput->pBuffers[input_token_idx].pvBuffer, bin_len);
699 lstrcpynA(buffer, "TT ", max_len-1);
701 if((ret = encodeBase64(bin, bin_len, buffer+3,
702 max_len-3, &buffer_len)) != SEC_E_OK)
705 TRACE("Server sent: %s\n", debugstr_a(buffer));
707 /* send TT base64 blob to ntlm_auth */
708 if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
711 TRACE("Helper replied: %s\n", debugstr_a(buffer));
713 if( (strncmp(buffer, "KK ", 3) != 0) &&
714 (strncmp(buffer, "AF ", 3) !=0))
716 TRACE("Helper returned %c%c\n", buffer[0], buffer[1]);
717 ret = SEC_E_INVALID_TOKEN;
721 /* decode the blob and send it to server */
722 if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len,
723 &bin_len)) != SEC_E_OK)
728 phNewContext->dwUpper = ctxt_attr;
729 phNewContext->dwLower = (ULONG_PTR)helper;
734 /* put the decoded client blob into the out buffer */
736 if (!pOutput || ((token_idx = ntlm_GetTokenBufferIndex(pOutput)) == -1))
738 TRACE("no SECBUFFER_TOKEN buffer could be found\n");
739 ret = SEC_E_BUFFER_TOO_SMALL;
740 if ((phContext == NULL) && (pInput == NULL))
742 cleanup_helper(helper);
743 phNewContext->dwUpper = 0;
744 phNewContext->dwLower = 0;
749 if (fContextReq & ISC_REQ_ALLOCATE_MEMORY)
751 pOutput->pBuffers[token_idx].pvBuffer = SECUR32_ALLOC(bin_len);
752 pOutput->pBuffers[token_idx].cbBuffer = bin_len;
754 else if (pOutput->pBuffers[token_idx].cbBuffer < bin_len)
756 TRACE("out buffer is NULL or has not enough space\n");
757 ret = SEC_E_BUFFER_TOO_SMALL;
758 if ((phContext == NULL) && (pInput == NULL))
760 cleanup_helper(helper);
761 phNewContext->dwUpper = 0;
762 phNewContext->dwLower = 0;
767 if (!pOutput->pBuffers[token_idx].pvBuffer)
769 TRACE("out buffer is NULL\n");
770 ret = SEC_E_INTERNAL_ERROR;
771 if ((phContext == NULL) && (pInput == NULL))
773 cleanup_helper(helper);
774 phNewContext->dwUpper = 0;
775 phNewContext->dwLower = 0;
780 pOutput->pBuffers[token_idx].cbBuffer = bin_len;
781 memcpy(pOutput->pBuffers[token_idx].pvBuffer, bin, bin_len);
785 TRACE("Getting negotiated flags\n");
786 lstrcpynA(buffer, "GF", max_len - 1);
787 if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
792 TRACE("No flags negotiated.\n");
793 helper->neg_flags = 0l;
797 TRACE("Negotiated %s\n", debugstr_a(buffer));
798 sscanf(buffer + 3, "%lx", &(helper->neg_flags));
799 TRACE("Stored 0x%08lx as flags\n", helper->neg_flags);
802 TRACE("Getting session key\n");
803 lstrcpynA(buffer, "GK", max_len - 1);
804 if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
807 if(strncmp(buffer, "BH", 2) == 0)
808 TRACE("No key negotiated.\n");
809 else if(strncmp(buffer, "GK ", 3) == 0)
811 if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len,
812 &bin_len)) != SEC_E_OK)
814 TRACE("Failed to decode session key\n");
816 TRACE("Session key is %s\n", debugstr_a(buffer+3));
817 HeapFree(GetProcessHeap(), 0, helper->session_key);
818 helper->session_key = HeapAlloc(GetProcessHeap(), 0, bin_len);
819 if(!helper->session_key)
821 TRACE("Failed to allocate memory for session key\n");
822 ret = SEC_E_INTERNAL_ERROR;
825 memcpy(helper->session_key, bin, bin_len);
828 helper->crypt.ntlm.a4i = SECUR32_arc4Alloc();
829 SECUR32_arc4Init(helper->crypt.ntlm.a4i, helper->session_key, 16);
830 helper->crypt.ntlm.seq_num = 0l;
831 SECUR32_CreateNTLMv2SubKeys(helper);
832 helper->crypt.ntlm2.send_a4i = SECUR32_arc4Alloc();
833 helper->crypt.ntlm2.recv_a4i = SECUR32_arc4Alloc();
834 SECUR32_arc4Init(helper->crypt.ntlm2.send_a4i,
835 (BYTE *)helper->crypt.ntlm2.send_seal_key, 16);
836 SECUR32_arc4Init(helper->crypt.ntlm2.recv_a4i,
837 (BYTE *)helper->crypt.ntlm2.recv_seal_key, 16);
838 helper->crypt.ntlm2.send_seq_no = 0l;
839 helper->crypt.ntlm2.recv_seq_no = 0l;
843 HeapFree(GetProcessHeap(), 0, want_flags);
844 HeapFree(GetProcessHeap(), 0, buffer);
845 HeapFree(GetProcessHeap(), 0, bin);
849 /***********************************************************************
850 * InitializeSecurityContextA
852 static SECURITY_STATUS SEC_ENTRY ntlm_InitializeSecurityContextA(
853 PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR *pszTargetName,
854 ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep,
855 PSecBufferDesc pInput,ULONG Reserved2, PCtxtHandle phNewContext,
856 PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
859 SEC_WCHAR *target = NULL;
861 TRACE("%p %p %s %d %d %d %p %d %p %p %p %p\n", phCredential, phContext,
862 debugstr_a(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
863 Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
865 if(pszTargetName != NULL)
867 int target_size = MultiByteToWideChar(CP_ACP, 0, pszTargetName,
868 strlen(pszTargetName)+1, NULL, 0);
869 target = HeapAlloc(GetProcessHeap(), 0, target_size *
871 MultiByteToWideChar(CP_ACP, 0, pszTargetName, strlen(pszTargetName)+1,
872 target, target_size);
875 ret = ntlm_InitializeSecurityContextW(phCredential, phContext, target,
876 fContextReq, Reserved1, TargetDataRep, pInput, Reserved2,
877 phNewContext, pOutput, pfContextAttr, ptsExpiry);
879 HeapFree(GetProcessHeap(), 0, target);
883 /***********************************************************************
884 * AcceptSecurityContext
886 static SECURITY_STATUS SEC_ENTRY ntlm_AcceptSecurityContext(
887 PCredHandle phCredential, PCtxtHandle phContext, PSecBufferDesc pInput,
888 ULONG fContextReq, ULONG TargetDataRep, PCtxtHandle phNewContext,
889 PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
892 char *buffer, *want_flags = NULL;
894 int buffer_len, bin_len, max_len = NTLM_MAX_BUF;
897 PNtlmCredentials ntlm_cred;
899 TRACE("%p %p %p %d %d %p %p %p %p\n", phCredential, phContext, pInput,
900 fContextReq, TargetDataRep, phNewContext, pOutput, pfContextAttr,
903 buffer = HeapAlloc(GetProcessHeap(), 0, sizeof(char) * NTLM_MAX_BUF);
904 bin = HeapAlloc(GetProcessHeap(),0, sizeof(BYTE) * NTLM_MAX_BUF);
906 if(TargetDataRep == SECURITY_NETWORK_DREP){
907 TRACE("Using SECURITY_NETWORK_DREP\n");
910 if(phContext == NULL)
912 static CHAR server_helper_protocol[] = "--helper-protocol=squid-2.5-ntlmssp";
913 SEC_CHAR *server_argv[] = { ntlm_auth,
914 server_helper_protocol,
919 ret = SEC_E_INVALID_HANDLE;
923 ntlm_cred = (PNtlmCredentials)phCredential->dwLower;
925 if(ntlm_cred->mode != NTLM_SERVER)
927 ret = SEC_E_INVALID_HANDLE;
931 /* This is the first call to AcceptSecurityHandle */
934 ret = SEC_E_INCOMPLETE_MESSAGE;
938 if(pInput->cBuffers < 1)
940 ret = SEC_E_INCOMPLETE_MESSAGE;
944 if(pInput->pBuffers[0].cbBuffer > max_len)
946 ret = SEC_E_INVALID_TOKEN;
950 bin_len = pInput->pBuffers[0].cbBuffer;
952 if( (ret = fork_helper(&helper, ntlm_auth, server_argv)) !=
955 ret = SEC_E_INTERNAL_ERROR;
958 helper->mode = NTLM_SERVER;
960 /* Handle all the flags */
961 want_flags = HeapAlloc(GetProcessHeap(), 0, 73);
962 if(want_flags == NULL)
964 TRACE("Failed to allocate memory for the want_flags!\n");
965 ret = SEC_E_INSUFFICIENT_MEMORY;
966 cleanup_helper(helper);
969 lstrcpyA(want_flags, "SF");
970 if(fContextReq & ASC_REQ_ALLOCATE_MEMORY)
972 FIXME("ASC_REQ_ALLOCATE_MEMORY stub\n");
974 if(fContextReq & ASC_REQ_CONFIDENTIALITY)
976 lstrcatA(want_flags, " NTLMSSP_FEATURE_SEAL");
978 if(fContextReq & ASC_REQ_CONNECTION)
980 /* This is default, so we'll enable it */
981 lstrcatA(want_flags, " NTLMSSP_FEATURE_SESSION_KEY");
982 ctxt_attr |= ASC_RET_CONNECTION;
984 if(fContextReq & ASC_REQ_EXTENDED_ERROR)
986 FIXME("ASC_REQ_EXTENDED_ERROR stub\n");
988 if(fContextReq & ASC_REQ_INTEGRITY)
990 lstrcatA(want_flags, " NTLMSSP_FEATURE_SIGN");
992 if(fContextReq & ASC_REQ_MUTUAL_AUTH)
994 FIXME("ASC_REQ_MUTUAL_AUTH stub\n");
996 if(fContextReq & ASC_REQ_REPLAY_DETECT)
998 FIXME("ASC_REQ_REPLAY_DETECT stub\n");
1000 if(fContextReq & ISC_REQ_SEQUENCE_DETECT)
1002 FIXME("ASC_REQ_SEQUENCE_DETECT stub\n");
1004 if(fContextReq & ISC_REQ_STREAM)
1006 FIXME("ASC_REQ_STREAM stub\n");
1008 /* Done with the flags */
1010 if(lstrlenA(want_flags) > 3)
1012 TRACE("Server set want_flags: %s\n", debugstr_a(want_flags));
1013 lstrcpynA(buffer, want_flags, max_len - 1);
1014 if((ret = run_helper(helper, buffer, max_len, &buffer_len)) !=
1017 cleanup_helper(helper);
1020 if(!strncmp(buffer, "BH", 2))
1021 TRACE("Helper doesn't understand new command set\n");
1024 /* This is the YR request from the client, encode to base64 */
1026 memcpy(bin, pInput->pBuffers[0].pvBuffer, bin_len);
1028 lstrcpynA(buffer, "YR ", max_len-1);
1030 if((ret = encodeBase64(bin, bin_len, buffer+3, max_len-3,
1031 &buffer_len)) != SEC_E_OK)
1033 cleanup_helper(helper);
1037 TRACE("Client sent: %s\n", debugstr_a(buffer));
1039 if((ret = run_helper(helper, buffer, max_len, &buffer_len)) !=
1042 cleanup_helper(helper);
1046 TRACE("Reply from ntlm_auth: %s\n", debugstr_a(buffer));
1047 /* The expected answer is TT <base64 blob> */
1049 if(strncmp(buffer, "TT ", 3) != 0)
1051 ret = SEC_E_INTERNAL_ERROR;
1052 cleanup_helper(helper);
1056 if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len,
1057 &bin_len)) != SEC_E_OK)
1059 cleanup_helper(helper);
1063 /* send this to the client */
1066 ret = SEC_E_INSUFFICIENT_MEMORY;
1067 cleanup_helper(helper);
1071 if(pOutput->cBuffers < 1)
1073 ret = SEC_E_INSUFFICIENT_MEMORY;
1074 cleanup_helper(helper);
1078 pOutput->pBuffers[0].cbBuffer = bin_len;
1079 pOutput->pBuffers[0].BufferType = SECBUFFER_DATA;
1080 memcpy(pOutput->pBuffers[0].pvBuffer, bin, bin_len);
1081 ret = SEC_I_CONTINUE_NEEDED;
1086 /* we expect a KK request from client */
1089 ret = SEC_E_INCOMPLETE_MESSAGE;
1093 if(pInput->cBuffers < 1)
1095 ret = SEC_E_INCOMPLETE_MESSAGE;
1101 ret = SEC_E_INVALID_HANDLE;
1105 helper = (PNegoHelper)phContext->dwLower;
1107 if(helper->mode != NTLM_SERVER)
1109 ret = SEC_E_INVALID_HANDLE;
1113 if(pInput->pBuffers[0].cbBuffer > max_len)
1115 ret = SEC_E_INVALID_TOKEN;
1119 bin_len = pInput->pBuffers[0].cbBuffer;
1121 memcpy(bin, pInput->pBuffers[0].pvBuffer, bin_len);
1123 lstrcpynA(buffer, "KK ", max_len-1);
1125 if((ret = encodeBase64(bin, bin_len, buffer+3, max_len-3,
1126 &buffer_len)) != SEC_E_OK)
1131 TRACE("Client sent: %s\n", debugstr_a(buffer));
1133 if((ret = run_helper(helper, buffer, max_len, &buffer_len)) !=
1139 TRACE("Reply from ntlm_auth: %s\n", debugstr_a(buffer));
1141 /* At this point, we get a NA if the user didn't authenticate, but a BH
1142 * if ntlm_auth could not connect to winbindd. Apart from running Wine
1143 * as root, there is no way to fix this for now, so just handle this as
1144 * a failed login. */
1145 if(strncmp(buffer, "AF ", 3) != 0)
1147 if(strncmp(buffer, "NA ", 3) == 0)
1149 ret = SEC_E_LOGON_DENIED;
1154 size_t ntlm_pipe_err_len = strlen("BH NT_STATUS_ACCESS_DENIED");
1156 if( (buffer_len >= ntlm_pipe_err_len) &&
1157 (strncmp(buffer, "BH NT_STATUS_ACCESS_DENIED",
1158 ntlm_pipe_err_len) == 0))
1160 TRACE("Connection to winbindd failed\n");
1161 ret = SEC_E_LOGON_DENIED;
1164 ret = SEC_E_INTERNAL_ERROR;
1169 pOutput->pBuffers[0].cbBuffer = 0;
1172 TRACE("Getting negotiated flags\n");
1173 lstrcpynA(buffer, "GF", max_len - 1);
1174 if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
1179 TRACE("No flags negotiated, or helper does not support GF command\n");
1183 TRACE("Negotiated %s\n", debugstr_a(buffer));
1184 sscanf(buffer + 3, "%lx", &(helper->neg_flags));
1185 TRACE("Stored 0x%08lx as flags\n", helper->neg_flags);
1188 TRACE("Getting session key\n");
1189 lstrcpynA(buffer, "GK", max_len - 1);
1190 if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
1194 TRACE("Helper does not support GK command\n");
1197 if(strncmp(buffer, "BH ", 3) == 0)
1199 TRACE("Helper sent %s\n", debugstr_a(buffer+3));
1200 helper->session_key = HeapAlloc(GetProcessHeap(), 0, 16);
1201 /*FIXME: Generate the dummy session key = MD4(MD4(password))*/
1202 memset(helper->session_key, 0 , 16);
1204 else if(strncmp(buffer, "GK ", 3) == 0)
1206 if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len,
1207 &bin_len)) != SEC_E_OK)
1209 TRACE("Failed to decode session key\n");
1211 TRACE("Session key is %s\n", debugstr_a(buffer+3));
1212 helper->session_key = HeapAlloc(GetProcessHeap(), 0, 16);
1213 if(!helper->session_key)
1215 TRACE("Failed to allocate memory for session key\n");
1216 ret = SEC_E_INTERNAL_ERROR;
1219 memcpy(helper->session_key, bin, 16);
1222 helper->crypt.ntlm.a4i = SECUR32_arc4Alloc();
1223 SECUR32_arc4Init(helper->crypt.ntlm.a4i, helper->session_key, 16);
1224 helper->crypt.ntlm.seq_num = 0l;
1227 phNewContext->dwUpper = ctxt_attr;
1228 phNewContext->dwLower = (ULONG_PTR)helper;
1231 HeapFree(GetProcessHeap(), 0, want_flags);
1232 HeapFree(GetProcessHeap(), 0, buffer);
1233 HeapFree(GetProcessHeap(), 0, bin);
1237 /***********************************************************************
1240 static SECURITY_STATUS SEC_ENTRY ntlm_CompleteAuthToken(PCtxtHandle phContext,
1241 PSecBufferDesc pToken)
1243 /* We never need to call CompleteAuthToken anyway */
1244 TRACE("%p %p\n", phContext, pToken);
1246 return SEC_E_INVALID_HANDLE;
1251 /***********************************************************************
1252 * DeleteSecurityContext
1254 static SECURITY_STATUS SEC_ENTRY ntlm_DeleteSecurityContext(PCtxtHandle phContext)
1258 TRACE("%p\n", phContext);
1260 return SEC_E_INVALID_HANDLE;
1262 helper = (PNegoHelper)phContext->dwLower;
1264 phContext->dwUpper = 0;
1265 phContext->dwLower = 0;
1267 SECUR32_arc4Cleanup(helper->crypt.ntlm.a4i);
1268 HeapFree(GetProcessHeap(), 0, helper->session_key);
1269 SECUR32_arc4Cleanup(helper->crypt.ntlm2.send_a4i);
1270 SECUR32_arc4Cleanup(helper->crypt.ntlm2.recv_a4i);
1271 HeapFree(GetProcessHeap(), 0, helper->crypt.ntlm2.send_sign_key);
1272 HeapFree(GetProcessHeap(), 0, helper->crypt.ntlm2.send_seal_key);
1273 HeapFree(GetProcessHeap(), 0, helper->crypt.ntlm2.recv_sign_key);
1274 HeapFree(GetProcessHeap(), 0, helper->crypt.ntlm2.recv_seal_key);
1276 cleanup_helper(helper);
1281 /***********************************************************************
1282 * QueryContextAttributesW
1284 static SECURITY_STATUS SEC_ENTRY ntlm_QueryContextAttributesW(PCtxtHandle phContext,
1285 ULONG ulAttribute, void *pBuffer)
1287 TRACE("%p %d %p\n", phContext, ulAttribute, pBuffer);
1289 return SEC_E_INVALID_HANDLE;
1293 #define _x(x) case (x) : FIXME(#x" stub\n"); break
1294 _x(SECPKG_ATTR_ACCESS_TOKEN);
1295 _x(SECPKG_ATTR_AUTHORITY);
1296 _x(SECPKG_ATTR_DCE_INFO);
1297 case SECPKG_ATTR_FLAGS:
1299 PSecPkgContext_Flags spcf = (PSecPkgContext_Flags)pBuffer;
1300 PNegoHelper helper = (PNegoHelper)phContext->dwLower;
1303 if(helper->neg_flags & NTLMSSP_NEGOTIATE_SIGN)
1304 spcf->Flags |= ISC_RET_INTEGRITY;
1305 if(helper->neg_flags & NTLMSSP_NEGOTIATE_SEAL)
1306 spcf->Flags |= ISC_RET_CONFIDENTIALITY;
1309 _x(SECPKG_ATTR_KEY_INFO);
1310 _x(SECPKG_ATTR_LIFESPAN);
1311 _x(SECPKG_ATTR_NAMES);
1312 _x(SECPKG_ATTR_NATIVE_NAMES);
1313 _x(SECPKG_ATTR_NEGOTIATION_INFO);
1314 _x(SECPKG_ATTR_PACKAGE_INFO);
1315 _x(SECPKG_ATTR_PASSWORD_EXPIRY);
1316 _x(SECPKG_ATTR_SESSION_KEY);
1317 case SECPKG_ATTR_SIZES:
1319 PSecPkgContext_Sizes spcs = (PSecPkgContext_Sizes)pBuffer;
1320 spcs->cbMaxToken = NTLM_MAX_BUF;
1321 spcs->cbMaxSignature = 16;
1322 spcs->cbBlockSize = 0;
1323 spcs->cbSecurityTrailer = 16;
1326 _x(SECPKG_ATTR_STREAM_SIZES);
1327 _x(SECPKG_ATTR_TARGET_INFORMATION);
1330 TRACE("Unknown value %d passed for ulAttribute\n", ulAttribute);
1333 return SEC_E_UNSUPPORTED_FUNCTION;
1336 /***********************************************************************
1337 * QueryContextAttributesA
1339 static SECURITY_STATUS SEC_ENTRY ntlm_QueryContextAttributesA(PCtxtHandle phContext,
1340 ULONG ulAttribute, void *pBuffer)
1342 return ntlm_QueryContextAttributesW(phContext, ulAttribute, pBuffer);
1345 /***********************************************************************
1346 * ImpersonateSecurityContext
1348 static SECURITY_STATUS SEC_ENTRY ntlm_ImpersonateSecurityContext(PCtxtHandle phContext)
1350 SECURITY_STATUS ret;
1352 TRACE("%p\n", phContext);
1355 ret = SEC_E_UNSUPPORTED_FUNCTION;
1359 ret = SEC_E_INVALID_HANDLE;
1364 /***********************************************************************
1365 * RevertSecurityContext
1367 static SECURITY_STATUS SEC_ENTRY ntlm_RevertSecurityContext(PCtxtHandle phContext)
1369 SECURITY_STATUS ret;
1371 TRACE("%p\n", phContext);
1374 ret = SEC_E_UNSUPPORTED_FUNCTION;
1378 ret = SEC_E_INVALID_HANDLE;
1383 /***********************************************************************
1384 * ntlm_CreateSignature
1385 * As both MakeSignature and VerifySignature need this, but different keys
1386 * are needed for NTLMv2, the logic goes into a helper function.
1387 * To ensure maximal reusability, we can specify the direction as NTLM_SEND for
1388 * signing/encrypting and NTLM_RECV for verfying/decrypting. When encrypting,
1389 * the signature is encrypted after the message was encrypted, so
1390 * CreateSignature shouldn't do it. In this case, encrypt_sig can be set to
1393 static SECURITY_STATUS ntlm_CreateSignature(PNegoHelper helper, PSecBufferDesc pMessage,
1394 int token_idx, SignDirection direction, BOOL encrypt_sig)
1396 ULONG sign_version = 1;
1399 TRACE("%p, %p, %d, %d, %d\n", helper, pMessage, token_idx, direction,
1402 sig = pMessage->pBuffers[token_idx].pvBuffer;
1404 if(helper->neg_flags & NTLMSSP_NEGOTIATE_NTLM2 &&
1405 helper->neg_flags & NTLMSSP_NEGOTIATE_SIGN)
1409 HMAC_MD5_CTX hmac_md5_ctx;
1411 TRACE("Signing NTLM2 style\n");
1413 if(direction == NTLM_SEND)
1415 seq_no[0] = (helper->crypt.ntlm2.send_seq_no >> 0) & 0xff;
1416 seq_no[1] = (helper->crypt.ntlm2.send_seq_no >> 8) & 0xff;
1417 seq_no[2] = (helper->crypt.ntlm2.send_seq_no >> 16) & 0xff;
1418 seq_no[3] = (helper->crypt.ntlm2.send_seq_no >> 24) & 0xff;
1420 ++(helper->crypt.ntlm2.send_seq_no);
1422 HMACMD5Init(&hmac_md5_ctx, helper->crypt.ntlm2.send_sign_key, 16);
1426 seq_no[0] = (helper->crypt.ntlm2.recv_seq_no >> 0) & 0xff;
1427 seq_no[1] = (helper->crypt.ntlm2.recv_seq_no >> 8) & 0xff;
1428 seq_no[2] = (helper->crypt.ntlm2.recv_seq_no >> 16) & 0xff;
1429 seq_no[3] = (helper->crypt.ntlm2.recv_seq_no >> 24) & 0xff;
1431 ++(helper->crypt.ntlm2.recv_seq_no);
1433 HMACMD5Init(&hmac_md5_ctx, helper->crypt.ntlm2.recv_sign_key, 16);
1436 HMACMD5Update(&hmac_md5_ctx, seq_no, 4);
1437 for( i = 0; i < pMessage->cBuffers; ++i )
1439 if(pMessage->pBuffers[i].BufferType & SECBUFFER_DATA)
1440 HMACMD5Update(&hmac_md5_ctx, (BYTE *)pMessage->pBuffers[i].pvBuffer,
1441 pMessage->pBuffers[i].cbBuffer);
1444 HMACMD5Final(&hmac_md5_ctx, digest);
1446 if(encrypt_sig && helper->neg_flags & NTLMSSP_NEGOTIATE_KEY_EXCHANGE)
1448 if(direction == NTLM_SEND)
1449 SECUR32_arc4Process(helper->crypt.ntlm2.send_a4i, digest, 8);
1451 SECUR32_arc4Process(helper->crypt.ntlm2.recv_a4i, digest, 8);
1454 /* The NTLM2 signature is the sign version */
1455 sig[ 0] = (sign_version >> 0) & 0xff;
1456 sig[ 1] = (sign_version >> 8) & 0xff;
1457 sig[ 2] = (sign_version >> 16) & 0xff;
1458 sig[ 3] = (sign_version >> 24) & 0xff;
1459 /* The first 8 bytes of the digest */
1460 memcpy(sig+4, digest, 8);
1461 /* And the sequence number */
1462 memcpy(sig+12, seq_no, 4);
1464 pMessage->pBuffers[token_idx].cbBuffer = 16;
1468 if(helper->neg_flags & NTLMSSP_NEGOTIATE_SIGN)
1471 TRACE("Signing NTLM1 style\n");
1473 for(i=0; i < pMessage->cBuffers; ++i)
1475 if(pMessage->pBuffers[i].BufferType & SECBUFFER_DATA)
1477 crc = ComputeCrc32(pMessage->pBuffers[i].pvBuffer,
1478 pMessage->pBuffers[i].cbBuffer, crc);
1482 sig[ 0] = (sign_version >> 0) & 0xff;
1483 sig[ 1] = (sign_version >> 8) & 0xff;
1484 sig[ 2] = (sign_version >> 16) & 0xff;
1485 sig[ 3] = (sign_version >> 24) & 0xff;
1486 memset(sig+4, 0, 4);
1487 sig[ 8] = (crc >> 0) & 0xff;
1488 sig[ 9] = (crc >> 8) & 0xff;
1489 sig[10] = (crc >> 16) & 0xff;
1490 sig[11] = (crc >> 24) & 0xff;
1491 sig[12] = (helper->crypt.ntlm.seq_num >> 0) & 0xff;
1492 sig[13] = (helper->crypt.ntlm.seq_num >> 8) & 0xff;
1493 sig[14] = (helper->crypt.ntlm.seq_num >> 16) & 0xff;
1494 sig[15] = (helper->crypt.ntlm.seq_num >> 24) & 0xff;
1496 ++(helper->crypt.ntlm.seq_num);
1499 SECUR32_arc4Process(helper->crypt.ntlm.a4i, sig+4, 12);
1503 if(helper->neg_flags & NTLMSSP_NEGOTIATE_ALWAYS_SIGN || helper->neg_flags == 0)
1505 TRACE("Creating a dummy signature.\n");
1506 /* A dummy signature is 0x01 followed by 15 bytes of 0x00 */
1507 memset(pMessage->pBuffers[token_idx].pvBuffer, 0, 16);
1508 memset(pMessage->pBuffers[token_idx].pvBuffer, 0x01, 1);
1509 pMessage->pBuffers[token_idx].cbBuffer = 16;
1513 return SEC_E_UNSUPPORTED_FUNCTION;
1516 /***********************************************************************
1519 static SECURITY_STATUS SEC_ENTRY ntlm_MakeSignature(PCtxtHandle phContext, ULONG fQOP,
1520 PSecBufferDesc pMessage, ULONG MessageSeqNo)
1525 TRACE("%p %d %p %d\n", phContext, fQOP, pMessage, MessageSeqNo);
1527 return SEC_E_INVALID_HANDLE;
1530 FIXME("Ignoring fQOP 0x%08x\n", fQOP);
1533 FIXME("Ignoring MessageSeqNo\n");
1535 if(!pMessage || !pMessage->pBuffers || pMessage->cBuffers < 2)
1536 return SEC_E_INVALID_TOKEN;
1538 /* If we didn't find a SECBUFFER_TOKEN type buffer */
1539 if((token_idx = ntlm_GetTokenBufferIndex(pMessage)) == -1)
1540 return SEC_E_INVALID_TOKEN;
1542 if(pMessage->pBuffers[token_idx].cbBuffer < 16)
1543 return SEC_E_BUFFER_TOO_SMALL;
1545 helper = (PNegoHelper)phContext->dwLower;
1546 TRACE("Negotiated flags are: 0x%08lx\n", helper->neg_flags);
1548 return ntlm_CreateSignature(helper, pMessage, token_idx, NTLM_SEND, TRUE);
1551 /***********************************************************************
1554 static SECURITY_STATUS SEC_ENTRY ntlm_VerifySignature(PCtxtHandle phContext,
1555 PSecBufferDesc pMessage, ULONG MessageSeqNo, PULONG pfQOP)
1561 SECURITY_STATUS ret;
1562 SecBufferDesc local_desc;
1563 PSecBuffer local_buff;
1566 TRACE("%p %p %d %p\n", phContext, pMessage, MessageSeqNo, pfQOP);
1568 return SEC_E_INVALID_HANDLE;
1570 if(!pMessage || !pMessage->pBuffers || pMessage->cBuffers < 2)
1571 return SEC_E_INVALID_TOKEN;
1573 if((token_idx = ntlm_GetTokenBufferIndex(pMessage)) == -1)
1574 return SEC_E_INVALID_TOKEN;
1576 if(pMessage->pBuffers[token_idx].cbBuffer < 16)
1577 return SEC_E_BUFFER_TOO_SMALL;
1580 FIXME("Ignoring MessageSeqNo\n");
1582 helper = (PNegoHelper)phContext->dwLower;
1583 TRACE("Negotiated flags: 0x%08lx\n", helper->neg_flags);
1585 local_buff = HeapAlloc(GetProcessHeap(), 0, pMessage->cBuffers * sizeof(SecBuffer));
1587 local_desc.ulVersion = SECBUFFER_VERSION;
1588 local_desc.cBuffers = pMessage->cBuffers;
1589 local_desc.pBuffers = local_buff;
1591 for(i=0; i < pMessage->cBuffers; ++i)
1593 if(pMessage->pBuffers[i].BufferType == SECBUFFER_TOKEN)
1595 local_buff[i].BufferType = SECBUFFER_TOKEN;
1596 local_buff[i].cbBuffer = 16;
1597 local_buff[i].pvBuffer = local_sig;
1601 local_buff[i].BufferType = pMessage->pBuffers[i].BufferType;
1602 local_buff[i].cbBuffer = pMessage->pBuffers[i].cbBuffer;
1603 local_buff[i].pvBuffer = pMessage->pBuffers[i].pvBuffer;
1607 if((ret = ntlm_CreateSignature(helper, &local_desc, token_idx, NTLM_RECV, TRUE)) != SEC_E_OK)
1610 if(memcmp(((PBYTE)local_buff[token_idx].pvBuffer) + 8,
1611 ((PBYTE)pMessage->pBuffers[token_idx].pvBuffer) + 8, 8))
1612 ret = SEC_E_MESSAGE_ALTERED;
1616 HeapFree(GetProcessHeap(), 0, local_buff);
1623 /***********************************************************************
1624 * FreeCredentialsHandle
1626 static SECURITY_STATUS SEC_ENTRY ntlm_FreeCredentialsHandle(
1627 PCredHandle phCredential)
1629 SECURITY_STATUS ret;
1632 PNtlmCredentials ntlm_cred = (PNtlmCredentials) phCredential->dwLower;
1633 phCredential->dwUpper = 0;
1634 phCredential->dwLower = 0;
1635 if (ntlm_cred->password)
1636 memset(ntlm_cred->password, 0, ntlm_cred->pwlen);
1637 HeapFree(GetProcessHeap(), 0, ntlm_cred->password);
1638 HeapFree(GetProcessHeap(), 0, ntlm_cred->username_arg);
1639 HeapFree(GetProcessHeap(), 0, ntlm_cred->domain_arg);
1648 /***********************************************************************
1651 static SECURITY_STATUS SEC_ENTRY ntlm_EncryptMessage(PCtxtHandle phContext,
1652 ULONG fQOP, PSecBufferDesc pMessage, ULONG MessageSeqNo)
1655 int token_idx, data_idx;
1657 TRACE("(%p %d %p %d)\n", phContext, fQOP, pMessage, MessageSeqNo);
1660 return SEC_E_INVALID_HANDLE;
1663 FIXME("Ignoring fQOP\n");
1666 FIXME("Ignoring MessageSeqNo\n");
1668 if(!pMessage || !pMessage->pBuffers || pMessage->cBuffers < 2)
1669 return SEC_E_INVALID_TOKEN;
1671 if((token_idx = ntlm_GetTokenBufferIndex(pMessage)) == -1)
1672 return SEC_E_INVALID_TOKEN;
1674 if((data_idx = ntlm_GetDataBufferIndex(pMessage)) ==-1 )
1675 return SEC_E_INVALID_TOKEN;
1677 if(pMessage->pBuffers[token_idx].cbBuffer < 16)
1678 return SEC_E_BUFFER_TOO_SMALL;
1680 helper = (PNegoHelper) phContext->dwLower;
1682 if(helper->neg_flags & NTLMSSP_NEGOTIATE_NTLM2 &&
1683 helper->neg_flags & NTLMSSP_NEGOTIATE_SEAL)
1685 ntlm_CreateSignature(helper, pMessage, token_idx, NTLM_SEND, FALSE);
1686 SECUR32_arc4Process(helper->crypt.ntlm2.send_a4i,
1687 (BYTE *)pMessage->pBuffers[data_idx].pvBuffer,
1688 pMessage->pBuffers[data_idx].cbBuffer);
1690 if(helper->neg_flags & NTLMSSP_NEGOTIATE_KEY_EXCHANGE)
1691 SECUR32_arc4Process(helper->crypt.ntlm2.send_a4i,
1692 ((BYTE *)pMessage->pBuffers[token_idx].pvBuffer)+4, 8);
1702 /* EncryptMessage always produces real signatures, so make sure
1703 * NTLMSSP_NEGOTIATE_SIGN is set*/
1704 save_flags = helper->neg_flags;
1705 helper->neg_flags |= NTLMSSP_NEGOTIATE_SIGN;
1706 ntlm_CreateSignature(helper, pMessage, token_idx, NTLM_SEND, FALSE);
1707 helper->neg_flags = save_flags;
1709 sig = pMessage->pBuffers[token_idx].pvBuffer;
1711 SECUR32_arc4Process(helper->crypt.ntlm.a4i,
1712 pMessage->pBuffers[data_idx].pvBuffer,
1713 pMessage->pBuffers[data_idx].cbBuffer);
1714 SECUR32_arc4Process(helper->crypt.ntlm.a4i, sig+4, 12);
1716 if(helper->neg_flags & NTLMSSP_NEGOTIATE_ALWAYS_SIGN || helper->neg_flags == 0)
1717 memset(sig+4, 0, 4);
1724 /***********************************************************************
1727 static SECURITY_STATUS SEC_ENTRY ntlm_DecryptMessage(PCtxtHandle phContext,
1728 PSecBufferDesc pMessage, ULONG MessageSeqNo, PULONG pfQOP)
1730 SECURITY_STATUS ret;
1731 ULONG ntlmssp_flags_save;
1733 int token_idx, data_idx;
1734 TRACE("(%p %p %d %p)\n", phContext, pMessage, MessageSeqNo, pfQOP);
1737 return SEC_E_INVALID_HANDLE;
1740 FIXME("Ignoring MessageSeqNo\n");
1742 if(!pMessage || !pMessage->pBuffers || pMessage->cBuffers < 2)
1743 return SEC_E_INVALID_TOKEN;
1745 if((token_idx = ntlm_GetTokenBufferIndex(pMessage)) == -1)
1746 return SEC_E_INVALID_TOKEN;
1748 if((data_idx = ntlm_GetDataBufferIndex(pMessage)) ==-1)
1749 return SEC_E_INVALID_TOKEN;
1751 if(pMessage->pBuffers[token_idx].cbBuffer < 16)
1752 return SEC_E_BUFFER_TOO_SMALL;
1754 helper = (PNegoHelper) phContext->dwLower;
1756 if(helper->neg_flags & NTLMSSP_NEGOTIATE_NTLM2 && helper->neg_flags & NTLMSSP_NEGOTIATE_SEAL)
1758 SECUR32_arc4Process(helper->crypt.ntlm2.recv_a4i,
1759 pMessage->pBuffers[data_idx].pvBuffer,
1760 pMessage->pBuffers[data_idx].cbBuffer);
1764 SECUR32_arc4Process(helper->crypt.ntlm.a4i,
1765 pMessage->pBuffers[data_idx].pvBuffer,
1766 pMessage->pBuffers[data_idx].cbBuffer);
1769 /* Make sure we use a session key for the signature check, EncryptMessage
1770 * always does that, even in the dummy case */
1771 ntlmssp_flags_save = helper->neg_flags;
1773 helper->neg_flags |= NTLMSSP_NEGOTIATE_SIGN;
1774 ret = ntlm_VerifySignature(phContext, pMessage, MessageSeqNo, pfQOP);
1776 helper->neg_flags = ntlmssp_flags_save;
1781 static const SecurityFunctionTableA ntlmTableA = {
1783 NULL, /* EnumerateSecurityPackagesA */
1784 ntlm_QueryCredentialsAttributesA, /* QueryCredentialsAttributesA */
1785 ntlm_AcquireCredentialsHandleA, /* AcquireCredentialsHandleA */
1786 ntlm_FreeCredentialsHandle, /* FreeCredentialsHandle */
1787 NULL, /* Reserved2 */
1788 ntlm_InitializeSecurityContextA, /* InitializeSecurityContextA */
1789 ntlm_AcceptSecurityContext, /* AcceptSecurityContext */
1790 ntlm_CompleteAuthToken, /* CompleteAuthToken */
1791 ntlm_DeleteSecurityContext, /* DeleteSecurityContext */
1792 NULL, /* ApplyControlToken */
1793 ntlm_QueryContextAttributesA, /* QueryContextAttributesA */
1794 ntlm_ImpersonateSecurityContext, /* ImpersonateSecurityContext */
1795 ntlm_RevertSecurityContext, /* RevertSecurityContext */
1796 ntlm_MakeSignature, /* MakeSignature */
1797 ntlm_VerifySignature, /* VerifySignature */
1798 FreeContextBuffer, /* FreeContextBuffer */
1799 NULL, /* QuerySecurityPackageInfoA */
1800 NULL, /* Reserved3 */
1801 NULL, /* Reserved4 */
1802 NULL, /* ExportSecurityContext */
1803 NULL, /* ImportSecurityContextA */
1804 NULL, /* AddCredentialsA */
1805 NULL, /* Reserved8 */
1806 NULL, /* QuerySecurityContextToken */
1807 ntlm_EncryptMessage, /* EncryptMessage */
1808 ntlm_DecryptMessage, /* DecryptMessage */
1809 NULL, /* SetContextAttributesA */
1812 static const SecurityFunctionTableW ntlmTableW = {
1814 NULL, /* EnumerateSecurityPackagesW */
1815 ntlm_QueryCredentialsAttributesW, /* QueryCredentialsAttributesW */
1816 ntlm_AcquireCredentialsHandleW, /* AcquireCredentialsHandleW */
1817 ntlm_FreeCredentialsHandle, /* FreeCredentialsHandle */
1818 NULL, /* Reserved2 */
1819 ntlm_InitializeSecurityContextW, /* InitializeSecurityContextW */
1820 ntlm_AcceptSecurityContext, /* AcceptSecurityContext */
1821 ntlm_CompleteAuthToken, /* CompleteAuthToken */
1822 ntlm_DeleteSecurityContext, /* DeleteSecurityContext */
1823 NULL, /* ApplyControlToken */
1824 ntlm_QueryContextAttributesW, /* QueryContextAttributesW */
1825 ntlm_ImpersonateSecurityContext, /* ImpersonateSecurityContext */
1826 ntlm_RevertSecurityContext, /* RevertSecurityContext */
1827 ntlm_MakeSignature, /* MakeSignature */
1828 ntlm_VerifySignature, /* VerifySignature */
1829 FreeContextBuffer, /* FreeContextBuffer */
1830 NULL, /* QuerySecurityPackageInfoW */
1831 NULL, /* Reserved3 */
1832 NULL, /* Reserved4 */
1833 NULL, /* ExportSecurityContext */
1834 NULL, /* ImportSecurityContextW */
1835 NULL, /* AddCredentialsW */
1836 NULL, /* Reserved8 */
1837 NULL, /* QuerySecurityContextToken */
1838 ntlm_EncryptMessage, /* EncryptMessage */
1839 ntlm_DecryptMessage, /* DecryptMessage */
1840 NULL, /* SetContextAttributesW */
1843 #define NTLM_COMMENT \
1844 { 'N', 'T', 'L', 'M', ' ', \
1845 'S', 'e', 'c', 'u', 'r', 'i', 't', 'y', ' ', \
1846 'P', 'a', 'c', 'k', 'a', 'g', 'e', 0}
1848 static CHAR ntlm_comment_A[] = NTLM_COMMENT;
1849 static WCHAR ntlm_comment_W[] = NTLM_COMMENT;
1851 #define NTLM_NAME {'N', 'T', 'L', 'M', 0}
1853 static char ntlm_name_A[] = NTLM_NAME;
1854 static WCHAR ntlm_name_W[] = NTLM_NAME;
1856 /* According to Windows, NTLM has the following capabilities. */
1858 SECPKG_FLAG_INTEGRITY | \
1859 SECPKG_FLAG_PRIVACY | \
1860 SECPKG_FLAG_TOKEN_ONLY | \
1861 SECPKG_FLAG_CONNECTION | \
1862 SECPKG_FLAG_MULTI_REQUIRED | \
1863 SECPKG_FLAG_IMPERSONATION | \
1864 SECPKG_FLAG_ACCEPT_WIN32_NAME | \
1865 SECPKG_FLAG_READONLY_WITH_CHECKSUM)
1867 static const SecPkgInfoW infoW = {
1876 static const SecPkgInfoA infoA = {
1885 void SECUR32_initNTLMSP(void)
1887 SECURITY_STATUS ret;
1889 static CHAR version[] = "--version";
1891 SEC_CHAR *args[] = {
1896 if((ret = fork_helper(&helper, ntlm_auth, args)) != SEC_E_OK)
1898 /* Cheat and allocate a helper anyway, so cleanup later will work. */
1899 helper = HeapAlloc(GetProcessHeap(),0, sizeof(PNegoHelper));
1900 helper->major = helper->minor = helper->micro = -1;
1903 check_version(helper);
1905 if( (helper->major > MIN_NTLM_AUTH_MAJOR_VERSION) ||
1906 (helper->major == MIN_NTLM_AUTH_MAJOR_VERSION &&
1907 helper->minor > MIN_NTLM_AUTH_MINOR_VERSION) ||
1908 (helper->major == MIN_NTLM_AUTH_MAJOR_VERSION &&
1909 helper->minor == MIN_NTLM_AUTH_MINOR_VERSION &&
1910 helper->micro >= MIN_NTLM_AUTH_MICRO_VERSION) )
1912 SecureProvider *provider = SECUR32_addProvider(&ntlmTableA, &ntlmTableW, NULL);
1913 SECUR32_addPackages(provider, 1L, &infoA, &infoW);
1917 ERR("%s was not found or is outdated. "
1918 "Make sure that ntlm_auth >= %d.%d.%d is in your path.\n",
1920 MIN_NTLM_AUTH_MAJOR_VERSION,
1921 MIN_NTLM_AUTH_MINOR_VERSION,
1922 MIN_NTLM_AUTH_MICRO_VERSION);
1923 ERR("Usually, you can find it in the winbind package of your "
1927 cleanup_helper(helper);