quartz: Fix discontinuities in wave 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             char *ptr;
619             if((ptr = strstr(want_flags, "NTLMSSP_FEATURE_SEAL")) == NULL)
620                 lstrcatA(want_flags, " NTLMSSP_FEATURE_SEAL");
621         }
622         if(fContextReq & ISC_REQ_CONNECTION)
623             ctxt_attr |= ISC_RET_CONNECTION;
624         if(fContextReq & ISC_REQ_EXTENDED_ERROR)
625             ctxt_attr |= ISC_RET_EXTENDED_ERROR;
626         if(fContextReq & ISC_REQ_INTEGRITY)
627         {
628             char *ptr;
629             if((ptr = strstr(want_flags, "NTLMSSP_FEATURE_SIGN")) == NULL)
630                 lstrcatA(want_flags, " NTLMSSP_FEATURE_SIGN");
631         }
632         if(fContextReq & ISC_REQ_MUTUAL_AUTH)
633             ctxt_attr |= ISC_RET_MUTUAL_AUTH;
634         if(fContextReq & ISC_REQ_REPLAY_DETECT)
635         {
636             char *ptr;
637             if((ptr = strstr(want_flags, "NTLMSSP_FEATURE_SIGN")) == NULL)
638                 lstrcatA(want_flags, " NTLMSSP_FEATURE_SIGN");
639         }
640         if(fContextReq & ISC_REQ_SEQUENCE_DETECT)
641         {
642             char *ptr;
643             if((ptr = strstr(want_flags, "NTLMSSP_FEATURE_SIGN")) == NULL)
644                 lstrcatA(want_flags, " NTLMSSP_FEATURE_SIGN");
645         }
646         if(fContextReq & ISC_REQ_STREAM)
647             FIXME("ISC_REQ_STREAM\n");
648         if(fContextReq & ISC_REQ_USE_DCE_STYLE)
649             ctxt_attr |= ISC_RET_USED_DCE_STYLE;
650         if(fContextReq & ISC_REQ_DELEGATE)
651             ctxt_attr |= ISC_RET_DELEGATE;
652
653         /* If no password is given, try to use cached credentials. Fall back to an empty
654          * password if this failed. */
655         if(!password && !ntlm_cred->password)
656         {
657             lstrcpynA(buffer, "OK", max_len-1);
658             if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
659             {
660                 cleanup_helper(helper);
661                 goto isc_end;
662             }
663             /* If the helper replied with "PW", using cached credentials failed */
664             if(!strncmp(buffer, "PW", 2))
665             {
666                 TRACE("Using cached credentials failed.\n");
667                 ret = SEC_E_NO_CREDENTIALS;
668                 goto isc_end;
669             }
670             else /* Just do a noop on the next run */
671                 lstrcpynA(buffer, "OK", max_len-1);
672         }
673         else
674         {
675             lstrcpynA(buffer, "PW ", max_len-1);
676             if((ret = encodeBase64(password ? (unsigned char *)password : (unsigned char *)ntlm_cred->password,
677                         password ? pwlen : ntlm_cred->pwlen, buffer+3,
678                         max_len-3, &buffer_len)) != SEC_E_OK)
679             {
680                 cleanup_helper(helper);
681                 goto isc_end;
682             }
683
684         }
685
686         TRACE("Sending to helper: %s\n", debugstr_a(buffer));
687         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
688         {
689             cleanup_helper(helper);
690             goto isc_end;
691         }
692
693         TRACE("Helper returned %s\n", debugstr_a(buffer));
694
695         if(lstrlenA(want_flags) > 2)
696         {
697             TRACE("Want flags are %s\n", debugstr_a(want_flags));
698             lstrcpynA(buffer, want_flags, max_len-1);
699             if((ret = run_helper(helper, buffer, max_len, &buffer_len)) 
700                     != SEC_E_OK)
701                 goto isc_end;
702             if(!strncmp(buffer, "BH", 2))
703                 ERR("Helper doesn't understand new command set. Expect more things to fail.\n");
704         }
705
706         lstrcpynA(buffer, "YR", max_len-1);
707
708         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
709         {
710             cleanup_helper(helper);
711             goto isc_end;
712         }
713
714         TRACE("%s\n", buffer);
715
716         if(strncmp(buffer, "YR ", 3) != 0)
717         {
718             /* Something borked */
719             TRACE("Helper returned %c%c\n", buffer[0], buffer[1]);
720             ret = SEC_E_INTERNAL_ERROR;
721             cleanup_helper(helper);
722             goto isc_end;
723         }
724         if((ret = decodeBase64(buffer+3, buffer_len-3, bin,
725                         max_len-1, &bin_len)) != SEC_E_OK)
726         {
727             cleanup_helper(helper);
728             goto isc_end;
729         }
730
731         /* put the decoded client blob into the out buffer */
732
733         phNewContext->dwUpper = ctxt_attr;
734         phNewContext->dwLower = (ULONG_PTR)helper;
735
736         ret = SEC_I_CONTINUE_NEEDED;
737     }
738     else
739     {
740         int input_token_idx;
741
742         /* handle second call here */
743         /* encode server data to base64 */
744         if (!pInput || ((input_token_idx = ntlm_GetTokenBufferIndex(pInput)) == -1))
745         {
746             ret = SEC_E_INVALID_TOKEN;
747             goto isc_end;
748         }
749
750         if(!phContext)
751         {
752             ret = SEC_E_INVALID_HANDLE;
753             goto isc_end;
754         }
755
756         /* As the server side of sspi never calls this, make sure that
757          * the handler is a client handler.
758          */
759         helper = (PNegoHelper)phContext->dwLower;
760         if(helper->mode != NTLM_CLIENT)
761         {
762             TRACE("Helper mode = %d\n", helper->mode);
763             ret = SEC_E_INVALID_HANDLE;
764             goto isc_end;
765         }
766
767         if (!pInput->pBuffers[input_token_idx].pvBuffer)
768         {
769             ret = SEC_E_INTERNAL_ERROR;
770             goto isc_end;
771         }
772
773         if(pInput->pBuffers[input_token_idx].cbBuffer > max_len)
774         {
775             TRACE("pInput->pBuffers[%d].cbBuffer is: %ld\n",
776                     input_token_idx,
777                     pInput->pBuffers[input_token_idx].cbBuffer);
778             ret = SEC_E_INVALID_TOKEN;
779             goto isc_end;
780         }
781         else
782             bin_len = pInput->pBuffers[input_token_idx].cbBuffer;
783
784         memcpy(bin, pInput->pBuffers[input_token_idx].pvBuffer, bin_len);
785
786         lstrcpynA(buffer, "TT ", max_len-1);
787
788         if((ret = encodeBase64(bin, bin_len, buffer+3,
789                         max_len-3, &buffer_len)) != SEC_E_OK)
790             goto isc_end;
791
792         TRACE("Server sent: %s\n", debugstr_a(buffer));
793
794         /* send TT base64 blob to ntlm_auth */
795         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
796             goto isc_end;
797
798         TRACE("Helper replied: %s\n", debugstr_a(buffer));
799
800         if( (strncmp(buffer, "KK ", 3) != 0) &&
801                 (strncmp(buffer, "AF ", 3) !=0))
802         {
803             TRACE("Helper returned %c%c\n", buffer[0], buffer[1]);
804             ret = SEC_E_INVALID_TOKEN;
805             goto isc_end;
806         }
807
808         /* decode the blob and send it to server */
809         if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len,
810                         &bin_len)) != SEC_E_OK)
811         {
812             goto isc_end;
813         }
814
815         phNewContext->dwUpper = ctxt_attr;
816         phNewContext->dwLower = (ULONG_PTR)helper;
817
818         ret = SEC_E_OK;
819     }
820
821     /* put the decoded client blob into the out buffer */
822
823     if (!pOutput || ((token_idx = ntlm_GetTokenBufferIndex(pOutput)) == -1))
824     {
825         TRACE("no SECBUFFER_TOKEN buffer could be found\n");
826         ret = SEC_E_BUFFER_TOO_SMALL;
827         if ((phContext == NULL) && (pInput == NULL))
828         {
829             cleanup_helper(helper);
830             phNewContext->dwUpper = 0;
831             phNewContext->dwLower = 0;
832         }
833         goto isc_end;
834     }
835
836     if (fContextReq & ISC_REQ_ALLOCATE_MEMORY)
837     {
838         pOutput->pBuffers[token_idx].pvBuffer = HeapAlloc(GetProcessHeap(), 0, bin_len);
839         pOutput->pBuffers[token_idx].cbBuffer = bin_len;
840     }
841     else if (pOutput->pBuffers[token_idx].cbBuffer < bin_len)
842     {
843         TRACE("out buffer is NULL or has not enough space\n");
844         ret = SEC_E_BUFFER_TOO_SMALL;
845         if ((phContext == NULL) && (pInput == NULL))
846         {
847             cleanup_helper(helper);
848             phNewContext->dwUpper = 0;
849             phNewContext->dwLower = 0;
850         }
851         goto isc_end;
852     }
853
854     if (!pOutput->pBuffers[token_idx].pvBuffer)
855     {
856         TRACE("out buffer is NULL\n");
857         ret = SEC_E_INTERNAL_ERROR;
858         if ((phContext == NULL) && (pInput == NULL))
859         {
860             cleanup_helper(helper);
861             phNewContext->dwUpper = 0;
862             phNewContext->dwLower = 0;
863         }
864         goto isc_end;
865     }
866
867     pOutput->pBuffers[token_idx].cbBuffer = bin_len;
868     memcpy(pOutput->pBuffers[token_idx].pvBuffer, bin, bin_len);
869
870     if(ret == SEC_E_OK)
871     {
872         TRACE("Getting negotiated flags\n");
873         lstrcpynA(buffer, "GF", max_len - 1);
874         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
875             goto isc_end;
876
877         if(buffer_len < 3)
878         {
879             TRACE("No flags negotiated.\n");
880             helper->neg_flags = 0l;
881         }
882         else
883         {
884             TRACE("Negotiated %s\n", debugstr_a(buffer));
885             sscanf(buffer + 3, "%lx", &(helper->neg_flags));
886             TRACE("Stored 0x%08lx as flags\n", helper->neg_flags);
887         }
888
889         TRACE("Getting session key\n");
890         lstrcpynA(buffer, "GK", max_len - 1);
891         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
892             goto isc_end;
893
894         if(strncmp(buffer, "BH", 2) == 0)
895             TRACE("No key negotiated.\n");
896         else if(strncmp(buffer, "GK ", 3) == 0)
897         {
898             if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len, 
899                             &bin_len)) != SEC_E_OK)
900             {
901                 TRACE("Failed to decode session key\n");
902             }
903             TRACE("Session key is %s\n", debugstr_a(buffer+3));
904             HeapFree(GetProcessHeap(), 0, helper->session_key);
905             helper->session_key = HeapAlloc(GetProcessHeap(), 0, bin_len);
906             if(!helper->session_key)
907             {
908                 TRACE("Failed to allocate memory for session key\n");
909                 ret = SEC_E_INTERNAL_ERROR;
910                 goto isc_end;
911             }
912             memcpy(helper->session_key, bin, bin_len);
913         }
914
915         helper->crypt.ntlm.a4i = SECUR32_arc4Alloc();
916         SECUR32_arc4Init(helper->crypt.ntlm.a4i, helper->session_key, 16);
917         helper->crypt.ntlm.seq_num = 0l;
918         SECUR32_CreateNTLMv2SubKeys(helper);
919         helper->crypt.ntlm2.send_a4i = SECUR32_arc4Alloc();
920         helper->crypt.ntlm2.recv_a4i = SECUR32_arc4Alloc();
921         SECUR32_arc4Init(helper->crypt.ntlm2.send_a4i,
922                          helper->crypt.ntlm2.send_seal_key, 16);
923         SECUR32_arc4Init(helper->crypt.ntlm2.recv_a4i,
924                          helper->crypt.ntlm2.recv_seal_key, 16);
925         helper->crypt.ntlm2.send_seq_no = 0l;
926         helper->crypt.ntlm2.recv_seq_no = 0l;
927     }
928
929 isc_end:
930     HeapFree(GetProcessHeap(), 0, username);
931     HeapFree(GetProcessHeap(), 0, domain);
932     HeapFree(GetProcessHeap(), 0, password);
933     HeapFree(GetProcessHeap(), 0, want_flags);
934     HeapFree(GetProcessHeap(), 0, buffer);
935     HeapFree(GetProcessHeap(), 0, bin);
936     return ret;
937 }
938
939 /***********************************************************************
940  *              InitializeSecurityContextA
941  */
942 static SECURITY_STATUS SEC_ENTRY ntlm_InitializeSecurityContextA(
943  PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR *pszTargetName,
944  ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep, 
945  PSecBufferDesc pInput,ULONG Reserved2, PCtxtHandle phNewContext, 
946  PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
947 {
948     SECURITY_STATUS ret;
949     SEC_WCHAR *target = NULL;
950
951     TRACE("%p %p %s %d %d %d %p %d %p %p %p %p\n", phCredential, phContext,
952      debugstr_a(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
953      Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
954
955     if(pszTargetName != NULL)
956     {
957         int target_size = MultiByteToWideChar(CP_ACP, 0, pszTargetName,
958             strlen(pszTargetName)+1, NULL, 0);
959         target = HeapAlloc(GetProcessHeap(), 0, target_size *
960                 sizeof(SEC_WCHAR));
961         MultiByteToWideChar(CP_ACP, 0, pszTargetName, strlen(pszTargetName)+1,
962             target, target_size);
963     }
964
965     ret = ntlm_InitializeSecurityContextW(phCredential, phContext, target,
966             fContextReq, Reserved1, TargetDataRep, pInput, Reserved2,
967             phNewContext, pOutput, pfContextAttr, ptsExpiry);
968
969     HeapFree(GetProcessHeap(), 0, target);
970     return ret;
971 }
972
973 /***********************************************************************
974  *              AcceptSecurityContext
975  */
976 static SECURITY_STATUS SEC_ENTRY ntlm_AcceptSecurityContext(
977  PCredHandle phCredential, PCtxtHandle phContext, PSecBufferDesc pInput,
978  ULONG fContextReq, ULONG TargetDataRep, PCtxtHandle phNewContext, 
979  PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
980 {
981     SECURITY_STATUS ret;
982     char *buffer, *want_flags = NULL;
983     PBYTE bin;
984     int buffer_len, bin_len, max_len = NTLM_MAX_BUF;
985     ULONG ctxt_attr = 0;
986     PNegoHelper helper;
987     PNtlmCredentials ntlm_cred;
988
989     TRACE("%p %p %p %d %d %p %p %p %p\n", phCredential, phContext, pInput,
990      fContextReq, TargetDataRep, phNewContext, pOutput, pfContextAttr,
991      ptsExpiry);
992
993     buffer = HeapAlloc(GetProcessHeap(), 0, sizeof(char) * NTLM_MAX_BUF);
994     bin    = HeapAlloc(GetProcessHeap(),0, sizeof(BYTE) * NTLM_MAX_BUF);
995
996     if(TargetDataRep == SECURITY_NETWORK_DREP){
997         TRACE("Using SECURITY_NETWORK_DREP\n");
998     }
999
1000     if(phContext == NULL)
1001     {
1002         static CHAR server_helper_protocol[] = "--helper-protocol=squid-2.5-ntlmssp";
1003         SEC_CHAR *server_argv[] = { ntlm_auth,
1004             server_helper_protocol,
1005             NULL };
1006
1007         if (!phCredential)
1008         {
1009             ret = SEC_E_INVALID_HANDLE;
1010             goto asc_end;
1011         }
1012
1013         ntlm_cred = (PNtlmCredentials)phCredential->dwLower;
1014
1015         if(ntlm_cred->mode != NTLM_SERVER)
1016         {
1017             ret = SEC_E_INVALID_HANDLE;
1018             goto asc_end;
1019         }
1020
1021         /* This is the first call to AcceptSecurityHandle */
1022         if(pInput == NULL)
1023         {
1024             ret = SEC_E_INCOMPLETE_MESSAGE;
1025             goto asc_end;
1026         }
1027
1028         if(pInput->cBuffers < 1)
1029         {
1030             ret = SEC_E_INCOMPLETE_MESSAGE;
1031             goto asc_end;
1032         }
1033
1034         if(pInput->pBuffers[0].cbBuffer > max_len)
1035         {
1036             ret = SEC_E_INVALID_TOKEN;
1037             goto asc_end;
1038         }
1039         else
1040             bin_len = pInput->pBuffers[0].cbBuffer;
1041
1042         if( (ret = fork_helper(&helper, ntlm_auth, server_argv)) !=
1043             SEC_E_OK)
1044         {
1045             ret = SEC_E_INTERNAL_ERROR;
1046             goto asc_end;
1047         }
1048         helper->mode = NTLM_SERVER;
1049
1050         /* Handle all the flags */
1051         want_flags = HeapAlloc(GetProcessHeap(), 0, 73);
1052         if(want_flags == NULL)
1053         {
1054             TRACE("Failed to allocate memory for the want_flags!\n");
1055             ret = SEC_E_INSUFFICIENT_MEMORY;
1056             cleanup_helper(helper);
1057             goto asc_end;
1058         }
1059         lstrcpyA(want_flags, "SF");
1060         if(fContextReq & ASC_REQ_ALLOCATE_MEMORY)
1061         {
1062             FIXME("ASC_REQ_ALLOCATE_MEMORY stub\n");
1063         }
1064         if(fContextReq & ASC_REQ_CONFIDENTIALITY)
1065         {
1066             lstrcatA(want_flags, " NTLMSSP_FEATURE_SEAL");
1067         }
1068         if(fContextReq & ASC_REQ_CONNECTION)
1069         {
1070             /* This is default, so we'll enable it */
1071             lstrcatA(want_flags, " NTLMSSP_FEATURE_SESSION_KEY");
1072             ctxt_attr |= ASC_RET_CONNECTION;
1073         }
1074         if(fContextReq & ASC_REQ_EXTENDED_ERROR)
1075         {
1076             FIXME("ASC_REQ_EXTENDED_ERROR stub\n");
1077         }
1078         if(fContextReq & ASC_REQ_INTEGRITY)
1079         {
1080             lstrcatA(want_flags, " NTLMSSP_FEATURE_SIGN");
1081         }
1082         if(fContextReq & ASC_REQ_MUTUAL_AUTH)
1083         {
1084             FIXME("ASC_REQ_MUTUAL_AUTH stub\n");
1085         }
1086         if(fContextReq & ASC_REQ_REPLAY_DETECT)
1087         {
1088             FIXME("ASC_REQ_REPLAY_DETECT stub\n");
1089         }
1090         if(fContextReq & ISC_REQ_SEQUENCE_DETECT)
1091         {
1092             FIXME("ASC_REQ_SEQUENCE_DETECT stub\n");
1093         }
1094         if(fContextReq & ISC_REQ_STREAM)
1095         {
1096             FIXME("ASC_REQ_STREAM stub\n");
1097         }
1098         /* Done with the flags */
1099
1100         if(lstrlenA(want_flags) > 3)
1101         {
1102             TRACE("Server set want_flags: %s\n", debugstr_a(want_flags));
1103             lstrcpynA(buffer, want_flags, max_len - 1);
1104             if((ret = run_helper(helper, buffer, max_len, &buffer_len)) !=
1105                     SEC_E_OK)
1106             {
1107                 cleanup_helper(helper);
1108                 goto asc_end;
1109             }
1110             if(!strncmp(buffer, "BH", 2))
1111                 TRACE("Helper doesn't understand new command set\n");
1112         }
1113
1114         /* This is the YR request from the client, encode to base64 */
1115
1116         memcpy(bin, pInput->pBuffers[0].pvBuffer, bin_len);
1117
1118         lstrcpynA(buffer, "YR ", max_len-1);
1119
1120         if((ret = encodeBase64(bin, bin_len, buffer+3, max_len-3,
1121                     &buffer_len)) != SEC_E_OK)
1122         {
1123             cleanup_helper(helper);
1124             goto asc_end;
1125         }
1126
1127         TRACE("Client sent: %s\n", debugstr_a(buffer));
1128
1129         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) !=
1130                     SEC_E_OK)
1131         {
1132             cleanup_helper(helper);
1133             goto asc_end;
1134         }
1135
1136         TRACE("Reply from ntlm_auth: %s\n", debugstr_a(buffer));
1137         /* The expected answer is TT <base64 blob> */
1138
1139         if(strncmp(buffer, "TT ", 3) != 0)
1140         {
1141             ret = SEC_E_INTERNAL_ERROR;
1142             cleanup_helper(helper);
1143             goto asc_end;
1144         }
1145
1146         if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len,
1147                         &bin_len)) != SEC_E_OK)
1148         {
1149             cleanup_helper(helper);
1150             goto asc_end;
1151         }
1152
1153         /* send this to the client */
1154         if(pOutput == NULL)
1155         {
1156             ret = SEC_E_INSUFFICIENT_MEMORY;
1157             cleanup_helper(helper);
1158             goto asc_end;
1159         }
1160
1161         if(pOutput->cBuffers < 1)
1162         {
1163             ret = SEC_E_INSUFFICIENT_MEMORY;
1164             cleanup_helper(helper);
1165             goto asc_end;
1166         }
1167
1168         pOutput->pBuffers[0].cbBuffer = bin_len;
1169         pOutput->pBuffers[0].BufferType = SECBUFFER_DATA;
1170         memcpy(pOutput->pBuffers[0].pvBuffer, bin, bin_len);
1171         ret = SEC_I_CONTINUE_NEEDED;
1172
1173     }
1174     else
1175     {
1176         /* we expect a KK request from client */
1177         if(pInput == NULL)
1178         {
1179             ret = SEC_E_INCOMPLETE_MESSAGE;
1180             goto asc_end;
1181         }
1182
1183         if(pInput->cBuffers < 1)
1184         {
1185             ret = SEC_E_INCOMPLETE_MESSAGE;
1186             goto asc_end;
1187         }
1188
1189         if(!phContext)
1190         {
1191             ret = SEC_E_INVALID_HANDLE;
1192             goto asc_end;
1193         }
1194
1195         helper = (PNegoHelper)phContext->dwLower;
1196
1197         if(helper->mode != NTLM_SERVER)
1198         {
1199             ret = SEC_E_INVALID_HANDLE;
1200             goto asc_end;
1201         }
1202
1203         if(pInput->pBuffers[0].cbBuffer > max_len)
1204         {
1205             ret = SEC_E_INVALID_TOKEN;
1206             goto asc_end;
1207         }
1208         else
1209             bin_len = pInput->pBuffers[0].cbBuffer;
1210
1211         memcpy(bin, pInput->pBuffers[0].pvBuffer, bin_len);
1212
1213         lstrcpynA(buffer, "KK ", max_len-1);
1214
1215         if((ret = encodeBase64(bin, bin_len, buffer+3, max_len-3,
1216                     &buffer_len)) != SEC_E_OK)
1217         {
1218             goto asc_end;
1219         }
1220
1221         TRACE("Client sent: %s\n", debugstr_a(buffer));
1222
1223         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) !=
1224                     SEC_E_OK)
1225         {
1226             goto asc_end;
1227         }
1228
1229         TRACE("Reply from ntlm_auth: %s\n", debugstr_a(buffer));
1230
1231         /* At this point, we get a NA if the user didn't authenticate, but a BH
1232          * if ntlm_auth could not connect to winbindd. Apart from running Wine
1233          * as root, there is no way to fix this for now, so just handle this as
1234          * a failed login. */
1235         if(strncmp(buffer, "AF ", 3) != 0)
1236         {
1237             if(strncmp(buffer, "NA ", 3) == 0)
1238             {
1239                 ret = SEC_E_LOGON_DENIED;
1240                 goto asc_end;
1241             }
1242             else
1243             {
1244                 size_t ntlm_pipe_err_len = strlen("BH NT_STATUS_ACCESS_DENIED");
1245
1246                 if( (buffer_len >= ntlm_pipe_err_len) &&
1247                     (strncmp(buffer, "BH NT_STATUS_ACCESS_DENIED",
1248                              ntlm_pipe_err_len) == 0))
1249                 {
1250                     TRACE("Connection to winbindd failed\n");
1251                     ret = SEC_E_LOGON_DENIED;
1252                 }
1253                 else
1254                     ret = SEC_E_INTERNAL_ERROR;
1255
1256                 goto asc_end;
1257             }
1258         }
1259         pOutput->pBuffers[0].cbBuffer = 0;
1260         ret = SEC_E_OK;
1261
1262         TRACE("Getting negotiated flags\n");
1263         lstrcpynA(buffer, "GF", max_len - 1);
1264         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
1265             goto asc_end;
1266
1267         if(buffer_len < 3)
1268         {
1269             TRACE("No flags negotiated, or helper does not support GF command\n");
1270         }
1271         else
1272         {
1273             TRACE("Negotiated %s\n", debugstr_a(buffer));
1274             sscanf(buffer + 3, "%lx", &(helper->neg_flags));
1275             TRACE("Stored 0x%08lx as flags\n", helper->neg_flags);
1276         }
1277
1278         TRACE("Getting session key\n");
1279         lstrcpynA(buffer, "GK", max_len - 1);
1280         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
1281             goto asc_end;
1282
1283         if(buffer_len < 3)
1284             TRACE("Helper does not support GK command\n");
1285         else
1286         {
1287             if(strncmp(buffer, "BH ", 3) == 0)
1288             {
1289                 TRACE("Helper sent %s\n", debugstr_a(buffer+3));
1290                 helper->session_key = HeapAlloc(GetProcessHeap(), 0, 16);
1291                 /*FIXME: Generate the dummy session key = MD4(MD4(password))*/
1292                 memset(helper->session_key, 0 , 16);
1293             }
1294             else if(strncmp(buffer, "GK ", 3) == 0)
1295             {
1296                 if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len, 
1297                                 &bin_len)) != SEC_E_OK)
1298                 {
1299                     TRACE("Failed to decode session key\n");
1300                 }
1301                 TRACE("Session key is %s\n", debugstr_a(buffer+3));
1302                 helper->session_key = HeapAlloc(GetProcessHeap(), 0, 16);
1303                 if(!helper->session_key)
1304                 {
1305                     TRACE("Failed to allocate memory for session key\n");
1306                     ret = SEC_E_INTERNAL_ERROR;
1307                     goto asc_end;
1308                 }
1309                 memcpy(helper->session_key, bin, 16);
1310             }
1311         }
1312         helper->crypt.ntlm.a4i = SECUR32_arc4Alloc();
1313         SECUR32_arc4Init(helper->crypt.ntlm.a4i, helper->session_key, 16);
1314         helper->crypt.ntlm.seq_num = 0l;
1315     }
1316
1317     phNewContext->dwUpper = ctxt_attr;
1318     phNewContext->dwLower = (ULONG_PTR)helper;
1319
1320 asc_end:
1321     HeapFree(GetProcessHeap(), 0, want_flags);
1322     HeapFree(GetProcessHeap(), 0, buffer);
1323     HeapFree(GetProcessHeap(), 0, bin);
1324     return ret;
1325 }
1326
1327 /***********************************************************************
1328  *              CompleteAuthToken
1329  */
1330 static SECURITY_STATUS SEC_ENTRY ntlm_CompleteAuthToken(PCtxtHandle phContext,
1331  PSecBufferDesc pToken)
1332 {
1333     /* We never need to call CompleteAuthToken anyway */
1334     TRACE("%p %p\n", phContext, pToken);
1335     if (!phContext)
1336         return SEC_E_INVALID_HANDLE;
1337     
1338     return SEC_E_OK;
1339 }
1340
1341 /***********************************************************************
1342  *              DeleteSecurityContext
1343  */
1344 static SECURITY_STATUS SEC_ENTRY ntlm_DeleteSecurityContext(PCtxtHandle phContext)
1345 {
1346     PNegoHelper helper;
1347
1348     TRACE("%p\n", phContext);
1349     if (!phContext)
1350         return SEC_E_INVALID_HANDLE;
1351
1352     helper = (PNegoHelper)phContext->dwLower;
1353
1354     phContext->dwUpper = 0;
1355     phContext->dwLower = 0;
1356
1357     SECUR32_arc4Cleanup(helper->crypt.ntlm.a4i);
1358     HeapFree(GetProcessHeap(), 0, helper->session_key);
1359     SECUR32_arc4Cleanup(helper->crypt.ntlm2.send_a4i);
1360     SECUR32_arc4Cleanup(helper->crypt.ntlm2.recv_a4i);
1361     HeapFree(GetProcessHeap(), 0, helper->crypt.ntlm2.send_sign_key);
1362     HeapFree(GetProcessHeap(), 0, helper->crypt.ntlm2.send_seal_key);
1363     HeapFree(GetProcessHeap(), 0, helper->crypt.ntlm2.recv_sign_key);
1364     HeapFree(GetProcessHeap(), 0, helper->crypt.ntlm2.recv_seal_key);
1365
1366     cleanup_helper(helper);
1367
1368     return SEC_E_OK;
1369 }
1370
1371 /***********************************************************************
1372  *              QueryContextAttributesW
1373  */
1374 static SECURITY_STATUS SEC_ENTRY ntlm_QueryContextAttributesW(PCtxtHandle phContext,
1375  ULONG ulAttribute, void *pBuffer)
1376 {
1377     TRACE("%p %d %p\n", phContext, ulAttribute, pBuffer);
1378     if (!phContext)
1379         return SEC_E_INVALID_HANDLE;
1380
1381     switch(ulAttribute)
1382     {
1383 #define _x(x) case (x) : FIXME(#x" stub\n"); break
1384         _x(SECPKG_ATTR_ACCESS_TOKEN);
1385         _x(SECPKG_ATTR_AUTHORITY);
1386         _x(SECPKG_ATTR_DCE_INFO);
1387         case SECPKG_ATTR_FLAGS:
1388         {
1389             PSecPkgContext_Flags spcf = (PSecPkgContext_Flags)pBuffer;
1390             PNegoHelper helper = (PNegoHelper)phContext->dwLower;
1391
1392             spcf->Flags = 0;
1393             if(helper->neg_flags & NTLMSSP_NEGOTIATE_SIGN)
1394                 spcf->Flags |= ISC_RET_INTEGRITY;
1395             if(helper->neg_flags & NTLMSSP_NEGOTIATE_SEAL)
1396                 spcf->Flags |= ISC_RET_CONFIDENTIALITY;
1397             return SEC_E_OK;
1398         }
1399         _x(SECPKG_ATTR_KEY_INFO);
1400         _x(SECPKG_ATTR_LIFESPAN);
1401         _x(SECPKG_ATTR_NAMES);
1402         _x(SECPKG_ATTR_NATIVE_NAMES);
1403         _x(SECPKG_ATTR_NEGOTIATION_INFO);
1404         _x(SECPKG_ATTR_PACKAGE_INFO);
1405         _x(SECPKG_ATTR_PASSWORD_EXPIRY);
1406         _x(SECPKG_ATTR_SESSION_KEY);
1407         case SECPKG_ATTR_SIZES:
1408         {
1409             PSecPkgContext_Sizes spcs = (PSecPkgContext_Sizes)pBuffer;
1410             spcs->cbMaxToken = NTLM_MAX_BUF;
1411             spcs->cbMaxSignature = 16;
1412             spcs->cbBlockSize = 0;
1413             spcs->cbSecurityTrailer = 16;
1414             return SEC_E_OK;
1415         }
1416         _x(SECPKG_ATTR_STREAM_SIZES);
1417         _x(SECPKG_ATTR_TARGET_INFORMATION);
1418 #undef _x
1419         default:
1420             TRACE("Unknown value %d passed for ulAttribute\n", ulAttribute);
1421     }
1422
1423     return SEC_E_UNSUPPORTED_FUNCTION;
1424 }
1425
1426 /***********************************************************************
1427  *              QueryContextAttributesA
1428  */
1429 static SECURITY_STATUS SEC_ENTRY ntlm_QueryContextAttributesA(PCtxtHandle phContext,
1430  ULONG ulAttribute, void *pBuffer)
1431 {
1432     return ntlm_QueryContextAttributesW(phContext, ulAttribute, pBuffer);
1433 }
1434
1435 /***********************************************************************
1436  *              ImpersonateSecurityContext
1437  */
1438 static SECURITY_STATUS SEC_ENTRY ntlm_ImpersonateSecurityContext(PCtxtHandle phContext)
1439 {
1440     SECURITY_STATUS ret;
1441
1442     TRACE("%p\n", phContext);
1443     if (phContext)
1444     {
1445         ret = SEC_E_UNSUPPORTED_FUNCTION;
1446     }
1447     else
1448     {
1449         ret = SEC_E_INVALID_HANDLE;
1450     }
1451     return ret;
1452 }
1453
1454 /***********************************************************************
1455  *              RevertSecurityContext
1456  */
1457 static SECURITY_STATUS SEC_ENTRY ntlm_RevertSecurityContext(PCtxtHandle phContext)
1458 {
1459     SECURITY_STATUS ret;
1460
1461     TRACE("%p\n", phContext);
1462     if (phContext)
1463     {
1464         ret = SEC_E_UNSUPPORTED_FUNCTION;
1465     }
1466     else
1467     {
1468         ret = SEC_E_INVALID_HANDLE;
1469     }
1470     return ret;
1471 }
1472
1473 /***********************************************************************
1474  *             ntlm_CreateSignature
1475  * As both MakeSignature and VerifySignature need this, but different keys
1476  * are needed for NTLMv2, the logic goes into a helper function.
1477  * To ensure maximal reusability, we can specify the direction as NTLM_SEND for
1478  * signing/encrypting and NTLM_RECV for verfying/decrypting. When encrypting,
1479  * the signature is encrypted after the message was encrypted, so
1480  * CreateSignature shouldn't do it. In this case, encrypt_sig can be set to
1481  * false.
1482  */
1483 static SECURITY_STATUS ntlm_CreateSignature(PNegoHelper helper, PSecBufferDesc pMessage,
1484         int token_idx, SignDirection direction, BOOL encrypt_sig)
1485 {
1486     ULONG sign_version = 1;
1487     UINT i;
1488     PBYTE sig;
1489     TRACE("%p, %p, %d, %d, %d\n", helper, pMessage, token_idx, direction,
1490             encrypt_sig);
1491
1492     sig = pMessage->pBuffers[token_idx].pvBuffer;
1493
1494     if(helper->neg_flags & NTLMSSP_NEGOTIATE_NTLM2 &&
1495             helper->neg_flags & NTLMSSP_NEGOTIATE_SIGN)
1496     {
1497         BYTE digest[16];
1498         BYTE seq_no[4];
1499         HMAC_MD5_CTX hmac_md5_ctx;
1500
1501         TRACE("Signing NTLM2 style\n");
1502
1503         if(direction == NTLM_SEND)
1504         {
1505             seq_no[0] = (helper->crypt.ntlm2.send_seq_no >>  0) & 0xff;
1506             seq_no[1] = (helper->crypt.ntlm2.send_seq_no >>  8) & 0xff;
1507             seq_no[2] = (helper->crypt.ntlm2.send_seq_no >> 16) & 0xff;
1508             seq_no[3] = (helper->crypt.ntlm2.send_seq_no >> 24) & 0xff;
1509
1510             ++(helper->crypt.ntlm2.send_seq_no);
1511
1512             HMACMD5Init(&hmac_md5_ctx, helper->crypt.ntlm2.send_sign_key, 16);
1513         }
1514         else
1515         {
1516             seq_no[0] = (helper->crypt.ntlm2.recv_seq_no >>  0) & 0xff;
1517             seq_no[1] = (helper->crypt.ntlm2.recv_seq_no >>  8) & 0xff;
1518             seq_no[2] = (helper->crypt.ntlm2.recv_seq_no >> 16) & 0xff;
1519             seq_no[3] = (helper->crypt.ntlm2.recv_seq_no >> 24) & 0xff;
1520
1521             ++(helper->crypt.ntlm2.recv_seq_no);
1522
1523             HMACMD5Init(&hmac_md5_ctx, helper->crypt.ntlm2.recv_sign_key, 16);
1524         }
1525
1526         HMACMD5Update(&hmac_md5_ctx, seq_no, 4);
1527         for( i = 0; i < pMessage->cBuffers; ++i )
1528         {
1529             if(pMessage->pBuffers[i].BufferType & SECBUFFER_DATA)
1530                 HMACMD5Update(&hmac_md5_ctx, (BYTE *)pMessage->pBuffers[i].pvBuffer,
1531                         pMessage->pBuffers[i].cbBuffer);
1532         }
1533
1534         HMACMD5Final(&hmac_md5_ctx, digest);
1535
1536         if(encrypt_sig && helper->neg_flags & NTLMSSP_NEGOTIATE_KEY_EXCHANGE)
1537         {
1538             if(direction == NTLM_SEND)
1539                 SECUR32_arc4Process(helper->crypt.ntlm2.send_a4i, digest, 8);
1540             else
1541                 SECUR32_arc4Process(helper->crypt.ntlm2.recv_a4i, digest, 8);
1542         }
1543
1544         /* The NTLM2 signature is the sign version */
1545         sig[ 0] = (sign_version >>  0) & 0xff;
1546         sig[ 1] = (sign_version >>  8) & 0xff;
1547         sig[ 2] = (sign_version >> 16) & 0xff;
1548         sig[ 3] = (sign_version >> 24) & 0xff;
1549         /* The first 8 bytes of the digest */
1550         memcpy(sig+4, digest, 8);
1551         /* And the sequence number */
1552         memcpy(sig+12, seq_no, 4);
1553
1554         pMessage->pBuffers[token_idx].cbBuffer = 16;
1555
1556         return SEC_E_OK;
1557     }
1558     if(helper->neg_flags & NTLMSSP_NEGOTIATE_SIGN)
1559     {
1560         ULONG crc = 0U;
1561         TRACE("Signing NTLM1 style\n");
1562
1563         for(i=0; i < pMessage->cBuffers; ++i)
1564         {
1565             if(pMessage->pBuffers[i].BufferType & SECBUFFER_DATA)
1566             {
1567                 crc = ComputeCrc32(pMessage->pBuffers[i].pvBuffer,
1568                     pMessage->pBuffers[i].cbBuffer, crc);
1569             }
1570         }
1571
1572         sig[ 0] = (sign_version >>  0) & 0xff;
1573         sig[ 1] = (sign_version >>  8) & 0xff;
1574         sig[ 2] = (sign_version >> 16) & 0xff;
1575         sig[ 3] = (sign_version >> 24) & 0xff;
1576         memset(sig+4, 0, 4);
1577         sig[ 8] = (crc >>  0) & 0xff;
1578         sig[ 9] = (crc >>  8) & 0xff;
1579         sig[10] = (crc >> 16) & 0xff;
1580         sig[11] = (crc >> 24) & 0xff;
1581         sig[12] = (helper->crypt.ntlm.seq_num >>  0) & 0xff;
1582         sig[13] = (helper->crypt.ntlm.seq_num >>  8) & 0xff;
1583         sig[14] = (helper->crypt.ntlm.seq_num >> 16) & 0xff;
1584         sig[15] = (helper->crypt.ntlm.seq_num >> 24) & 0xff;
1585
1586         ++(helper->crypt.ntlm.seq_num);
1587
1588         if(encrypt_sig)
1589             SECUR32_arc4Process(helper->crypt.ntlm.a4i, sig+4, 12);
1590         return SEC_E_OK;
1591     }
1592
1593     if(helper->neg_flags & NTLMSSP_NEGOTIATE_ALWAYS_SIGN || helper->neg_flags == 0)
1594     {
1595         TRACE("Creating a dummy signature.\n");
1596         /* A dummy signature is 0x01 followed by 15 bytes of 0x00 */
1597         memset(pMessage->pBuffers[token_idx].pvBuffer, 0, 16);
1598         memset(pMessage->pBuffers[token_idx].pvBuffer, 0x01, 1);
1599         pMessage->pBuffers[token_idx].cbBuffer = 16;
1600         return SEC_E_OK;
1601     }
1602
1603     return SEC_E_UNSUPPORTED_FUNCTION;
1604 }
1605
1606 /***********************************************************************
1607  *              MakeSignature
1608  */
1609 static SECURITY_STATUS SEC_ENTRY ntlm_MakeSignature(PCtxtHandle phContext, ULONG fQOP,
1610  PSecBufferDesc pMessage, ULONG MessageSeqNo)
1611 {
1612     PNegoHelper helper;
1613     int token_idx;
1614
1615     TRACE("%p %d %p %d\n", phContext, fQOP, pMessage, MessageSeqNo);
1616     if (!phContext)
1617         return SEC_E_INVALID_HANDLE;
1618
1619     if(fQOP)
1620         FIXME("Ignoring fQOP 0x%08x\n", fQOP);
1621
1622     if(MessageSeqNo)
1623         FIXME("Ignoring MessageSeqNo\n");
1624
1625     if(!pMessage || !pMessage->pBuffers || pMessage->cBuffers < 2)
1626         return SEC_E_INVALID_TOKEN;
1627
1628     /* If we didn't find a SECBUFFER_TOKEN type buffer */
1629     if((token_idx = ntlm_GetTokenBufferIndex(pMessage)) == -1)
1630         return SEC_E_INVALID_TOKEN;
1631
1632     if(pMessage->pBuffers[token_idx].cbBuffer < 16)
1633         return SEC_E_BUFFER_TOO_SMALL;
1634
1635     helper = (PNegoHelper)phContext->dwLower;
1636     TRACE("Negotiated flags are: 0x%08lx\n", helper->neg_flags);
1637
1638     return ntlm_CreateSignature(helper, pMessage, token_idx, NTLM_SEND, TRUE);
1639 }
1640
1641 /***********************************************************************
1642  *              VerifySignature
1643  */
1644 static SECURITY_STATUS SEC_ENTRY ntlm_VerifySignature(PCtxtHandle phContext,
1645  PSecBufferDesc pMessage, ULONG MessageSeqNo, PULONG pfQOP)
1646 {
1647     PNegoHelper helper;
1648     ULONG fQOP = 0;
1649     UINT i;
1650     int token_idx;
1651     SECURITY_STATUS ret;
1652     SecBufferDesc local_desc;
1653     PSecBuffer     local_buff;
1654     BYTE          local_sig[16];
1655
1656     TRACE("%p %p %d %p\n", phContext, pMessage, MessageSeqNo, pfQOP);
1657     if(!phContext)
1658         return SEC_E_INVALID_HANDLE;
1659
1660     if(!pMessage || !pMessage->pBuffers || pMessage->cBuffers < 2)
1661         return SEC_E_INVALID_TOKEN;
1662
1663     if((token_idx = ntlm_GetTokenBufferIndex(pMessage)) == -1)
1664         return SEC_E_INVALID_TOKEN;
1665
1666     if(pMessage->pBuffers[token_idx].cbBuffer < 16)
1667         return SEC_E_BUFFER_TOO_SMALL;
1668
1669     if(MessageSeqNo)
1670         FIXME("Ignoring MessageSeqNo\n");
1671
1672     helper = (PNegoHelper)phContext->dwLower;
1673     TRACE("Negotiated flags: 0x%08lx\n", helper->neg_flags);
1674
1675     local_buff = HeapAlloc(GetProcessHeap(), 0, pMessage->cBuffers * sizeof(SecBuffer));
1676
1677     local_desc.ulVersion = SECBUFFER_VERSION;
1678     local_desc.cBuffers = pMessage->cBuffers;
1679     local_desc.pBuffers = local_buff;
1680
1681     for(i=0; i < pMessage->cBuffers; ++i)
1682     {
1683         if(pMessage->pBuffers[i].BufferType == SECBUFFER_TOKEN)
1684         {
1685             local_buff[i].BufferType = SECBUFFER_TOKEN;
1686             local_buff[i].cbBuffer = 16;
1687             local_buff[i].pvBuffer = local_sig;
1688         }
1689         else
1690         {
1691             local_buff[i].BufferType = pMessage->pBuffers[i].BufferType;
1692             local_buff[i].cbBuffer = pMessage->pBuffers[i].cbBuffer;
1693             local_buff[i].pvBuffer = pMessage->pBuffers[i].pvBuffer;
1694         }
1695     }
1696
1697     if((ret = ntlm_CreateSignature(helper, &local_desc, token_idx, NTLM_RECV, TRUE)) != SEC_E_OK)
1698         return ret;
1699
1700     if(memcmp(((PBYTE)local_buff[token_idx].pvBuffer) + 8,
1701                 ((PBYTE)pMessage->pBuffers[token_idx].pvBuffer) + 8, 8))
1702         ret = SEC_E_MESSAGE_ALTERED;
1703     else
1704         ret = SEC_E_OK;
1705
1706     HeapFree(GetProcessHeap(), 0, local_buff);
1707     pfQOP = &fQOP;
1708
1709     return ret;
1710
1711 }
1712
1713 /***********************************************************************
1714  *             FreeCredentialsHandle
1715  */
1716 static SECURITY_STATUS SEC_ENTRY ntlm_FreeCredentialsHandle(
1717         PCredHandle phCredential)
1718 {
1719     SECURITY_STATUS ret;
1720
1721     if(phCredential){
1722         PNtlmCredentials ntlm_cred = (PNtlmCredentials) phCredential->dwLower;
1723         phCredential->dwUpper = 0;
1724         phCredential->dwLower = 0;
1725         if (ntlm_cred->password)
1726             memset(ntlm_cred->password, 0, ntlm_cred->pwlen);
1727         HeapFree(GetProcessHeap(), 0, ntlm_cred->password);
1728         HeapFree(GetProcessHeap(), 0, ntlm_cred->username_arg);
1729         HeapFree(GetProcessHeap(), 0, ntlm_cred->domain_arg);
1730         ret = SEC_E_OK;
1731     }
1732     else
1733         ret = SEC_E_OK;
1734     
1735     return ret;
1736 }
1737
1738 /***********************************************************************
1739  *             EncryptMessage
1740  */
1741 static SECURITY_STATUS SEC_ENTRY ntlm_EncryptMessage(PCtxtHandle phContext,
1742         ULONG fQOP, PSecBufferDesc pMessage, ULONG MessageSeqNo)
1743 {
1744     PNegoHelper helper;
1745     int token_idx, data_idx;
1746
1747     TRACE("(%p %d %p %d)\n", phContext, fQOP, pMessage, MessageSeqNo);
1748
1749     if(!phContext)
1750         return SEC_E_INVALID_HANDLE;
1751
1752     if(fQOP)
1753         FIXME("Ignoring fQOP\n");
1754
1755     if(MessageSeqNo)
1756         FIXME("Ignoring MessageSeqNo\n");
1757
1758     if(!pMessage || !pMessage->pBuffers || pMessage->cBuffers < 2)
1759         return SEC_E_INVALID_TOKEN;
1760
1761     if((token_idx = ntlm_GetTokenBufferIndex(pMessage)) == -1)
1762         return SEC_E_INVALID_TOKEN;
1763
1764     if((data_idx = ntlm_GetDataBufferIndex(pMessage)) ==-1 )
1765         return SEC_E_INVALID_TOKEN;
1766
1767     if(pMessage->pBuffers[token_idx].cbBuffer < 16)
1768         return SEC_E_BUFFER_TOO_SMALL;
1769
1770     helper = (PNegoHelper) phContext->dwLower;
1771
1772     if(helper->neg_flags & NTLMSSP_NEGOTIATE_NTLM2 && 
1773             helper->neg_flags & NTLMSSP_NEGOTIATE_SEAL)
1774     { 
1775         ntlm_CreateSignature(helper, pMessage, token_idx, NTLM_SEND, FALSE);
1776         SECUR32_arc4Process(helper->crypt.ntlm2.send_a4i,
1777                 (BYTE *)pMessage->pBuffers[data_idx].pvBuffer,
1778                 pMessage->pBuffers[data_idx].cbBuffer);
1779
1780         if(helper->neg_flags & NTLMSSP_NEGOTIATE_KEY_EXCHANGE)
1781             SECUR32_arc4Process(helper->crypt.ntlm2.send_a4i,
1782                     ((BYTE *)pMessage->pBuffers[token_idx].pvBuffer)+4, 8);
1783
1784
1785         return SEC_E_OK;
1786     }
1787     else
1788     {
1789         PBYTE sig;
1790         ULONG save_flags;
1791
1792         /* EncryptMessage always produces real signatures, so make sure
1793          * NTLMSSP_NEGOTIATE_SIGN is set*/
1794         save_flags = helper->neg_flags;
1795         helper->neg_flags |= NTLMSSP_NEGOTIATE_SIGN;
1796         ntlm_CreateSignature(helper, pMessage, token_idx, NTLM_SEND, FALSE);
1797         helper->neg_flags = save_flags;
1798
1799         sig = pMessage->pBuffers[token_idx].pvBuffer;
1800
1801         SECUR32_arc4Process(helper->crypt.ntlm.a4i,
1802                 pMessage->pBuffers[data_idx].pvBuffer,
1803                 pMessage->pBuffers[data_idx].cbBuffer);
1804         SECUR32_arc4Process(helper->crypt.ntlm.a4i, sig+4, 12);
1805
1806         if(helper->neg_flags & NTLMSSP_NEGOTIATE_ALWAYS_SIGN || helper->neg_flags == 0)
1807             memset(sig+4, 0, 4);
1808
1809     }
1810
1811     return SEC_E_OK;
1812 }
1813
1814 /***********************************************************************
1815  *             DecryptMessage
1816  */
1817 static SECURITY_STATUS SEC_ENTRY ntlm_DecryptMessage(PCtxtHandle phContext,
1818         PSecBufferDesc pMessage, ULONG MessageSeqNo, PULONG pfQOP)
1819 {
1820     SECURITY_STATUS ret;
1821     ULONG ntlmssp_flags_save;
1822     PNegoHelper helper;
1823     int token_idx, data_idx;
1824     TRACE("(%p %p %d %p)\n", phContext, pMessage, MessageSeqNo, pfQOP);
1825
1826     if(!phContext)
1827         return SEC_E_INVALID_HANDLE;
1828
1829     if(MessageSeqNo)
1830         FIXME("Ignoring MessageSeqNo\n");
1831
1832     if(!pMessage || !pMessage->pBuffers || pMessage->cBuffers < 2)
1833         return SEC_E_INVALID_TOKEN;
1834
1835     if((token_idx = ntlm_GetTokenBufferIndex(pMessage)) == -1)
1836         return SEC_E_INVALID_TOKEN;
1837
1838     if((data_idx = ntlm_GetDataBufferIndex(pMessage)) ==-1)
1839         return SEC_E_INVALID_TOKEN;
1840
1841     if(pMessage->pBuffers[token_idx].cbBuffer < 16)
1842         return SEC_E_BUFFER_TOO_SMALL;
1843
1844     helper = (PNegoHelper) phContext->dwLower;
1845
1846     if(helper->neg_flags & NTLMSSP_NEGOTIATE_NTLM2 && helper->neg_flags & NTLMSSP_NEGOTIATE_SEAL)
1847     {
1848         SECUR32_arc4Process(helper->crypt.ntlm2.recv_a4i,
1849                 pMessage->pBuffers[data_idx].pvBuffer,
1850                 pMessage->pBuffers[data_idx].cbBuffer);
1851     }
1852     else
1853     {
1854         SECUR32_arc4Process(helper->crypt.ntlm.a4i,
1855                 pMessage->pBuffers[data_idx].pvBuffer,
1856                 pMessage->pBuffers[data_idx].cbBuffer);
1857     }
1858
1859     /* Make sure we use a session key for the signature check, EncryptMessage
1860      * always does that, even in the dummy case */
1861     ntlmssp_flags_save = helper->neg_flags;
1862
1863     helper->neg_flags |= NTLMSSP_NEGOTIATE_SIGN;
1864     ret = ntlm_VerifySignature(phContext, pMessage, MessageSeqNo, pfQOP);
1865
1866     helper->neg_flags = ntlmssp_flags_save;
1867
1868     return ret;
1869 }
1870
1871 static const SecurityFunctionTableA ntlmTableA = {
1872     1,
1873     NULL,   /* EnumerateSecurityPackagesA */
1874     ntlm_QueryCredentialsAttributesA,   /* QueryCredentialsAttributesA */
1875     ntlm_AcquireCredentialsHandleA,     /* AcquireCredentialsHandleA */
1876     ntlm_FreeCredentialsHandle,         /* FreeCredentialsHandle */
1877     NULL,   /* Reserved2 */
1878     ntlm_InitializeSecurityContextA,    /* InitializeSecurityContextA */
1879     ntlm_AcceptSecurityContext,         /* AcceptSecurityContext */
1880     ntlm_CompleteAuthToken,             /* CompleteAuthToken */
1881     ntlm_DeleteSecurityContext,         /* DeleteSecurityContext */
1882     NULL,  /* ApplyControlToken */
1883     ntlm_QueryContextAttributesA,       /* QueryContextAttributesA */
1884     ntlm_ImpersonateSecurityContext,    /* ImpersonateSecurityContext */
1885     ntlm_RevertSecurityContext,         /* RevertSecurityContext */
1886     ntlm_MakeSignature,                 /* MakeSignature */
1887     ntlm_VerifySignature,               /* VerifySignature */
1888     FreeContextBuffer,                  /* FreeContextBuffer */
1889     NULL,   /* QuerySecurityPackageInfoA */
1890     NULL,   /* Reserved3 */
1891     NULL,   /* Reserved4 */
1892     NULL,   /* ExportSecurityContext */
1893     NULL,   /* ImportSecurityContextA */
1894     NULL,   /* AddCredentialsA */
1895     NULL,   /* Reserved8 */
1896     NULL,   /* QuerySecurityContextToken */
1897     ntlm_EncryptMessage,                /* EncryptMessage */
1898     ntlm_DecryptMessage,                /* DecryptMessage */
1899     NULL,   /* SetContextAttributesA */
1900 };
1901
1902 static const SecurityFunctionTableW ntlmTableW = {
1903     1,
1904     NULL,   /* EnumerateSecurityPackagesW */
1905     ntlm_QueryCredentialsAttributesW,   /* QueryCredentialsAttributesW */
1906     ntlm_AcquireCredentialsHandleW,     /* AcquireCredentialsHandleW */
1907     ntlm_FreeCredentialsHandle,         /* FreeCredentialsHandle */
1908     NULL,   /* Reserved2 */
1909     ntlm_InitializeSecurityContextW,    /* InitializeSecurityContextW */
1910     ntlm_AcceptSecurityContext,         /* AcceptSecurityContext */
1911     ntlm_CompleteAuthToken,             /* CompleteAuthToken */
1912     ntlm_DeleteSecurityContext,         /* DeleteSecurityContext */
1913     NULL,  /* ApplyControlToken */
1914     ntlm_QueryContextAttributesW,       /* QueryContextAttributesW */
1915     ntlm_ImpersonateSecurityContext,    /* ImpersonateSecurityContext */
1916     ntlm_RevertSecurityContext,         /* RevertSecurityContext */
1917     ntlm_MakeSignature,                 /* MakeSignature */
1918     ntlm_VerifySignature,               /* VerifySignature */
1919     FreeContextBuffer,                  /* FreeContextBuffer */
1920     NULL,   /* QuerySecurityPackageInfoW */
1921     NULL,   /* Reserved3 */
1922     NULL,   /* Reserved4 */
1923     NULL,   /* ExportSecurityContext */
1924     NULL,   /* ImportSecurityContextW */
1925     NULL,   /* AddCredentialsW */
1926     NULL,   /* Reserved8 */
1927     NULL,   /* QuerySecurityContextToken */
1928     ntlm_EncryptMessage,                /* EncryptMessage */
1929     ntlm_DecryptMessage,                /* DecryptMessage */
1930     NULL,   /* SetContextAttributesW */
1931 };
1932
1933 #define NTLM_COMMENT \
1934    { 'N', 'T', 'L', 'M', ' ', \
1935      'S', 'e', 'c', 'u', 'r', 'i', 't', 'y', ' ', \
1936      'P', 'a', 'c', 'k', 'a', 'g', 'e', 0}
1937
1938 static CHAR ntlm_comment_A[] = NTLM_COMMENT;
1939 static WCHAR ntlm_comment_W[] = NTLM_COMMENT;
1940
1941 #define NTLM_NAME {'N', 'T', 'L', 'M', 0}
1942
1943 static char ntlm_name_A[] = NTLM_NAME;
1944 static WCHAR ntlm_name_W[] = NTLM_NAME;
1945
1946 /* According to Windows, NTLM has the following capabilities.  */
1947 #define CAPS ( \
1948         SECPKG_FLAG_INTEGRITY | \
1949         SECPKG_FLAG_PRIVACY | \
1950         SECPKG_FLAG_TOKEN_ONLY | \
1951         SECPKG_FLAG_CONNECTION | \
1952         SECPKG_FLAG_MULTI_REQUIRED | \
1953         SECPKG_FLAG_IMPERSONATION | \
1954         SECPKG_FLAG_ACCEPT_WIN32_NAME | \
1955         SECPKG_FLAG_READONLY_WITH_CHECKSUM)
1956
1957 static const SecPkgInfoW infoW = {
1958     CAPS,
1959     1,
1960     RPC_C_AUTHN_WINNT,
1961     NTLM_MAX_BUF,
1962     ntlm_name_W,
1963     ntlm_comment_W
1964 };
1965
1966 static const SecPkgInfoA infoA = {
1967     CAPS,
1968     1,
1969     RPC_C_AUTHN_WINNT,
1970     NTLM_MAX_BUF,
1971     ntlm_name_A,
1972     ntlm_comment_A
1973 };
1974
1975 void SECUR32_initNTLMSP(void)
1976 {
1977     SECURITY_STATUS ret;
1978     PNegoHelper helper;
1979     static CHAR version[] = "--version";
1980
1981     SEC_CHAR *args[] = {
1982         ntlm_auth,
1983         version,
1984         NULL };
1985
1986     if((ret = fork_helper(&helper, ntlm_auth, args)) != SEC_E_OK)
1987     {
1988         /* Cheat and allocate a helper anyway, so cleanup later will work. */
1989         helper = HeapAlloc(GetProcessHeap(),0, sizeof(PNegoHelper));
1990         helper->major = helper->minor = helper->micro = -1;
1991     }
1992     else
1993         check_version(helper);
1994
1995     if( (helper->major >  MIN_NTLM_AUTH_MAJOR_VERSION) ||
1996         (helper->major == MIN_NTLM_AUTH_MAJOR_VERSION  &&
1997          helper->minor >  MIN_NTLM_AUTH_MINOR_VERSION) ||
1998         (helper->major == MIN_NTLM_AUTH_MAJOR_VERSION  &&
1999          helper->minor == MIN_NTLM_AUTH_MINOR_VERSION  &&
2000          helper->micro >= MIN_NTLM_AUTH_MICRO_VERSION) )
2001     {
2002         SecureProvider *provider = SECUR32_addProvider(&ntlmTableA, &ntlmTableW, NULL);
2003         SECUR32_addPackages(provider, 1L, &infoA, &infoW);
2004     }
2005     else
2006     {
2007         ERR("%s was not found or is outdated. "
2008             "Make sure that ntlm_auth >= %d.%d.%d is in your path.\n",
2009             ntlm_auth,
2010             MIN_NTLM_AUTH_MAJOR_VERSION,
2011             MIN_NTLM_AUTH_MINOR_VERSION,
2012             MIN_NTLM_AUTH_MICRO_VERSION);
2013         ERR("Usually, you can find it in the winbind package of your "
2014             "distribution.\n");
2015
2016     }
2017     cleanup_helper(helper);
2018 }