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