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