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