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