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