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