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