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.
31 #include "secur32_priv.h"
33 #include "wine/unicode.h"
34 #include "wine/debug.h"
36 WINE_DEFAULT_DEBUG_CHANNEL(ntlm);
38 #define NTLM_MAX_BUF 1904
39 #define MIN_NTLM_AUTH_MAJOR_VERSION 3
40 #define MIN_NTLM_AUTH_MINOR_VERSION 0
41 #define MIN_NTLM_AUTH_MICRO_VERSION 25
43 static CHAR ntlm_auth[] = "ntlm_auth";
45 typedef struct _NtlmCredentials
49 /* these are all in the Unix codepage */
52 char *password; /* not nul-terminated */
54 } NtlmCredentials, *PNtlmCredentials;
56 /***********************************************************************
57 * QueryCredentialsAttributesA
59 static SECURITY_STATUS SEC_ENTRY ntlm_QueryCredentialsAttributesA(
60 PCredHandle phCredential, ULONG ulAttribute, PVOID pBuffer)
64 TRACE("(%p, %d, %p)\n", phCredential, ulAttribute, pBuffer);
66 if(ulAttribute == SECPKG_ATTR_NAMES)
68 FIXME("SECPKG_CRED_ATTR_NAMES: stub\n");
69 ret = SEC_E_UNSUPPORTED_FUNCTION;
72 ret = SEC_E_UNSUPPORTED_FUNCTION;
77 /***********************************************************************
78 * QueryCredentialsAttributesW
80 static SECURITY_STATUS SEC_ENTRY ntlm_QueryCredentialsAttributesW(
81 PCredHandle phCredential, ULONG ulAttribute, PVOID pBuffer)
85 TRACE("(%p, %d, %p)\n", phCredential, ulAttribute, pBuffer);
87 if(ulAttribute == SECPKG_ATTR_NAMES)
89 FIXME("SECPKG_CRED_ATTR_NAMES: stub\n");
90 ret = SEC_E_UNSUPPORTED_FUNCTION;
93 ret = SEC_E_UNSUPPORTED_FUNCTION;
98 static char *ntlm_GetUsernameArg(LPCWSTR userW, INT userW_length)
100 static const char username_arg[] = "--username=";
104 unixcp_size = WideCharToMultiByte(CP_UNIXCP, WC_NO_BEST_FIT_CHARS,
105 userW, userW_length, NULL, 0, NULL, NULL) + sizeof(username_arg);
106 user = HeapAlloc(GetProcessHeap(), 0, unixcp_size);
107 if (!user) return NULL;
108 memcpy(user, username_arg, sizeof(username_arg) - 1);
109 WideCharToMultiByte(CP_UNIXCP, WC_NO_BEST_FIT_CHARS, userW, userW_length,
110 user + sizeof(username_arg) - 1,
111 unixcp_size - sizeof(username_arg) + 1, NULL, NULL);
112 user[unixcp_size - 1] = '\0';
116 static char *ntlm_GetDomainArg(LPCWSTR domainW, INT domainW_length)
118 static const char domain_arg[] = "--domain=";
122 unixcp_size = WideCharToMultiByte(CP_UNIXCP, WC_NO_BEST_FIT_CHARS,
123 domainW, domainW_length, NULL, 0, NULL, NULL) + sizeof(domain_arg);
124 domain = HeapAlloc(GetProcessHeap(), 0, unixcp_size);
125 if (!domain) return NULL;
126 memcpy(domain, domain_arg, sizeof(domain_arg) - 1);
127 WideCharToMultiByte(CP_UNIXCP, WC_NO_BEST_FIT_CHARS, domainW,
128 domainW_length, domain + sizeof(domain_arg) - 1,
129 unixcp_size - sizeof(domain) + 1, NULL, NULL);
130 domain[unixcp_size - 1] = '\0';
134 /***********************************************************************
135 * AcquireCredentialsHandleW
137 static SECURITY_STATUS SEC_ENTRY ntlm_AcquireCredentialsHandleW(
138 SEC_WCHAR *pszPrincipal, SEC_WCHAR *pszPackage, ULONG fCredentialUse,
139 PLUID pLogonID, PVOID pAuthData, SEC_GET_KEY_FN pGetKeyFn,
140 PVOID pGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
143 PNtlmCredentials ntlm_cred = NULL;
144 SEC_WCHAR *username = NULL, *domain = NULL;
146 TRACE("(%s, %s, 0x%08x, %p, %p, %p, %p, %p, %p)\n",
147 debugstr_w(pszPrincipal), debugstr_w(pszPackage), fCredentialUse,
148 pLogonID, pAuthData, pGetKeyFn, pGetKeyArgument, phCredential, ptsExpiry);
150 switch(fCredentialUse)
152 case SECPKG_CRED_INBOUND:
153 ntlm_cred = HeapAlloc(GetProcessHeap(), 0, sizeof(*ntlm_cred));
155 ret = SEC_E_INSUFFICIENT_MEMORY;
158 ntlm_cred->mode = NTLM_SERVER;
159 ntlm_cred->username_arg = NULL;
160 ntlm_cred->domain_arg = NULL;
161 ntlm_cred->password = NULL;
162 ntlm_cred->pwlen = 0;
163 phCredential->dwUpper = fCredentialUse;
164 phCredential->dwLower = (ULONG_PTR)ntlm_cred;
168 case SECPKG_CRED_OUTBOUND:
170 ntlm_cred = HeapAlloc(GetProcessHeap(), 0, sizeof(*ntlm_cred));
173 ret = SEC_E_INSUFFICIENT_MEMORY;
176 ntlm_cred->mode = NTLM_CLIENT;
177 ntlm_cred->username_arg = NULL;
178 ntlm_cred->domain_arg = NULL;
179 ntlm_cred->password = NULL;
180 ntlm_cred->pwlen = 0;
182 if(pAuthData != NULL)
184 PSEC_WINNT_AUTH_IDENTITY_W auth_data =
185 (PSEC_WINNT_AUTH_IDENTITY_W)pAuthData;
187 TRACE("Username is %s\n", debugstr_wn(auth_data->User, auth_data->UserLength));
188 TRACE("Domain name is %s\n", debugstr_wn(auth_data->Domain, auth_data->DomainLength));
190 ntlm_cred->username_arg = ntlm_GetUsernameArg(auth_data->User, auth_data->UserLength);
191 ntlm_cred->domain_arg = ntlm_GetDomainArg(auth_data->Domain, auth_data->DomainLength);
193 if(auth_data->PasswordLength != 0)
195 ntlm_cred->pwlen = WideCharToMultiByte(CP_UNIXCP,
196 WC_NO_BEST_FIT_CHARS, auth_data->Password,
197 auth_data->PasswordLength, NULL, 0, NULL,
200 ntlm_cred->password = HeapAlloc(GetProcessHeap(), 0,
203 WideCharToMultiByte(CP_UNIXCP, WC_NO_BEST_FIT_CHARS,
204 auth_data->Password, auth_data->PasswordLength,
205 ntlm_cred->password, ntlm_cred->pwlen, NULL, NULL);
209 phCredential->dwUpper = fCredentialUse;
210 phCredential->dwLower = (ULONG_PTR)ntlm_cred;
211 TRACE("ACH phCredential->dwUpper: 0x%08lx, dwLower: 0x%08lx\n",
212 phCredential->dwUpper, phCredential->dwLower);
216 case SECPKG_CRED_BOTH:
217 FIXME("AcquireCredentialsHandle: SECPKG_CRED_BOTH stub\n");
218 ret = SEC_E_UNSUPPORTED_FUNCTION;
223 ret = SEC_E_UNKNOWN_CREDENTIALS;
226 HeapFree(GetProcessHeap(), 0, username);
227 HeapFree(GetProcessHeap(), 0, domain);
232 /***********************************************************************
233 * AcquireCredentialsHandleA
235 static SECURITY_STATUS SEC_ENTRY ntlm_AcquireCredentialsHandleA(
236 SEC_CHAR *pszPrincipal, SEC_CHAR *pszPackage, ULONG fCredentialUse,
237 PLUID pLogonID, PVOID pAuthData, SEC_GET_KEY_FN pGetKeyFn,
238 PVOID pGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
241 int user_sizeW, domain_sizeW, passwd_sizeW;
243 SEC_WCHAR *user = NULL, *domain = NULL, *passwd = NULL, *package = NULL;
245 PSEC_WINNT_AUTH_IDENTITY_W pAuthDataW = NULL;
246 PSEC_WINNT_AUTH_IDENTITY_A identity = NULL;
248 TRACE("(%s, %s, 0x%08x, %p, %p, %p, %p, %p, %p)\n",
249 debugstr_a(pszPrincipal), debugstr_a(pszPackage), fCredentialUse,
250 pLogonID, pAuthData, pGetKeyFn, pGetKeyArgument, phCredential, ptsExpiry);
252 if(pszPackage != NULL)
254 int package_sizeW = MultiByteToWideChar(CP_ACP, 0, pszPackage, -1,
257 package = HeapAlloc(GetProcessHeap(), 0, package_sizeW *
259 MultiByteToWideChar(CP_ACP, 0, pszPackage, -1, package, package_sizeW);
263 if(pAuthData != NULL)
265 identity = (PSEC_WINNT_AUTH_IDENTITY_A)pAuthData;
267 if(identity->Flags == SEC_WINNT_AUTH_IDENTITY_ANSI)
269 pAuthDataW = HeapAlloc(GetProcessHeap(), 0,
270 sizeof(SEC_WINNT_AUTH_IDENTITY_W));
272 if(identity->UserLength != 0)
274 user_sizeW = MultiByteToWideChar(CP_ACP, 0,
275 (LPCSTR)identity->User, identity->UserLength, NULL, 0);
276 user = HeapAlloc(GetProcessHeap(), 0, user_sizeW *
278 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)identity->User,
279 identity->UserLength, user, user_sizeW);
286 if(identity->DomainLength != 0)
288 domain_sizeW = MultiByteToWideChar(CP_ACP, 0,
289 (LPCSTR)identity->Domain, identity->DomainLength, NULL, 0);
290 domain = HeapAlloc(GetProcessHeap(), 0, domain_sizeW
291 * sizeof(SEC_WCHAR));
292 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)identity->Domain,
293 identity->DomainLength, domain, domain_sizeW);
300 if(identity->PasswordLength != 0)
302 passwd_sizeW = MultiByteToWideChar(CP_ACP, 0,
303 (LPCSTR)identity->Password, identity->PasswordLength,
305 passwd = HeapAlloc(GetProcessHeap(), 0, passwd_sizeW
306 * sizeof(SEC_WCHAR));
307 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)identity->Password,
308 identity->PasswordLength, passwd, passwd_sizeW);
315 pAuthDataW->Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
316 pAuthDataW->User = user;
317 pAuthDataW->UserLength = user_sizeW;
318 pAuthDataW->Domain = domain;
319 pAuthDataW->DomainLength = domain_sizeW;
320 pAuthDataW->Password = passwd;
321 pAuthDataW->PasswordLength = passwd_sizeW;
325 pAuthDataW = (PSEC_WINNT_AUTH_IDENTITY_W)identity;
329 ret = ntlm_AcquireCredentialsHandleW(NULL, package, fCredentialUse,
330 pLogonID, pAuthDataW, pGetKeyFn, pGetKeyArgument, phCredential,
333 HeapFree(GetProcessHeap(), 0, package);
334 HeapFree(GetProcessHeap(), 0, user);
335 HeapFree(GetProcessHeap(), 0, domain);
336 HeapFree(GetProcessHeap(), 0, passwd);
337 if(pAuthDataW != (PSEC_WINNT_AUTH_IDENTITY_W)identity)
338 HeapFree(GetProcessHeap(), 0, pAuthDataW);
343 /*************************************************************************
344 * ntlm_GetTokenBufferIndex
345 * Calculates the index of the secbuffer with BufferType == SECBUFFER_TOKEN
346 * Returns index if found or -1 if not found.
348 static int ntlm_GetTokenBufferIndex(PSecBufferDesc pMessage)
352 TRACE("%p\n", pMessage);
354 for( i = 0; i < pMessage->cBuffers; ++i )
356 if(pMessage->pBuffers[i].BufferType == SECBUFFER_TOKEN)
363 /*************************************************************************
364 * ntlm_GetDataBufferIndex
365 * Calculates the index of the first secbuffer with BufferType == SECBUFFER_DATA
366 * Returns index if found or -1 if not found.
368 static int ntlm_GetDataBufferIndex(PSecBufferDesc pMessage)
372 TRACE("%p\n", pMessage);
374 for( i = 0; i < pMessage->cBuffers; ++i )
376 if(pMessage->pBuffers[i].BufferType == SECBUFFER_DATA)
383 static BOOL ntlm_GetCachedCredential(const SEC_WCHAR *pszTargetName, PCREDENTIALW *cred)
393 /* try to get the start of the hostname from service principal name (SPN) */
394 pszHost = strchrW(pszTargetName, '/');
397 /* skip slash character */
400 /* find end of host by detecting start of instance port or start of referrer */
401 p = strchrW(pszHost, ':');
403 p = strchrW(pszHost, '/');
405 p = pszHost + strlenW(pszHost);
407 else /* otherwise not an SPN, just a host */
409 pszHost = pszTargetName;
410 p = pszHost + strlenW(pszHost);
413 pszHostOnly = HeapAlloc(GetProcessHeap(), 0, (p - pszHost + 1) * sizeof(WCHAR));
417 memcpy(pszHostOnly, pszHost, (p - pszHost) * sizeof(WCHAR));
418 pszHostOnly[p - pszHost] = '\0';
420 ret = CredReadW(pszHostOnly, CRED_TYPE_DOMAIN_PASSWORD, 0, cred);
422 HeapFree(GetProcessHeap(), 0, pszHostOnly);
426 /***********************************************************************
427 * InitializeSecurityContextW
429 static SECURITY_STATUS SEC_ENTRY ntlm_InitializeSecurityContextW(
430 PCredHandle phCredential, PCtxtHandle phContext, SEC_WCHAR *pszTargetName,
431 ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep,
432 PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext,
433 PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
436 PNtlmCredentials ntlm_cred = NULL;
437 PNegoHelper helper = NULL;
439 char* buffer, *want_flags = NULL;
441 int buffer_len, bin_len, max_len = NTLM_MAX_BUF;
443 SEC_CHAR *username = NULL;
444 SEC_CHAR *domain = NULL;
445 SEC_CHAR *password = NULL;
447 TRACE("%p %p %s %d %d %d %p %d %p %p %p %p\n", phCredential, phContext,
448 debugstr_w(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
449 Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
451 /****************************************
452 * When communicating with the client, there can be the
453 * following reply packets:
454 * YR <base64 blob> should be sent to the server
455 * PW should be sent back to helper with
456 * base64 encoded password
457 * AF <base64 blob> client is done, blob should be
458 * sent to server with KK prefixed
459 * GF <string list> A string list of negotiated flags
460 * GK <base64 blob> base64 encoded session key
461 * BH <char reason> something broke
463 /* The squid cache size is 2010 chars, and that's what ntlm_auth uses */
465 if(TargetDataRep == SECURITY_NETWORK_DREP){
466 TRACE("Setting SECURITY_NETWORK_DREP\n");
469 buffer = HeapAlloc(GetProcessHeap(), 0, sizeof(char) * NTLM_MAX_BUF);
470 bin = HeapAlloc(GetProcessHeap(), 0, sizeof(BYTE) * NTLM_MAX_BUF);
472 if((phContext == NULL) && (pInput == NULL))
474 static char helper_protocol[] = "--helper-protocol=ntlmssp-client-1";
475 static CHAR credentials_argv[] = "--use-cached-creds";
476 SEC_CHAR *client_argv[5];
479 TRACE("First time in ISC()\n");
483 ret = SEC_E_INVALID_HANDLE;
487 /* As the server side of sspi never calls this, make sure that
488 * the handler is a client handler.
490 ntlm_cred = (PNtlmCredentials)phCredential->dwLower;
491 if(ntlm_cred->mode != NTLM_CLIENT)
493 TRACE("Cred mode = %d\n", ntlm_cred->mode);
494 ret = SEC_E_INVALID_HANDLE;
498 client_argv[0] = ntlm_auth;
499 client_argv[1] = helper_protocol;
500 if (!ntlm_cred->username_arg && !ntlm_cred->domain_arg)
502 LPWKSTA_USER_INFO_1 ui = NULL;
503 NET_API_STATUS status;
506 if (ntlm_GetCachedCredential(pszTargetName, &cred))
509 p = strchrW(cred->UserName, '\\');
512 domain = ntlm_GetDomainArg(cred->UserName, p - cred->UserName);
517 domain = ntlm_GetDomainArg(NULL, 0);
521 username = ntlm_GetUsernameArg(p, -1);
523 if(cred->CredentialBlobSize != 0)
525 pwlen = WideCharToMultiByte(CP_UNIXCP,
526 WC_NO_BEST_FIT_CHARS, (LPWSTR)cred->CredentialBlob,
527 cred->CredentialBlobSize / sizeof(WCHAR), NULL, 0,
530 password = HeapAlloc(GetProcessHeap(), 0, pwlen);
532 WideCharToMultiByte(CP_UNIXCP, WC_NO_BEST_FIT_CHARS,
533 (LPWSTR)cred->CredentialBlob,
534 cred->CredentialBlobSize / sizeof(WCHAR),
535 password, pwlen, NULL, NULL);
540 client_argv[2] = username;
541 client_argv[3] = domain;
542 client_argv[4] = NULL;
546 status = NetWkstaUserGetInfo(NULL, 1, (LPBYTE *)&ui);
547 if (status != NERR_Success || ui == NULL)
549 ret = SEC_E_NO_CREDENTIALS;
552 username = ntlm_GetUsernameArg(ui->wkui1_username, -1);
554 TRACE("using cached credentials\n");
556 client_argv[2] = username;
557 client_argv[3] = credentials_argv;
558 client_argv[4] = NULL;
563 client_argv[2] = ntlm_cred->username_arg;
564 client_argv[3] = ntlm_cred->domain_arg;
565 client_argv[4] = NULL;
568 if((ret = fork_helper(&helper, ntlm_auth, client_argv)) != SEC_E_OK)
571 helper->mode = NTLM_CLIENT;
572 helper->session_key = HeapAlloc(GetProcessHeap(), 0, 16);
573 if (!helper->session_key)
575 cleanup_helper(helper);
576 ret = SEC_E_INSUFFICIENT_MEMORY;
580 /* Generate the dummy session key = MD4(MD4(password))*/
581 if(password || ntlm_cred->password)
583 SEC_WCHAR *unicode_password;
586 TRACE("Converting password to unicode.\n");
587 passwd_lenW = MultiByteToWideChar(CP_ACP, 0,
588 password ? (LPCSTR)password : (LPCSTR)ntlm_cred->password,
589 password ? pwlen : ntlm_cred->pwlen,
591 unicode_password = HeapAlloc(GetProcessHeap(), 0,
592 passwd_lenW * sizeof(SEC_WCHAR));
593 MultiByteToWideChar(CP_ACP, 0, password ? (LPCSTR)password : (LPCSTR)ntlm_cred->password,
594 password ? pwlen : ntlm_cred->pwlen, unicode_password, passwd_lenW);
596 SECUR32_CreateNTLMv1SessionKey((PBYTE)unicode_password,
597 passwd_lenW * sizeof(SEC_WCHAR), helper->session_key);
599 HeapFree(GetProcessHeap(), 0, unicode_password);
602 memset(helper->session_key, 0, 16);
604 /* Allocate space for a maximal string of
605 * "SF NTLMSSP_FEATURE_SIGN NTLMSSP_FEATURE_SEAL
606 * NTLMSSP_FEATURE_SESSION_KEY"
608 want_flags = HeapAlloc(GetProcessHeap(), 0, 73);
609 if(want_flags == NULL)
611 cleanup_helper(helper);
612 ret = SEC_E_INSUFFICIENT_MEMORY;
615 lstrcpyA(want_flags, "SF");
616 if(fContextReq & ISC_REQ_CONFIDENTIALITY)
618 if(strstr(want_flags, "NTLMSSP_FEATURE_SEAL") == NULL)
619 lstrcatA(want_flags, " NTLMSSP_FEATURE_SEAL");
621 if(fContextReq & ISC_REQ_CONNECTION)
622 ctxt_attr |= ISC_RET_CONNECTION;
623 if(fContextReq & ISC_REQ_EXTENDED_ERROR)
624 ctxt_attr |= ISC_RET_EXTENDED_ERROR;
625 if(fContextReq & ISC_REQ_INTEGRITY)
627 if(strstr(want_flags, "NTLMSSP_FEATURE_SIGN") == NULL)
628 lstrcatA(want_flags, " NTLMSSP_FEATURE_SIGN");
630 if(fContextReq & ISC_REQ_MUTUAL_AUTH)
631 ctxt_attr |= ISC_RET_MUTUAL_AUTH;
632 if(fContextReq & ISC_REQ_REPLAY_DETECT)
634 if(strstr(want_flags, "NTLMSSP_FEATURE_SIGN") == NULL)
635 lstrcatA(want_flags, " NTLMSSP_FEATURE_SIGN");
637 if(fContextReq & ISC_REQ_SEQUENCE_DETECT)
639 if(strstr(want_flags, "NTLMSSP_FEATURE_SIGN") == NULL)
640 lstrcatA(want_flags, " NTLMSSP_FEATURE_SIGN");
642 if(fContextReq & ISC_REQ_STREAM)
643 FIXME("ISC_REQ_STREAM\n");
644 if(fContextReq & ISC_REQ_USE_DCE_STYLE)
645 ctxt_attr |= ISC_RET_USED_DCE_STYLE;
646 if(fContextReq & ISC_REQ_DELEGATE)
647 ctxt_attr |= ISC_RET_DELEGATE;
649 /* If no password is given, try to use cached credentials. Fall back to an empty
650 * password if this failed. */
651 if(!password && !ntlm_cred->password)
653 lstrcpynA(buffer, "OK", max_len-1);
654 if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
656 cleanup_helper(helper);
659 /* If the helper replied with "PW", using cached credentials failed */
660 if(!strncmp(buffer, "PW", 2))
662 TRACE("Using cached credentials failed.\n");
663 ret = SEC_E_NO_CREDENTIALS;
666 else /* Just do a noop on the next run */
667 lstrcpynA(buffer, "OK", max_len-1);
671 lstrcpynA(buffer, "PW ", max_len-1);
672 if((ret = encodeBase64(password ? (unsigned char *)password : (unsigned char *)ntlm_cred->password,
673 password ? pwlen : ntlm_cred->pwlen, buffer+3,
674 max_len-3, &buffer_len)) != SEC_E_OK)
676 cleanup_helper(helper);
682 TRACE("Sending to helper: %s\n", debugstr_a(buffer));
683 if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
685 cleanup_helper(helper);
689 TRACE("Helper returned %s\n", debugstr_a(buffer));
691 if(lstrlenA(want_flags) > 2)
693 TRACE("Want flags are %s\n", debugstr_a(want_flags));
694 lstrcpynA(buffer, want_flags, max_len-1);
695 if((ret = run_helper(helper, buffer, max_len, &buffer_len))
698 if(!strncmp(buffer, "BH", 2))
699 ERR("Helper doesn't understand new command set. Expect more things to fail.\n");
702 lstrcpynA(buffer, "YR", max_len-1);
704 if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
706 cleanup_helper(helper);
710 TRACE("%s\n", buffer);
712 if(strncmp(buffer, "YR ", 3) != 0)
714 /* Something borked */
715 TRACE("Helper returned %c%c\n", buffer[0], buffer[1]);
716 ret = SEC_E_INTERNAL_ERROR;
717 cleanup_helper(helper);
720 if((ret = decodeBase64(buffer+3, buffer_len-3, bin,
721 max_len-1, &bin_len)) != SEC_E_OK)
723 cleanup_helper(helper);
727 /* put the decoded client blob into the out buffer */
729 phNewContext->dwUpper = ctxt_attr;
730 phNewContext->dwLower = (ULONG_PTR)helper;
732 ret = SEC_I_CONTINUE_NEEDED;
738 /* handle second call here */
739 /* encode server data to base64 */
740 if (!pInput || ((input_token_idx = ntlm_GetTokenBufferIndex(pInput)) == -1))
742 ret = SEC_E_INVALID_TOKEN;
748 ret = SEC_E_INVALID_HANDLE;
752 /* As the server side of sspi never calls this, make sure that
753 * the handler is a client handler.
755 helper = (PNegoHelper)phContext->dwLower;
756 if(helper->mode != NTLM_CLIENT)
758 TRACE("Helper mode = %d\n", helper->mode);
759 ret = SEC_E_INVALID_HANDLE;
763 if (!pInput->pBuffers[input_token_idx].pvBuffer)
765 ret = SEC_E_INTERNAL_ERROR;
769 if(pInput->pBuffers[input_token_idx].cbBuffer > max_len)
771 TRACE("pInput->pBuffers[%d].cbBuffer is: %ld\n",
773 pInput->pBuffers[input_token_idx].cbBuffer);
774 ret = SEC_E_INVALID_TOKEN;
778 bin_len = pInput->pBuffers[input_token_idx].cbBuffer;
780 memcpy(bin, pInput->pBuffers[input_token_idx].pvBuffer, bin_len);
782 lstrcpynA(buffer, "TT ", max_len-1);
784 if((ret = encodeBase64(bin, bin_len, buffer+3,
785 max_len-3, &buffer_len)) != SEC_E_OK)
788 TRACE("Server sent: %s\n", debugstr_a(buffer));
790 /* send TT base64 blob to ntlm_auth */
791 if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
794 TRACE("Helper replied: %s\n", debugstr_a(buffer));
796 if( (strncmp(buffer, "KK ", 3) != 0) &&
797 (strncmp(buffer, "AF ", 3) !=0))
799 TRACE("Helper returned %c%c\n", buffer[0], buffer[1]);
800 ret = SEC_E_INVALID_TOKEN;
804 /* decode the blob and send it to server */
805 if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len,
806 &bin_len)) != SEC_E_OK)
811 phNewContext->dwUpper = ctxt_attr;
812 phNewContext->dwLower = (ULONG_PTR)helper;
817 /* put the decoded client blob into the out buffer */
819 if (!pOutput || ((token_idx = ntlm_GetTokenBufferIndex(pOutput)) == -1))
821 TRACE("no SECBUFFER_TOKEN buffer could be found\n");
822 ret = SEC_E_BUFFER_TOO_SMALL;
823 if ((phContext == NULL) && (pInput == NULL))
825 cleanup_helper(helper);
826 phNewContext->dwUpper = 0;
827 phNewContext->dwLower = 0;
832 if (fContextReq & ISC_REQ_ALLOCATE_MEMORY)
834 pOutput->pBuffers[token_idx].pvBuffer = HeapAlloc(GetProcessHeap(), 0, bin_len);
835 pOutput->pBuffers[token_idx].cbBuffer = bin_len;
837 else if (pOutput->pBuffers[token_idx].cbBuffer < bin_len)
839 TRACE("out buffer is NULL or has not enough space\n");
840 ret = SEC_E_BUFFER_TOO_SMALL;
841 if ((phContext == NULL) && (pInput == NULL))
843 cleanup_helper(helper);
844 phNewContext->dwUpper = 0;
845 phNewContext->dwLower = 0;
850 if (!pOutput->pBuffers[token_idx].pvBuffer)
852 TRACE("out buffer is NULL\n");
853 ret = SEC_E_INTERNAL_ERROR;
854 if ((phContext == NULL) && (pInput == NULL))
856 cleanup_helper(helper);
857 phNewContext->dwUpper = 0;
858 phNewContext->dwLower = 0;
863 pOutput->pBuffers[token_idx].cbBuffer = bin_len;
864 memcpy(pOutput->pBuffers[token_idx].pvBuffer, bin, bin_len);
868 TRACE("Getting negotiated flags\n");
869 lstrcpynA(buffer, "GF", max_len - 1);
870 if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
875 TRACE("No flags negotiated.\n");
876 helper->neg_flags = 0l;
880 TRACE("Negotiated %s\n", debugstr_a(buffer));
881 sscanf(buffer + 3, "%lx", &(helper->neg_flags));
882 TRACE("Stored 0x%08lx as flags\n", helper->neg_flags);
885 TRACE("Getting session key\n");
886 lstrcpynA(buffer, "GK", max_len - 1);
887 if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
890 if(strncmp(buffer, "BH", 2) == 0)
891 TRACE("No key negotiated.\n");
892 else if(strncmp(buffer, "GK ", 3) == 0)
894 if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len,
895 &bin_len)) != SEC_E_OK)
897 TRACE("Failed to decode session key\n");
899 TRACE("Session key is %s\n", debugstr_a(buffer+3));
900 HeapFree(GetProcessHeap(), 0, helper->session_key);
901 helper->session_key = HeapAlloc(GetProcessHeap(), 0, bin_len);
902 if(!helper->session_key)
904 TRACE("Failed to allocate memory for session key\n");
905 ret = SEC_E_INTERNAL_ERROR;
908 memcpy(helper->session_key, bin, bin_len);
911 helper->crypt.ntlm.a4i = SECUR32_arc4Alloc();
912 SECUR32_arc4Init(helper->crypt.ntlm.a4i, helper->session_key, 16);
913 helper->crypt.ntlm.seq_num = 0l;
914 SECUR32_CreateNTLMv2SubKeys(helper);
915 helper->crypt.ntlm2.send_a4i = SECUR32_arc4Alloc();
916 helper->crypt.ntlm2.recv_a4i = SECUR32_arc4Alloc();
917 SECUR32_arc4Init(helper->crypt.ntlm2.send_a4i,
918 helper->crypt.ntlm2.send_seal_key, 16);
919 SECUR32_arc4Init(helper->crypt.ntlm2.recv_a4i,
920 helper->crypt.ntlm2.recv_seal_key, 16);
921 helper->crypt.ntlm2.send_seq_no = 0l;
922 helper->crypt.ntlm2.recv_seq_no = 0l;
926 HeapFree(GetProcessHeap(), 0, username);
927 HeapFree(GetProcessHeap(), 0, domain);
928 HeapFree(GetProcessHeap(), 0, password);
929 HeapFree(GetProcessHeap(), 0, want_flags);
930 HeapFree(GetProcessHeap(), 0, buffer);
931 HeapFree(GetProcessHeap(), 0, bin);
935 /***********************************************************************
936 * InitializeSecurityContextA
938 static SECURITY_STATUS SEC_ENTRY ntlm_InitializeSecurityContextA(
939 PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR *pszTargetName,
940 ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep,
941 PSecBufferDesc pInput,ULONG Reserved2, PCtxtHandle phNewContext,
942 PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
945 SEC_WCHAR *target = NULL;
947 TRACE("%p %p %s %d %d %d %p %d %p %p %p %p\n", phCredential, phContext,
948 debugstr_a(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
949 Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
951 if(pszTargetName != NULL)
953 int target_size = MultiByteToWideChar(CP_ACP, 0, pszTargetName,
954 strlen(pszTargetName)+1, NULL, 0);
955 target = HeapAlloc(GetProcessHeap(), 0, target_size *
957 MultiByteToWideChar(CP_ACP, 0, pszTargetName, strlen(pszTargetName)+1,
958 target, target_size);
961 ret = ntlm_InitializeSecurityContextW(phCredential, phContext, target,
962 fContextReq, Reserved1, TargetDataRep, pInput, Reserved2,
963 phNewContext, pOutput, pfContextAttr, ptsExpiry);
965 HeapFree(GetProcessHeap(), 0, target);
969 /***********************************************************************
970 * AcceptSecurityContext
972 static SECURITY_STATUS SEC_ENTRY ntlm_AcceptSecurityContext(
973 PCredHandle phCredential, PCtxtHandle phContext, PSecBufferDesc pInput,
974 ULONG fContextReq, ULONG TargetDataRep, PCtxtHandle phNewContext,
975 PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
978 char *buffer, *want_flags = NULL;
980 int buffer_len, bin_len, max_len = NTLM_MAX_BUF;
983 PNtlmCredentials ntlm_cred;
985 TRACE("%p %p %p %d %d %p %p %p %p\n", phCredential, phContext, pInput,
986 fContextReq, TargetDataRep, phNewContext, pOutput, pfContextAttr,
989 buffer = HeapAlloc(GetProcessHeap(), 0, sizeof(char) * NTLM_MAX_BUF);
990 bin = HeapAlloc(GetProcessHeap(),0, sizeof(BYTE) * NTLM_MAX_BUF);
992 if(TargetDataRep == SECURITY_NETWORK_DREP){
993 TRACE("Using SECURITY_NETWORK_DREP\n");
996 if(phContext == NULL)
998 static CHAR server_helper_protocol[] = "--helper-protocol=squid-2.5-ntlmssp";
999 SEC_CHAR *server_argv[] = { ntlm_auth,
1000 server_helper_protocol,
1005 ret = SEC_E_INVALID_HANDLE;
1009 ntlm_cred = (PNtlmCredentials)phCredential->dwLower;
1011 if(ntlm_cred->mode != NTLM_SERVER)
1013 ret = SEC_E_INVALID_HANDLE;
1017 /* This is the first call to AcceptSecurityHandle */
1020 ret = SEC_E_INCOMPLETE_MESSAGE;
1024 if(pInput->cBuffers < 1)
1026 ret = SEC_E_INCOMPLETE_MESSAGE;
1030 if(pInput->pBuffers[0].cbBuffer > max_len)
1032 ret = SEC_E_INVALID_TOKEN;
1036 bin_len = pInput->pBuffers[0].cbBuffer;
1038 if( (ret = fork_helper(&helper, ntlm_auth, server_argv)) !=
1041 ret = SEC_E_INTERNAL_ERROR;
1044 helper->mode = NTLM_SERVER;
1046 /* Handle all the flags */
1047 want_flags = HeapAlloc(GetProcessHeap(), 0, 73);
1048 if(want_flags == NULL)
1050 TRACE("Failed to allocate memory for the want_flags!\n");
1051 ret = SEC_E_INSUFFICIENT_MEMORY;
1052 cleanup_helper(helper);
1055 lstrcpyA(want_flags, "SF");
1056 if(fContextReq & ASC_REQ_ALLOCATE_MEMORY)
1058 FIXME("ASC_REQ_ALLOCATE_MEMORY stub\n");
1060 if(fContextReq & ASC_REQ_CONFIDENTIALITY)
1062 lstrcatA(want_flags, " NTLMSSP_FEATURE_SEAL");
1064 if(fContextReq & ASC_REQ_CONNECTION)
1066 /* This is default, so we'll enable it */
1067 lstrcatA(want_flags, " NTLMSSP_FEATURE_SESSION_KEY");
1068 ctxt_attr |= ASC_RET_CONNECTION;
1070 if(fContextReq & ASC_REQ_EXTENDED_ERROR)
1072 FIXME("ASC_REQ_EXTENDED_ERROR stub\n");
1074 if(fContextReq & ASC_REQ_INTEGRITY)
1076 lstrcatA(want_flags, " NTLMSSP_FEATURE_SIGN");
1078 if(fContextReq & ASC_REQ_MUTUAL_AUTH)
1080 FIXME("ASC_REQ_MUTUAL_AUTH stub\n");
1082 if(fContextReq & ASC_REQ_REPLAY_DETECT)
1084 FIXME("ASC_REQ_REPLAY_DETECT stub\n");
1086 if(fContextReq & ISC_REQ_SEQUENCE_DETECT)
1088 FIXME("ASC_REQ_SEQUENCE_DETECT stub\n");
1090 if(fContextReq & ISC_REQ_STREAM)
1092 FIXME("ASC_REQ_STREAM stub\n");
1094 /* Done with the flags */
1096 if(lstrlenA(want_flags) > 3)
1098 TRACE("Server set want_flags: %s\n", debugstr_a(want_flags));
1099 lstrcpynA(buffer, want_flags, max_len - 1);
1100 if((ret = run_helper(helper, buffer, max_len, &buffer_len)) !=
1103 cleanup_helper(helper);
1106 if(!strncmp(buffer, "BH", 2))
1107 TRACE("Helper doesn't understand new command set\n");
1110 /* This is the YR request from the client, encode to base64 */
1112 memcpy(bin, pInput->pBuffers[0].pvBuffer, bin_len);
1114 lstrcpynA(buffer, "YR ", max_len-1);
1116 if((ret = encodeBase64(bin, bin_len, buffer+3, max_len-3,
1117 &buffer_len)) != SEC_E_OK)
1119 cleanup_helper(helper);
1123 TRACE("Client sent: %s\n", debugstr_a(buffer));
1125 if((ret = run_helper(helper, buffer, max_len, &buffer_len)) !=
1128 cleanup_helper(helper);
1132 TRACE("Reply from ntlm_auth: %s\n", debugstr_a(buffer));
1133 /* The expected answer is TT <base64 blob> */
1135 if(strncmp(buffer, "TT ", 3) != 0)
1137 ret = SEC_E_INTERNAL_ERROR;
1138 cleanup_helper(helper);
1142 if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len,
1143 &bin_len)) != SEC_E_OK)
1145 cleanup_helper(helper);
1149 /* send this to the client */
1152 ret = SEC_E_INSUFFICIENT_MEMORY;
1153 cleanup_helper(helper);
1157 if(pOutput->cBuffers < 1)
1159 ret = SEC_E_INSUFFICIENT_MEMORY;
1160 cleanup_helper(helper);
1164 pOutput->pBuffers[0].cbBuffer = bin_len;
1165 pOutput->pBuffers[0].BufferType = SECBUFFER_DATA;
1166 memcpy(pOutput->pBuffers[0].pvBuffer, bin, bin_len);
1167 ret = SEC_I_CONTINUE_NEEDED;
1172 /* we expect a KK request from client */
1175 ret = SEC_E_INCOMPLETE_MESSAGE;
1179 if(pInput->cBuffers < 1)
1181 ret = SEC_E_INCOMPLETE_MESSAGE;
1187 ret = SEC_E_INVALID_HANDLE;
1191 helper = (PNegoHelper)phContext->dwLower;
1193 if(helper->mode != NTLM_SERVER)
1195 ret = SEC_E_INVALID_HANDLE;
1199 if(pInput->pBuffers[0].cbBuffer > max_len)
1201 ret = SEC_E_INVALID_TOKEN;
1205 bin_len = pInput->pBuffers[0].cbBuffer;
1207 memcpy(bin, pInput->pBuffers[0].pvBuffer, bin_len);
1209 lstrcpynA(buffer, "KK ", max_len-1);
1211 if((ret = encodeBase64(bin, bin_len, buffer+3, max_len-3,
1212 &buffer_len)) != SEC_E_OK)
1217 TRACE("Client sent: %s\n", debugstr_a(buffer));
1219 if((ret = run_helper(helper, buffer, max_len, &buffer_len)) !=
1225 TRACE("Reply from ntlm_auth: %s\n", debugstr_a(buffer));
1227 /* At this point, we get a NA if the user didn't authenticate, but a BH
1228 * if ntlm_auth could not connect to winbindd. Apart from running Wine
1229 * as root, there is no way to fix this for now, so just handle this as
1230 * a failed login. */
1231 if(strncmp(buffer, "AF ", 3) != 0)
1233 if(strncmp(buffer, "NA ", 3) == 0)
1235 ret = SEC_E_LOGON_DENIED;
1240 size_t ntlm_pipe_err_len = strlen("BH NT_STATUS_ACCESS_DENIED");
1242 if( (buffer_len >= ntlm_pipe_err_len) &&
1243 (strncmp(buffer, "BH NT_STATUS_ACCESS_DENIED",
1244 ntlm_pipe_err_len) == 0))
1246 TRACE("Connection to winbindd failed\n");
1247 ret = SEC_E_LOGON_DENIED;
1250 ret = SEC_E_INTERNAL_ERROR;
1255 pOutput->pBuffers[0].cbBuffer = 0;
1258 TRACE("Getting negotiated flags\n");
1259 lstrcpynA(buffer, "GF", max_len - 1);
1260 if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
1265 TRACE("No flags negotiated, or helper does not support GF command\n");
1269 TRACE("Negotiated %s\n", debugstr_a(buffer));
1270 sscanf(buffer + 3, "%lx", &(helper->neg_flags));
1271 TRACE("Stored 0x%08lx as flags\n", helper->neg_flags);
1274 TRACE("Getting session key\n");
1275 lstrcpynA(buffer, "GK", max_len - 1);
1276 if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
1280 TRACE("Helper does not support GK command\n");
1283 if(strncmp(buffer, "BH ", 3) == 0)
1285 TRACE("Helper sent %s\n", debugstr_a(buffer+3));
1286 helper->session_key = HeapAlloc(GetProcessHeap(), 0, 16);
1287 /*FIXME: Generate the dummy session key = MD4(MD4(password))*/
1288 memset(helper->session_key, 0 , 16);
1290 else if(strncmp(buffer, "GK ", 3) == 0)
1292 if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len,
1293 &bin_len)) != SEC_E_OK)
1295 TRACE("Failed to decode session key\n");
1297 TRACE("Session key is %s\n", debugstr_a(buffer+3));
1298 helper->session_key = HeapAlloc(GetProcessHeap(), 0, 16);
1299 if(!helper->session_key)
1301 TRACE("Failed to allocate memory for session key\n");
1302 ret = SEC_E_INTERNAL_ERROR;
1305 memcpy(helper->session_key, bin, 16);
1308 helper->crypt.ntlm.a4i = SECUR32_arc4Alloc();
1309 SECUR32_arc4Init(helper->crypt.ntlm.a4i, helper->session_key, 16);
1310 helper->crypt.ntlm.seq_num = 0l;
1313 phNewContext->dwUpper = ctxt_attr;
1314 phNewContext->dwLower = (ULONG_PTR)helper;
1317 HeapFree(GetProcessHeap(), 0, want_flags);
1318 HeapFree(GetProcessHeap(), 0, buffer);
1319 HeapFree(GetProcessHeap(), 0, bin);
1323 /***********************************************************************
1326 static SECURITY_STATUS SEC_ENTRY ntlm_CompleteAuthToken(PCtxtHandle phContext,
1327 PSecBufferDesc pToken)
1329 /* We never need to call CompleteAuthToken anyway */
1330 TRACE("%p %p\n", phContext, pToken);
1332 return SEC_E_INVALID_HANDLE;
1337 /***********************************************************************
1338 * DeleteSecurityContext
1340 static SECURITY_STATUS SEC_ENTRY ntlm_DeleteSecurityContext(PCtxtHandle phContext)
1344 TRACE("%p\n", phContext);
1346 return SEC_E_INVALID_HANDLE;
1348 helper = (PNegoHelper)phContext->dwLower;
1350 phContext->dwUpper = 0;
1351 phContext->dwLower = 0;
1353 SECUR32_arc4Cleanup(helper->crypt.ntlm.a4i);
1354 HeapFree(GetProcessHeap(), 0, helper->session_key);
1355 SECUR32_arc4Cleanup(helper->crypt.ntlm2.send_a4i);
1356 SECUR32_arc4Cleanup(helper->crypt.ntlm2.recv_a4i);
1357 HeapFree(GetProcessHeap(), 0, helper->crypt.ntlm2.send_sign_key);
1358 HeapFree(GetProcessHeap(), 0, helper->crypt.ntlm2.send_seal_key);
1359 HeapFree(GetProcessHeap(), 0, helper->crypt.ntlm2.recv_sign_key);
1360 HeapFree(GetProcessHeap(), 0, helper->crypt.ntlm2.recv_seal_key);
1362 cleanup_helper(helper);
1367 /***********************************************************************
1368 * QueryContextAttributesW
1370 static SECURITY_STATUS SEC_ENTRY ntlm_QueryContextAttributesW(PCtxtHandle phContext,
1371 ULONG ulAttribute, void *pBuffer)
1373 TRACE("%p %d %p\n", phContext, ulAttribute, pBuffer);
1375 return SEC_E_INVALID_HANDLE;
1379 #define _x(x) case (x) : FIXME(#x" stub\n"); break
1380 _x(SECPKG_ATTR_ACCESS_TOKEN);
1381 _x(SECPKG_ATTR_AUTHORITY);
1382 _x(SECPKG_ATTR_DCE_INFO);
1383 case SECPKG_ATTR_FLAGS:
1385 PSecPkgContext_Flags spcf = (PSecPkgContext_Flags)pBuffer;
1386 PNegoHelper helper = (PNegoHelper)phContext->dwLower;
1389 if(helper->neg_flags & NTLMSSP_NEGOTIATE_SIGN)
1390 spcf->Flags |= ISC_RET_INTEGRITY;
1391 if(helper->neg_flags & NTLMSSP_NEGOTIATE_SEAL)
1392 spcf->Flags |= ISC_RET_CONFIDENTIALITY;
1395 _x(SECPKG_ATTR_KEY_INFO);
1396 _x(SECPKG_ATTR_LIFESPAN);
1397 _x(SECPKG_ATTR_NAMES);
1398 _x(SECPKG_ATTR_NATIVE_NAMES);
1399 _x(SECPKG_ATTR_NEGOTIATION_INFO);
1400 _x(SECPKG_ATTR_PACKAGE_INFO);
1401 _x(SECPKG_ATTR_PASSWORD_EXPIRY);
1402 _x(SECPKG_ATTR_SESSION_KEY);
1403 case SECPKG_ATTR_SIZES:
1405 PSecPkgContext_Sizes spcs = (PSecPkgContext_Sizes)pBuffer;
1406 spcs->cbMaxToken = NTLM_MAX_BUF;
1407 spcs->cbMaxSignature = 16;
1408 spcs->cbBlockSize = 0;
1409 spcs->cbSecurityTrailer = 16;
1412 _x(SECPKG_ATTR_STREAM_SIZES);
1413 _x(SECPKG_ATTR_TARGET_INFORMATION);
1416 TRACE("Unknown value %d passed for ulAttribute\n", ulAttribute);
1419 return SEC_E_UNSUPPORTED_FUNCTION;
1422 /***********************************************************************
1423 * QueryContextAttributesA
1425 static SECURITY_STATUS SEC_ENTRY ntlm_QueryContextAttributesA(PCtxtHandle phContext,
1426 ULONG ulAttribute, void *pBuffer)
1428 return ntlm_QueryContextAttributesW(phContext, ulAttribute, pBuffer);
1431 /***********************************************************************
1432 * ImpersonateSecurityContext
1434 static SECURITY_STATUS SEC_ENTRY ntlm_ImpersonateSecurityContext(PCtxtHandle phContext)
1436 SECURITY_STATUS ret;
1438 TRACE("%p\n", phContext);
1441 ret = SEC_E_UNSUPPORTED_FUNCTION;
1445 ret = SEC_E_INVALID_HANDLE;
1450 /***********************************************************************
1451 * RevertSecurityContext
1453 static SECURITY_STATUS SEC_ENTRY ntlm_RevertSecurityContext(PCtxtHandle phContext)
1455 SECURITY_STATUS ret;
1457 TRACE("%p\n", phContext);
1460 ret = SEC_E_UNSUPPORTED_FUNCTION;
1464 ret = SEC_E_INVALID_HANDLE;
1469 /***********************************************************************
1470 * ntlm_CreateSignature
1471 * As both MakeSignature and VerifySignature need this, but different keys
1472 * are needed for NTLMv2, the logic goes into a helper function.
1473 * To ensure maximal reusability, we can specify the direction as NTLM_SEND for
1474 * signing/encrypting and NTLM_RECV for verfying/decrypting. When encrypting,
1475 * the signature is encrypted after the message was encrypted, so
1476 * CreateSignature shouldn't do it. In this case, encrypt_sig can be set to
1479 static SECURITY_STATUS ntlm_CreateSignature(PNegoHelper helper, PSecBufferDesc pMessage,
1480 int token_idx, SignDirection direction, BOOL encrypt_sig)
1482 ULONG sign_version = 1;
1485 TRACE("%p, %p, %d, %d, %d\n", helper, pMessage, token_idx, direction,
1488 sig = pMessage->pBuffers[token_idx].pvBuffer;
1490 if(helper->neg_flags & NTLMSSP_NEGOTIATE_NTLM2 &&
1491 helper->neg_flags & NTLMSSP_NEGOTIATE_SIGN)
1495 HMAC_MD5_CTX hmac_md5_ctx;
1497 TRACE("Signing NTLM2 style\n");
1499 if(direction == NTLM_SEND)
1501 seq_no[0] = (helper->crypt.ntlm2.send_seq_no >> 0) & 0xff;
1502 seq_no[1] = (helper->crypt.ntlm2.send_seq_no >> 8) & 0xff;
1503 seq_no[2] = (helper->crypt.ntlm2.send_seq_no >> 16) & 0xff;
1504 seq_no[3] = (helper->crypt.ntlm2.send_seq_no >> 24) & 0xff;
1506 ++(helper->crypt.ntlm2.send_seq_no);
1508 HMACMD5Init(&hmac_md5_ctx, helper->crypt.ntlm2.send_sign_key, 16);
1512 seq_no[0] = (helper->crypt.ntlm2.recv_seq_no >> 0) & 0xff;
1513 seq_no[1] = (helper->crypt.ntlm2.recv_seq_no >> 8) & 0xff;
1514 seq_no[2] = (helper->crypt.ntlm2.recv_seq_no >> 16) & 0xff;
1515 seq_no[3] = (helper->crypt.ntlm2.recv_seq_no >> 24) & 0xff;
1517 ++(helper->crypt.ntlm2.recv_seq_no);
1519 HMACMD5Init(&hmac_md5_ctx, helper->crypt.ntlm2.recv_sign_key, 16);
1522 HMACMD5Update(&hmac_md5_ctx, seq_no, 4);
1523 for( i = 0; i < pMessage->cBuffers; ++i )
1525 if(pMessage->pBuffers[i].BufferType & SECBUFFER_DATA)
1526 HMACMD5Update(&hmac_md5_ctx, (BYTE *)pMessage->pBuffers[i].pvBuffer,
1527 pMessage->pBuffers[i].cbBuffer);
1530 HMACMD5Final(&hmac_md5_ctx, digest);
1532 if(encrypt_sig && helper->neg_flags & NTLMSSP_NEGOTIATE_KEY_EXCHANGE)
1534 if(direction == NTLM_SEND)
1535 SECUR32_arc4Process(helper->crypt.ntlm2.send_a4i, digest, 8);
1537 SECUR32_arc4Process(helper->crypt.ntlm2.recv_a4i, digest, 8);
1540 /* The NTLM2 signature is the sign version */
1541 sig[ 0] = (sign_version >> 0) & 0xff;
1542 sig[ 1] = (sign_version >> 8) & 0xff;
1543 sig[ 2] = (sign_version >> 16) & 0xff;
1544 sig[ 3] = (sign_version >> 24) & 0xff;
1545 /* The first 8 bytes of the digest */
1546 memcpy(sig+4, digest, 8);
1547 /* And the sequence number */
1548 memcpy(sig+12, seq_no, 4);
1550 pMessage->pBuffers[token_idx].cbBuffer = 16;
1554 if(helper->neg_flags & NTLMSSP_NEGOTIATE_SIGN)
1557 TRACE("Signing NTLM1 style\n");
1559 for(i=0; i < pMessage->cBuffers; ++i)
1561 if(pMessage->pBuffers[i].BufferType & SECBUFFER_DATA)
1563 crc = ComputeCrc32(pMessage->pBuffers[i].pvBuffer,
1564 pMessage->pBuffers[i].cbBuffer, crc);
1568 sig[ 0] = (sign_version >> 0) & 0xff;
1569 sig[ 1] = (sign_version >> 8) & 0xff;
1570 sig[ 2] = (sign_version >> 16) & 0xff;
1571 sig[ 3] = (sign_version >> 24) & 0xff;
1572 memset(sig+4, 0, 4);
1573 sig[ 8] = (crc >> 0) & 0xff;
1574 sig[ 9] = (crc >> 8) & 0xff;
1575 sig[10] = (crc >> 16) & 0xff;
1576 sig[11] = (crc >> 24) & 0xff;
1577 sig[12] = (helper->crypt.ntlm.seq_num >> 0) & 0xff;
1578 sig[13] = (helper->crypt.ntlm.seq_num >> 8) & 0xff;
1579 sig[14] = (helper->crypt.ntlm.seq_num >> 16) & 0xff;
1580 sig[15] = (helper->crypt.ntlm.seq_num >> 24) & 0xff;
1582 ++(helper->crypt.ntlm.seq_num);
1585 SECUR32_arc4Process(helper->crypt.ntlm.a4i, sig+4, 12);
1589 if(helper->neg_flags & NTLMSSP_NEGOTIATE_ALWAYS_SIGN || helper->neg_flags == 0)
1591 TRACE("Creating a dummy signature.\n");
1592 /* A dummy signature is 0x01 followed by 15 bytes of 0x00 */
1593 memset(pMessage->pBuffers[token_idx].pvBuffer, 0, 16);
1594 memset(pMessage->pBuffers[token_idx].pvBuffer, 0x01, 1);
1595 pMessage->pBuffers[token_idx].cbBuffer = 16;
1599 return SEC_E_UNSUPPORTED_FUNCTION;
1602 /***********************************************************************
1605 static SECURITY_STATUS SEC_ENTRY ntlm_MakeSignature(PCtxtHandle phContext, ULONG fQOP,
1606 PSecBufferDesc pMessage, ULONG MessageSeqNo)
1611 TRACE("%p %d %p %d\n", phContext, fQOP, pMessage, MessageSeqNo);
1613 return SEC_E_INVALID_HANDLE;
1616 FIXME("Ignoring fQOP 0x%08x\n", fQOP);
1619 FIXME("Ignoring MessageSeqNo\n");
1621 if(!pMessage || !pMessage->pBuffers || pMessage->cBuffers < 2)
1622 return SEC_E_INVALID_TOKEN;
1624 /* If we didn't find a SECBUFFER_TOKEN type buffer */
1625 if((token_idx = ntlm_GetTokenBufferIndex(pMessage)) == -1)
1626 return SEC_E_INVALID_TOKEN;
1628 if(pMessage->pBuffers[token_idx].cbBuffer < 16)
1629 return SEC_E_BUFFER_TOO_SMALL;
1631 helper = (PNegoHelper)phContext->dwLower;
1632 TRACE("Negotiated flags are: 0x%08lx\n", helper->neg_flags);
1634 return ntlm_CreateSignature(helper, pMessage, token_idx, NTLM_SEND, TRUE);
1637 /***********************************************************************
1640 static SECURITY_STATUS SEC_ENTRY ntlm_VerifySignature(PCtxtHandle phContext,
1641 PSecBufferDesc pMessage, ULONG MessageSeqNo, PULONG pfQOP)
1647 SECURITY_STATUS ret;
1648 SecBufferDesc local_desc;
1649 PSecBuffer local_buff;
1652 TRACE("%p %p %d %p\n", phContext, pMessage, MessageSeqNo, pfQOP);
1654 return SEC_E_INVALID_HANDLE;
1656 if(!pMessage || !pMessage->pBuffers || pMessage->cBuffers < 2)
1657 return SEC_E_INVALID_TOKEN;
1659 if((token_idx = ntlm_GetTokenBufferIndex(pMessage)) == -1)
1660 return SEC_E_INVALID_TOKEN;
1662 if(pMessage->pBuffers[token_idx].cbBuffer < 16)
1663 return SEC_E_BUFFER_TOO_SMALL;
1666 FIXME("Ignoring MessageSeqNo\n");
1668 helper = (PNegoHelper)phContext->dwLower;
1669 TRACE("Negotiated flags: 0x%08lx\n", helper->neg_flags);
1671 local_buff = HeapAlloc(GetProcessHeap(), 0, pMessage->cBuffers * sizeof(SecBuffer));
1673 local_desc.ulVersion = SECBUFFER_VERSION;
1674 local_desc.cBuffers = pMessage->cBuffers;
1675 local_desc.pBuffers = local_buff;
1677 for(i=0; i < pMessage->cBuffers; ++i)
1679 if(pMessage->pBuffers[i].BufferType == SECBUFFER_TOKEN)
1681 local_buff[i].BufferType = SECBUFFER_TOKEN;
1682 local_buff[i].cbBuffer = 16;
1683 local_buff[i].pvBuffer = local_sig;
1687 local_buff[i].BufferType = pMessage->pBuffers[i].BufferType;
1688 local_buff[i].cbBuffer = pMessage->pBuffers[i].cbBuffer;
1689 local_buff[i].pvBuffer = pMessage->pBuffers[i].pvBuffer;
1693 if((ret = ntlm_CreateSignature(helper, &local_desc, token_idx, NTLM_RECV, TRUE)) != SEC_E_OK)
1696 if(memcmp(((PBYTE)local_buff[token_idx].pvBuffer) + 8,
1697 ((PBYTE)pMessage->pBuffers[token_idx].pvBuffer) + 8, 8))
1698 ret = SEC_E_MESSAGE_ALTERED;
1702 HeapFree(GetProcessHeap(), 0, local_buff);
1709 /***********************************************************************
1710 * FreeCredentialsHandle
1712 static SECURITY_STATUS SEC_ENTRY ntlm_FreeCredentialsHandle(
1713 PCredHandle phCredential)
1715 SECURITY_STATUS ret;
1718 PNtlmCredentials ntlm_cred = (PNtlmCredentials) phCredential->dwLower;
1719 phCredential->dwUpper = 0;
1720 phCredential->dwLower = 0;
1721 if (ntlm_cred->password)
1722 memset(ntlm_cred->password, 0, ntlm_cred->pwlen);
1723 HeapFree(GetProcessHeap(), 0, ntlm_cred->password);
1724 HeapFree(GetProcessHeap(), 0, ntlm_cred->username_arg);
1725 HeapFree(GetProcessHeap(), 0, ntlm_cred->domain_arg);
1734 /***********************************************************************
1737 static SECURITY_STATUS SEC_ENTRY ntlm_EncryptMessage(PCtxtHandle phContext,
1738 ULONG fQOP, PSecBufferDesc pMessage, ULONG MessageSeqNo)
1741 int token_idx, data_idx;
1743 TRACE("(%p %d %p %d)\n", phContext, fQOP, pMessage, MessageSeqNo);
1746 return SEC_E_INVALID_HANDLE;
1749 FIXME("Ignoring fQOP\n");
1752 FIXME("Ignoring MessageSeqNo\n");
1754 if(!pMessage || !pMessage->pBuffers || pMessage->cBuffers < 2)
1755 return SEC_E_INVALID_TOKEN;
1757 if((token_idx = ntlm_GetTokenBufferIndex(pMessage)) == -1)
1758 return SEC_E_INVALID_TOKEN;
1760 if((data_idx = ntlm_GetDataBufferIndex(pMessage)) ==-1 )
1761 return SEC_E_INVALID_TOKEN;
1763 if(pMessage->pBuffers[token_idx].cbBuffer < 16)
1764 return SEC_E_BUFFER_TOO_SMALL;
1766 helper = (PNegoHelper) phContext->dwLower;
1768 if(helper->neg_flags & NTLMSSP_NEGOTIATE_NTLM2 &&
1769 helper->neg_flags & NTLMSSP_NEGOTIATE_SEAL)
1771 ntlm_CreateSignature(helper, pMessage, token_idx, NTLM_SEND, FALSE);
1772 SECUR32_arc4Process(helper->crypt.ntlm2.send_a4i,
1773 (BYTE *)pMessage->pBuffers[data_idx].pvBuffer,
1774 pMessage->pBuffers[data_idx].cbBuffer);
1776 if(helper->neg_flags & NTLMSSP_NEGOTIATE_KEY_EXCHANGE)
1777 SECUR32_arc4Process(helper->crypt.ntlm2.send_a4i,
1778 ((BYTE *)pMessage->pBuffers[token_idx].pvBuffer)+4, 8);
1788 /* EncryptMessage always produces real signatures, so make sure
1789 * NTLMSSP_NEGOTIATE_SIGN is set*/
1790 save_flags = helper->neg_flags;
1791 helper->neg_flags |= NTLMSSP_NEGOTIATE_SIGN;
1792 ntlm_CreateSignature(helper, pMessage, token_idx, NTLM_SEND, FALSE);
1793 helper->neg_flags = save_flags;
1795 sig = pMessage->pBuffers[token_idx].pvBuffer;
1797 SECUR32_arc4Process(helper->crypt.ntlm.a4i,
1798 pMessage->pBuffers[data_idx].pvBuffer,
1799 pMessage->pBuffers[data_idx].cbBuffer);
1800 SECUR32_arc4Process(helper->crypt.ntlm.a4i, sig+4, 12);
1802 if(helper->neg_flags & NTLMSSP_NEGOTIATE_ALWAYS_SIGN || helper->neg_flags == 0)
1803 memset(sig+4, 0, 4);
1810 /***********************************************************************
1813 static SECURITY_STATUS SEC_ENTRY ntlm_DecryptMessage(PCtxtHandle phContext,
1814 PSecBufferDesc pMessage, ULONG MessageSeqNo, PULONG pfQOP)
1816 SECURITY_STATUS ret;
1817 ULONG ntlmssp_flags_save;
1819 int token_idx, data_idx;
1820 TRACE("(%p %p %d %p)\n", phContext, pMessage, MessageSeqNo, pfQOP);
1823 return SEC_E_INVALID_HANDLE;
1826 FIXME("Ignoring MessageSeqNo\n");
1828 if(!pMessage || !pMessage->pBuffers || pMessage->cBuffers < 2)
1829 return SEC_E_INVALID_TOKEN;
1831 if((token_idx = ntlm_GetTokenBufferIndex(pMessage)) == -1)
1832 return SEC_E_INVALID_TOKEN;
1834 if((data_idx = ntlm_GetDataBufferIndex(pMessage)) ==-1)
1835 return SEC_E_INVALID_TOKEN;
1837 if(pMessage->pBuffers[token_idx].cbBuffer < 16)
1838 return SEC_E_BUFFER_TOO_SMALL;
1840 helper = (PNegoHelper) phContext->dwLower;
1842 if(helper->neg_flags & NTLMSSP_NEGOTIATE_NTLM2 && helper->neg_flags & NTLMSSP_NEGOTIATE_SEAL)
1844 SECUR32_arc4Process(helper->crypt.ntlm2.recv_a4i,
1845 pMessage->pBuffers[data_idx].pvBuffer,
1846 pMessage->pBuffers[data_idx].cbBuffer);
1850 SECUR32_arc4Process(helper->crypt.ntlm.a4i,
1851 pMessage->pBuffers[data_idx].pvBuffer,
1852 pMessage->pBuffers[data_idx].cbBuffer);
1855 /* Make sure we use a session key for the signature check, EncryptMessage
1856 * always does that, even in the dummy case */
1857 ntlmssp_flags_save = helper->neg_flags;
1859 helper->neg_flags |= NTLMSSP_NEGOTIATE_SIGN;
1860 ret = ntlm_VerifySignature(phContext, pMessage, MessageSeqNo, pfQOP);
1862 helper->neg_flags = ntlmssp_flags_save;
1867 static const SecurityFunctionTableA ntlmTableA = {
1869 NULL, /* EnumerateSecurityPackagesA */
1870 ntlm_QueryCredentialsAttributesA, /* QueryCredentialsAttributesA */
1871 ntlm_AcquireCredentialsHandleA, /* AcquireCredentialsHandleA */
1872 ntlm_FreeCredentialsHandle, /* FreeCredentialsHandle */
1873 NULL, /* Reserved2 */
1874 ntlm_InitializeSecurityContextA, /* InitializeSecurityContextA */
1875 ntlm_AcceptSecurityContext, /* AcceptSecurityContext */
1876 ntlm_CompleteAuthToken, /* CompleteAuthToken */
1877 ntlm_DeleteSecurityContext, /* DeleteSecurityContext */
1878 NULL, /* ApplyControlToken */
1879 ntlm_QueryContextAttributesA, /* QueryContextAttributesA */
1880 ntlm_ImpersonateSecurityContext, /* ImpersonateSecurityContext */
1881 ntlm_RevertSecurityContext, /* RevertSecurityContext */
1882 ntlm_MakeSignature, /* MakeSignature */
1883 ntlm_VerifySignature, /* VerifySignature */
1884 FreeContextBuffer, /* FreeContextBuffer */
1885 NULL, /* QuerySecurityPackageInfoA */
1886 NULL, /* Reserved3 */
1887 NULL, /* Reserved4 */
1888 NULL, /* ExportSecurityContext */
1889 NULL, /* ImportSecurityContextA */
1890 NULL, /* AddCredentialsA */
1891 NULL, /* Reserved8 */
1892 NULL, /* QuerySecurityContextToken */
1893 ntlm_EncryptMessage, /* EncryptMessage */
1894 ntlm_DecryptMessage, /* DecryptMessage */
1895 NULL, /* SetContextAttributesA */
1898 static const SecurityFunctionTableW ntlmTableW = {
1900 NULL, /* EnumerateSecurityPackagesW */
1901 ntlm_QueryCredentialsAttributesW, /* QueryCredentialsAttributesW */
1902 ntlm_AcquireCredentialsHandleW, /* AcquireCredentialsHandleW */
1903 ntlm_FreeCredentialsHandle, /* FreeCredentialsHandle */
1904 NULL, /* Reserved2 */
1905 ntlm_InitializeSecurityContextW, /* InitializeSecurityContextW */
1906 ntlm_AcceptSecurityContext, /* AcceptSecurityContext */
1907 ntlm_CompleteAuthToken, /* CompleteAuthToken */
1908 ntlm_DeleteSecurityContext, /* DeleteSecurityContext */
1909 NULL, /* ApplyControlToken */
1910 ntlm_QueryContextAttributesW, /* QueryContextAttributesW */
1911 ntlm_ImpersonateSecurityContext, /* ImpersonateSecurityContext */
1912 ntlm_RevertSecurityContext, /* RevertSecurityContext */
1913 ntlm_MakeSignature, /* MakeSignature */
1914 ntlm_VerifySignature, /* VerifySignature */
1915 FreeContextBuffer, /* FreeContextBuffer */
1916 NULL, /* QuerySecurityPackageInfoW */
1917 NULL, /* Reserved3 */
1918 NULL, /* Reserved4 */
1919 NULL, /* ExportSecurityContext */
1920 NULL, /* ImportSecurityContextW */
1921 NULL, /* AddCredentialsW */
1922 NULL, /* Reserved8 */
1923 NULL, /* QuerySecurityContextToken */
1924 ntlm_EncryptMessage, /* EncryptMessage */
1925 ntlm_DecryptMessage, /* DecryptMessage */
1926 NULL, /* SetContextAttributesW */
1929 #define NTLM_COMMENT \
1930 { 'N', 'T', 'L', 'M', ' ', \
1931 'S', 'e', 'c', 'u', 'r', 'i', 't', 'y', ' ', \
1932 'P', 'a', 'c', 'k', 'a', 'g', 'e', 0}
1934 static CHAR ntlm_comment_A[] = NTLM_COMMENT;
1935 static WCHAR ntlm_comment_W[] = NTLM_COMMENT;
1937 #define NTLM_NAME {'N', 'T', 'L', 'M', 0}
1939 static char ntlm_name_A[] = NTLM_NAME;
1940 static WCHAR ntlm_name_W[] = NTLM_NAME;
1942 /* According to Windows, NTLM has the following capabilities. */
1944 SECPKG_FLAG_INTEGRITY | \
1945 SECPKG_FLAG_PRIVACY | \
1946 SECPKG_FLAG_TOKEN_ONLY | \
1947 SECPKG_FLAG_CONNECTION | \
1948 SECPKG_FLAG_MULTI_REQUIRED | \
1949 SECPKG_FLAG_IMPERSONATION | \
1950 SECPKG_FLAG_ACCEPT_WIN32_NAME | \
1951 SECPKG_FLAG_READONLY_WITH_CHECKSUM)
1953 static const SecPkgInfoW infoW = {
1962 static const SecPkgInfoA infoA = {
1971 void SECUR32_initNTLMSP(void)
1974 static CHAR version[] = "--version";
1976 SEC_CHAR *args[] = {
1981 if(fork_helper(&helper, ntlm_auth, args) != SEC_E_OK)
1983 /* Cheat and allocate a helper anyway, so cleanup later will work. */
1984 helper = HeapAlloc(GetProcessHeap(),0, sizeof(NegoHelper));
1985 helper->major = helper->minor = helper->micro = -1;
1988 check_version(helper);
1990 if( (helper->major > MIN_NTLM_AUTH_MAJOR_VERSION) ||
1991 (helper->major == MIN_NTLM_AUTH_MAJOR_VERSION &&
1992 helper->minor > MIN_NTLM_AUTH_MINOR_VERSION) ||
1993 (helper->major == MIN_NTLM_AUTH_MAJOR_VERSION &&
1994 helper->minor == MIN_NTLM_AUTH_MINOR_VERSION &&
1995 helper->micro >= MIN_NTLM_AUTH_MICRO_VERSION) )
1997 SecureProvider *provider = SECUR32_addProvider(&ntlmTableA, &ntlmTableW, NULL);
1998 SECUR32_addPackages(provider, 1L, &infoA, &infoW);
2002 ERR("%s was not found or is outdated. "
2003 "Make sure that ntlm_auth >= %d.%d.%d is in your path.\n",
2005 MIN_NTLM_AUTH_MAJOR_VERSION,
2006 MIN_NTLM_AUTH_MINOR_VERSION,
2007 MIN_NTLM_AUTH_MICRO_VERSION);
2008 ERR("Usually, you can find it in the winbind package of your "
2012 cleanup_helper(helper);