jscript: Added parser.
[wine] / dlls / secur32 / ntlm.c
1 /*
2  * Copyright 2005, 2006 Kai Blin
3  *
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.
8  *
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.
13  *
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
17  *
18  * This file implements the NTLM security provider.
19  */
20
21 #include <assert.h>
22 #include <stdarg.h>
23 #include <stdio.h>
24 #include "windef.h"
25 #include "winbase.h"
26 #include "winnls.h"
27 #include "wincred.h"
28 #include "rpc.h"
29 #include "sspi.h"
30 #include "lm.h"
31 #include "secur32_priv.h"
32 #include "hmac_md5.h"
33 #include "wine/unicode.h"
34 #include "wine/debug.h"
35
36 WINE_DEFAULT_DEBUG_CHANNEL(ntlm);
37
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
42
43 static CHAR ntlm_auth[] = "ntlm_auth";
44
45 typedef struct _NtlmCredentials
46 {
47     HelperMode mode;
48
49     /* these are all in the Unix codepage */
50     char *username_arg;
51     char *domain_arg;
52     char *password; /* not nul-terminated */
53     int pwlen;
54 } NtlmCredentials, *PNtlmCredentials;
55
56 /***********************************************************************
57  *              QueryCredentialsAttributesA
58  */
59 static SECURITY_STATUS SEC_ENTRY ntlm_QueryCredentialsAttributesA(
60         PCredHandle phCredential, ULONG ulAttribute, PVOID pBuffer)
61 {
62     SECURITY_STATUS ret;
63
64     TRACE("(%p, %d, %p)\n", phCredential, ulAttribute, pBuffer);
65
66     if(ulAttribute == SECPKG_ATTR_NAMES)
67     {
68         FIXME("SECPKG_CRED_ATTR_NAMES: stub\n");
69         ret = SEC_E_UNSUPPORTED_FUNCTION;
70     }
71     else
72         ret = SEC_E_UNSUPPORTED_FUNCTION;
73     
74     return ret;
75 }
76
77 /***********************************************************************
78  *              QueryCredentialsAttributesW
79  */
80 static SECURITY_STATUS SEC_ENTRY ntlm_QueryCredentialsAttributesW(
81         PCredHandle phCredential, ULONG ulAttribute, PVOID pBuffer)
82 {
83     SECURITY_STATUS ret;
84
85     TRACE("(%p, %d, %p)\n", phCredential, ulAttribute, pBuffer);
86
87     if(ulAttribute == SECPKG_ATTR_NAMES)
88     {
89         FIXME("SECPKG_CRED_ATTR_NAMES: stub\n");
90         ret = SEC_E_UNSUPPORTED_FUNCTION;
91     }
92     else
93         ret = SEC_E_UNSUPPORTED_FUNCTION;
94     
95     return ret;
96 }
97
98 static char *ntlm_GetUsernameArg(LPCWSTR userW, INT userW_length)
99 {
100     static const char username_arg[] = "--username=";
101     char *user;
102     int unixcp_size;
103
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';
113     return user;
114 }
115
116 static char *ntlm_GetDomainArg(LPCWSTR domainW, INT domainW_length)
117 {
118     static const char domain_arg[] = "--domain=";
119     char *domain;
120     int unixcp_size;
121
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';
131     return domain;
132 }
133
134 /***********************************************************************
135  *              AcquireCredentialsHandleW
136  */
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)
141 {
142     SECURITY_STATUS ret;
143     PNtlmCredentials ntlm_cred = NULL;
144     SEC_WCHAR *username = NULL, *domain = NULL;
145
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);
149
150     switch(fCredentialUse)
151     {
152         case SECPKG_CRED_INBOUND:
153             ntlm_cred = HeapAlloc(GetProcessHeap(), 0, sizeof(*ntlm_cred));
154             if (!ntlm_cred)
155                 ret = SEC_E_INSUFFICIENT_MEMORY;
156             else
157             {
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;
165                 ret = SEC_E_OK;
166             }
167             break;
168         case SECPKG_CRED_OUTBOUND:
169             {
170                 ntlm_cred = HeapAlloc(GetProcessHeap(), 0, sizeof(*ntlm_cred));
171                 if (!ntlm_cred)
172                 {
173                     ret = SEC_E_INSUFFICIENT_MEMORY;
174                     break;
175                 }
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;
181
182                 if(pAuthData != NULL)
183                 {
184                     PSEC_WINNT_AUTH_IDENTITY_W auth_data =
185                         (PSEC_WINNT_AUTH_IDENTITY_W)pAuthData;
186
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));
189
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);
192
193                     if(auth_data->PasswordLength != 0)
194                     {
195                         ntlm_cred->pwlen = WideCharToMultiByte(CP_UNIXCP,
196                                                                WC_NO_BEST_FIT_CHARS, auth_data->Password,
197                                                                auth_data->PasswordLength, NULL, 0, NULL,
198                                                                NULL);
199
200                         ntlm_cred->password = HeapAlloc(GetProcessHeap(), 0,
201                                                         ntlm_cred->pwlen);
202
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);
206                     }
207                 }
208
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);
213                 ret = SEC_E_OK;
214                 break;
215             }
216         case SECPKG_CRED_BOTH:
217             FIXME("AcquireCredentialsHandle: SECPKG_CRED_BOTH stub\n");
218             ret = SEC_E_UNSUPPORTED_FUNCTION;
219             phCredential = NULL;
220             break;
221         default:
222             phCredential = NULL;
223             ret = SEC_E_UNKNOWN_CREDENTIALS;
224     }
225
226     HeapFree(GetProcessHeap(), 0, username);
227     HeapFree(GetProcessHeap(), 0, domain);
228
229     return ret;
230 }
231
232 /***********************************************************************
233  *              AcquireCredentialsHandleA
234  */
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)
239 {
240     SECURITY_STATUS ret;
241     int user_sizeW, domain_sizeW, passwd_sizeW;
242     
243     SEC_WCHAR *user = NULL, *domain = NULL, *passwd = NULL, *package = NULL;
244     
245     PSEC_WINNT_AUTH_IDENTITY_W pAuthDataW = NULL;
246     PSEC_WINNT_AUTH_IDENTITY_A identity  = NULL;
247
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);
251     
252     if(pszPackage != NULL)
253     {
254         int package_sizeW = MultiByteToWideChar(CP_ACP, 0, pszPackage, -1,
255                 NULL, 0);
256
257         package = HeapAlloc(GetProcessHeap(), 0, package_sizeW * 
258                 sizeof(SEC_WCHAR));
259         MultiByteToWideChar(CP_ACP, 0, pszPackage, -1, package, package_sizeW);
260     }
261
262     
263     if(pAuthData != NULL)
264     {
265         identity = (PSEC_WINNT_AUTH_IDENTITY_A)pAuthData;
266         
267         if(identity->Flags == SEC_WINNT_AUTH_IDENTITY_ANSI)
268         {
269             pAuthDataW = HeapAlloc(GetProcessHeap(), 0, 
270                     sizeof(SEC_WINNT_AUTH_IDENTITY_W));
271
272             if(identity->UserLength != 0)
273             {
274                 user_sizeW = MultiByteToWideChar(CP_ACP, 0, 
275                     (LPCSTR)identity->User, identity->UserLength, NULL, 0);
276                 user = HeapAlloc(GetProcessHeap(), 0, user_sizeW * 
277                         sizeof(SEC_WCHAR));
278                 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)identity->User, 
279                     identity->UserLength, user, user_sizeW);
280             }
281             else
282             {
283                 user_sizeW = 0;
284             }
285              
286             if(identity->DomainLength != 0)
287             {
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);
294             }
295             else
296             {
297                 domain_sizeW = 0;
298             }
299
300             if(identity->PasswordLength != 0)
301             {
302                 passwd_sizeW = MultiByteToWideChar(CP_ACP, 0, 
303                     (LPCSTR)identity->Password, identity->PasswordLength,
304                     NULL, 0);
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);
309             }
310             else
311             {
312                 passwd_sizeW = 0;
313             }
314             
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;
322         }
323         else
324         {
325             pAuthDataW = (PSEC_WINNT_AUTH_IDENTITY_W)identity;
326         }
327     }       
328     
329     ret = ntlm_AcquireCredentialsHandleW(NULL, package, fCredentialUse, 
330             pLogonID, pAuthDataW, pGetKeyFn, pGetKeyArgument, phCredential,
331             ptsExpiry);
332     
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);
339     
340     return ret;
341 }
342
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.
347  */
348 static int ntlm_GetTokenBufferIndex(PSecBufferDesc pMessage)
349 {
350     UINT i;
351
352     TRACE("%p\n", pMessage);
353
354     for( i = 0; i < pMessage->cBuffers; ++i )
355     {
356         if(pMessage->pBuffers[i].BufferType == SECBUFFER_TOKEN)
357             return i;
358     }
359
360     return -1;
361 }
362
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.
367  */
368 static int ntlm_GetDataBufferIndex(PSecBufferDesc pMessage)
369 {
370     UINT i;
371
372     TRACE("%p\n", pMessage);
373
374     for( i = 0; i < pMessage->cBuffers; ++i )
375     {
376         if(pMessage->pBuffers[i].BufferType == SECBUFFER_DATA)
377             return i;
378     }
379
380     return -1;
381 }
382
383 static BOOL ntlm_GetCachedCredential(const SEC_WCHAR *pszTargetName, PCREDENTIALW *cred)
384 {
385     LPCWSTR p;
386     LPCWSTR pszHost;
387     LPWSTR pszHostOnly;
388     BOOL ret;
389
390     if (!pszTargetName)
391         return FALSE;
392
393     /* try to get the start of the hostname from service principal name (SPN) */
394     pszHost = strchrW(pszTargetName, '/');
395     if (pszHost)
396     {
397         /* skip slash character */
398         pszHost++;
399
400         /* find end of host by detecting start of instance port or start of referrer */
401         p = strchrW(pszHost, ':');
402         if (!p)
403             p = strchrW(pszHost, '/');
404         if (!p)
405             p = pszHost + strlenW(pszHost);
406     }
407     else /* otherwise not an SPN, just a host */
408     {
409         pszHost = pszTargetName;
410         p = pszHost + strlenW(pszHost);
411     }
412
413     pszHostOnly = HeapAlloc(GetProcessHeap(), 0, (p - pszHost + 1) * sizeof(WCHAR));
414     if (!pszHostOnly)
415         return FALSE;
416
417     memcpy(pszHostOnly, pszHost, (p - pszHost) * sizeof(WCHAR));
418     pszHostOnly[p - pszHost] = '\0';
419
420     ret = CredReadW(pszHostOnly, CRED_TYPE_DOMAIN_PASSWORD, 0, cred);
421
422     HeapFree(GetProcessHeap(), 0, pszHostOnly);
423     return ret;
424 }
425
426 /***********************************************************************
427  *              InitializeSecurityContextW
428  */
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)
434 {
435     SECURITY_STATUS ret;
436     PNtlmCredentials ntlm_cred = NULL;
437     PNegoHelper helper = NULL;
438     ULONG ctxt_attr = 0;
439     char* buffer, *want_flags = NULL;
440     PBYTE bin;
441     int buffer_len, bin_len, max_len = NTLM_MAX_BUF;
442     int token_idx;
443     SEC_CHAR *username = NULL;
444     SEC_CHAR *domain = NULL;
445     SEC_CHAR *password = NULL;
446
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);
450
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
462      */
463     /* The squid cache size is 2010 chars, and that's what ntlm_auth uses */
464
465     if(TargetDataRep == SECURITY_NETWORK_DREP){
466         TRACE("Setting SECURITY_NETWORK_DREP\n");
467     }
468
469     buffer = HeapAlloc(GetProcessHeap(), 0, sizeof(char) * NTLM_MAX_BUF);
470     bin = HeapAlloc(GetProcessHeap(), 0, sizeof(BYTE) * NTLM_MAX_BUF);
471
472     if((phContext == NULL) && (pInput == NULL))
473     {
474         static char helper_protocol[] = "--helper-protocol=ntlmssp-client-1";
475         static CHAR credentials_argv[] = "--use-cached-creds";
476         SEC_CHAR *client_argv[5];
477         int pwlen = 0;
478
479         TRACE("First time in ISC()\n");
480
481         if(!phCredential)
482         {
483             ret = SEC_E_INVALID_HANDLE;
484             goto isc_end;
485         }
486
487         /* As the server side of sspi never calls this, make sure that
488          * the handler is a client handler.
489          */
490         ntlm_cred = (PNtlmCredentials)phCredential->dwLower;
491         if(ntlm_cred->mode != NTLM_CLIENT)
492         {
493             TRACE("Cred mode = %d\n", ntlm_cred->mode);
494             ret = SEC_E_INVALID_HANDLE;
495             goto isc_end;
496         }
497
498         client_argv[0] = ntlm_auth;
499         client_argv[1] = helper_protocol;
500         if (!ntlm_cred->username_arg && !ntlm_cred->domain_arg)
501         {
502             LPWKSTA_USER_INFO_1 ui = NULL;
503             NET_API_STATUS status;
504             PCREDENTIALW cred;
505
506             if (ntlm_GetCachedCredential(pszTargetName, &cred))
507             {
508                 LPWSTR p;
509                 p = strchrW(cred->UserName, '\\');
510                 if (p)
511                 {
512                     domain = ntlm_GetDomainArg(cred->UserName, p - cred->UserName);
513                     p++;
514                 }
515                 else
516                 {
517                     domain = ntlm_GetDomainArg(NULL, 0);
518                     p = cred->UserName;
519                 }
520
521                 username = ntlm_GetUsernameArg(p, -1);
522
523                 if(cred->CredentialBlobSize != 0)
524                 {
525                     pwlen = WideCharToMultiByte(CP_UNIXCP,
526                         WC_NO_BEST_FIT_CHARS, (LPWSTR)cred->CredentialBlob,
527                         cred->CredentialBlobSize / sizeof(WCHAR), NULL, 0,
528                         NULL, NULL);
529
530                     password = HeapAlloc(GetProcessHeap(), 0, pwlen);
531
532                     WideCharToMultiByte(CP_UNIXCP, WC_NO_BEST_FIT_CHARS,
533                                         (LPWSTR)cred->CredentialBlob,
534                                         cred->CredentialBlobSize / sizeof(WCHAR),
535                                         password, pwlen, NULL, NULL);
536                 }
537
538                 CredFree(cred);
539
540                 client_argv[2] = username;
541                 client_argv[3] = domain;
542                 client_argv[4] = NULL;
543             }
544             else
545             {
546                 status = NetWkstaUserGetInfo(NULL, 1, (LPBYTE *)&ui);
547                 if (status != NERR_Success || ui == NULL)
548                 {
549                     ret = SEC_E_NO_CREDENTIALS;
550                     goto isc_end;
551                 }
552                 username = ntlm_GetUsernameArg(ui->wkui1_username, -1);
553
554                 TRACE("using cached credentials\n");
555
556                 client_argv[2] = username;
557                 client_argv[3] = credentials_argv;
558                 client_argv[4] = NULL;
559             }
560         }
561         else
562         {
563             client_argv[2] = ntlm_cred->username_arg;
564             client_argv[3] = ntlm_cred->domain_arg;
565             client_argv[4] = NULL;
566         }
567
568         if((ret = fork_helper(&helper, ntlm_auth, client_argv)) != SEC_E_OK)
569             goto isc_end;
570
571         helper->mode = NTLM_CLIENT;
572         helper->session_key = HeapAlloc(GetProcessHeap(), 0, 16);
573         if (!helper->session_key)
574         {
575             cleanup_helper(helper);
576             ret = SEC_E_INSUFFICIENT_MEMORY;
577             goto isc_end;
578         }
579
580         /* Generate the dummy session key = MD4(MD4(password))*/
581         if(password || ntlm_cred->password)
582         {
583             SEC_WCHAR *unicode_password;
584             int passwd_lenW;
585
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,
590                                               NULL, 0);
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);
595
596             SECUR32_CreateNTLMv1SessionKey((PBYTE)unicode_password,
597                                            passwd_lenW * sizeof(SEC_WCHAR), helper->session_key);
598
599             HeapFree(GetProcessHeap(), 0, unicode_password);
600         }
601         else
602             memset(helper->session_key, 0, 16);
603
604         /* Allocate space for a maximal string of 
605          * "SF NTLMSSP_FEATURE_SIGN NTLMSSP_FEATURE_SEAL
606          * NTLMSSP_FEATURE_SESSION_KEY"
607          */
608         want_flags = HeapAlloc(GetProcessHeap(), 0, 73);
609         if(want_flags == NULL)
610         {
611             cleanup_helper(helper);
612             ret = SEC_E_INSUFFICIENT_MEMORY;
613             goto isc_end;
614         }
615         lstrcpyA(want_flags, "SF");
616         if(fContextReq & ISC_REQ_CONFIDENTIALITY)
617         {
618             if(strstr(want_flags, "NTLMSSP_FEATURE_SEAL") == NULL)
619                 lstrcatA(want_flags, " NTLMSSP_FEATURE_SEAL");
620         }
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)
626         {
627             if(strstr(want_flags, "NTLMSSP_FEATURE_SIGN") == NULL)
628                 lstrcatA(want_flags, " NTLMSSP_FEATURE_SIGN");
629         }
630         if(fContextReq & ISC_REQ_MUTUAL_AUTH)
631             ctxt_attr |= ISC_RET_MUTUAL_AUTH;
632         if(fContextReq & ISC_REQ_REPLAY_DETECT)
633         {
634             if(strstr(want_flags, "NTLMSSP_FEATURE_SIGN") == NULL)
635                 lstrcatA(want_flags, " NTLMSSP_FEATURE_SIGN");
636         }
637         if(fContextReq & ISC_REQ_SEQUENCE_DETECT)
638         {
639             if(strstr(want_flags, "NTLMSSP_FEATURE_SIGN") == NULL)
640                 lstrcatA(want_flags, " NTLMSSP_FEATURE_SIGN");
641         }
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;
648
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)
652         {
653             lstrcpynA(buffer, "OK", max_len-1);
654             if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
655             {
656                 cleanup_helper(helper);
657                 goto isc_end;
658             }
659             /* If the helper replied with "PW", using cached credentials failed */
660             if(!strncmp(buffer, "PW", 2))
661             {
662                 TRACE("Using cached credentials failed.\n");
663                 ret = SEC_E_NO_CREDENTIALS;
664                 goto isc_end;
665             }
666             else /* Just do a noop on the next run */
667                 lstrcpynA(buffer, "OK", max_len-1);
668         }
669         else
670         {
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)
675             {
676                 cleanup_helper(helper);
677                 goto isc_end;
678             }
679
680         }
681
682         TRACE("Sending to helper: %s\n", debugstr_a(buffer));
683         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
684         {
685             cleanup_helper(helper);
686             goto isc_end;
687         }
688
689         TRACE("Helper returned %s\n", debugstr_a(buffer));
690
691         if(lstrlenA(want_flags) > 2)
692         {
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)) 
696                     != SEC_E_OK)
697                 goto isc_end;
698             if(!strncmp(buffer, "BH", 2))
699                 ERR("Helper doesn't understand new command set. Expect more things to fail.\n");
700         }
701
702         lstrcpynA(buffer, "YR", max_len-1);
703
704         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
705         {
706             cleanup_helper(helper);
707             goto isc_end;
708         }
709
710         TRACE("%s\n", buffer);
711
712         if(strncmp(buffer, "YR ", 3) != 0)
713         {
714             /* Something borked */
715             TRACE("Helper returned %c%c\n", buffer[0], buffer[1]);
716             ret = SEC_E_INTERNAL_ERROR;
717             cleanup_helper(helper);
718             goto isc_end;
719         }
720         if((ret = decodeBase64(buffer+3, buffer_len-3, bin,
721                         max_len-1, &bin_len)) != SEC_E_OK)
722         {
723             cleanup_helper(helper);
724             goto isc_end;
725         }
726
727         /* put the decoded client blob into the out buffer */
728
729         phNewContext->dwUpper = ctxt_attr;
730         phNewContext->dwLower = (ULONG_PTR)helper;
731
732         ret = SEC_I_CONTINUE_NEEDED;
733     }
734     else
735     {
736         int input_token_idx;
737
738         /* handle second call here */
739         /* encode server data to base64 */
740         if (!pInput || ((input_token_idx = ntlm_GetTokenBufferIndex(pInput)) == -1))
741         {
742             ret = SEC_E_INVALID_TOKEN;
743             goto isc_end;
744         }
745
746         if(!phContext)
747         {
748             ret = SEC_E_INVALID_HANDLE;
749             goto isc_end;
750         }
751
752         /* As the server side of sspi never calls this, make sure that
753          * the handler is a client handler.
754          */
755         helper = (PNegoHelper)phContext->dwLower;
756         if(helper->mode != NTLM_CLIENT)
757         {
758             TRACE("Helper mode = %d\n", helper->mode);
759             ret = SEC_E_INVALID_HANDLE;
760             goto isc_end;
761         }
762
763         if (!pInput->pBuffers[input_token_idx].pvBuffer)
764         {
765             ret = SEC_E_INTERNAL_ERROR;
766             goto isc_end;
767         }
768
769         if(pInput->pBuffers[input_token_idx].cbBuffer > max_len)
770         {
771             TRACE("pInput->pBuffers[%d].cbBuffer is: %ld\n",
772                     input_token_idx,
773                     pInput->pBuffers[input_token_idx].cbBuffer);
774             ret = SEC_E_INVALID_TOKEN;
775             goto isc_end;
776         }
777         else
778             bin_len = pInput->pBuffers[input_token_idx].cbBuffer;
779
780         memcpy(bin, pInput->pBuffers[input_token_idx].pvBuffer, bin_len);
781
782         lstrcpynA(buffer, "TT ", max_len-1);
783
784         if((ret = encodeBase64(bin, bin_len, buffer+3,
785                         max_len-3, &buffer_len)) != SEC_E_OK)
786             goto isc_end;
787
788         TRACE("Server sent: %s\n", debugstr_a(buffer));
789
790         /* send TT base64 blob to ntlm_auth */
791         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
792             goto isc_end;
793
794         TRACE("Helper replied: %s\n", debugstr_a(buffer));
795
796         if( (strncmp(buffer, "KK ", 3) != 0) &&
797                 (strncmp(buffer, "AF ", 3) !=0))
798         {
799             TRACE("Helper returned %c%c\n", buffer[0], buffer[1]);
800             ret = SEC_E_INVALID_TOKEN;
801             goto isc_end;
802         }
803
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)
807         {
808             goto isc_end;
809         }
810
811         phNewContext->dwUpper = ctxt_attr;
812         phNewContext->dwLower = (ULONG_PTR)helper;
813
814         ret = SEC_E_OK;
815     }
816
817     /* put the decoded client blob into the out buffer */
818
819     if (!pOutput || ((token_idx = ntlm_GetTokenBufferIndex(pOutput)) == -1))
820     {
821         TRACE("no SECBUFFER_TOKEN buffer could be found\n");
822         ret = SEC_E_BUFFER_TOO_SMALL;
823         if ((phContext == NULL) && (pInput == NULL))
824         {
825             cleanup_helper(helper);
826             phNewContext->dwUpper = 0;
827             phNewContext->dwLower = 0;
828         }
829         goto isc_end;
830     }
831
832     if (fContextReq & ISC_REQ_ALLOCATE_MEMORY)
833     {
834         pOutput->pBuffers[token_idx].pvBuffer = HeapAlloc(GetProcessHeap(), 0, bin_len);
835         pOutput->pBuffers[token_idx].cbBuffer = bin_len;
836     }
837     else if (pOutput->pBuffers[token_idx].cbBuffer < bin_len)
838     {
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))
842         {
843             cleanup_helper(helper);
844             phNewContext->dwUpper = 0;
845             phNewContext->dwLower = 0;
846         }
847         goto isc_end;
848     }
849
850     if (!pOutput->pBuffers[token_idx].pvBuffer)
851     {
852         TRACE("out buffer is NULL\n");
853         ret = SEC_E_INTERNAL_ERROR;
854         if ((phContext == NULL) && (pInput == NULL))
855         {
856             cleanup_helper(helper);
857             phNewContext->dwUpper = 0;
858             phNewContext->dwLower = 0;
859         }
860         goto isc_end;
861     }
862
863     pOutput->pBuffers[token_idx].cbBuffer = bin_len;
864     memcpy(pOutput->pBuffers[token_idx].pvBuffer, bin, bin_len);
865
866     if(ret == SEC_E_OK)
867     {
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)
871             goto isc_end;
872
873         if(buffer_len < 3)
874         {
875             TRACE("No flags negotiated.\n");
876             helper->neg_flags = 0l;
877         }
878         else
879         {
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);
883         }
884
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)
888             goto isc_end;
889
890         if(strncmp(buffer, "BH", 2) == 0)
891             TRACE("No key negotiated.\n");
892         else if(strncmp(buffer, "GK ", 3) == 0)
893         {
894             if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len, 
895                             &bin_len)) != SEC_E_OK)
896             {
897                 TRACE("Failed to decode session key\n");
898             }
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)
903             {
904                 TRACE("Failed to allocate memory for session key\n");
905                 ret = SEC_E_INTERNAL_ERROR;
906                 goto isc_end;
907             }
908             memcpy(helper->session_key, bin, bin_len);
909         }
910
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;
923     }
924
925 isc_end:
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);
932     return ret;
933 }
934
935 /***********************************************************************
936  *              InitializeSecurityContextA
937  */
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)
943 {
944     SECURITY_STATUS ret;
945     SEC_WCHAR *target = NULL;
946
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);
950
951     if(pszTargetName != NULL)
952     {
953         int target_size = MultiByteToWideChar(CP_ACP, 0, pszTargetName,
954             strlen(pszTargetName)+1, NULL, 0);
955         target = HeapAlloc(GetProcessHeap(), 0, target_size *
956                 sizeof(SEC_WCHAR));
957         MultiByteToWideChar(CP_ACP, 0, pszTargetName, strlen(pszTargetName)+1,
958             target, target_size);
959     }
960
961     ret = ntlm_InitializeSecurityContextW(phCredential, phContext, target,
962             fContextReq, Reserved1, TargetDataRep, pInput, Reserved2,
963             phNewContext, pOutput, pfContextAttr, ptsExpiry);
964
965     HeapFree(GetProcessHeap(), 0, target);
966     return ret;
967 }
968
969 /***********************************************************************
970  *              AcceptSecurityContext
971  */
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)
976 {
977     SECURITY_STATUS ret;
978     char *buffer, *want_flags = NULL;
979     PBYTE bin;
980     int buffer_len, bin_len, max_len = NTLM_MAX_BUF;
981     ULONG ctxt_attr = 0;
982     PNegoHelper helper;
983     PNtlmCredentials ntlm_cred;
984
985     TRACE("%p %p %p %d %d %p %p %p %p\n", phCredential, phContext, pInput,
986      fContextReq, TargetDataRep, phNewContext, pOutput, pfContextAttr,
987      ptsExpiry);
988
989     buffer = HeapAlloc(GetProcessHeap(), 0, sizeof(char) * NTLM_MAX_BUF);
990     bin    = HeapAlloc(GetProcessHeap(),0, sizeof(BYTE) * NTLM_MAX_BUF);
991
992     if(TargetDataRep == SECURITY_NETWORK_DREP){
993         TRACE("Using SECURITY_NETWORK_DREP\n");
994     }
995
996     if(phContext == NULL)
997     {
998         static CHAR server_helper_protocol[] = "--helper-protocol=squid-2.5-ntlmssp";
999         SEC_CHAR *server_argv[] = { ntlm_auth,
1000             server_helper_protocol,
1001             NULL };
1002
1003         if (!phCredential)
1004         {
1005             ret = SEC_E_INVALID_HANDLE;
1006             goto asc_end;
1007         }
1008
1009         ntlm_cred = (PNtlmCredentials)phCredential->dwLower;
1010
1011         if(ntlm_cred->mode != NTLM_SERVER)
1012         {
1013             ret = SEC_E_INVALID_HANDLE;
1014             goto asc_end;
1015         }
1016
1017         /* This is the first call to AcceptSecurityHandle */
1018         if(pInput == NULL)
1019         {
1020             ret = SEC_E_INCOMPLETE_MESSAGE;
1021             goto asc_end;
1022         }
1023
1024         if(pInput->cBuffers < 1)
1025         {
1026             ret = SEC_E_INCOMPLETE_MESSAGE;
1027             goto asc_end;
1028         }
1029
1030         if(pInput->pBuffers[0].cbBuffer > max_len)
1031         {
1032             ret = SEC_E_INVALID_TOKEN;
1033             goto asc_end;
1034         }
1035         else
1036             bin_len = pInput->pBuffers[0].cbBuffer;
1037
1038         if( (ret = fork_helper(&helper, ntlm_auth, server_argv)) !=
1039             SEC_E_OK)
1040         {
1041             ret = SEC_E_INTERNAL_ERROR;
1042             goto asc_end;
1043         }
1044         helper->mode = NTLM_SERVER;
1045
1046         /* Handle all the flags */
1047         want_flags = HeapAlloc(GetProcessHeap(), 0, 73);
1048         if(want_flags == NULL)
1049         {
1050             TRACE("Failed to allocate memory for the want_flags!\n");
1051             ret = SEC_E_INSUFFICIENT_MEMORY;
1052             cleanup_helper(helper);
1053             goto asc_end;
1054         }
1055         lstrcpyA(want_flags, "SF");
1056         if(fContextReq & ASC_REQ_ALLOCATE_MEMORY)
1057         {
1058             FIXME("ASC_REQ_ALLOCATE_MEMORY stub\n");
1059         }
1060         if(fContextReq & ASC_REQ_CONFIDENTIALITY)
1061         {
1062             lstrcatA(want_flags, " NTLMSSP_FEATURE_SEAL");
1063         }
1064         if(fContextReq & ASC_REQ_CONNECTION)
1065         {
1066             /* This is default, so we'll enable it */
1067             lstrcatA(want_flags, " NTLMSSP_FEATURE_SESSION_KEY");
1068             ctxt_attr |= ASC_RET_CONNECTION;
1069         }
1070         if(fContextReq & ASC_REQ_EXTENDED_ERROR)
1071         {
1072             FIXME("ASC_REQ_EXTENDED_ERROR stub\n");
1073         }
1074         if(fContextReq & ASC_REQ_INTEGRITY)
1075         {
1076             lstrcatA(want_flags, " NTLMSSP_FEATURE_SIGN");
1077         }
1078         if(fContextReq & ASC_REQ_MUTUAL_AUTH)
1079         {
1080             FIXME("ASC_REQ_MUTUAL_AUTH stub\n");
1081         }
1082         if(fContextReq & ASC_REQ_REPLAY_DETECT)
1083         {
1084             FIXME("ASC_REQ_REPLAY_DETECT stub\n");
1085         }
1086         if(fContextReq & ISC_REQ_SEQUENCE_DETECT)
1087         {
1088             FIXME("ASC_REQ_SEQUENCE_DETECT stub\n");
1089         }
1090         if(fContextReq & ISC_REQ_STREAM)
1091         {
1092             FIXME("ASC_REQ_STREAM stub\n");
1093         }
1094         /* Done with the flags */
1095
1096         if(lstrlenA(want_flags) > 3)
1097         {
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)) !=
1101                     SEC_E_OK)
1102             {
1103                 cleanup_helper(helper);
1104                 goto asc_end;
1105             }
1106             if(!strncmp(buffer, "BH", 2))
1107                 TRACE("Helper doesn't understand new command set\n");
1108         }
1109
1110         /* This is the YR request from the client, encode to base64 */
1111
1112         memcpy(bin, pInput->pBuffers[0].pvBuffer, bin_len);
1113
1114         lstrcpynA(buffer, "YR ", max_len-1);
1115
1116         if((ret = encodeBase64(bin, bin_len, buffer+3, max_len-3,
1117                     &buffer_len)) != SEC_E_OK)
1118         {
1119             cleanup_helper(helper);
1120             goto asc_end;
1121         }
1122
1123         TRACE("Client sent: %s\n", debugstr_a(buffer));
1124
1125         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) !=
1126                     SEC_E_OK)
1127         {
1128             cleanup_helper(helper);
1129             goto asc_end;
1130         }
1131
1132         TRACE("Reply from ntlm_auth: %s\n", debugstr_a(buffer));
1133         /* The expected answer is TT <base64 blob> */
1134
1135         if(strncmp(buffer, "TT ", 3) != 0)
1136         {
1137             ret = SEC_E_INTERNAL_ERROR;
1138             cleanup_helper(helper);
1139             goto asc_end;
1140         }
1141
1142         if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len,
1143                         &bin_len)) != SEC_E_OK)
1144         {
1145             cleanup_helper(helper);
1146             goto asc_end;
1147         }
1148
1149         /* send this to the client */
1150         if(pOutput == NULL)
1151         {
1152             ret = SEC_E_INSUFFICIENT_MEMORY;
1153             cleanup_helper(helper);
1154             goto asc_end;
1155         }
1156
1157         if(pOutput->cBuffers < 1)
1158         {
1159             ret = SEC_E_INSUFFICIENT_MEMORY;
1160             cleanup_helper(helper);
1161             goto asc_end;
1162         }
1163
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;
1168
1169     }
1170     else
1171     {
1172         /* we expect a KK request from client */
1173         if(pInput == NULL)
1174         {
1175             ret = SEC_E_INCOMPLETE_MESSAGE;
1176             goto asc_end;
1177         }
1178
1179         if(pInput->cBuffers < 1)
1180         {
1181             ret = SEC_E_INCOMPLETE_MESSAGE;
1182             goto asc_end;
1183         }
1184
1185         if(!phContext)
1186         {
1187             ret = SEC_E_INVALID_HANDLE;
1188             goto asc_end;
1189         }
1190
1191         helper = (PNegoHelper)phContext->dwLower;
1192
1193         if(helper->mode != NTLM_SERVER)
1194         {
1195             ret = SEC_E_INVALID_HANDLE;
1196             goto asc_end;
1197         }
1198
1199         if(pInput->pBuffers[0].cbBuffer > max_len)
1200         {
1201             ret = SEC_E_INVALID_TOKEN;
1202             goto asc_end;
1203         }
1204         else
1205             bin_len = pInput->pBuffers[0].cbBuffer;
1206
1207         memcpy(bin, pInput->pBuffers[0].pvBuffer, bin_len);
1208
1209         lstrcpynA(buffer, "KK ", max_len-1);
1210
1211         if((ret = encodeBase64(bin, bin_len, buffer+3, max_len-3,
1212                     &buffer_len)) != SEC_E_OK)
1213         {
1214             goto asc_end;
1215         }
1216
1217         TRACE("Client sent: %s\n", debugstr_a(buffer));
1218
1219         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) !=
1220                     SEC_E_OK)
1221         {
1222             goto asc_end;
1223         }
1224
1225         TRACE("Reply from ntlm_auth: %s\n", debugstr_a(buffer));
1226
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)
1232         {
1233             if(strncmp(buffer, "NA ", 3) == 0)
1234             {
1235                 ret = SEC_E_LOGON_DENIED;
1236                 goto asc_end;
1237             }
1238             else
1239             {
1240                 size_t ntlm_pipe_err_len = strlen("BH NT_STATUS_ACCESS_DENIED");
1241
1242                 if( (buffer_len >= ntlm_pipe_err_len) &&
1243                     (strncmp(buffer, "BH NT_STATUS_ACCESS_DENIED",
1244                              ntlm_pipe_err_len) == 0))
1245                 {
1246                     TRACE("Connection to winbindd failed\n");
1247                     ret = SEC_E_LOGON_DENIED;
1248                 }
1249                 else
1250                     ret = SEC_E_INTERNAL_ERROR;
1251
1252                 goto asc_end;
1253             }
1254         }
1255         pOutput->pBuffers[0].cbBuffer = 0;
1256         ret = SEC_E_OK;
1257
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)
1261             goto asc_end;
1262
1263         if(buffer_len < 3)
1264         {
1265             TRACE("No flags negotiated, or helper does not support GF command\n");
1266         }
1267         else
1268         {
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);
1272         }
1273
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)
1277             goto asc_end;
1278
1279         if(buffer_len < 3)
1280             TRACE("Helper does not support GK command\n");
1281         else
1282         {
1283             if(strncmp(buffer, "BH ", 3) == 0)
1284             {
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);
1289             }
1290             else if(strncmp(buffer, "GK ", 3) == 0)
1291             {
1292                 if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len, 
1293                                 &bin_len)) != SEC_E_OK)
1294                 {
1295                     TRACE("Failed to decode session key\n");
1296                 }
1297                 TRACE("Session key is %s\n", debugstr_a(buffer+3));
1298                 helper->session_key = HeapAlloc(GetProcessHeap(), 0, 16);
1299                 if(!helper->session_key)
1300                 {
1301                     TRACE("Failed to allocate memory for session key\n");
1302                     ret = SEC_E_INTERNAL_ERROR;
1303                     goto asc_end;
1304                 }
1305                 memcpy(helper->session_key, bin, 16);
1306             }
1307         }
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;
1311     }
1312
1313     phNewContext->dwUpper = ctxt_attr;
1314     phNewContext->dwLower = (ULONG_PTR)helper;
1315
1316 asc_end:
1317     HeapFree(GetProcessHeap(), 0, want_flags);
1318     HeapFree(GetProcessHeap(), 0, buffer);
1319     HeapFree(GetProcessHeap(), 0, bin);
1320     return ret;
1321 }
1322
1323 /***********************************************************************
1324  *              CompleteAuthToken
1325  */
1326 static SECURITY_STATUS SEC_ENTRY ntlm_CompleteAuthToken(PCtxtHandle phContext,
1327  PSecBufferDesc pToken)
1328 {
1329     /* We never need to call CompleteAuthToken anyway */
1330     TRACE("%p %p\n", phContext, pToken);
1331     if (!phContext)
1332         return SEC_E_INVALID_HANDLE;
1333     
1334     return SEC_E_OK;
1335 }
1336
1337 /***********************************************************************
1338  *              DeleteSecurityContext
1339  */
1340 static SECURITY_STATUS SEC_ENTRY ntlm_DeleteSecurityContext(PCtxtHandle phContext)
1341 {
1342     PNegoHelper helper;
1343
1344     TRACE("%p\n", phContext);
1345     if (!phContext)
1346         return SEC_E_INVALID_HANDLE;
1347
1348     helper = (PNegoHelper)phContext->dwLower;
1349
1350     phContext->dwUpper = 0;
1351     phContext->dwLower = 0;
1352
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);
1361
1362     cleanup_helper(helper);
1363
1364     return SEC_E_OK;
1365 }
1366
1367 /***********************************************************************
1368  *              QueryContextAttributesW
1369  */
1370 static SECURITY_STATUS SEC_ENTRY ntlm_QueryContextAttributesW(PCtxtHandle phContext,
1371  ULONG ulAttribute, void *pBuffer)
1372 {
1373     TRACE("%p %d %p\n", phContext, ulAttribute, pBuffer);
1374     if (!phContext)
1375         return SEC_E_INVALID_HANDLE;
1376
1377     switch(ulAttribute)
1378     {
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:
1384         {
1385             PSecPkgContext_Flags spcf = (PSecPkgContext_Flags)pBuffer;
1386             PNegoHelper helper = (PNegoHelper)phContext->dwLower;
1387
1388             spcf->Flags = 0;
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;
1393             return SEC_E_OK;
1394         }
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:
1404         {
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;
1410             return SEC_E_OK;
1411         }
1412         _x(SECPKG_ATTR_STREAM_SIZES);
1413         _x(SECPKG_ATTR_TARGET_INFORMATION);
1414 #undef _x
1415         default:
1416             TRACE("Unknown value %d passed for ulAttribute\n", ulAttribute);
1417     }
1418
1419     return SEC_E_UNSUPPORTED_FUNCTION;
1420 }
1421
1422 /***********************************************************************
1423  *              QueryContextAttributesA
1424  */
1425 static SECURITY_STATUS SEC_ENTRY ntlm_QueryContextAttributesA(PCtxtHandle phContext,
1426  ULONG ulAttribute, void *pBuffer)
1427 {
1428     return ntlm_QueryContextAttributesW(phContext, ulAttribute, pBuffer);
1429 }
1430
1431 /***********************************************************************
1432  *              ImpersonateSecurityContext
1433  */
1434 static SECURITY_STATUS SEC_ENTRY ntlm_ImpersonateSecurityContext(PCtxtHandle phContext)
1435 {
1436     SECURITY_STATUS ret;
1437
1438     TRACE("%p\n", phContext);
1439     if (phContext)
1440     {
1441         ret = SEC_E_UNSUPPORTED_FUNCTION;
1442     }
1443     else
1444     {
1445         ret = SEC_E_INVALID_HANDLE;
1446     }
1447     return ret;
1448 }
1449
1450 /***********************************************************************
1451  *              RevertSecurityContext
1452  */
1453 static SECURITY_STATUS SEC_ENTRY ntlm_RevertSecurityContext(PCtxtHandle phContext)
1454 {
1455     SECURITY_STATUS ret;
1456
1457     TRACE("%p\n", phContext);
1458     if (phContext)
1459     {
1460         ret = SEC_E_UNSUPPORTED_FUNCTION;
1461     }
1462     else
1463     {
1464         ret = SEC_E_INVALID_HANDLE;
1465     }
1466     return ret;
1467 }
1468
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
1477  * false.
1478  */
1479 static SECURITY_STATUS ntlm_CreateSignature(PNegoHelper helper, PSecBufferDesc pMessage,
1480         int token_idx, SignDirection direction, BOOL encrypt_sig)
1481 {
1482     ULONG sign_version = 1;
1483     UINT i;
1484     PBYTE sig;
1485     TRACE("%p, %p, %d, %d, %d\n", helper, pMessage, token_idx, direction,
1486             encrypt_sig);
1487
1488     sig = pMessage->pBuffers[token_idx].pvBuffer;
1489
1490     if(helper->neg_flags & NTLMSSP_NEGOTIATE_NTLM2 &&
1491             helper->neg_flags & NTLMSSP_NEGOTIATE_SIGN)
1492     {
1493         BYTE digest[16];
1494         BYTE seq_no[4];
1495         HMAC_MD5_CTX hmac_md5_ctx;
1496
1497         TRACE("Signing NTLM2 style\n");
1498
1499         if(direction == NTLM_SEND)
1500         {
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;
1505
1506             ++(helper->crypt.ntlm2.send_seq_no);
1507
1508             HMACMD5Init(&hmac_md5_ctx, helper->crypt.ntlm2.send_sign_key, 16);
1509         }
1510         else
1511         {
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;
1516
1517             ++(helper->crypt.ntlm2.recv_seq_no);
1518
1519             HMACMD5Init(&hmac_md5_ctx, helper->crypt.ntlm2.recv_sign_key, 16);
1520         }
1521
1522         HMACMD5Update(&hmac_md5_ctx, seq_no, 4);
1523         for( i = 0; i < pMessage->cBuffers; ++i )
1524         {
1525             if(pMessage->pBuffers[i].BufferType & SECBUFFER_DATA)
1526                 HMACMD5Update(&hmac_md5_ctx, (BYTE *)pMessage->pBuffers[i].pvBuffer,
1527                         pMessage->pBuffers[i].cbBuffer);
1528         }
1529
1530         HMACMD5Final(&hmac_md5_ctx, digest);
1531
1532         if(encrypt_sig && helper->neg_flags & NTLMSSP_NEGOTIATE_KEY_EXCHANGE)
1533         {
1534             if(direction == NTLM_SEND)
1535                 SECUR32_arc4Process(helper->crypt.ntlm2.send_a4i, digest, 8);
1536             else
1537                 SECUR32_arc4Process(helper->crypt.ntlm2.recv_a4i, digest, 8);
1538         }
1539
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);
1549
1550         pMessage->pBuffers[token_idx].cbBuffer = 16;
1551
1552         return SEC_E_OK;
1553     }
1554     if(helper->neg_flags & NTLMSSP_NEGOTIATE_SIGN)
1555     {
1556         ULONG crc = 0U;
1557         TRACE("Signing NTLM1 style\n");
1558
1559         for(i=0; i < pMessage->cBuffers; ++i)
1560         {
1561             if(pMessage->pBuffers[i].BufferType & SECBUFFER_DATA)
1562             {
1563                 crc = ComputeCrc32(pMessage->pBuffers[i].pvBuffer,
1564                     pMessage->pBuffers[i].cbBuffer, crc);
1565             }
1566         }
1567
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;
1581
1582         ++(helper->crypt.ntlm.seq_num);
1583
1584         if(encrypt_sig)
1585             SECUR32_arc4Process(helper->crypt.ntlm.a4i, sig+4, 12);
1586         return SEC_E_OK;
1587     }
1588
1589     if(helper->neg_flags & NTLMSSP_NEGOTIATE_ALWAYS_SIGN || helper->neg_flags == 0)
1590     {
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;
1596         return SEC_E_OK;
1597     }
1598
1599     return SEC_E_UNSUPPORTED_FUNCTION;
1600 }
1601
1602 /***********************************************************************
1603  *              MakeSignature
1604  */
1605 static SECURITY_STATUS SEC_ENTRY ntlm_MakeSignature(PCtxtHandle phContext, ULONG fQOP,
1606  PSecBufferDesc pMessage, ULONG MessageSeqNo)
1607 {
1608     PNegoHelper helper;
1609     int token_idx;
1610
1611     TRACE("%p %d %p %d\n", phContext, fQOP, pMessage, MessageSeqNo);
1612     if (!phContext)
1613         return SEC_E_INVALID_HANDLE;
1614
1615     if(fQOP)
1616         FIXME("Ignoring fQOP 0x%08x\n", fQOP);
1617
1618     if(MessageSeqNo)
1619         FIXME("Ignoring MessageSeqNo\n");
1620
1621     if(!pMessage || !pMessage->pBuffers || pMessage->cBuffers < 2)
1622         return SEC_E_INVALID_TOKEN;
1623
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;
1627
1628     if(pMessage->pBuffers[token_idx].cbBuffer < 16)
1629         return SEC_E_BUFFER_TOO_SMALL;
1630
1631     helper = (PNegoHelper)phContext->dwLower;
1632     TRACE("Negotiated flags are: 0x%08lx\n", helper->neg_flags);
1633
1634     return ntlm_CreateSignature(helper, pMessage, token_idx, NTLM_SEND, TRUE);
1635 }
1636
1637 /***********************************************************************
1638  *              VerifySignature
1639  */
1640 static SECURITY_STATUS SEC_ENTRY ntlm_VerifySignature(PCtxtHandle phContext,
1641  PSecBufferDesc pMessage, ULONG MessageSeqNo, PULONG pfQOP)
1642 {
1643     PNegoHelper helper;
1644     ULONG fQOP = 0;
1645     UINT i;
1646     int token_idx;
1647     SECURITY_STATUS ret;
1648     SecBufferDesc local_desc;
1649     PSecBuffer     local_buff;
1650     BYTE          local_sig[16];
1651
1652     TRACE("%p %p %d %p\n", phContext, pMessage, MessageSeqNo, pfQOP);
1653     if(!phContext)
1654         return SEC_E_INVALID_HANDLE;
1655
1656     if(!pMessage || !pMessage->pBuffers || pMessage->cBuffers < 2)
1657         return SEC_E_INVALID_TOKEN;
1658
1659     if((token_idx = ntlm_GetTokenBufferIndex(pMessage)) == -1)
1660         return SEC_E_INVALID_TOKEN;
1661
1662     if(pMessage->pBuffers[token_idx].cbBuffer < 16)
1663         return SEC_E_BUFFER_TOO_SMALL;
1664
1665     if(MessageSeqNo)
1666         FIXME("Ignoring MessageSeqNo\n");
1667
1668     helper = (PNegoHelper)phContext->dwLower;
1669     TRACE("Negotiated flags: 0x%08lx\n", helper->neg_flags);
1670
1671     local_buff = HeapAlloc(GetProcessHeap(), 0, pMessage->cBuffers * sizeof(SecBuffer));
1672
1673     local_desc.ulVersion = SECBUFFER_VERSION;
1674     local_desc.cBuffers = pMessage->cBuffers;
1675     local_desc.pBuffers = local_buff;
1676
1677     for(i=0; i < pMessage->cBuffers; ++i)
1678     {
1679         if(pMessage->pBuffers[i].BufferType == SECBUFFER_TOKEN)
1680         {
1681             local_buff[i].BufferType = SECBUFFER_TOKEN;
1682             local_buff[i].cbBuffer = 16;
1683             local_buff[i].pvBuffer = local_sig;
1684         }
1685         else
1686         {
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;
1690         }
1691     }
1692
1693     if((ret = ntlm_CreateSignature(helper, &local_desc, token_idx, NTLM_RECV, TRUE)) != SEC_E_OK)
1694         return ret;
1695
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;
1699     else
1700         ret = SEC_E_OK;
1701
1702     HeapFree(GetProcessHeap(), 0, local_buff);
1703     pfQOP = &fQOP;
1704
1705     return ret;
1706
1707 }
1708
1709 /***********************************************************************
1710  *             FreeCredentialsHandle
1711  */
1712 static SECURITY_STATUS SEC_ENTRY ntlm_FreeCredentialsHandle(
1713         PCredHandle phCredential)
1714 {
1715     SECURITY_STATUS ret;
1716
1717     if(phCredential){
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);
1726         ret = SEC_E_OK;
1727     }
1728     else
1729         ret = SEC_E_OK;
1730     
1731     return ret;
1732 }
1733
1734 /***********************************************************************
1735  *             EncryptMessage
1736  */
1737 static SECURITY_STATUS SEC_ENTRY ntlm_EncryptMessage(PCtxtHandle phContext,
1738         ULONG fQOP, PSecBufferDesc pMessage, ULONG MessageSeqNo)
1739 {
1740     PNegoHelper helper;
1741     int token_idx, data_idx;
1742
1743     TRACE("(%p %d %p %d)\n", phContext, fQOP, pMessage, MessageSeqNo);
1744
1745     if(!phContext)
1746         return SEC_E_INVALID_HANDLE;
1747
1748     if(fQOP)
1749         FIXME("Ignoring fQOP\n");
1750
1751     if(MessageSeqNo)
1752         FIXME("Ignoring MessageSeqNo\n");
1753
1754     if(!pMessage || !pMessage->pBuffers || pMessage->cBuffers < 2)
1755         return SEC_E_INVALID_TOKEN;
1756
1757     if((token_idx = ntlm_GetTokenBufferIndex(pMessage)) == -1)
1758         return SEC_E_INVALID_TOKEN;
1759
1760     if((data_idx = ntlm_GetDataBufferIndex(pMessage)) ==-1 )
1761         return SEC_E_INVALID_TOKEN;
1762
1763     if(pMessage->pBuffers[token_idx].cbBuffer < 16)
1764         return SEC_E_BUFFER_TOO_SMALL;
1765
1766     helper = (PNegoHelper) phContext->dwLower;
1767
1768     if(helper->neg_flags & NTLMSSP_NEGOTIATE_NTLM2 && 
1769             helper->neg_flags & NTLMSSP_NEGOTIATE_SEAL)
1770     { 
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);
1775
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);
1779
1780
1781         return SEC_E_OK;
1782     }
1783     else
1784     {
1785         PBYTE sig;
1786         ULONG save_flags;
1787
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;
1794
1795         sig = pMessage->pBuffers[token_idx].pvBuffer;
1796
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);
1801
1802         if(helper->neg_flags & NTLMSSP_NEGOTIATE_ALWAYS_SIGN || helper->neg_flags == 0)
1803             memset(sig+4, 0, 4);
1804
1805     }
1806
1807     return SEC_E_OK;
1808 }
1809
1810 /***********************************************************************
1811  *             DecryptMessage
1812  */
1813 static SECURITY_STATUS SEC_ENTRY ntlm_DecryptMessage(PCtxtHandle phContext,
1814         PSecBufferDesc pMessage, ULONG MessageSeqNo, PULONG pfQOP)
1815 {
1816     SECURITY_STATUS ret;
1817     ULONG ntlmssp_flags_save;
1818     PNegoHelper helper;
1819     int token_idx, data_idx;
1820     TRACE("(%p %p %d %p)\n", phContext, pMessage, MessageSeqNo, pfQOP);
1821
1822     if(!phContext)
1823         return SEC_E_INVALID_HANDLE;
1824
1825     if(MessageSeqNo)
1826         FIXME("Ignoring MessageSeqNo\n");
1827
1828     if(!pMessage || !pMessage->pBuffers || pMessage->cBuffers < 2)
1829         return SEC_E_INVALID_TOKEN;
1830
1831     if((token_idx = ntlm_GetTokenBufferIndex(pMessage)) == -1)
1832         return SEC_E_INVALID_TOKEN;
1833
1834     if((data_idx = ntlm_GetDataBufferIndex(pMessage)) ==-1)
1835         return SEC_E_INVALID_TOKEN;
1836
1837     if(pMessage->pBuffers[token_idx].cbBuffer < 16)
1838         return SEC_E_BUFFER_TOO_SMALL;
1839
1840     helper = (PNegoHelper) phContext->dwLower;
1841
1842     if(helper->neg_flags & NTLMSSP_NEGOTIATE_NTLM2 && helper->neg_flags & NTLMSSP_NEGOTIATE_SEAL)
1843     {
1844         SECUR32_arc4Process(helper->crypt.ntlm2.recv_a4i,
1845                 pMessage->pBuffers[data_idx].pvBuffer,
1846                 pMessage->pBuffers[data_idx].cbBuffer);
1847     }
1848     else
1849     {
1850         SECUR32_arc4Process(helper->crypt.ntlm.a4i,
1851                 pMessage->pBuffers[data_idx].pvBuffer,
1852                 pMessage->pBuffers[data_idx].cbBuffer);
1853     }
1854
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;
1858
1859     helper->neg_flags |= NTLMSSP_NEGOTIATE_SIGN;
1860     ret = ntlm_VerifySignature(phContext, pMessage, MessageSeqNo, pfQOP);
1861
1862     helper->neg_flags = ntlmssp_flags_save;
1863
1864     return ret;
1865 }
1866
1867 static const SecurityFunctionTableA ntlmTableA = {
1868     1,
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 */
1896 };
1897
1898 static const SecurityFunctionTableW ntlmTableW = {
1899     1,
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 */
1927 };
1928
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}
1933
1934 static CHAR ntlm_comment_A[] = NTLM_COMMENT;
1935 static WCHAR ntlm_comment_W[] = NTLM_COMMENT;
1936
1937 #define NTLM_NAME {'N', 'T', 'L', 'M', 0}
1938
1939 static char ntlm_name_A[] = NTLM_NAME;
1940 static WCHAR ntlm_name_W[] = NTLM_NAME;
1941
1942 /* According to Windows, NTLM has the following capabilities.  */
1943 #define CAPS ( \
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)
1952
1953 static const SecPkgInfoW infoW = {
1954     CAPS,
1955     1,
1956     RPC_C_AUTHN_WINNT,
1957     NTLM_MAX_BUF,
1958     ntlm_name_W,
1959     ntlm_comment_W
1960 };
1961
1962 static const SecPkgInfoA infoA = {
1963     CAPS,
1964     1,
1965     RPC_C_AUTHN_WINNT,
1966     NTLM_MAX_BUF,
1967     ntlm_name_A,
1968     ntlm_comment_A
1969 };
1970
1971 void SECUR32_initNTLMSP(void)
1972 {
1973     PNegoHelper helper;
1974     static CHAR version[] = "--version";
1975
1976     SEC_CHAR *args[] = {
1977         ntlm_auth,
1978         version,
1979         NULL };
1980
1981     if(fork_helper(&helper, ntlm_auth, args) != SEC_E_OK)
1982     {
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;
1986     }
1987     else
1988         check_version(helper);
1989
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) )
1996     {
1997         SecureProvider *provider = SECUR32_addProvider(&ntlmTableA, &ntlmTableW, NULL);
1998         SECUR32_addPackages(provider, 1L, &infoA, &infoW);
1999     }
2000     else
2001     {
2002         ERR("%s was not found or is outdated. "
2003             "Make sure that ntlm_auth >= %d.%d.%d is in your path.\n",
2004             ntlm_auth,
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 "
2009             "distribution.\n");
2010
2011     }
2012     cleanup_helper(helper);
2013 }