ntdll: Match the definition of NtQueryEvent() with its declaration.
[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                 goto isc_end;
528
529         }
530
531         TRACE("Sending to helper: %s\n", debugstr_a(buffer));
532         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
533             goto isc_end;
534
535         TRACE("Helper returned %s\n", debugstr_a(buffer));
536
537         if(lstrlenA(want_flags) > 2)
538         {
539             TRACE("Want flags are %s\n", debugstr_a(want_flags));
540             lstrcpynA(buffer, want_flags, max_len-1);
541             if((ret = run_helper(helper, buffer, max_len, &buffer_len)) 
542                     != SEC_E_OK)
543                 goto isc_end;
544             if(!strncmp(buffer, "BH", 2))
545                 ERR("Helper doesn't understand new command set. Expect more things to fail.\n");
546         }
547
548         lstrcpynA(buffer, "YR", max_len-1);
549
550         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
551             goto isc_end;
552
553         TRACE("%s\n", buffer);
554
555         if(strncmp(buffer, "YR ", 3) != 0)
556         {
557             /* Something borked */
558             TRACE("Helper returned %c%c\n", buffer[0], buffer[1]);
559             ret = SEC_E_INTERNAL_ERROR;
560             goto isc_end;
561         }
562         if((ret = decodeBase64(buffer+3, buffer_len-3, bin,
563                         max_len-1, &bin_len)) != SEC_E_OK)
564             goto isc_end;
565
566         /* put the decoded client blob into the out buffer */
567
568         phNewContext->dwUpper = ctxt_attr;
569         phNewContext->dwLower = (ULONG_PTR)helper;
570
571         ret = SEC_I_CONTINUE_NEEDED;
572     }
573     else
574     {
575         int input_token_idx;
576
577         /* handle second call here */
578         /* encode server data to base64 */
579         if (!pInput || ((input_token_idx = ntlm_GetTokenBufferIndex(pInput)) == -1))
580         {
581             ret = SEC_E_INVALID_TOKEN;
582             goto isc_end;
583         }
584
585         if(!phContext)
586             return SEC_E_INVALID_HANDLE;
587
588         /* As the server side of sspi never calls this, make sure that
589          * the handler is a client handler.
590          */
591         helper = (PNegoHelper)phContext->dwLower;
592         if(helper->mode != NTLM_CLIENT)
593         {
594             TRACE("Helper mode = %d\n", helper->mode);
595             return SEC_E_INVALID_HANDLE;
596         }
597
598         if (!pInput->pBuffers[input_token_idx].pvBuffer)
599         {
600             ret = SEC_E_INTERNAL_ERROR;
601             goto isc_end;
602         }
603
604         if(pInput->pBuffers[input_token_idx].cbBuffer > max_len)
605         {
606             TRACE("pInput->pBuffers[%d].cbBuffer is: %ld\n",
607                     input_token_idx,
608                     pInput->pBuffers[input_token_idx].cbBuffer);
609             ret = SEC_E_INVALID_TOKEN;
610             goto isc_end;
611         }
612         else
613             bin_len = pInput->pBuffers[input_token_idx].cbBuffer;
614
615         memcpy(bin, pInput->pBuffers[input_token_idx].pvBuffer, bin_len);
616
617         lstrcpynA(buffer, "TT ", max_len-1);
618
619         if((ret = encodeBase64(bin, bin_len, buffer+3,
620                         max_len-3, &buffer_len)) != SEC_E_OK)
621             goto isc_end;
622
623         TRACE("Server sent: %s\n", debugstr_a(buffer));
624
625         /* send TT base64 blob to ntlm_auth */
626         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
627             goto isc_end;
628
629         TRACE("Helper replied: %s\n", debugstr_a(buffer));
630
631         if( (strncmp(buffer, "KK ", 3) != 0) &&
632                 (strncmp(buffer, "AF ", 3) !=0))
633         {
634             TRACE("Helper returned %c%c\n", buffer[0], buffer[1]);
635             ret = SEC_E_INVALID_TOKEN;
636             goto isc_end;
637         }
638
639         /* decode the blob and send it to server */
640         if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len,
641                         &bin_len)) != SEC_E_OK)
642         {
643             goto isc_end;
644         }
645
646         phNewContext->dwUpper = ctxt_attr;
647         phNewContext->dwLower = (ULONG_PTR)helper;
648
649         ret = SEC_E_OK;
650     }
651
652     /* put the decoded client blob into the out buffer */
653
654     if (!pOutput || ((token_idx = ntlm_GetTokenBufferIndex(pOutput)) == -1))
655     {
656         TRACE("no SECBUFFER_TOKEN buffer could be found\n");
657         ret = SEC_E_BUFFER_TOO_SMALL;
658         goto isc_end;
659     }
660
661     if (fContextReq & ISC_REQ_ALLOCATE_MEMORY)
662     {
663         pOutput->pBuffers[token_idx].pvBuffer = SECUR32_ALLOC(bin_len);
664         pOutput->pBuffers[token_idx].cbBuffer = bin_len;
665     }
666     else if (pOutput->pBuffers[token_idx].cbBuffer < bin_len)
667     {
668         TRACE("out buffer is NULL or has not enough space\n");
669         ret = SEC_E_BUFFER_TOO_SMALL;
670         goto isc_end;
671     }
672
673     if (!pOutput->pBuffers[token_idx].pvBuffer)
674     {
675         TRACE("out buffer is NULL\n");
676         ret = SEC_E_INTERNAL_ERROR;
677         goto isc_end;
678     }
679
680     pOutput->pBuffers[token_idx].cbBuffer = bin_len;
681     memcpy(pOutput->pBuffers[token_idx].pvBuffer, bin, bin_len);
682
683     if(ret == SEC_E_OK)
684     {
685         TRACE("Getting negotiated flags\n");
686         lstrcpynA(buffer, "GF", max_len - 1);
687         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
688             goto isc_end;
689
690         if(buffer_len < 3)
691         {
692             TRACE("No flags negotiated.\n");
693             helper->neg_flags = 0l;
694         }
695         else
696         {
697             TRACE("Negotiated %s\n", debugstr_a(buffer));
698             sscanf(buffer + 3, "%lx", &(helper->neg_flags));
699             TRACE("Stored 0x%08lx as flags\n", helper->neg_flags);
700         }
701
702         TRACE("Getting session key\n");
703         lstrcpynA(buffer, "GK", max_len - 1);
704         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
705             goto isc_end;
706
707         if(strncmp(buffer, "BH", 2) == 0)
708         {
709             TRACE("No key negotiated.\n");
710             helper->valid_session_key = FALSE;
711             helper->session_key = HeapAlloc(GetProcessHeap(), 0, 16);
712             /*Generate the dummy session key = MD4(MD4(password))*/
713             if(helper->password)
714             {
715                 SEC_WCHAR *unicode_password;
716                 int passwd_lenW;
717
718                 TRACE("Converting password to unicode.\n");
719                 passwd_lenW = MultiByteToWideChar(CP_ACP, 0,
720                         (LPCSTR)helper->password, helper->pwlen,
721                         NULL, 0);
722                 unicode_password = HeapAlloc(GetProcessHeap(), 0,
723                         passwd_lenW * sizeof(SEC_WCHAR));
724                 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)helper->password,
725                         helper->pwlen, unicode_password, passwd_lenW);
726
727                 SECUR32_CreateNTLMv1SessionKey((PBYTE)unicode_password,
728                         passwd_lenW * sizeof(SEC_WCHAR), helper->session_key);
729
730                 HeapFree(GetProcessHeap(), 0, unicode_password);
731             }
732             else
733                 memset(helper->session_key, 0, 16);
734         }
735         else if(strncmp(buffer, "GK ", 3) == 0)
736         {
737             if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len, 
738                             &bin_len)) != SEC_E_OK)
739             {
740                 TRACE("Failed to decode session key\n");
741             }
742             TRACE("Session key is %s\n", debugstr_a(buffer+3));
743             helper->valid_session_key = TRUE;
744             helper->session_key = HeapAlloc(GetProcessHeap(), 0, bin_len);
745             if(!helper->session_key)
746             {
747                 TRACE("Failed to allocate memory for session key\n");
748                 ret = SEC_E_INTERNAL_ERROR;
749                 goto isc_end;
750             }
751             memcpy(helper->session_key, bin, bin_len);
752         }
753
754         helper->crypt.ntlm.a4i = SECUR32_arc4Alloc();
755         SECUR32_arc4Init(helper->crypt.ntlm.a4i, helper->session_key, 16);
756         helper->crypt.ntlm.seq_num = 0l;
757         SECUR32_CreateNTLMv2SubKeys(helper);
758         helper->crypt.ntlm2.send_a4i = SECUR32_arc4Alloc();
759         helper->crypt.ntlm2.recv_a4i = SECUR32_arc4Alloc();
760         SECUR32_arc4Init(helper->crypt.ntlm2.send_a4i,
761                 (BYTE *)helper->crypt.ntlm2.send_seal_key, 16);
762         SECUR32_arc4Init(helper->crypt.ntlm2.recv_a4i,
763                (BYTE *)helper->crypt.ntlm2.recv_seal_key, 16);
764         helper->crypt.ntlm2.send_seq_no = 0l;
765         helper->crypt.ntlm2.recv_seq_no = 0l;
766     }
767
768 isc_end:
769     HeapFree(GetProcessHeap(), 0, want_flags);
770     HeapFree(GetProcessHeap(), 0, buffer);
771     HeapFree(GetProcessHeap(), 0, bin);
772     return ret;
773 }
774
775 /***********************************************************************
776  *              InitializeSecurityContextA
777  */
778 static SECURITY_STATUS SEC_ENTRY ntlm_InitializeSecurityContextA(
779  PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR *pszTargetName,
780  ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep, 
781  PSecBufferDesc pInput,ULONG Reserved2, PCtxtHandle phNewContext, 
782  PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
783 {
784     SECURITY_STATUS ret;
785     SEC_WCHAR *target = NULL;
786
787     TRACE("%p %p %s %d %d %d %p %d %p %p %p %p\n", phCredential, phContext,
788      debugstr_a(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
789      Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
790
791     if(pszTargetName != NULL)
792     {
793         int target_size = MultiByteToWideChar(CP_ACP, 0, pszTargetName,
794             strlen(pszTargetName)+1, NULL, 0);
795         target = HeapAlloc(GetProcessHeap(), 0, target_size *
796                 sizeof(SEC_WCHAR));
797         MultiByteToWideChar(CP_ACP, 0, pszTargetName, strlen(pszTargetName)+1,
798             target, target_size);
799     }
800
801     ret = ntlm_InitializeSecurityContextW(phCredential, phContext, target,
802             fContextReq, Reserved1, TargetDataRep, pInput, Reserved2,
803             phNewContext, pOutput, pfContextAttr, ptsExpiry);
804
805     HeapFree(GetProcessHeap(), 0, target);
806     return ret;
807 }
808
809 /***********************************************************************
810  *              AcceptSecurityContext
811  */
812 static SECURITY_STATUS SEC_ENTRY ntlm_AcceptSecurityContext(
813  PCredHandle phCredential, PCtxtHandle phContext, PSecBufferDesc pInput,
814  ULONG fContextReq, ULONG TargetDataRep, PCtxtHandle phNewContext, 
815  PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
816 {
817     SECURITY_STATUS ret;
818     char *buffer, *want_flags = NULL;
819     PBYTE bin;
820     int buffer_len, bin_len, max_len = NTLM_MAX_BUF;
821     ULONG ctxt_attr = 0;
822     PNegoHelper helper;
823
824     TRACE("%p %p %p %d %d %p %p %p %p\n", phCredential, phContext, pInput,
825      fContextReq, TargetDataRep, phNewContext, pOutput, pfContextAttr,
826      ptsExpiry);
827
828     if (!phCredential)
829         return SEC_E_INVALID_HANDLE;
830
831     helper = (PNegoHelper)phCredential->dwLower;
832
833     buffer = HeapAlloc(GetProcessHeap(), 0, sizeof(char) * NTLM_MAX_BUF);
834     bin    = HeapAlloc(GetProcessHeap(),0, sizeof(BYTE) * NTLM_MAX_BUF);
835
836     if(helper->mode != NTLM_SERVER)
837     {
838         ret = SEC_E_INVALID_HANDLE;
839         goto asc_end;
840     }
841
842     if(TargetDataRep == SECURITY_NETWORK_DREP){
843         TRACE("Using SECURITY_NETWORK_DREP\n");
844     }
845
846     if(phContext == NULL)
847     {
848         /* This is the first call to AcceptSecurityHandle */
849         if(pInput == NULL)
850         {
851             ret = SEC_E_INCOMPLETE_MESSAGE;
852             goto asc_end;
853         }
854
855         if(pInput->cBuffers < 1)
856         {
857             ret = SEC_E_INCOMPLETE_MESSAGE;
858             goto asc_end;
859         }
860
861         if(pInput->pBuffers[0].cbBuffer > max_len)
862         {
863             ret = SEC_E_INVALID_TOKEN;
864             goto asc_end;
865         }
866         else
867             bin_len = pInput->pBuffers[0].cbBuffer;
868
869         /* Handle all the flags */
870         want_flags = HeapAlloc(GetProcessHeap(), 0, 73);
871         if(want_flags == NULL)
872         {
873             TRACE("Failed to allocate memory for the want_flags!\n");
874             ret = SEC_E_INSUFFICIENT_MEMORY;
875             goto asc_end;
876         }
877         lstrcpyA(want_flags, "SF");
878         if(fContextReq & ASC_REQ_ALLOCATE_MEMORY)
879         {
880             FIXME("ASC_REQ_ALLOCATE_MEMORY stub\n");
881         }
882         if(fContextReq & ASC_REQ_CONFIDENTIALITY)
883         {
884             lstrcatA(want_flags, " NTLMSSP_FEATURE_SEAL");
885         }
886         if(fContextReq & ASC_REQ_CONNECTION)
887         {
888             /* This is default, so we'll enable it */
889             lstrcatA(want_flags, " NTLMSSP_FEATURE_SESSION_KEY");
890             ctxt_attr |= ASC_RET_CONNECTION;
891         }
892         if(fContextReq & ASC_REQ_EXTENDED_ERROR)
893         {
894             FIXME("ASC_REQ_EXTENDED_ERROR stub\n");
895         }
896         if(fContextReq & ASC_REQ_INTEGRITY)
897         {
898             lstrcatA(want_flags, " NTLMSSP_FEATURE_SIGN");
899         }
900         if(fContextReq & ASC_REQ_MUTUAL_AUTH)
901         {
902             FIXME("ASC_REQ_MUTUAL_AUTH stub\n");
903         }
904         if(fContextReq & ASC_REQ_REPLAY_DETECT)
905         {
906             FIXME("ASC_REQ_REPLAY_DETECT stub\n");
907         }
908         if(fContextReq & ISC_REQ_SEQUENCE_DETECT)
909         {
910             FIXME("ASC_REQ_SEQUENCE_DETECT stub\n");
911         }
912         if(fContextReq & ISC_REQ_STREAM)
913         {
914             FIXME("ASC_REQ_STREAM stub\n");
915         }
916         /* Done with the flags */
917
918         if(lstrlenA(want_flags) > 3)
919         {
920             TRACE("Server set want_flags: %s\n", debugstr_a(want_flags));
921             lstrcpynA(buffer, want_flags, max_len - 1);
922             if((ret = run_helper(helper, buffer, max_len, &buffer_len)) !=
923                     SEC_E_OK)
924                 goto asc_end;
925             if(!strncmp(buffer, "BH", 2))
926                 TRACE("Helper doesn't understand new command set\n");
927         }
928
929         /* This is the YR request from the client, encode to base64 */
930
931         memcpy(bin, pInput->pBuffers[0].pvBuffer, bin_len);
932
933         lstrcpynA(buffer, "YR ", max_len-1);
934
935         if((ret = encodeBase64(bin, bin_len, buffer+3, max_len-3,
936                     &buffer_len)) != SEC_E_OK)
937         {
938             goto asc_end;
939         }
940
941         TRACE("Client sent: %s\n", debugstr_a(buffer));
942
943         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) !=
944                     SEC_E_OK)
945         {
946             goto asc_end;
947         }
948
949         TRACE("Reply from ntlm_auth: %s\n", debugstr_a(buffer));
950         /* The expected answer is TT <base64 blob> */
951
952         if(strncmp(buffer, "TT ", 3) != 0)
953         {
954             ret = SEC_E_INTERNAL_ERROR;
955             goto asc_end;
956         }
957
958         if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len,
959                         &bin_len)) != SEC_E_OK)
960         {
961             goto asc_end;
962         }
963
964         /* send this to the client */
965         if(pOutput == NULL)
966         {
967             ret = SEC_E_INSUFFICIENT_MEMORY;
968             goto asc_end;
969         }
970
971         if(pOutput->cBuffers < 1)
972         {
973             ret = SEC_E_INSUFFICIENT_MEMORY;
974             goto asc_end;
975         }
976
977         pOutput->pBuffers[0].cbBuffer = bin_len;
978         pOutput->pBuffers[0].BufferType = SECBUFFER_DATA;
979         memcpy(pOutput->pBuffers[0].pvBuffer, bin, bin_len);
980         ret = SEC_I_CONTINUE_NEEDED;
981
982     }
983     else
984     {
985         /* we expect a KK request from client */
986         if(pInput == NULL)
987         {
988             ret = SEC_E_INCOMPLETE_MESSAGE;
989             goto asc_end;
990         }
991
992         if(pInput->cBuffers < 1)
993         {
994             ret = SEC_E_INCOMPLETE_MESSAGE;
995             goto asc_end;
996         }
997
998         if(pInput->pBuffers[0].cbBuffer > max_len)
999         {
1000             ret = SEC_E_INVALID_TOKEN;
1001             goto asc_end;
1002         }
1003         else
1004             bin_len = pInput->pBuffers[0].cbBuffer;
1005
1006         memcpy(bin, pInput->pBuffers[0].pvBuffer, bin_len);
1007
1008         lstrcpynA(buffer, "KK ", max_len-1);
1009
1010         if((ret = encodeBase64(bin, bin_len, buffer+3, max_len-3,
1011                     &buffer_len)) != SEC_E_OK)
1012         {
1013             goto asc_end;
1014         }
1015
1016         TRACE("Client sent: %s\n", debugstr_a(buffer));
1017
1018         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) !=
1019                     SEC_E_OK)
1020         {
1021             goto asc_end;
1022         }
1023
1024         TRACE("Reply from ntlm_auth: %s\n", debugstr_a(buffer));
1025
1026         if(strncmp(buffer, "AF ", 3) != 0)
1027         {
1028             if(strncmp(buffer, "NA ", 3) == 0)
1029             {
1030                 ret = SEC_E_LOGON_DENIED;
1031                 goto asc_end;
1032             }
1033             else
1034             {
1035                 ret = SEC_E_INTERNAL_ERROR;
1036                 goto asc_end;
1037             }
1038         }
1039         pOutput->pBuffers[0].cbBuffer = 0;
1040         ret = SEC_E_OK;
1041
1042         TRACE("Getting negotiated flags\n");
1043         lstrcpynA(buffer, "GF", max_len - 1);
1044         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
1045             goto asc_end;
1046
1047         if(buffer_len < 3)
1048         {
1049             TRACE("No flags negotiated, or helper does not support GF command\n");
1050         }
1051         else
1052         {
1053             TRACE("Negotiated %s\n", debugstr_a(buffer));
1054             sscanf(buffer + 3, "%lx", &(helper->neg_flags));
1055             TRACE("Stored 0x%08lx as flags\n", helper->neg_flags);
1056         }
1057
1058         TRACE("Getting session key\n");
1059         lstrcpynA(buffer, "GK", max_len - 1);
1060         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
1061             goto asc_end;
1062
1063         if(buffer_len < 3)
1064             TRACE("Helper does not support GK command\n");
1065         else
1066         {
1067             if(strncmp(buffer, "BH ", 3) == 0)
1068             {
1069                 TRACE("Helper sent %s\n", debugstr_a(buffer+3));
1070                 helper->valid_session_key = FALSE;
1071                 helper->session_key = HeapAlloc(GetProcessHeap(), 0, 16);
1072                 /*FIXME: Generate the dummy session key = MD4(MD4(password))*/
1073                 memset(helper->session_key, 0 , 16);
1074             }
1075             else if(strncmp(buffer, "GK ", 3) == 0)
1076             {
1077                 if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len, 
1078                                 &bin_len)) != SEC_E_OK)
1079                 {
1080                     TRACE("Failed to decode session key\n");
1081                 }
1082                 TRACE("Session key is %s\n", debugstr_a(buffer+3));
1083                 helper->valid_session_key = TRUE;
1084                 helper->session_key = HeapAlloc(GetProcessHeap(), 0, 16);
1085                 if(!helper->session_key)
1086                 {
1087                     TRACE("Failed to allocate memory for session key\n");
1088                     ret = SEC_E_INTERNAL_ERROR;
1089                     goto asc_end;
1090                 }
1091                 memcpy(helper->session_key, bin, 16);
1092             }
1093         }
1094         helper->crypt.ntlm.a4i = SECUR32_arc4Alloc();
1095         SECUR32_arc4Init(helper->crypt.ntlm.a4i, helper->session_key, 16);
1096         helper->crypt.ntlm.seq_num = 0l;
1097     }
1098
1099     phNewContext->dwUpper = ctxt_attr;
1100     phNewContext->dwLower = (ULONG_PTR)helper;
1101
1102 asc_end:
1103     HeapFree(GetProcessHeap(), 0, want_flags);
1104     HeapFree(GetProcessHeap(), 0, buffer);
1105     HeapFree(GetProcessHeap(), 0, bin);
1106     return ret;
1107 }
1108
1109 /***********************************************************************
1110  *              CompleteAuthToken
1111  */
1112 static SECURITY_STATUS SEC_ENTRY ntlm_CompleteAuthToken(PCtxtHandle phContext,
1113  PSecBufferDesc pToken)
1114 {
1115     /* We never need to call CompleteAuthToken anyway */
1116     TRACE("%p %p\n", phContext, pToken);
1117     if (!phContext)
1118         return SEC_E_INVALID_HANDLE;
1119     
1120     return SEC_E_OK;
1121 }
1122
1123 /***********************************************************************
1124  *              DeleteSecurityContext
1125  */
1126 static SECURITY_STATUS SEC_ENTRY ntlm_DeleteSecurityContext(PCtxtHandle phContext)
1127 {
1128     PNegoHelper helper;
1129
1130     TRACE("%p\n", phContext);
1131     if (!phContext)
1132         return SEC_E_INVALID_HANDLE;
1133
1134     helper = (PNegoHelper)phContext->dwLower;
1135
1136     phContext->dwUpper = 0;
1137     phContext->dwLower = 0;
1138
1139     SECUR32_arc4Cleanup(helper->crypt.ntlm.a4i);
1140     HeapFree(GetProcessHeap(), 0, helper->session_key);
1141     helper->valid_session_key = FALSE;
1142     SECUR32_arc4Cleanup(helper->crypt.ntlm2.send_a4i);
1143     SECUR32_arc4Cleanup(helper->crypt.ntlm2.recv_a4i);
1144     HeapFree(GetProcessHeap(), 0, helper->crypt.ntlm2.send_sign_key);
1145     HeapFree(GetProcessHeap(), 0, helper->crypt.ntlm2.send_seal_key);
1146     HeapFree(GetProcessHeap(), 0, helper->crypt.ntlm2.recv_sign_key);
1147     HeapFree(GetProcessHeap(), 0, helper->crypt.ntlm2.recv_seal_key);
1148
1149     return SEC_E_OK;
1150 }
1151
1152 /***********************************************************************
1153  *              QueryContextAttributesW
1154  */
1155 static SECURITY_STATUS SEC_ENTRY ntlm_QueryContextAttributesW(PCtxtHandle phContext,
1156  ULONG ulAttribute, void *pBuffer)
1157 {
1158     TRACE("%p %d %p\n", phContext, ulAttribute, pBuffer);
1159     if (!phContext)
1160         return SEC_E_INVALID_HANDLE;
1161
1162     switch(ulAttribute)
1163     {
1164 #define _x(x) case (x) : FIXME(#x" stub\n"); break
1165         _x(SECPKG_ATTR_ACCESS_TOKEN);
1166         _x(SECPKG_ATTR_AUTHORITY);
1167         _x(SECPKG_ATTR_DCE_INFO);
1168         case SECPKG_ATTR_FLAGS:
1169         {
1170             PSecPkgContext_Flags spcf = (PSecPkgContext_Flags)pBuffer;
1171             PNegoHelper helper = (PNegoHelper)phContext->dwLower;
1172
1173             spcf->Flags = 0;
1174             if(helper->neg_flags & NTLMSSP_NEGOTIATE_SIGN)
1175                 spcf->Flags |= ISC_RET_INTEGRITY;
1176             if(helper->neg_flags & NTLMSSP_NEGOTIATE_SEAL)
1177                 spcf->Flags |= ISC_RET_CONFIDENTIALITY;
1178             return SEC_E_OK;
1179         }
1180         _x(SECPKG_ATTR_KEY_INFO);
1181         _x(SECPKG_ATTR_LIFESPAN);
1182         _x(SECPKG_ATTR_NAMES);
1183         _x(SECPKG_ATTR_NATIVE_NAMES);
1184         _x(SECPKG_ATTR_NEGOTIATION_INFO);
1185         _x(SECPKG_ATTR_PACKAGE_INFO);
1186         _x(SECPKG_ATTR_PASSWORD_EXPIRY);
1187         _x(SECPKG_ATTR_SESSION_KEY);
1188         case SECPKG_ATTR_SIZES:
1189         {
1190             PSecPkgContext_Sizes spcs = (PSecPkgContext_Sizes)pBuffer;
1191             spcs->cbMaxToken = NTLM_MAX_BUF;
1192             spcs->cbMaxSignature = 16;
1193             spcs->cbBlockSize = 0;
1194             spcs->cbSecurityTrailer = 16;
1195             return SEC_E_OK;
1196         }
1197         _x(SECPKG_ATTR_STREAM_SIZES);
1198         _x(SECPKG_ATTR_TARGET_INFORMATION);
1199 #undef _x
1200         default:
1201             TRACE("Unknown value %d passed for ulAttribute\n", ulAttribute);
1202     }
1203
1204     return SEC_E_UNSUPPORTED_FUNCTION;
1205 }
1206
1207 /***********************************************************************
1208  *              QueryContextAttributesA
1209  */
1210 static SECURITY_STATUS SEC_ENTRY ntlm_QueryContextAttributesA(PCtxtHandle phContext,
1211  ULONG ulAttribute, void *pBuffer)
1212 {
1213     return ntlm_QueryContextAttributesW(phContext, ulAttribute, pBuffer);
1214 }
1215
1216 /***********************************************************************
1217  *              ImpersonateSecurityContext
1218  */
1219 static SECURITY_STATUS SEC_ENTRY ntlm_ImpersonateSecurityContext(PCtxtHandle phContext)
1220 {
1221     SECURITY_STATUS ret;
1222
1223     TRACE("%p\n", phContext);
1224     if (phContext)
1225     {
1226         ret = SEC_E_UNSUPPORTED_FUNCTION;
1227     }
1228     else
1229     {
1230         ret = SEC_E_INVALID_HANDLE;
1231     }
1232     return ret;
1233 }
1234
1235 /***********************************************************************
1236  *              RevertSecurityContext
1237  */
1238 static SECURITY_STATUS SEC_ENTRY ntlm_RevertSecurityContext(PCtxtHandle phContext)
1239 {
1240     SECURITY_STATUS ret;
1241
1242     TRACE("%p\n", phContext);
1243     if (phContext)
1244     {
1245         ret = SEC_E_UNSUPPORTED_FUNCTION;
1246     }
1247     else
1248     {
1249         ret = SEC_E_INVALID_HANDLE;
1250     }
1251     return ret;
1252 }
1253
1254 /***********************************************************************
1255  *             ntlm_CreateSignature
1256  * As both MakeSignature and VerifySignature need this, but different keys
1257  * are needed for NTLMv2, the logic goes into a helper function.
1258  * To ensure maximal reusability, we can specify the direction as NTLM_SEND for
1259  * signing/encrypting and NTLM_RECV for verfying/decrypting. When encrypting,
1260  * the signature is encrypted after the message was encrypted, so
1261  * CreateSignature shouldn't do it. In this case, encrypt_sig can be set to
1262  * false.
1263  */
1264 static SECURITY_STATUS ntlm_CreateSignature(PNegoHelper helper, PSecBufferDesc pMessage,
1265         int token_idx, SignDirection direction, BOOL encrypt_sig)
1266 {
1267     ULONG sign_version = 1;
1268     UINT i;
1269     PBYTE sig;
1270     TRACE("%p, %p, %d, %d, %d\n", helper, pMessage, token_idx, direction,
1271             encrypt_sig);
1272
1273     sig = pMessage->pBuffers[token_idx].pvBuffer;
1274
1275     if(helper->neg_flags & NTLMSSP_NEGOTIATE_NTLM2 &&
1276             helper->neg_flags & NTLMSSP_NEGOTIATE_SIGN)
1277     {
1278         BYTE digest[16];
1279         BYTE seq_no[4];
1280         HMAC_MD5_CTX hmac_md5_ctx;
1281
1282         TRACE("Signing NTLM2 style\n");
1283
1284         if(direction == NTLM_SEND)
1285         {
1286             seq_no[0] = (helper->crypt.ntlm2.send_seq_no >>  0) & 0xff;
1287             seq_no[1] = (helper->crypt.ntlm2.send_seq_no >>  8) & 0xff;
1288             seq_no[2] = (helper->crypt.ntlm2.send_seq_no >> 16) & 0xff;
1289             seq_no[3] = (helper->crypt.ntlm2.send_seq_no >> 24) & 0xff;
1290
1291             ++(helper->crypt.ntlm2.send_seq_no);
1292
1293             HMACMD5Init(&hmac_md5_ctx, helper->crypt.ntlm2.send_sign_key, 16);
1294         }
1295         else
1296         {
1297             seq_no[0] = (helper->crypt.ntlm2.recv_seq_no >>  0) & 0xff;
1298             seq_no[1] = (helper->crypt.ntlm2.recv_seq_no >>  8) & 0xff;
1299             seq_no[2] = (helper->crypt.ntlm2.recv_seq_no >> 16) & 0xff;
1300             seq_no[3] = (helper->crypt.ntlm2.recv_seq_no >> 24) & 0xff;
1301
1302             ++(helper->crypt.ntlm2.recv_seq_no);
1303
1304             HMACMD5Init(&hmac_md5_ctx, helper->crypt.ntlm2.recv_sign_key, 16);
1305         }
1306
1307         HMACMD5Update(&hmac_md5_ctx, seq_no, 4);
1308         for( i = 0; i < pMessage->cBuffers; ++i )
1309         {
1310             if(pMessage->pBuffers[i].BufferType & SECBUFFER_DATA)
1311                 HMACMD5Update(&hmac_md5_ctx, (BYTE *)pMessage->pBuffers[i].pvBuffer,
1312                         pMessage->pBuffers[i].cbBuffer);
1313         }
1314
1315         HMACMD5Final(&hmac_md5_ctx, digest);
1316
1317         if(encrypt_sig && helper->neg_flags & NTLMSSP_NEGOTIATE_KEY_EXCHANGE)
1318         {
1319             if(direction == NTLM_SEND)
1320                 SECUR32_arc4Process(helper->crypt.ntlm2.send_a4i, digest, 8);
1321             else
1322                 SECUR32_arc4Process(helper->crypt.ntlm2.recv_a4i, digest, 8);
1323         }
1324
1325         /* The NTLM2 signature is the sign version */
1326         sig[ 0] = (sign_version >>  0) & 0xff;
1327         sig[ 1] = (sign_version >>  8) & 0xff;
1328         sig[ 2] = (sign_version >> 16) & 0xff;
1329         sig[ 3] = (sign_version >> 24) & 0xff;
1330         /* The first 8 bytes of the digest */
1331         memcpy(sig+4, digest, 8);
1332         /* And the sequence number */
1333         memcpy(sig+12, seq_no, 4);
1334
1335         pMessage->pBuffers[token_idx].cbBuffer = 16;
1336
1337         return SEC_E_OK;
1338     }
1339     if(helper->neg_flags & NTLMSSP_NEGOTIATE_SIGN)
1340     {
1341         ULONG crc = 0U;
1342         TRACE("Signing NTLM1 style\n");
1343
1344         for(i=0; i < pMessage->cBuffers; ++i)
1345         {
1346             if(pMessage->pBuffers[i].BufferType & SECBUFFER_DATA)
1347             {
1348                 crc = ComputeCrc32(pMessage->pBuffers[i].pvBuffer,
1349                     pMessage->pBuffers[i].cbBuffer, crc);
1350             }
1351         }
1352
1353         sig[ 0] = (sign_version >>  0) & 0xff;
1354         sig[ 1] = (sign_version >>  8) & 0xff;
1355         sig[ 2] = (sign_version >> 16) & 0xff;
1356         sig[ 3] = (sign_version >> 24) & 0xff;
1357         memset(sig+4, 0, 4);
1358         sig[ 8] = (crc >>  0) & 0xff;
1359         sig[ 9] = (crc >>  8) & 0xff;
1360         sig[10] = (crc >> 16) & 0xff;
1361         sig[11] = (crc >> 24) & 0xff;
1362         sig[12] = (helper->crypt.ntlm.seq_num >>  0) & 0xff;
1363         sig[13] = (helper->crypt.ntlm.seq_num >>  8) & 0xff;
1364         sig[14] = (helper->crypt.ntlm.seq_num >> 16) & 0xff;
1365         sig[15] = (helper->crypt.ntlm.seq_num >> 24) & 0xff;
1366
1367         ++(helper->crypt.ntlm.seq_num);
1368
1369         if(encrypt_sig)
1370             SECUR32_arc4Process(helper->crypt.ntlm.a4i, sig+4, 12);
1371         return SEC_E_OK;
1372     }
1373
1374     if(helper->neg_flags & NTLMSSP_NEGOTIATE_ALWAYS_SIGN || helper->neg_flags == 0)
1375     {
1376         TRACE("Creating a dummy signature.\n");
1377         /* A dummy signature is 0x01 followed by 15 bytes of 0x00 */
1378         memset(pMessage->pBuffers[token_idx].pvBuffer, 0, 16);
1379         memset(pMessage->pBuffers[token_idx].pvBuffer, 0x01, 1);
1380         pMessage->pBuffers[token_idx].cbBuffer = 16;
1381         return SEC_E_OK;
1382     }
1383
1384     return SEC_E_UNSUPPORTED_FUNCTION;
1385 }
1386
1387 /***********************************************************************
1388  *              MakeSignature
1389  */
1390 static SECURITY_STATUS SEC_ENTRY ntlm_MakeSignature(PCtxtHandle phContext, ULONG fQOP,
1391  PSecBufferDesc pMessage, ULONG MessageSeqNo)
1392 {
1393     PNegoHelper helper;
1394     int token_idx;
1395
1396     TRACE("%p %d %p %d\n", phContext, fQOP, pMessage, MessageSeqNo);
1397     if (!phContext)
1398         return SEC_E_INVALID_HANDLE;
1399
1400     if(fQOP)
1401         FIXME("Ignoring fQOP 0x%08x\n", fQOP);
1402
1403     if(MessageSeqNo)
1404         FIXME("Ignoring MessageSeqNo\n");
1405
1406     if(!pMessage || !pMessage->pBuffers || pMessage->cBuffers < 2)
1407         return SEC_E_INVALID_TOKEN;
1408
1409     /* If we didn't find a SECBUFFER_TOKEN type buffer */
1410     if((token_idx = ntlm_GetTokenBufferIndex(pMessage)) == -1)
1411         return SEC_E_INVALID_TOKEN;
1412
1413     if(pMessage->pBuffers[token_idx].cbBuffer < 16)
1414         return SEC_E_BUFFER_TOO_SMALL;
1415
1416     helper = (PNegoHelper)phContext->dwLower;
1417     TRACE("Negotiated flags are: 0x%08lx\n", helper->neg_flags);
1418
1419     return ntlm_CreateSignature(helper, pMessage, token_idx, NTLM_SEND, TRUE);
1420 }
1421
1422 /***********************************************************************
1423  *              VerifySignature
1424  */
1425 static SECURITY_STATUS SEC_ENTRY ntlm_VerifySignature(PCtxtHandle phContext,
1426  PSecBufferDesc pMessage, ULONG MessageSeqNo, PULONG pfQOP)
1427 {
1428     PNegoHelper helper;
1429     ULONG fQOP = 0;
1430     UINT i;
1431     int token_idx;
1432     SECURITY_STATUS ret;
1433     SecBufferDesc local_desc;
1434     PSecBuffer     local_buff;
1435     BYTE          local_sig[16];
1436
1437     TRACE("%p %p %d %p\n", phContext, pMessage, MessageSeqNo, pfQOP);
1438     if(!phContext)
1439         return SEC_E_INVALID_HANDLE;
1440
1441     if(!pMessage || !pMessage->pBuffers || pMessage->cBuffers < 2)
1442         return SEC_E_INVALID_TOKEN;
1443
1444     if((token_idx = ntlm_GetTokenBufferIndex(pMessage)) == -1)
1445         return SEC_E_INVALID_TOKEN;
1446
1447     if(pMessage->pBuffers[token_idx].cbBuffer < 16)
1448         return SEC_E_BUFFER_TOO_SMALL;
1449
1450     if(MessageSeqNo)
1451         FIXME("Ignoring MessageSeqNo\n");
1452
1453     helper = (PNegoHelper)phContext->dwLower;
1454     TRACE("Negotiated flags: 0x%08lx\n", helper->neg_flags);
1455
1456     local_buff = HeapAlloc(GetProcessHeap(), 0, pMessage->cBuffers * sizeof(SecBuffer));
1457
1458     local_desc.ulVersion = SECBUFFER_VERSION;
1459     local_desc.cBuffers = pMessage->cBuffers;
1460     local_desc.pBuffers = local_buff;
1461
1462     for(i=0; i < pMessage->cBuffers; ++i)
1463     {
1464         if(pMessage->pBuffers[i].BufferType == SECBUFFER_TOKEN)
1465         {
1466             local_buff[i].BufferType = SECBUFFER_TOKEN;
1467             local_buff[i].cbBuffer = 16;
1468             local_buff[i].pvBuffer = local_sig;
1469         }
1470         else
1471         {
1472             local_buff[i].BufferType = pMessage->pBuffers[i].BufferType;
1473             local_buff[i].cbBuffer = pMessage->pBuffers[i].cbBuffer;
1474             local_buff[i].pvBuffer = pMessage->pBuffers[i].pvBuffer;
1475         }
1476     }
1477
1478     if((ret = ntlm_CreateSignature(helper, &local_desc, token_idx, NTLM_RECV, TRUE)) != SEC_E_OK)
1479         return ret;
1480
1481     if(memcmp(((PBYTE)local_buff[token_idx].pvBuffer) + 8,
1482                 ((PBYTE)pMessage->pBuffers[token_idx].pvBuffer) + 8, 8))
1483         ret = SEC_E_MESSAGE_ALTERED;
1484     else
1485         ret = SEC_E_OK;
1486
1487     HeapFree(GetProcessHeap(), 0, local_buff);
1488     pfQOP = &fQOP;
1489
1490     return ret;
1491
1492 }
1493
1494 /***********************************************************************
1495  *             FreeCredentialsHandle
1496  */
1497 static SECURITY_STATUS SEC_ENTRY ntlm_FreeCredentialsHandle(
1498         PCredHandle phCredential)
1499 {
1500     SECURITY_STATUS ret;
1501
1502     if(phCredential){
1503         PNegoHelper helper = (PNegoHelper) phCredential->dwLower;
1504         phCredential->dwUpper = 0;
1505         phCredential->dwLower = 0;
1506         if (helper->password)
1507             memset(helper->password, 0, helper->pwlen);
1508         HeapFree(GetProcessHeap(), 0, helper->password);
1509         cleanup_helper(helper);
1510         ret = SEC_E_OK;
1511     }
1512     else
1513         ret = SEC_E_OK;
1514     
1515     return ret;
1516 }
1517
1518 /***********************************************************************
1519  *             EncryptMessage
1520  */
1521 static SECURITY_STATUS SEC_ENTRY ntlm_EncryptMessage(PCtxtHandle phContext,
1522         ULONG fQOP, PSecBufferDesc pMessage, ULONG MessageSeqNo)
1523 {
1524     PNegoHelper helper;
1525     int token_idx;
1526
1527     TRACE("(%p %d %p %d)\n", phContext, fQOP, pMessage, MessageSeqNo);
1528
1529     if(!phContext)
1530         return SEC_E_INVALID_HANDLE;
1531
1532     if(fQOP)
1533         FIXME("Ignoring fQOP\n");
1534
1535     if(MessageSeqNo)
1536         FIXME("Ignoring MessageSeqNo\n");
1537
1538     if(!pMessage || !pMessage->pBuffers || pMessage->cBuffers < 2)
1539         return SEC_E_INVALID_TOKEN;
1540
1541     if((token_idx = ntlm_GetTokenBufferIndex(pMessage)) == -1)
1542         return SEC_E_INVALID_TOKEN;
1543
1544     if(pMessage->pBuffers[token_idx].cbBuffer < 16)
1545         return SEC_E_BUFFER_TOO_SMALL;
1546
1547     helper = (PNegoHelper) phContext->dwLower;
1548
1549     if(helper->neg_flags & NTLMSSP_NEGOTIATE_NTLM2 && 
1550             helper->neg_flags & NTLMSSP_NEGOTIATE_SEAL)
1551     { 
1552         ntlm_CreateSignature(helper, pMessage, token_idx, NTLM_SEND, FALSE);
1553         SECUR32_arc4Process(helper->crypt.ntlm2.send_a4i,
1554                 (BYTE *)pMessage->pBuffers[1].pvBuffer,
1555                 pMessage->pBuffers[1].cbBuffer);
1556
1557         if(helper->neg_flags & NTLMSSP_NEGOTIATE_KEY_EXCHANGE)
1558             SECUR32_arc4Process(helper->crypt.ntlm2.send_a4i,
1559                     ((BYTE *)pMessage->pBuffers[token_idx].pvBuffer)+4, 8);
1560
1561
1562         return SEC_E_OK;
1563     }
1564     else
1565     {
1566         PBYTE sig;
1567         ULONG save_flags;
1568
1569         /* EncryptMessage always produces real signatures, so make sure
1570          * NTLMSSP_NEGOTIATE_SIGN is set*/
1571         save_flags = helper->neg_flags;
1572         helper->neg_flags |= NTLMSSP_NEGOTIATE_SIGN;
1573         ntlm_CreateSignature(helper, pMessage, token_idx, NTLM_SEND, FALSE);
1574         helper->neg_flags = save_flags;
1575
1576         sig = pMessage->pBuffers[token_idx].pvBuffer;
1577
1578         SECUR32_arc4Process(helper->crypt.ntlm.a4i, pMessage->pBuffers[1].pvBuffer,
1579                 pMessage->pBuffers[1].cbBuffer);
1580         SECUR32_arc4Process(helper->crypt.ntlm.a4i, sig+4, 12);
1581
1582         if(helper->neg_flags & NTLMSSP_NEGOTIATE_ALWAYS_SIGN || helper->neg_flags == 0)
1583             memset(sig+4, 0, 4);
1584
1585     }
1586
1587     return SEC_E_OK;
1588 }
1589
1590 /***********************************************************************
1591  *             DecryptMessage
1592  */
1593 static SECURITY_STATUS SEC_ENTRY ntlm_DecryptMessage(PCtxtHandle phContext,
1594         PSecBufferDesc pMessage, ULONG MessageSeqNo, PULONG pfQOP)
1595 {
1596     SECURITY_STATUS ret;
1597     ULONG ntlmssp_flags_save;
1598     PNegoHelper helper;
1599     int token_idx;
1600     TRACE("(%p %p %d %p)\n", phContext, pMessage, MessageSeqNo, pfQOP);
1601
1602     if(!phContext)
1603         return SEC_E_INVALID_HANDLE;
1604
1605     if(MessageSeqNo)
1606         FIXME("Ignoring MessageSeqNo\n");
1607
1608     if(!pMessage || !pMessage->pBuffers || pMessage->cBuffers < 2)
1609         return SEC_E_INVALID_TOKEN;
1610
1611     if((token_idx = ntlm_GetTokenBufferIndex(pMessage)) == -1)
1612         return SEC_E_INVALID_TOKEN;
1613
1614     if(pMessage->pBuffers[token_idx].cbBuffer < 16)
1615         return SEC_E_BUFFER_TOO_SMALL;
1616
1617     helper = (PNegoHelper) phContext->dwLower;
1618
1619     if(helper->neg_flags & NTLMSSP_NEGOTIATE_NTLM2 && helper->neg_flags & NTLMSSP_NEGOTIATE_SEAL)
1620     {
1621         SECUR32_arc4Process(helper->crypt.ntlm2.recv_a4i,
1622                 pMessage->pBuffers[1].pvBuffer, pMessage->pBuffers[1].cbBuffer);
1623     }
1624     else
1625     {
1626         SECUR32_arc4Process(helper->crypt.ntlm.a4i,
1627                 pMessage->pBuffers[1].pvBuffer, pMessage->pBuffers[1].cbBuffer);
1628     }
1629
1630     /* Make sure we use a session key for the signature check, EncryptMessage
1631      * always does that, even in the dummy case */
1632     ntlmssp_flags_save = helper->neg_flags;
1633
1634     helper->neg_flags |= NTLMSSP_NEGOTIATE_SIGN;
1635     ret = ntlm_VerifySignature(phContext, pMessage, MessageSeqNo, pfQOP);
1636
1637     helper->neg_flags = ntlmssp_flags_save;
1638
1639     return ret;
1640 }
1641
1642 static const SecurityFunctionTableA ntlmTableA = {
1643     1,
1644     NULL,   /* EnumerateSecurityPackagesA */
1645     ntlm_QueryCredentialsAttributesA,   /* QueryCredentialsAttributesA */
1646     ntlm_AcquireCredentialsHandleA,     /* AcquireCredentialsHandleA */
1647     ntlm_FreeCredentialsHandle,         /* FreeCredentialsHandle */
1648     NULL,   /* Reserved2 */
1649     ntlm_InitializeSecurityContextA,    /* InitializeSecurityContextA */
1650     ntlm_AcceptSecurityContext,         /* AcceptSecurityContext */
1651     ntlm_CompleteAuthToken,             /* CompleteAuthToken */
1652     ntlm_DeleteSecurityContext,         /* DeleteSecurityContext */
1653     NULL,  /* ApplyControlToken */
1654     ntlm_QueryContextAttributesA,       /* QueryContextAttributesA */
1655     ntlm_ImpersonateSecurityContext,    /* ImpersonateSecurityContext */
1656     ntlm_RevertSecurityContext,         /* RevertSecurityContext */
1657     ntlm_MakeSignature,                 /* MakeSignature */
1658     ntlm_VerifySignature,               /* VerifySignature */
1659     FreeContextBuffer,                  /* FreeContextBuffer */
1660     NULL,   /* QuerySecurityPackageInfoA */
1661     NULL,   /* Reserved3 */
1662     NULL,   /* Reserved4 */
1663     NULL,   /* ExportSecurityContext */
1664     NULL,   /* ImportSecurityContextA */
1665     NULL,   /* AddCredentialsA */
1666     NULL,   /* Reserved8 */
1667     NULL,   /* QuerySecurityContextToken */
1668     ntlm_EncryptMessage,                /* EncryptMessage */
1669     ntlm_DecryptMessage,                /* DecryptMessage */
1670     NULL,   /* SetContextAttributesA */
1671 };
1672
1673 static const SecurityFunctionTableW ntlmTableW = {
1674     1,
1675     NULL,   /* EnumerateSecurityPackagesW */
1676     ntlm_QueryCredentialsAttributesW,   /* QueryCredentialsAttributesW */
1677     ntlm_AcquireCredentialsHandleW,     /* AcquireCredentialsHandleW */
1678     ntlm_FreeCredentialsHandle,         /* FreeCredentialsHandle */
1679     NULL,   /* Reserved2 */
1680     ntlm_InitializeSecurityContextW,    /* InitializeSecurityContextW */
1681     ntlm_AcceptSecurityContext,         /* AcceptSecurityContext */
1682     ntlm_CompleteAuthToken,             /* CompleteAuthToken */
1683     ntlm_DeleteSecurityContext,         /* DeleteSecurityContext */
1684     NULL,  /* ApplyControlToken */
1685     ntlm_QueryContextAttributesW,       /* QueryContextAttributesW */
1686     ntlm_ImpersonateSecurityContext,    /* ImpersonateSecurityContext */
1687     ntlm_RevertSecurityContext,         /* RevertSecurityContext */
1688     ntlm_MakeSignature,                 /* MakeSignature */
1689     ntlm_VerifySignature,               /* VerifySignature */
1690     FreeContextBuffer,                  /* FreeContextBuffer */
1691     NULL,   /* QuerySecurityPackageInfoW */
1692     NULL,   /* Reserved3 */
1693     NULL,   /* Reserved4 */
1694     NULL,   /* ExportSecurityContext */
1695     NULL,   /* ImportSecurityContextW */
1696     NULL,   /* AddCredentialsW */
1697     NULL,   /* Reserved8 */
1698     NULL,   /* QuerySecurityContextToken */
1699     ntlm_EncryptMessage,                /* EncryptMessage */
1700     ntlm_DecryptMessage,                /* DecryptMessage */
1701     NULL,   /* SetContextAttributesW */
1702 };
1703
1704 #define NTLM_COMMENT \
1705    { 'N', 'T', 'L', 'M', ' ', \
1706      'S', 'e', 'c', 'u', 'r', 'i', 't', 'y', ' ', \
1707      'P', 'a', 'c', 'k', 'a', 'g', 'e', 0}
1708
1709 static CHAR ntlm_comment_A[] = NTLM_COMMENT;
1710 static WCHAR ntlm_comment_W[] = NTLM_COMMENT;
1711
1712 #define NTLM_NAME {'N', 'T', 'L', 'M', 0}
1713
1714 static char ntlm_name_A[] = NTLM_NAME;
1715 static WCHAR ntlm_name_W[] = NTLM_NAME;
1716
1717 /* According to Windows, NTLM has the following capabilities.  */
1718 #define CAPS ( \
1719         SECPKG_FLAG_INTEGRITY | \
1720         SECPKG_FLAG_PRIVACY | \
1721         SECPKG_FLAG_TOKEN_ONLY | \
1722         SECPKG_FLAG_CONNECTION | \
1723         SECPKG_FLAG_MULTI_REQUIRED | \
1724         SECPKG_FLAG_IMPERSONATION | \
1725         SECPKG_FLAG_ACCEPT_WIN32_NAME | \
1726         SECPKG_FLAG_READONLY_WITH_CHECKSUM)
1727
1728 static const SecPkgInfoW infoW = {
1729     CAPS,
1730     1,
1731     RPC_C_AUTHN_WINNT,
1732     NTLM_MAX_BUF,
1733     ntlm_name_W,
1734     ntlm_comment_W
1735 };
1736
1737 static const SecPkgInfoA infoA = {
1738     CAPS,
1739     1,
1740     RPC_C_AUTHN_WINNT,
1741     NTLM_MAX_BUF,
1742     ntlm_name_A,
1743     ntlm_comment_A
1744 };
1745
1746 void SECUR32_initNTLMSP(void)
1747 {
1748     SECURITY_STATUS ret;
1749     PNegoHelper helper;
1750     static CHAR version[] = "--version";
1751
1752     SEC_CHAR *args[] = {
1753         ntlm_auth,
1754         version,
1755         NULL };
1756
1757     if((ret = fork_helper(&helper, ntlm_auth, args)) != SEC_E_OK)
1758     {
1759         /* Cheat and allocate a helper anyway, so cleanup later will work. */
1760         helper = HeapAlloc(GetProcessHeap(),0, sizeof(PNegoHelper));
1761         helper->major = helper->minor = helper->micro = -1;
1762     }
1763     else
1764         check_version(helper);
1765
1766     if( (helper->major >  MIN_NTLM_AUTH_MAJOR_VERSION) ||
1767         (helper->major == MIN_NTLM_AUTH_MAJOR_VERSION  &&
1768          helper->minor >  MIN_NTLM_AUTH_MINOR_VERSION) ||
1769         (helper->major == MIN_NTLM_AUTH_MAJOR_VERSION  &&
1770          helper->minor == MIN_NTLM_AUTH_MINOR_VERSION  &&
1771          helper->micro >= MIN_NTLM_AUTH_MICRO_VERSION) )
1772     {
1773         SecureProvider *provider = SECUR32_addProvider(&ntlmTableA, &ntlmTableW, NULL);
1774         SECUR32_addPackages(provider, 1L, &infoA, &infoW);
1775     }
1776     else
1777     {
1778         ERR("%s was not found or is outdated. "
1779             "Make sure that ntlm_auth >= %d.%d.%d is in your path.\n",
1780             ntlm_auth,
1781             MIN_NTLM_AUTH_MAJOR_VERSION,
1782             MIN_NTLM_AUTH_MINOR_VERSION,
1783             MIN_NTLM_AUTH_MICRO_VERSION);
1784     }
1785     cleanup_helper(helper);
1786 }