secur32: Add real signing / verifying to NTLM provider.
[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 "wine/debug.h"
32
33 WINE_DEFAULT_DEBUG_CHANNEL(secur32);
34
35 #define NTLM_MAX_BUF 1904
36
37
38 /***********************************************************************
39  *              QueryCredentialsAttributesA
40  */
41 static SECURITY_STATUS SEC_ENTRY ntlm_QueryCredentialsAttributesA(
42         PCredHandle phCredential, ULONG ulAttribute, PVOID pBuffer)
43 {
44     SECURITY_STATUS ret;
45
46     TRACE("(%p, %ld, %p)\n", phCredential, ulAttribute, pBuffer);
47
48     if(ulAttribute == SECPKG_ATTR_NAMES)
49     {
50         FIXME("SECPKG_CRED_ATTR_NAMES: stub\n");
51         ret = SEC_E_UNSUPPORTED_FUNCTION;
52     }
53     else
54         ret = SEC_E_UNSUPPORTED_FUNCTION;
55     
56     return ret;
57 }
58
59 /***********************************************************************
60  *              QueryCredentialsAttributesW
61  */
62 static SECURITY_STATUS SEC_ENTRY ntlm_QueryCredentialsAttributesW(
63         PCredHandle phCredential, ULONG ulAttribute, PVOID pBuffer)
64 {
65     SECURITY_STATUS ret;
66
67     TRACE("(%p, %ld, %p)\n", phCredential, ulAttribute, pBuffer);
68
69     if(ulAttribute == SECPKG_ATTR_NAMES)
70     {
71         FIXME("SECPKG_CRED_ATTR_NAMES: stub\n");
72         ret = SEC_E_UNSUPPORTED_FUNCTION;
73     }
74     else
75         ret = SEC_E_UNSUPPORTED_FUNCTION;
76     
77     return ret;
78 }
79
80 /***********************************************************************
81  *              AcquireCredentialsHandleW
82  */
83 static SECURITY_STATUS SEC_ENTRY ntlm_AcquireCredentialsHandleW(
84  SEC_WCHAR *pszPrincipal, SEC_WCHAR *pszPackage, ULONG fCredentialUse,
85  PLUID pLogonID, PVOID pAuthData, SEC_GET_KEY_FN pGetKeyFn,
86  PVOID pGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
87 {
88     SECURITY_STATUS ret;
89     PNegoHelper helper = NULL;
90     static CHAR ntlm_auth[] = "ntlm_auth",
91                 helper_protocol[] = "--helper-protocol=squid-2.5-ntlmssp";
92
93     SEC_CHAR *client_user_arg = NULL;
94     SEC_CHAR *client_domain_arg = NULL;
95     SEC_WCHAR *username = NULL, *domain = NULL;
96
97     SEC_CHAR *client_argv[5];
98     SEC_CHAR *server_argv[] = { ntlm_auth,
99         helper_protocol,
100         NULL };
101
102     TRACE("(%s, %s, 0x%08lx, %p, %p, %p, %p, %p, %p)\n",
103      debugstr_w(pszPrincipal), debugstr_w(pszPackage), fCredentialUse,
104      pLogonID, pAuthData, pGetKeyFn, pGetKeyArgument, phCredential, ptsExpiry);
105
106
107     switch(fCredentialUse)
108     {
109         case SECPKG_CRED_INBOUND:
110             if( (ret = fork_helper(&helper, "ntlm_auth", server_argv)) !=
111                     SEC_E_OK)
112             {
113                 phCredential = NULL;
114                 break;
115             }
116             else
117             {
118                 helper->mode = NTLM_SERVER;
119                 phCredential->dwUpper = fCredentialUse;
120                 phCredential->dwLower = (ULONG_PTR)helper;
121             }
122             ret = SEC_E_OK;
123             break;
124         case SECPKG_CRED_OUTBOUND:
125             {
126                 static const char username_arg[] = "--username=";
127                 static const char domain_arg[] = "--domain=";
128                 static char ntlm_auth[] = "ntlm_auth";
129                 static char helper_protocol[] = "--helper-protocol=ntlmssp-client-1";
130                 int unixcp_size;
131
132                 if(pAuthData == NULL)
133                 {
134                     LPWKSTA_USER_INFO_1 ui = NULL;
135                     NET_API_STATUS status;
136
137                     status = NetWkstaUserGetInfo(NULL, 1, (LPBYTE *)&ui);
138                     if (status != NERR_Success || ui == NULL)
139                     {
140                         ret = SEC_E_NO_CREDENTIALS;
141                         phCredential = NULL;
142                         break;
143                     }
144                     
145                     username = HeapAlloc(GetProcessHeap(), 0, 
146                             (lstrlenW(ui->wkui1_username)+1) * 
147                             sizeof(SEC_WCHAR));
148                     lstrcpyW(username, ui->wkui1_username);
149                         
150                     /* same for the domain */
151                     domain = HeapAlloc(GetProcessHeap(), 0, 
152                             (lstrlenW(ui->wkui1_logon_domain)+1) * 
153                             sizeof(SEC_WCHAR));
154                     lstrcpyW(domain, ui->wkui1_logon_domain);
155                     NetApiBufferFree(ui);
156                 }
157                 else
158                 {
159                     PSEC_WINNT_AUTH_IDENTITY_W auth_data = 
160                         (PSEC_WINNT_AUTH_IDENTITY_W)pAuthData;
161
162                     if (!auth_data->UserLength || !auth_data->DomainLength)
163                     {
164                         ret = SEC_E_NO_CREDENTIALS;
165                         phCredential = NULL;
166                         break;
167                     }
168                     /* Get username and domain from pAuthData */
169                     username = HeapAlloc(GetProcessHeap(), 0, 
170                             (auth_data->UserLength + 1) * sizeof(SEC_WCHAR));
171                     lstrcpyW(username, auth_data->User);
172
173                     domain = HeapAlloc(GetProcessHeap(), 0,
174                             (auth_data->DomainLength + 1) * sizeof(SEC_WCHAR));
175                     lstrcpyW(domain, auth_data->Domain);
176                 }
177                 TRACE("Username is %s\n", debugstr_w(username));
178                 unixcp_size =  WideCharToMultiByte(CP_UNIXCP, WC_NO_BEST_FIT_CHARS,
179                         username, -1, NULL, 0, NULL, NULL) + sizeof(username_arg);
180                 client_user_arg = HeapAlloc(GetProcessHeap(), 0, unixcp_size);
181                 lstrcpyA(client_user_arg, username_arg);
182                 WideCharToMultiByte(CP_UNIXCP, WC_NO_BEST_FIT_CHARS, username, -1,
183                         client_user_arg + sizeof(username_arg) - 1, 
184                         unixcp_size - sizeof(username_arg) + 1, NULL, NULL);
185
186                 TRACE("Domain name is %s\n", debugstr_w(domain));
187                 unixcp_size = WideCharToMultiByte(CP_UNIXCP, WC_NO_BEST_FIT_CHARS,
188                         domain, -1, NULL, 0,  NULL, NULL) + sizeof(domain_arg);
189                 client_domain_arg = HeapAlloc(GetProcessHeap(), 0, unixcp_size);
190                 lstrcpyA(client_domain_arg, domain_arg);
191                 WideCharToMultiByte(CP_UNIXCP, WC_NO_BEST_FIT_CHARS, domain,
192                         -1, client_domain_arg + sizeof(domain_arg) - 1, 
193                         unixcp_size - sizeof(domain) + 1, NULL, NULL);
194
195                 client_argv[0] = ntlm_auth;
196                 client_argv[1] = helper_protocol;
197                 client_argv[2] = client_user_arg;
198                 client_argv[3] = client_domain_arg;
199                 client_argv[4] = NULL;
200
201                 if((ret = fork_helper(&helper, "ntlm_auth", client_argv)) != 
202                         SEC_E_OK)
203                 {
204                     phCredential = NULL;
205                     break;
206                 }
207                 else
208                 {
209                     helper->mode = NTLM_CLIENT;
210
211                     if(pAuthData != NULL)
212                     {
213                         PSEC_WINNT_AUTH_IDENTITY_W auth_data = 
214                            (PSEC_WINNT_AUTH_IDENTITY_W)pAuthData;
215
216                         if(auth_data->PasswordLength != 0)
217                         {
218                             helper->pwlen = WideCharToMultiByte(CP_UNIXCP, 
219                                 WC_NO_BEST_FIT_CHARS, auth_data->Password, 
220                                 auth_data->PasswordLength+1, NULL, 0, NULL, NULL);
221                         
222                             helper->password = HeapAlloc(GetProcessHeap(), 0, 
223                                     helper->pwlen);
224
225                             WideCharToMultiByte(CP_UNIXCP, WC_NO_BEST_FIT_CHARS,
226                                 auth_data->Password, auth_data->PasswordLength+1,
227                                 helper->password, helper->pwlen, NULL, NULL);
228                         }
229                     }
230            
231                     phCredential->dwUpper = fCredentialUse;
232                     phCredential->dwLower = (ULONG_PTR)helper;
233                     TRACE("ACH phCredential->dwUpper: 0x%08lx, dwLower: 0x%08lx\n",
234                             phCredential->dwUpper, phCredential->dwLower);
235                 }
236                 ret = SEC_E_OK;
237                 break;
238             }
239         case SECPKG_CRED_BOTH:
240             FIXME("AcquireCredentialsHandle: SECPKG_CRED_BOTH stub\n");
241             ret = SEC_E_UNSUPPORTED_FUNCTION;
242             phCredential = NULL;
243             break;
244         default:
245             phCredential = NULL;
246             ret = SEC_E_UNKNOWN_CREDENTIALS;
247     }
248     
249
250     HeapFree(GetProcessHeap(), 0, client_user_arg);
251     HeapFree(GetProcessHeap(), 0, client_domain_arg);
252     HeapFree(GetProcessHeap(), 0, username);
253     HeapFree(GetProcessHeap(), 0, domain);
254
255     return ret;
256 }
257
258 /***********************************************************************
259  *              AcquireCredentialsHandleA
260  */
261 static SECURITY_STATUS SEC_ENTRY ntlm_AcquireCredentialsHandleA(
262  SEC_CHAR *pszPrincipal, SEC_CHAR *pszPackage, ULONG fCredentialUse,
263  PLUID pLogonID, PVOID pAuthData, SEC_GET_KEY_FN pGetKeyFn,
264  PVOID pGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
265 {
266     SECURITY_STATUS ret;
267     int user_sizeW, domain_sizeW, passwd_sizeW;
268     
269     SEC_WCHAR *user = NULL, *domain = NULL, *passwd = NULL, *package = NULL;
270     
271     PSEC_WINNT_AUTH_IDENTITY_W pAuthDataW = NULL;
272     PSEC_WINNT_AUTH_IDENTITY_A identity  = NULL;
273
274     TRACE("(%s, %s, 0x%08lx, %p, %p, %p, %p, %p, %p)\n",
275      debugstr_a(pszPrincipal), debugstr_a(pszPackage), fCredentialUse,
276      pLogonID, pAuthData, pGetKeyFn, pGetKeyArgument, phCredential, ptsExpiry);
277     
278     if(pszPackage != NULL)
279     {
280         int package_sizeW = MultiByteToWideChar(CP_ACP, 0, pszPackage, -1,
281                 NULL, 0);
282
283         package = HeapAlloc(GetProcessHeap(), 0, package_sizeW * 
284                 sizeof(SEC_WCHAR));
285         MultiByteToWideChar(CP_ACP, 0, pszPackage, -1, package, package_sizeW);
286     }
287
288     
289     if(pAuthData != NULL)
290     {
291         identity = (PSEC_WINNT_AUTH_IDENTITY_A)pAuthData;
292         
293         if(identity->Flags == SEC_WINNT_AUTH_IDENTITY_ANSI)
294         {
295             pAuthDataW = HeapAlloc(GetProcessHeap(), 0, 
296                     sizeof(SEC_WINNT_AUTH_IDENTITY_W));
297
298             if(identity->UserLength != 0)
299             {
300                 user_sizeW = MultiByteToWideChar(CP_ACP, 0, 
301                     (LPCSTR)identity->User, identity->UserLength+1, NULL, 0);
302                 user = HeapAlloc(GetProcessHeap(), 0, user_sizeW * 
303                         sizeof(SEC_WCHAR));
304                 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)identity->User, 
305                     identity->UserLength+1, user, user_sizeW);
306             }
307             else
308             {
309                 user_sizeW = 0;
310             }
311              
312             if(identity->DomainLength != 0)
313             {
314                 domain_sizeW = MultiByteToWideChar(CP_ACP, 0, 
315                     (LPCSTR)identity->Domain, identity->DomainLength+1, NULL, 0);
316                 domain = HeapAlloc(GetProcessHeap(), 0, domain_sizeW 
317                     * sizeof(SEC_WCHAR));
318                 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)identity->Domain, 
319                     identity->DomainLength+1, domain, domain_sizeW);
320             }
321             else
322             {
323                 domain_sizeW = 0;
324             }
325
326             if(identity->PasswordLength != 0)
327             {
328                 passwd_sizeW = MultiByteToWideChar(CP_ACP, 0, 
329                     (LPCSTR)identity->Password, identity->PasswordLength+1, 
330                     NULL, 0);
331                 passwd = HeapAlloc(GetProcessHeap(), 0, passwd_sizeW
332                     * sizeof(SEC_WCHAR));
333                 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)identity->Password,
334                     identity->PasswordLength+1, passwd, passwd_sizeW);
335             }
336             else
337             {
338                 passwd_sizeW = 0;
339             }
340             
341             pAuthDataW->Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
342             pAuthDataW->User = user;
343             pAuthDataW->UserLength = user_sizeW;
344             pAuthDataW->Domain = domain;
345             pAuthDataW->DomainLength = domain_sizeW;
346             pAuthDataW->Password = passwd;
347             pAuthDataW->PasswordLength = passwd_sizeW;
348         }
349         else
350         {
351             pAuthDataW = (PSEC_WINNT_AUTH_IDENTITY_W)identity;
352         }
353     }       
354     
355     ret = ntlm_AcquireCredentialsHandleW(NULL, package, fCredentialUse, 
356             pLogonID, pAuthDataW, pGetKeyFn, pGetKeyArgument, phCredential,
357             ptsExpiry);
358     
359     HeapFree(GetProcessHeap(), 0, package);
360     HeapFree(GetProcessHeap(), 0, user);
361     HeapFree(GetProcessHeap(), 0, domain);
362     HeapFree(GetProcessHeap(), 0, passwd);
363     if(pAuthDataW != (PSEC_WINNT_AUTH_IDENTITY_W)identity)
364         HeapFree(GetProcessHeap(), 0, pAuthDataW);
365     
366     return ret;
367 }
368
369 /***********************************************************************
370  *              InitializeSecurityContextW
371  */
372 static SECURITY_STATUS SEC_ENTRY ntlm_InitializeSecurityContextW(
373  PCredHandle phCredential, PCtxtHandle phContext, SEC_WCHAR *pszTargetName, 
374  ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep, 
375  PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext, 
376  PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
377 {
378     SECURITY_STATUS ret;
379     PNegoHelper helper;
380     ULONG ctxt_attr = 0;
381     char* buffer, *want_flags = NULL;
382     PBYTE bin;
383     int buffer_len, bin_len, max_len = NTLM_MAX_BUF;
384
385     TRACE("%p %p %s %ld %ld %ld %p %ld %p %p %p %p\n", phCredential, phContext,
386      debugstr_w(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
387      Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
388
389     if(!phCredential)
390         return SEC_E_INVALID_HANDLE;
391
392     /* As the server side of sspi never calls this, make sure that
393      * the handler is a client handler.
394      */
395     helper = (PNegoHelper)phCredential->dwLower;
396     if(helper->mode != NTLM_CLIENT)
397     {
398         TRACE("Helper mode = %d\n", helper->mode);
399         return SEC_E_INVALID_HANDLE;
400     }
401
402     /****************************************
403      * When communicating with the client, there can be the
404      * following reply packets:
405      * YR <base64 blob>         should be sent to the server
406      * PW                       should be sent back to helper with
407      *                          base64 encoded password
408      * AF <base64 blob>         client is done, blob should be
409      *                          sent to server with KK prefixed
410      * GF <string list>         A string list of negotiated flags
411      * GK <base64 blob>         base64 encoded session key
412      * BH <char reason>         something broke
413      */
414     /* The squid cache size is 2010 chars, and that's what ntlm_auth uses */
415
416     if (pszTargetName)
417     {
418         TRACE("According to a MS whitepaper pszTargetName is ignored.\n");
419     }
420
421     if(TargetDataRep == SECURITY_NETWORK_DREP){
422         TRACE("Setting SECURITY_NETWORK_DREP\n");
423     }
424
425     buffer = HeapAlloc(GetProcessHeap(), 0, sizeof(char) * NTLM_MAX_BUF);
426     bin = HeapAlloc(GetProcessHeap(), 0, sizeof(BYTE) * NTLM_MAX_BUF);
427
428     if((phContext == NULL) && (pInput == NULL))
429     {
430         TRACE("First time in ISC()\n");
431         /* Allocate space for a maximal string of 
432          * "SF NTLMSSP_FEATURE_SIGN NTLMSSP_FEATURE_SEAL
433          * NTLMSSP_FEATURE_SESSION_KEY"
434          */
435         want_flags = HeapAlloc(GetProcessHeap(), 0, 73);
436         if(want_flags == NULL)
437         {
438             ret = SEC_E_INSUFFICIENT_MEMORY;
439             goto isc_end;
440         }
441         lstrcpyA(want_flags, "SF");
442         if(fContextReq & ISC_REQ_CONFIDENTIALITY)
443             lstrcatA(want_flags, " NTLMSSP_FEATURE_SEAL");
444         if(fContextReq & ISC_REQ_CONNECTION)
445         {
446             /* This is default, so we'll enable it */
447             ctxt_attr |= ISC_RET_CONNECTION;
448             lstrcatA(want_flags, " NTLMSSP_FEATURE_SESSION_KEY");
449         }
450         if(fContextReq & ISC_REQ_EXTENDED_ERROR)
451             FIXME("ISC_REQ_EXTENDED_ERROR\n");
452         if(fContextReq & ISC_REQ_INTEGRITY)
453             lstrcatA(want_flags, " NTLMSSP_FEATURE_SIGN");
454         if(fContextReq & ISC_REQ_MUTUAL_AUTH)
455             FIXME("ISC_REQ_MUTUAL_AUTH\n");
456         if(fContextReq & ISC_REQ_REPLAY_DETECT)
457             FIXME("ISC_REQ_REPLAY_DETECT\n");
458         if(fContextReq & ISC_REQ_SEQUENCE_DETECT)
459             FIXME("ISC_REQ_SEQUENCE_DETECT\n");
460         if(fContextReq & ISC_REQ_STREAM)
461             FIXME("ISC_REQ_STREAM\n");
462
463         /* Request a challenge request from ntlm_auth */
464         if(helper->password == NULL)
465         {
466             FIXME("Using empty password for now.\n");
467             lstrcpynA(buffer, "PW AA==", max_len-1);
468         }
469         else
470         {
471             lstrcpynA(buffer, "PW ", max_len-1);
472             if((ret = encodeBase64((unsigned char*)helper->password,
473                         helper->pwlen-2, buffer+3,
474                         max_len-3, &buffer_len)) != SEC_E_OK)
475             {
476                 TRACE("Deleting password!\n");
477                 memset(helper->password, 0, helper->pwlen-2);
478                 HeapFree(GetProcessHeap(), 0, helper->password);
479                 goto isc_end;
480             }
481
482         }
483
484         TRACE("Sending to helper: %s\n", debugstr_a(buffer));
485         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
486             goto isc_end;
487
488         TRACE("Helper returned %s\n", debugstr_a(buffer));
489
490         if(lstrlenA(want_flags) > 2)
491         {
492             TRACE("Want flags are '%s'\n", debugstr_a(want_flags));
493             lstrcpynA(buffer, want_flags, max_len-1);
494             if((ret = run_helper(helper, buffer, max_len, &buffer_len)) 
495                     != SEC_E_OK)
496                 goto isc_end;
497             if(!strncmp(buffer, "BH", 2))
498                 TRACE("Helper doesn't understand new command set\n");
499         }
500
501         lstrcpynA(buffer, "YR", max_len-1);
502
503         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
504             goto isc_end;
505
506         TRACE("%s\n", buffer);
507
508         if(strncmp(buffer, "YR ", 3) != 0)
509         {
510             /* Something borked */
511             TRACE("Helper returned %c%c\n", buffer[0], buffer[1]);
512             ret = SEC_E_INTERNAL_ERROR;
513             goto isc_end;
514         }
515         if((ret = decodeBase64(buffer+3, buffer_len-3, bin,
516                         max_len-1, &bin_len)) != SEC_E_OK)
517             goto isc_end;
518
519         /* Mask away the NTLMv2 flag, as well as the key exchange flag */
520         bin[14] &= ~0x08;
521         bin[15] &= ~0x40;
522
523         /* put the decoded client blob into the out buffer */
524
525         ret = SEC_I_CONTINUE_NEEDED;
526     }
527     else
528     {
529         /* handle second call here */
530         /* encode server data to base64 */
531         if (!pInput || !pInput->cBuffers)
532         {
533             ret = SEC_E_INCOMPLETE_MESSAGE;
534             goto isc_end;
535         }
536
537         if (!pInput->pBuffers[0].pvBuffer)
538         {
539             ret = SEC_E_INTERNAL_ERROR;
540             goto isc_end;
541         }
542
543         if(pInput->pBuffers[0].cbBuffer > max_len)
544         {
545             TRACE("pInput->pBuffers[0].cbBuffer is: %ld\n",
546                     pInput->pBuffers[0].cbBuffer);
547             ret = SEC_E_INVALID_TOKEN;
548             goto isc_end;
549         }
550         else
551             bin_len = pInput->pBuffers[0].cbBuffer;
552
553         memcpy(bin, pInput->pBuffers[0].pvBuffer, bin_len);
554
555         lstrcpynA(buffer, "TT ", max_len-1);
556
557         if((ret = encodeBase64(bin, bin_len, buffer+3,
558                         max_len-3, &buffer_len)) != SEC_E_OK)
559             goto isc_end;
560
561         TRACE("Server sent: %s\n", debugstr_a(buffer));
562
563         /* send TT base64 blob to ntlm_auth */
564         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
565             goto isc_end;
566
567         TRACE("Helper replied: %s\n", debugstr_a(buffer));
568
569         if( (strncmp(buffer, "KK ", 3) != 0) &&
570                 (strncmp(buffer, "AF ", 3) !=0))
571         {
572             TRACE("Helper returned %c%c\n", buffer[0], buffer[1]);
573             ret = SEC_E_INVALID_TOKEN;
574             goto isc_end;
575         }
576
577         /* decode the blob and send it to server */
578         if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len,
579                         &bin_len)) != SEC_E_OK)
580         {
581             goto isc_end;
582         }
583
584         phNewContext->dwUpper = ctxt_attr;
585         phNewContext->dwLower = (ULONG_PTR)helper;
586
587         ret = SEC_E_OK;
588     }
589
590     /* put the decoded client blob into the out buffer */
591
592     if (fContextReq & ISC_REQ_ALLOCATE_MEMORY)
593     {
594         if (pOutput)
595         {
596             pOutput->cBuffers = 1;
597             pOutput->pBuffers[0].pvBuffer = SECUR32_ALLOC(bin_len);
598             pOutput->pBuffers[0].cbBuffer = bin_len;
599         }
600     }
601
602     if (!pOutput || !pOutput->cBuffers || pOutput->pBuffers[0].cbBuffer < bin_len)
603     {
604         TRACE("out buffer is NULL or has not enough space\n");
605         ret = SEC_E_BUFFER_TOO_SMALL;
606         goto isc_end;
607     }
608
609     if (!pOutput->pBuffers[0].pvBuffer)
610     {
611         TRACE("out buffer is NULL\n");
612         ret = SEC_E_INTERNAL_ERROR;
613         goto isc_end;
614     }
615
616     pOutput->pBuffers[0].cbBuffer = bin_len;
617     pOutput->pBuffers[0].BufferType = SECBUFFER_DATA;
618     memcpy(pOutput->pBuffers[0].pvBuffer, bin, bin_len);
619
620     if(ret == SEC_E_OK)
621     {
622         TRACE("Getting negotiated flags\n");
623         lstrcpynA(buffer, "GF", max_len - 1);
624         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
625             goto isc_end;
626
627         if(buffer_len < 3)
628         {
629             TRACE("No flags negotiated, or helper does not support GF command\n");
630         }
631         else
632         {
633             TRACE("Negotiated %s\n", debugstr_a(buffer));
634             sscanf(buffer + 3, "%lx", &(helper->neg_flags));
635             TRACE("Stored 0x%08lx as flags\n", helper->neg_flags);
636         }
637
638         TRACE("Getting session key\n");
639         lstrcpynA(buffer, "GK", max_len - 1);
640         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
641             goto isc_end;
642
643         if(buffer_len < 3)
644             TRACE("Helper does not support GK command\n");
645         else
646         {
647             if(strncmp(buffer, "BH ", 3) == 0)
648             {
649                 TRACE("Helper sent %s\n", debugstr_a(buffer+3));
650                 helper->valid_session_key = FALSE;
651                 helper->session_key = HeapAlloc(GetProcessHeap(), 0, 16);
652                 /*Generate the dummy session key = MD4(MD4(password))*/
653                 if(helper->password)
654                     SECUR32_CreateNTLMv1SessionKey(helper->password, helper->session_key);
655                 else
656                     memset(helper->session_key, 0, 16);
657             }
658             else if(strncmp(buffer, "GK ", 3) == 0)
659             {
660                 if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len, 
661                                 &bin_len)) != SEC_E_OK)
662                 {
663                     TRACE("Failed to decode session key\n");
664                 }
665                 TRACE("Session key is %s\n", debugstr_a(buffer+3));
666                 helper->valid_session_key = TRUE;
667                 if(!helper->session_key)
668                     helper->session_key = HeapAlloc(GetProcessHeap(), 0, bin_len);
669                 if(!helper->session_key)
670                 {
671                     TRACE("Failed to allocate memory for session key\n");
672                     ret = SEC_E_INTERNAL_ERROR;
673                     goto isc_end;
674                 }
675                 memcpy(helper->session_key, bin, bin_len);
676             }
677         }
678         helper->crypt.ntlm.a4i = SECUR32_arc4Alloc();
679         SECUR32_arc4Init(helper->crypt.ntlm.a4i, helper->session_key, 16);
680         helper->crypt.ntlm.seq_num = 0l;
681     }
682
683     if(ret != SEC_I_CONTINUE_NEEDED)
684     {
685         TRACE("Deleting password!\n");
686         if(helper->password)
687             memset(helper->password, 0, helper->pwlen-2);
688         HeapFree(GetProcessHeap(), 0, helper->password);
689     }
690 isc_end:
691     HeapFree(GetProcessHeap(), 0, want_flags);
692     HeapFree(GetProcessHeap(), 0, buffer);
693     HeapFree(GetProcessHeap(), 0, bin);
694     return ret;
695 }
696
697 /***********************************************************************
698  *              InitializeSecurityContextA
699  */
700 static SECURITY_STATUS SEC_ENTRY ntlm_InitializeSecurityContextA(
701  PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR *pszTargetName,
702  ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep, 
703  PSecBufferDesc pInput,ULONG Reserved2, PCtxtHandle phNewContext, 
704  PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
705 {
706     SECURITY_STATUS ret;
707
708     TRACE("%p %p %s %ld %ld %ld %p %ld %p %p %p %p\n", phCredential, phContext,
709      debugstr_a(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
710      Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
711     
712     if (phCredential)
713     {
714         SEC_WCHAR *target = NULL;
715         if(pszTargetName != NULL)
716         {
717             int target_size = MultiByteToWideChar(CP_ACP, 0, pszTargetName, 
718                 strlen(pszTargetName)+1, NULL, 0);
719             target = HeapAlloc(GetProcessHeap(), 0, target_size * 
720                     sizeof(SEC_WCHAR));
721             MultiByteToWideChar(CP_ACP, 0, pszTargetName, strlen(pszTargetName)+1,
722                 target, target_size);
723         }
724         
725         ret = ntlm_InitializeSecurityContextW(phCredential, phContext, target, 
726                 fContextReq, Reserved1, TargetDataRep, pInput, Reserved2,
727                 phNewContext, pOutput, pfContextAttr, ptsExpiry);
728         
729         HeapFree(GetProcessHeap(), 0, target);
730     }
731     else
732     {
733         ret = SEC_E_INVALID_HANDLE;
734     }
735     return ret;
736 }
737
738 /***********************************************************************
739  *              AcceptSecurityContext
740  */
741 static SECURITY_STATUS SEC_ENTRY ntlm_AcceptSecurityContext(
742  PCredHandle phCredential, PCtxtHandle phContext, PSecBufferDesc pInput,
743  ULONG fContextReq, ULONG TargetDataRep, PCtxtHandle phNewContext, 
744  PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
745 {
746     SECURITY_STATUS ret;
747     char *buffer, *want_flags = NULL;
748     PBYTE bin;
749     int buffer_len, bin_len, max_len = NTLM_MAX_BUF;
750     ULONG ctxt_attr = 0;
751     PNegoHelper helper;
752
753     TRACE("%p %p %p %ld %ld %p %p %p %p\n", phCredential, phContext, pInput,
754      fContextReq, TargetDataRep, phNewContext, pOutput, pfContextAttr,
755      ptsExpiry);
756
757     if (!phCredential)
758         return SEC_E_INVALID_HANDLE;
759
760     helper = (PNegoHelper)phCredential->dwLower;
761
762     buffer = HeapAlloc(GetProcessHeap(), 0, sizeof(char) * NTLM_MAX_BUF);
763     bin    = HeapAlloc(GetProcessHeap(),0, sizeof(BYTE) * NTLM_MAX_BUF);
764
765     if(helper->mode != NTLM_SERVER)
766     {
767         ret = SEC_E_INVALID_HANDLE;
768         goto asc_end;
769     }
770
771     if(TargetDataRep == SECURITY_NETWORK_DREP){
772         TRACE("Using SECURITY_NETWORK_DREP\n");
773     }
774
775     if(phContext == NULL)
776     {
777         /* This is the first call to AcceptSecurityHandle */
778         if(pInput == NULL)
779         {
780             ret = SEC_E_INCOMPLETE_MESSAGE;
781             goto asc_end;
782         }
783
784         if(pInput->cBuffers < 1)
785         {
786             ret = SEC_E_INCOMPLETE_MESSAGE;
787             goto asc_end;
788         }
789
790         if(pInput->pBuffers[0].cbBuffer > max_len)
791         {
792             ret = SEC_E_INVALID_TOKEN;
793             goto asc_end;
794         }
795         else
796             bin_len = pInput->pBuffers[0].cbBuffer;
797
798         /* Handle all the flags */
799         want_flags = HeapAlloc(GetProcessHeap(), 0, 73);
800         if(want_flags == NULL)
801         {
802             TRACE("Failed to allocate memory for the want_flags!\n");
803             ret = SEC_E_INSUFFICIENT_MEMORY;
804             goto asc_end;
805         }
806         lstrcpyA(want_flags, "SF");
807         if(fContextReq & ASC_REQ_ALLOCATE_MEMORY)
808         {
809             FIXME("ASC_REQ_ALLOCATE_MEMORY stub\n");
810         }
811         if(fContextReq & ASC_REQ_CONFIDENTIALITY)
812         {
813             lstrcatA(want_flags, " NTLMSSP_FEATURE_SEAL");
814         }
815         if(fContextReq & ASC_REQ_CONNECTION)
816         {
817             /* This is default, so we'll enable it */
818             lstrcatA(want_flags, " NTLMSSP_FEATURE_SESSION_KEY");
819             ctxt_attr |= ASC_RET_CONNECTION;
820         }
821         if(fContextReq & ASC_REQ_EXTENDED_ERROR)
822         {
823             FIXME("ASC_REQ_EXTENDED_ERROR stub\n");
824         }
825         if(fContextReq & ASC_REQ_INTEGRITY)
826         {
827             lstrcatA(want_flags, " NTLMSSP_FEATURE_SIGN");
828         }
829         if(fContextReq & ASC_REQ_MUTUAL_AUTH)
830         {
831             FIXME("ASC_REQ_MUTUAL_AUTH stub\n");
832         }
833         if(fContextReq & ASC_REQ_REPLAY_DETECT)
834         {
835             FIXME("ASC_REQ_REPLAY_DETECT stub\n");
836         }
837         if(fContextReq & ISC_REQ_SEQUENCE_DETECT)
838         {
839             FIXME("ASC_REQ_SEQUENCE_DETECT stub\n");
840         }
841         if(fContextReq & ISC_REQ_STREAM)
842         {
843             FIXME("ASC_REQ_STREAM stub\n");
844         }
845         /* Done with the flags */
846
847         if(lstrlenA(want_flags) > 3)
848         {
849             TRACE("Server set want_flags: %s\n", debugstr_a(want_flags));
850             lstrcpynA(buffer, want_flags, max_len - 1);
851             if((ret = run_helper(helper, buffer, max_len, &buffer_len)) !=
852                     SEC_E_OK)
853                 goto asc_end;
854             if(!strncmp(buffer, "BH", 2))
855                 TRACE("Helper doesn't understand new command set\n");
856         }
857
858         /* This is the YR request from the client, encode to base64 */
859
860         memcpy(bin, pInput->pBuffers[0].pvBuffer, bin_len);
861
862         lstrcpynA(buffer, "YR ", max_len-1);
863
864         if((ret = encodeBase64(bin, bin_len, buffer+3, max_len-3,
865                     &buffer_len)) != SEC_E_OK)
866         {
867             goto asc_end;
868         }
869
870         TRACE("Client sent: %s\n", debugstr_a(buffer));
871
872         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) !=
873                     SEC_E_OK)
874         {
875             goto asc_end;
876         }
877
878         TRACE("Reply from ntlm_auth: %s\n", debugstr_a(buffer));
879         /* The expected answer is TT <base64 blob> */
880
881         if(strncmp(buffer, "TT ", 3) != 0)
882         {
883             ret = SEC_E_INTERNAL_ERROR;
884             goto asc_end;
885         }
886
887         if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len,
888                         &bin_len)) != SEC_E_OK)
889         {
890             goto asc_end;
891         }
892
893         /* send this to the client */
894         if(pOutput == NULL)
895         {
896             ret = SEC_E_INSUFFICIENT_MEMORY;
897             goto asc_end;
898         }
899
900         if(pOutput->cBuffers < 1)
901         {
902             ret = SEC_E_INSUFFICIENT_MEMORY;
903             goto asc_end;
904         }
905
906         pOutput->pBuffers[0].cbBuffer = bin_len;
907         pOutput->pBuffers[0].BufferType = SECBUFFER_DATA;
908         memcpy(pOutput->pBuffers[0].pvBuffer, bin, bin_len);
909         ret = SEC_I_CONTINUE_NEEDED;
910
911     }
912     else
913     {
914         /* we expect a KK request from client */
915         if(pInput == NULL)
916         {
917             ret = SEC_E_INCOMPLETE_MESSAGE;
918             goto asc_end;
919         }
920
921         if(pInput->cBuffers < 1)
922         {
923             ret = SEC_E_INCOMPLETE_MESSAGE;
924             goto asc_end;
925         }
926
927         if(pInput->pBuffers[0].cbBuffer > max_len)
928         {
929             ret = SEC_E_INVALID_TOKEN;
930             goto asc_end;
931         }
932         else
933             bin_len = pInput->pBuffers[0].cbBuffer;
934
935         memcpy(bin, pInput->pBuffers[0].pvBuffer, bin_len);
936
937         lstrcpynA(buffer, "KK ", max_len-1);
938
939         if((ret = encodeBase64(bin, bin_len, buffer+3, max_len-3,
940                     &buffer_len)) != SEC_E_OK)
941         {
942             goto asc_end;
943         }
944
945         TRACE("Client sent: %s\n", debugstr_a(buffer));
946
947         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) !=
948                     SEC_E_OK)
949         {
950             goto asc_end;
951         }
952
953         TRACE("Reply from ntlm_auth: %s\n", debugstr_a(buffer));
954
955         if(strncmp(buffer, "AF ", 3) != 0)
956         {
957             if(strncmp(buffer, "NA ", 3) == 0)
958             {
959                 ret = SEC_E_LOGON_DENIED;
960                 goto asc_end;
961             }
962             else
963             {
964                 ret = SEC_E_INTERNAL_ERROR;
965                 goto asc_end;
966             }
967         }
968         pOutput->pBuffers[0].cbBuffer = 0;
969         ret = SEC_E_OK;
970
971         TRACE("Getting negotiated flags\n");
972         lstrcpynA(buffer, "GF", max_len - 1);
973         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
974             goto asc_end;
975
976         if(buffer_len < 3)
977         {
978             TRACE("No flags negotiated, or helper does not support GF command\n");
979         }
980         else
981         {
982             TRACE("Negotiated %s\n", debugstr_a(buffer));
983             sscanf(buffer + 3, "%lx", &(helper->neg_flags));
984             TRACE("Stored 0x%08lx as flags\n", helper->neg_flags);
985         }
986
987         TRACE("Getting session key\n");
988         lstrcpynA(buffer, "GK", max_len - 1);
989         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
990             goto asc_end;
991
992         if(buffer_len < 3)
993             TRACE("Helper does not support GK command\n");
994         else
995         {
996             if(strncmp(buffer, "BH ", 3) == 0)
997             {
998                 TRACE("Helper sent %s\n", debugstr_a(buffer+3));
999                 helper->valid_session_key = FALSE;
1000                 helper->session_key = HeapAlloc(GetProcessHeap(), 0, 16);
1001                 /*FIXME: Generate the dummy session key = MD4(MD4(password))*/
1002                 memset(helper->session_key, 0 , 16);
1003             }
1004             else if(strncmp(buffer, "GK ", 3) == 0)
1005             {
1006                 if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len, 
1007                                 &bin_len)) != SEC_E_OK)
1008                 {
1009                     TRACE("Failed to decode session key\n");
1010                 }
1011                 TRACE("Session key is %s\n", debugstr_a(buffer+3));
1012                 helper->valid_session_key = TRUE;
1013                 if(!helper->session_key)
1014                     helper->session_key = HeapAlloc(GetProcessHeap(), 0, 16);
1015                 if(!helper->session_key)
1016                 {
1017                     TRACE("Failed to allocate memory for session key\n");
1018                     ret = SEC_E_INTERNAL_ERROR;
1019                     goto asc_end;
1020                 }
1021                 memcpy(helper->session_key, bin, 16);
1022             }
1023         }
1024         helper->crypt.ntlm.a4i = SECUR32_arc4Alloc();
1025         SECUR32_arc4Init(helper->crypt.ntlm.a4i, helper->session_key, 16);
1026         helper->crypt.ntlm.seq_num = 0l;
1027     }
1028
1029     phNewContext->dwUpper = ctxt_attr;
1030     phNewContext->dwLower = (ULONG_PTR)helper;
1031
1032 asc_end:
1033     HeapFree(GetProcessHeap(), 0, want_flags);
1034     HeapFree(GetProcessHeap(), 0, buffer);
1035     HeapFree(GetProcessHeap(), 0, bin);
1036     return ret;
1037 }
1038
1039 /***********************************************************************
1040  *              CompleteAuthToken
1041  */
1042 static SECURITY_STATUS SEC_ENTRY ntlm_CompleteAuthToken(PCtxtHandle phContext,
1043  PSecBufferDesc pToken)
1044 {
1045     /* We never need to call CompleteAuthToken anyway */
1046     TRACE("%p %p\n", phContext, pToken);
1047     if (!phContext)
1048         return SEC_E_INVALID_HANDLE;
1049     
1050     return SEC_E_OK;
1051 }
1052
1053 /***********************************************************************
1054  *              DeleteSecurityContext
1055  */
1056 static SECURITY_STATUS SEC_ENTRY ntlm_DeleteSecurityContext(PCtxtHandle phContext)
1057 {
1058     SECURITY_STATUS ret;
1059
1060     TRACE("%p\n", phContext);
1061     if (phContext)
1062     {
1063         phContext->dwUpper = 0;
1064         phContext->dwLower = 0;
1065         ret = SEC_E_OK;
1066     }
1067     else
1068     {
1069         ret = SEC_E_INVALID_HANDLE;
1070     }
1071     return ret;
1072 }
1073
1074 /***********************************************************************
1075  *              QueryContextAttributesW
1076  */
1077 static SECURITY_STATUS SEC_ENTRY ntlm_QueryContextAttributesW(PCtxtHandle phContext,
1078  unsigned long ulAttribute, void *pBuffer)
1079 {
1080     TRACE("%p %ld %p\n", phContext, ulAttribute, pBuffer);
1081     if (!phContext)
1082         return SEC_E_INVALID_HANDLE;
1083
1084     switch(ulAttribute)
1085     {
1086 #define _x(x) case (x) : FIXME(#x" stub\n"); break
1087         _x(SECPKG_ATTR_ACCESS_TOKEN);
1088         _x(SECPKG_ATTR_AUTHORITY);
1089         _x(SECPKG_ATTR_DCE_INFO);
1090         case SECPKG_ATTR_FLAGS:
1091         {
1092             PSecPkgContext_Flags spcf = (PSecPkgContext_Flags)pBuffer;
1093             PNegoHelper helper = (PNegoHelper)phContext->dwLower;
1094
1095             spcf->Flags = 0;
1096             if(helper->neg_flags & NTLMSSP_NEGOTIATE_SIGN)
1097                 spcf->Flags |= ISC_RET_INTEGRITY;
1098             if(helper->neg_flags & NTLMSSP_NEGOTIATE_SEAL)
1099                 spcf->Flags |= ISC_RET_CONFIDENTIALITY;
1100             return SEC_E_OK;
1101         }
1102         _x(SECPKG_ATTR_KEY_INFO);
1103         _x(SECPKG_ATTR_LIFESPAN);
1104         _x(SECPKG_ATTR_NAMES);
1105         _x(SECPKG_ATTR_NATIVE_NAMES);
1106         _x(SECPKG_ATTR_NEGOTIATION_INFO);
1107         _x(SECPKG_ATTR_PACKAGE_INFO);
1108         _x(SECPKG_ATTR_PASSWORD_EXPIRY);
1109         _x(SECPKG_ATTR_SESSION_KEY);
1110         case SECPKG_ATTR_SIZES:
1111         {
1112             PSecPkgContext_Sizes spcs = (PSecPkgContext_Sizes)pBuffer;
1113             spcs->cbMaxToken = NTLM_MAX_BUF;
1114             spcs->cbMaxSignature = 16;
1115             spcs->cbBlockSize = 0;
1116             spcs->cbSecurityTrailer = 16;
1117             return SEC_E_OK;
1118         }
1119         _x(SECPKG_ATTR_STREAM_SIZES);
1120         _x(SECPKG_ATTR_TARGET_INFORMATION);
1121 #undef _x
1122         default:
1123             TRACE("Unknown value %ld passed for ulAttribute\n", ulAttribute);
1124     }
1125
1126     return SEC_E_UNSUPPORTED_FUNCTION;
1127 }
1128
1129 /***********************************************************************
1130  *              QueryContextAttributesA
1131  */
1132 static SECURITY_STATUS SEC_ENTRY ntlm_QueryContextAttributesA(PCtxtHandle phContext,
1133  unsigned long ulAttribute, void *pBuffer)
1134 {
1135     return ntlm_QueryContextAttributesW(phContext, ulAttribute, pBuffer);
1136 }
1137
1138 /***********************************************************************
1139  *              ImpersonateSecurityContext
1140  */
1141 static SECURITY_STATUS SEC_ENTRY ntlm_ImpersonateSecurityContext(PCtxtHandle phContext)
1142 {
1143     SECURITY_STATUS ret;
1144
1145     TRACE("%p\n", phContext);
1146     if (phContext)
1147     {
1148         ret = SEC_E_UNSUPPORTED_FUNCTION;
1149     }
1150     else
1151     {
1152         ret = SEC_E_INVALID_HANDLE;
1153     }
1154     return ret;
1155 }
1156
1157 /***********************************************************************
1158  *              RevertSecurityContext
1159  */
1160 static SECURITY_STATUS SEC_ENTRY ntlm_RevertSecurityContext(PCtxtHandle phContext)
1161 {
1162     SECURITY_STATUS ret;
1163
1164     TRACE("%p\n", phContext);
1165     if (phContext)
1166     {
1167         ret = SEC_E_UNSUPPORTED_FUNCTION;
1168     }
1169     else
1170     {
1171         ret = SEC_E_INVALID_HANDLE;
1172     }
1173     return ret;
1174 }
1175
1176 /***********************************************************************
1177  *              MakeSignature
1178  */
1179 static SECURITY_STATUS SEC_ENTRY ntlm_MakeSignature(PCtxtHandle phContext, ULONG fQOP,
1180  PSecBufferDesc pMessage, ULONG MessageSeqNo)
1181 {
1182     PNegoHelper helper;
1183     ULONG sign_version = 1;
1184
1185     TRACE("%p %ld %p %ld\n", phContext, fQOP, pMessage, MessageSeqNo);
1186     if (!phContext)
1187         return SEC_E_INVALID_HANDLE;
1188
1189     if(fQOP)
1190         FIXME("Ignoring fQOP 0x%08lx", fQOP);
1191
1192     if(MessageSeqNo)
1193         FIXME("Ignoring MessageSeqNo");
1194
1195     if(!pMessage || !pMessage->pBuffers || pMessage->cBuffers < 2 ||
1196             pMessage->pBuffers[0].BufferType != SECBUFFER_TOKEN ||
1197             !pMessage->pBuffers[0].pvBuffer)
1198         return SEC_E_INVALID_TOKEN;
1199
1200     if(pMessage->pBuffers[0].cbBuffer < 16)
1201         return SEC_E_BUFFER_TOO_SMALL;
1202
1203     helper = (PNegoHelper)phContext->dwLower;
1204     TRACE("Negotiated flags are: 0x%08lx\n", helper->neg_flags);
1205     if(helper->neg_flags & NTLMSSP_NEGOTIATE_NTLM2)
1206     {
1207         FIXME("Can't handle NTLMv2 signing yet. Aborting.\n");
1208         return SEC_E_UNSUPPORTED_FUNCTION;
1209     }
1210     if(helper->neg_flags & NTLMSSP_NEGOTIATE_SIGN)
1211     {
1212         PBYTE sig = pMessage->pBuffers[0].pvBuffer;
1213         ULONG crc = ComputeCrc32(pMessage->pBuffers[1].pvBuffer,
1214                 pMessage->pBuffers[1].cbBuffer);
1215
1216         sig[ 0] = (sign_version >>  0) & 0xff;
1217         sig[ 1] = (sign_version >>  8) & 0xff;
1218         sig[ 2] = (sign_version >> 16) & 0xff;
1219         sig[ 3] = (sign_version >> 24) & 0xff;
1220         memset(sig+4, 0, 4);
1221         sig[ 8] = (crc >>  0) & 0xff;
1222         sig[ 9] = (crc >>  8) & 0xff;
1223         sig[10] = (crc >> 16) & 0xff;
1224         sig[11] = (crc >> 24) & 0xff;
1225         sig[12] = (helper->crypt.ntlm.seq_num >>  0) & 0xff;
1226         sig[13] = (helper->crypt.ntlm.seq_num >>  8) & 0xff;
1227         sig[14] = (helper->crypt.ntlm.seq_num >> 16) & 0xff;
1228         sig[15] = (helper->crypt.ntlm.seq_num >> 24) & 0xff;
1229
1230         ++(helper->crypt.ntlm.seq_num);
1231
1232         SECUR32_arc4Process(helper->crypt.ntlm.a4i, sig+4, 12);
1233         return SEC_E_OK;
1234     }
1235
1236     if(helper->neg_flags & NTLMSSP_NEGOTIATE_KEY_EXCHANGE)
1237     {
1238         FIXME("Can't handle encrypted session key yet. Aborting.\n");
1239         return SEC_E_UNSUPPORTED_FUNCTION;
1240     }
1241
1242     if(helper->neg_flags & NTLMSSP_NEGOTIATE_ALWAYS_SIGN)
1243     {
1244         TRACE("Generating dummy signature\n");
1245         /* A dummy signature is 0x01 followed by 15 bytes of 0x00 */
1246         memset(pMessage->pBuffers[0].pvBuffer, 0, 16);
1247         memset(pMessage->pBuffers[0].pvBuffer, 0x01, 1);
1248         pMessage->pBuffers[0].cbBuffer = 16;
1249         return SEC_E_OK;
1250     }
1251
1252     return SEC_E_UNSUPPORTED_FUNCTION;
1253 }
1254
1255 /***********************************************************************
1256  *              VerifySignature
1257  */
1258 static SECURITY_STATUS SEC_ENTRY ntlm_VerifySignature(PCtxtHandle phContext,
1259  PSecBufferDesc pMessage, ULONG MessageSeqNo, PULONG pfQOP)
1260 {
1261     PNegoHelper helper;
1262     ULONG fQOP = 0;
1263
1264     TRACE("%p %p %ld %p\n", phContext, pMessage, MessageSeqNo, pfQOP);
1265     if(!phContext)
1266         return SEC_E_INVALID_HANDLE;
1267
1268     if(!pMessage || !pMessage->pBuffers || pMessage->cBuffers < 2 ||
1269             pMessage->pBuffers[0].BufferType != SECBUFFER_TOKEN ||
1270             !pMessage->pBuffers[0].pvBuffer)
1271         return SEC_E_INVALID_TOKEN;
1272
1273     if(pMessage->pBuffers[0].cbBuffer < 16)
1274         return SEC_E_BUFFER_TOO_SMALL;
1275
1276     if(MessageSeqNo)
1277         FIXME("Ignoring MessageSeqNo\n");
1278
1279     helper = (PNegoHelper)phContext->dwLower;
1280     TRACE("Negotiated flags: 0x%08lx\n", helper->neg_flags);
1281
1282     if(helper->neg_flags & NTLMSSP_NEGOTIATE_NTLM2)
1283     {
1284         FIXME("Can't handle NTLMv2 signing yet. Aborting.\n");
1285         return SEC_E_UNSUPPORTED_FUNCTION;
1286     }
1287
1288     if(helper->neg_flags & NTLMSSP_NEGOTIATE_SIGN)
1289     {
1290         SecBufferDesc local_desc;
1291         SecBuffer     local_buff[2];
1292         BYTE          local_sig[16];
1293
1294         local_desc.ulVersion = SECBUFFER_VERSION;
1295         local_desc.cBuffers = 2;
1296         local_desc.pBuffers = local_buff;
1297         local_buff[0].BufferType = SECBUFFER_TOKEN;
1298         local_buff[0].cbBuffer = 16;
1299         local_buff[0].pvBuffer = local_sig;
1300         local_buff[1].BufferType = SECBUFFER_DATA;
1301         local_buff[1].cbBuffer = pMessage->pBuffers[1].cbBuffer;
1302         local_buff[1].pvBuffer = pMessage->pBuffers[1].pvBuffer;
1303
1304         ntlm_MakeSignature(phContext, fQOP, &local_desc, MessageSeqNo);
1305
1306         if(memcmp(((PBYTE)local_buff[0].pvBuffer) + 8, ((PBYTE)pMessage->pBuffers[0].pvBuffer) + 8, 8))
1307             return SEC_E_MESSAGE_ALTERED;
1308
1309         return SEC_E_OK;
1310     }
1311
1312     if(helper->neg_flags & NTLMSSP_NEGOTIATE_KEY_EXCHANGE)
1313     {
1314         FIXME("Can't handle encrypted session keys yet. Aborting.\n");
1315         return SEC_E_UNSUPPORTED_FUNCTION;
1316     }
1317
1318     if(helper->neg_flags & NTLMSSP_NEGOTIATE_ALWAYS_SIGN)
1319     {
1320         const BYTE dummy_sig[] = {0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1321             0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
1322         TRACE("Assuming dummy signature.\n");
1323         if(memcmp(pMessage->pBuffers[0].pvBuffer, dummy_sig, sizeof(dummy_sig)) != 0)
1324         {
1325             TRACE("Failed to verify the packet signature. Not a dummy signature?\n");
1326             return SEC_E_MESSAGE_ALTERED;
1327         }
1328         else
1329         {
1330             pfQOP = &fQOP;
1331             return SEC_E_OK;
1332         }
1333     }
1334
1335     return SEC_E_UNSUPPORTED_FUNCTION;
1336 }
1337
1338 /***********************************************************************
1339  *             FreeCredentialsHandle
1340  */
1341 static SECURITY_STATUS SEC_ENTRY ntlm_FreeCredentialsHandle(
1342         PCredHandle phCredential)
1343 {
1344     SECURITY_STATUS ret;
1345
1346     if(phCredential){
1347         PNegoHelper helper = (PNegoHelper) phCredential->dwLower;
1348         phCredential->dwUpper = 0;
1349         phCredential->dwLower = 0;
1350         HeapFree(GetProcessHeap(), 0, helper->session_key);
1351         cleanup_helper(helper);
1352         ret = SEC_E_OK;
1353     }
1354     else
1355         ret = SEC_E_OK;
1356     
1357     return ret;
1358 }
1359
1360 /***********************************************************************
1361  *             EncryptMessage
1362  */
1363 static SECURITY_STATUS SEC_ENTRY ntlm_EncryptMessage(PCtxtHandle phContext,
1364         ULONG fQOP, PSecBufferDesc pMessage, ULONG MessageSeqNo)
1365 {
1366     TRACE("%p %ld %p %ld stub\n", phContext, fQOP, pMessage, MessageSeqNo);
1367
1368     if(!phContext)
1369         return SEC_E_INVALID_HANDLE;
1370
1371     return SEC_E_UNSUPPORTED_FUNCTION;
1372 }
1373
1374 /***********************************************************************
1375  *             DecryptMessage
1376  */
1377 static SECURITY_STATUS SEC_ENTRY ntlm_DecryptMessage(PCtxtHandle phContext,
1378         PSecBufferDesc pMessage, ULONG MessageSeqNo, PULONG pfQOP)
1379 {
1380     TRACE("%p %p %ld %p stub\n", phContext, pMessage, MessageSeqNo, pfQOP);
1381
1382     if(!phContext)
1383         return SEC_E_INVALID_HANDLE;
1384
1385     return SEC_E_UNSUPPORTED_FUNCTION;
1386 }
1387
1388 static SecurityFunctionTableA ntlmTableA = {
1389     1,
1390     NULL,   /* EnumerateSecurityPackagesA */
1391     ntlm_QueryCredentialsAttributesA,   /* QueryCredentialsAttributesA */
1392     ntlm_AcquireCredentialsHandleA,     /* AcquireCredentialsHandleA */
1393     ntlm_FreeCredentialsHandle,         /* FreeCredentialsHandle */
1394     NULL,   /* Reserved2 */
1395     ntlm_InitializeSecurityContextA,    /* InitializeSecurityContextA */
1396     ntlm_AcceptSecurityContext,         /* AcceptSecurityContext */
1397     ntlm_CompleteAuthToken,             /* CompleteAuthToken */
1398     ntlm_DeleteSecurityContext,         /* DeleteSecurityContext */
1399     NULL,  /* ApplyControlToken */
1400     ntlm_QueryContextAttributesA,       /* QueryContextAttributesA */
1401     ntlm_ImpersonateSecurityContext,    /* ImpersonateSecurityContext */
1402     ntlm_RevertSecurityContext,         /* RevertSecurityContext */
1403     ntlm_MakeSignature,                 /* MakeSignature */
1404     ntlm_VerifySignature,               /* VerifySignature */
1405     FreeContextBuffer,                  /* FreeContextBuffer */
1406     NULL,   /* QuerySecurityPackageInfoA */
1407     NULL,   /* Reserved3 */
1408     NULL,   /* Reserved4 */
1409     NULL,   /* ExportSecurityContext */
1410     NULL,   /* ImportSecurityContextA */
1411     NULL,   /* AddCredentialsA */
1412     NULL,   /* Reserved8 */
1413     NULL,   /* QuerySecurityContextToken */
1414     ntlm_EncryptMessage,                /* EncryptMessage */
1415     ntlm_DecryptMessage,                /* DecryptMessage */
1416     NULL,   /* SetContextAttributesA */
1417 };
1418
1419 static SecurityFunctionTableW ntlmTableW = {
1420     1,
1421     NULL,   /* EnumerateSecurityPackagesW */
1422     ntlm_QueryCredentialsAttributesW,   /* QueryCredentialsAttributesW */
1423     ntlm_AcquireCredentialsHandleW,     /* AcquireCredentialsHandleW */
1424     ntlm_FreeCredentialsHandle,         /* FreeCredentialsHandle */
1425     NULL,   /* Reserved2 */
1426     ntlm_InitializeSecurityContextW,    /* InitializeSecurityContextW */
1427     ntlm_AcceptSecurityContext,         /* AcceptSecurityContext */
1428     ntlm_CompleteAuthToken,             /* CompleteAuthToken */
1429     ntlm_DeleteSecurityContext,         /* DeleteSecurityContext */
1430     NULL,  /* ApplyControlToken */
1431     ntlm_QueryContextAttributesW,       /* QueryContextAttributesW */
1432     ntlm_ImpersonateSecurityContext,    /* ImpersonateSecurityContext */
1433     ntlm_RevertSecurityContext,         /* RevertSecurityContext */
1434     ntlm_MakeSignature,                 /* MakeSignature */
1435     ntlm_VerifySignature,               /* VerifySignature */
1436     FreeContextBuffer,                  /* FreeContextBuffer */
1437     NULL,   /* QuerySecurityPackageInfoW */
1438     NULL,   /* Reserved3 */
1439     NULL,   /* Reserved4 */
1440     NULL,   /* ExportSecurityContext */
1441     NULL,   /* ImportSecurityContextW */
1442     NULL,   /* AddCredentialsW */
1443     NULL,   /* Reserved8 */
1444     NULL,   /* QuerySecurityContextToken */
1445     ntlm_EncryptMessage,                /* EncryptMessage */
1446     ntlm_DecryptMessage,                /* DecryptMessage */
1447     NULL,   /* SetContextAttributesW */
1448 };
1449
1450 #define NTLM_COMMENT \
1451    { 'N', 'T', 'L', 'M', ' ', \
1452      'S', 'e', 'c', 'u', 'r', 'i', 't', 'y', ' ', \
1453      'P', 'a', 'c', 'k', 'a', 'g', 'e', 0}
1454
1455 static CHAR ntlm_comment_A[] = NTLM_COMMENT;
1456 static WCHAR ntlm_comment_W[] = NTLM_COMMENT;
1457
1458 #define NTLM_NAME {'N', 'T', 'L', 'M', 0}
1459
1460 static char ntlm_name_A[] = NTLM_NAME;
1461 static WCHAR ntlm_name_W[] = NTLM_NAME;
1462
1463 /* According to Windows, NTLM has the following capabilities.  */
1464 #define CAPS ( \
1465         SECPKG_FLAG_INTEGRITY | \
1466         SECPKG_FLAG_PRIVACY | \
1467         SECPKG_FLAG_TOKEN_ONLY | \
1468         SECPKG_FLAG_CONNECTION | \
1469         SECPKG_FLAG_MULTI_REQUIRED | \
1470         SECPKG_FLAG_IMPERSONATION | \
1471         SECPKG_FLAG_ACCEPT_WIN32_NAME | \
1472         SECPKG_FLAG_READONLY_WITH_CHECKSUM)
1473
1474 static const SecPkgInfoW infoW = {
1475     CAPS,
1476     1,
1477     RPC_C_AUTHN_WINNT,
1478     NTLM_MAX_BUF,
1479     ntlm_name_W,
1480     ntlm_comment_W
1481 };
1482
1483 static const SecPkgInfoA infoA = {
1484     CAPS,
1485     1,
1486     RPC_C_AUTHN_WINNT,
1487     NTLM_MAX_BUF,
1488     ntlm_name_A,
1489     ntlm_comment_A
1490 };
1491
1492 void SECUR32_initNTLMSP(void)
1493 {
1494     SECURITY_STATUS ret;
1495     PNegoHelper helper;
1496     static CHAR ntlm_auth[] = "ntlm_auth",
1497                 version[]   = "--version";
1498
1499     SEC_CHAR *args[] = {
1500         ntlm_auth,
1501         version,
1502         NULL };
1503
1504     if((ret = fork_helper(&helper, "ntlm_auth", args)) != SEC_E_OK)
1505     {
1506         /* Cheat and allocate a helper anyway, so cleanup later will work. */
1507         helper = HeapAlloc(GetProcessHeap(),0, sizeof(PNegoHelper));
1508         helper->version = -1;
1509     }
1510     else
1511         check_version(helper);
1512
1513     if(helper->version > 2)
1514     {
1515         SecureProvider *provider = SECUR32_addProvider(&ntlmTableA, &ntlmTableW, NULL);
1516         SECUR32_addPackages(provider, 1L, &infoA, &infoW);
1517     }
1518     cleanup_helper(helper);
1519 }