comctl32: header: Simplify the insert/delete code by using ReAlloc.
[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             helper->neg_flags = 0l;
631         }
632         else
633         {
634             TRACE("Negotiated %s\n", debugstr_a(buffer));
635             sscanf(buffer + 3, "%lx", &(helper->neg_flags));
636             TRACE("Stored 0x%08lx as flags\n", helper->neg_flags);
637         }
638
639         TRACE("Getting session key\n");
640         lstrcpynA(buffer, "GK", max_len - 1);
641         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
642             goto isc_end;
643
644         if(strncmp(buffer, "BH", 2) == 0)
645         {
646             TRACE("Helper does not understand command or no key negotiated.\n");
647             helper->valid_session_key = FALSE;
648             helper->session_key = HeapAlloc(GetProcessHeap(), 0, 16);
649             /*Generate the dummy session key = MD4(MD4(password))*/
650             if(helper->password)
651             {
652                 SEC_WCHAR *unicode_password;
653                 int passwd_lenW;
654
655                 TRACE("Converting password to unicode.\n");
656                 passwd_lenW = MultiByteToWideChar(CP_ACP, 0,
657                         (LPCSTR)helper->password, helper->pwlen,
658                         NULL, 0);
659                 unicode_password = HeapAlloc(GetProcessHeap(), 0,
660                         passwd_lenW * sizeof(SEC_WCHAR));
661                 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)helper->password,
662                         helper->pwlen, unicode_password, passwd_lenW);
663
664                 SECUR32_CreateNTLMv1SessionKey((PBYTE)unicode_password,
665                         lstrlenW(unicode_password) * sizeof(SEC_WCHAR), helper->session_key);
666
667                 HeapFree(GetProcessHeap(), 0, unicode_password);
668             }
669             else
670                 memset(helper->session_key, 0, 16);
671         }
672         else if(strncmp(buffer, "GK ", 3) == 0)
673         {
674             if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len, 
675                             &bin_len)) != SEC_E_OK)
676             {
677                 TRACE("Failed to decode session key\n");
678             }
679             TRACE("Session key is %s\n", debugstr_a(buffer+3));
680             helper->valid_session_key = TRUE;
681             if(!helper->session_key)
682                 helper->session_key = HeapAlloc(GetProcessHeap(), 0, bin_len);
683             if(!helper->session_key)
684             {
685                 TRACE("Failed to allocate memory for session key\n");
686                 ret = SEC_E_INTERNAL_ERROR;
687                 goto isc_end;
688             }
689             memcpy(helper->session_key, bin, bin_len);
690         }
691
692         helper->crypt.ntlm.a4i = SECUR32_arc4Alloc();
693         SECUR32_arc4Init(helper->crypt.ntlm.a4i, helper->session_key, 16);
694         helper->crypt.ntlm.seq_num = 0l;
695     }
696
697     if(ret != SEC_I_CONTINUE_NEEDED)
698     {
699         TRACE("Deleting password!\n");
700         if(helper->password)
701             memset(helper->password, 0, helper->pwlen-2);
702         HeapFree(GetProcessHeap(), 0, helper->password);
703     }
704 isc_end:
705     HeapFree(GetProcessHeap(), 0, want_flags);
706     HeapFree(GetProcessHeap(), 0, buffer);
707     HeapFree(GetProcessHeap(), 0, bin);
708     return ret;
709 }
710
711 /***********************************************************************
712  *              InitializeSecurityContextA
713  */
714 static SECURITY_STATUS SEC_ENTRY ntlm_InitializeSecurityContextA(
715  PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR *pszTargetName,
716  ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep, 
717  PSecBufferDesc pInput,ULONG Reserved2, PCtxtHandle phNewContext, 
718  PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
719 {
720     SECURITY_STATUS ret;
721
722     TRACE("%p %p %s %ld %ld %ld %p %ld %p %p %p %p\n", phCredential, phContext,
723      debugstr_a(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
724      Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
725     
726     if (phCredential)
727     {
728         SEC_WCHAR *target = NULL;
729         if(pszTargetName != NULL)
730         {
731             int target_size = MultiByteToWideChar(CP_ACP, 0, pszTargetName, 
732                 strlen(pszTargetName)+1, NULL, 0);
733             target = HeapAlloc(GetProcessHeap(), 0, target_size * 
734                     sizeof(SEC_WCHAR));
735             MultiByteToWideChar(CP_ACP, 0, pszTargetName, strlen(pszTargetName)+1,
736                 target, target_size);
737         }
738         
739         ret = ntlm_InitializeSecurityContextW(phCredential, phContext, target, 
740                 fContextReq, Reserved1, TargetDataRep, pInput, Reserved2,
741                 phNewContext, pOutput, pfContextAttr, ptsExpiry);
742         
743         HeapFree(GetProcessHeap(), 0, target);
744     }
745     else
746     {
747         ret = SEC_E_INVALID_HANDLE;
748     }
749     return ret;
750 }
751
752 /***********************************************************************
753  *              AcceptSecurityContext
754  */
755 static SECURITY_STATUS SEC_ENTRY ntlm_AcceptSecurityContext(
756  PCredHandle phCredential, PCtxtHandle phContext, PSecBufferDesc pInput,
757  ULONG fContextReq, ULONG TargetDataRep, PCtxtHandle phNewContext, 
758  PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
759 {
760     SECURITY_STATUS ret;
761     char *buffer, *want_flags = NULL;
762     PBYTE bin;
763     int buffer_len, bin_len, max_len = NTLM_MAX_BUF;
764     ULONG ctxt_attr = 0;
765     PNegoHelper helper;
766
767     TRACE("%p %p %p %ld %ld %p %p %p %p\n", phCredential, phContext, pInput,
768      fContextReq, TargetDataRep, phNewContext, pOutput, pfContextAttr,
769      ptsExpiry);
770
771     if (!phCredential)
772         return SEC_E_INVALID_HANDLE;
773
774     helper = (PNegoHelper)phCredential->dwLower;
775
776     buffer = HeapAlloc(GetProcessHeap(), 0, sizeof(char) * NTLM_MAX_BUF);
777     bin    = HeapAlloc(GetProcessHeap(),0, sizeof(BYTE) * NTLM_MAX_BUF);
778
779     if(helper->mode != NTLM_SERVER)
780     {
781         ret = SEC_E_INVALID_HANDLE;
782         goto asc_end;
783     }
784
785     if(TargetDataRep == SECURITY_NETWORK_DREP){
786         TRACE("Using SECURITY_NETWORK_DREP\n");
787     }
788
789     if(phContext == NULL)
790     {
791         /* This is the first call to AcceptSecurityHandle */
792         if(pInput == NULL)
793         {
794             ret = SEC_E_INCOMPLETE_MESSAGE;
795             goto asc_end;
796         }
797
798         if(pInput->cBuffers < 1)
799         {
800             ret = SEC_E_INCOMPLETE_MESSAGE;
801             goto asc_end;
802         }
803
804         if(pInput->pBuffers[0].cbBuffer > max_len)
805         {
806             ret = SEC_E_INVALID_TOKEN;
807             goto asc_end;
808         }
809         else
810             bin_len = pInput->pBuffers[0].cbBuffer;
811
812         /* Handle all the flags */
813         want_flags = HeapAlloc(GetProcessHeap(), 0, 73);
814         if(want_flags == NULL)
815         {
816             TRACE("Failed to allocate memory for the want_flags!\n");
817             ret = SEC_E_INSUFFICIENT_MEMORY;
818             goto asc_end;
819         }
820         lstrcpyA(want_flags, "SF");
821         if(fContextReq & ASC_REQ_ALLOCATE_MEMORY)
822         {
823             FIXME("ASC_REQ_ALLOCATE_MEMORY stub\n");
824         }
825         if(fContextReq & ASC_REQ_CONFIDENTIALITY)
826         {
827             lstrcatA(want_flags, " NTLMSSP_FEATURE_SEAL");
828         }
829         if(fContextReq & ASC_REQ_CONNECTION)
830         {
831             /* This is default, so we'll enable it */
832             lstrcatA(want_flags, " NTLMSSP_FEATURE_SESSION_KEY");
833             ctxt_attr |= ASC_RET_CONNECTION;
834         }
835         if(fContextReq & ASC_REQ_EXTENDED_ERROR)
836         {
837             FIXME("ASC_REQ_EXTENDED_ERROR stub\n");
838         }
839         if(fContextReq & ASC_REQ_INTEGRITY)
840         {
841             lstrcatA(want_flags, " NTLMSSP_FEATURE_SIGN");
842         }
843         if(fContextReq & ASC_REQ_MUTUAL_AUTH)
844         {
845             FIXME("ASC_REQ_MUTUAL_AUTH stub\n");
846         }
847         if(fContextReq & ASC_REQ_REPLAY_DETECT)
848         {
849             FIXME("ASC_REQ_REPLAY_DETECT stub\n");
850         }
851         if(fContextReq & ISC_REQ_SEQUENCE_DETECT)
852         {
853             FIXME("ASC_REQ_SEQUENCE_DETECT stub\n");
854         }
855         if(fContextReq & ISC_REQ_STREAM)
856         {
857             FIXME("ASC_REQ_STREAM stub\n");
858         }
859         /* Done with the flags */
860
861         if(lstrlenA(want_flags) > 3)
862         {
863             TRACE("Server set want_flags: %s\n", debugstr_a(want_flags));
864             lstrcpynA(buffer, want_flags, max_len - 1);
865             if((ret = run_helper(helper, buffer, max_len, &buffer_len)) !=
866                     SEC_E_OK)
867                 goto asc_end;
868             if(!strncmp(buffer, "BH", 2))
869                 TRACE("Helper doesn't understand new command set\n");
870         }
871
872         /* This is the YR request from the client, encode to base64 */
873
874         memcpy(bin, pInput->pBuffers[0].pvBuffer, bin_len);
875
876         lstrcpynA(buffer, "YR ", max_len-1);
877
878         if((ret = encodeBase64(bin, bin_len, buffer+3, max_len-3,
879                     &buffer_len)) != SEC_E_OK)
880         {
881             goto asc_end;
882         }
883
884         TRACE("Client sent: %s\n", debugstr_a(buffer));
885
886         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) !=
887                     SEC_E_OK)
888         {
889             goto asc_end;
890         }
891
892         TRACE("Reply from ntlm_auth: %s\n", debugstr_a(buffer));
893         /* The expected answer is TT <base64 blob> */
894
895         if(strncmp(buffer, "TT ", 3) != 0)
896         {
897             ret = SEC_E_INTERNAL_ERROR;
898             goto asc_end;
899         }
900
901         if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len,
902                         &bin_len)) != SEC_E_OK)
903         {
904             goto asc_end;
905         }
906
907         /* send this to the client */
908         if(pOutput == NULL)
909         {
910             ret = SEC_E_INSUFFICIENT_MEMORY;
911             goto asc_end;
912         }
913
914         if(pOutput->cBuffers < 1)
915         {
916             ret = SEC_E_INSUFFICIENT_MEMORY;
917             goto asc_end;
918         }
919
920         pOutput->pBuffers[0].cbBuffer = bin_len;
921         pOutput->pBuffers[0].BufferType = SECBUFFER_DATA;
922         memcpy(pOutput->pBuffers[0].pvBuffer, bin, bin_len);
923         ret = SEC_I_CONTINUE_NEEDED;
924
925     }
926     else
927     {
928         /* we expect a KK request from client */
929         if(pInput == NULL)
930         {
931             ret = SEC_E_INCOMPLETE_MESSAGE;
932             goto asc_end;
933         }
934
935         if(pInput->cBuffers < 1)
936         {
937             ret = SEC_E_INCOMPLETE_MESSAGE;
938             goto asc_end;
939         }
940
941         if(pInput->pBuffers[0].cbBuffer > max_len)
942         {
943             ret = SEC_E_INVALID_TOKEN;
944             goto asc_end;
945         }
946         else
947             bin_len = pInput->pBuffers[0].cbBuffer;
948
949         memcpy(bin, pInput->pBuffers[0].pvBuffer, bin_len);
950
951         lstrcpynA(buffer, "KK ", max_len-1);
952
953         if((ret = encodeBase64(bin, bin_len, buffer+3, max_len-3,
954                     &buffer_len)) != SEC_E_OK)
955         {
956             goto asc_end;
957         }
958
959         TRACE("Client sent: %s\n", debugstr_a(buffer));
960
961         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) !=
962                     SEC_E_OK)
963         {
964             goto asc_end;
965         }
966
967         TRACE("Reply from ntlm_auth: %s\n", debugstr_a(buffer));
968
969         if(strncmp(buffer, "AF ", 3) != 0)
970         {
971             if(strncmp(buffer, "NA ", 3) == 0)
972             {
973                 ret = SEC_E_LOGON_DENIED;
974                 goto asc_end;
975             }
976             else
977             {
978                 ret = SEC_E_INTERNAL_ERROR;
979                 goto asc_end;
980             }
981         }
982         pOutput->pBuffers[0].cbBuffer = 0;
983         ret = SEC_E_OK;
984
985         TRACE("Getting negotiated flags\n");
986         lstrcpynA(buffer, "GF", max_len - 1);
987         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
988             goto asc_end;
989
990         if(buffer_len < 3)
991         {
992             TRACE("No flags negotiated, or helper does not support GF command\n");
993         }
994         else
995         {
996             TRACE("Negotiated %s\n", debugstr_a(buffer));
997             sscanf(buffer + 3, "%lx", &(helper->neg_flags));
998             TRACE("Stored 0x%08lx as flags\n", helper->neg_flags);
999         }
1000
1001         TRACE("Getting session key\n");
1002         lstrcpynA(buffer, "GK", max_len - 1);
1003         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
1004             goto asc_end;
1005
1006         if(buffer_len < 3)
1007             TRACE("Helper does not support GK command\n");
1008         else
1009         {
1010             if(strncmp(buffer, "BH ", 3) == 0)
1011             {
1012                 TRACE("Helper sent %s\n", debugstr_a(buffer+3));
1013                 helper->valid_session_key = FALSE;
1014                 helper->session_key = HeapAlloc(GetProcessHeap(), 0, 16);
1015                 /*FIXME: Generate the dummy session key = MD4(MD4(password))*/
1016                 memset(helper->session_key, 0 , 16);
1017             }
1018             else if(strncmp(buffer, "GK ", 3) == 0)
1019             {
1020                 if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len, 
1021                                 &bin_len)) != SEC_E_OK)
1022                 {
1023                     TRACE("Failed to decode session key\n");
1024                 }
1025                 TRACE("Session key is %s\n", debugstr_a(buffer+3));
1026                 helper->valid_session_key = TRUE;
1027                 if(!helper->session_key)
1028                     helper->session_key = HeapAlloc(GetProcessHeap(), 0, 16);
1029                 if(!helper->session_key)
1030                 {
1031                     TRACE("Failed to allocate memory for session key\n");
1032                     ret = SEC_E_INTERNAL_ERROR;
1033                     goto asc_end;
1034                 }
1035                 memcpy(helper->session_key, bin, 16);
1036             }
1037         }
1038         helper->crypt.ntlm.a4i = SECUR32_arc4Alloc();
1039         SECUR32_arc4Init(helper->crypt.ntlm.a4i, helper->session_key, 16);
1040         helper->crypt.ntlm.seq_num = 0l;
1041     }
1042
1043     phNewContext->dwUpper = ctxt_attr;
1044     phNewContext->dwLower = (ULONG_PTR)helper;
1045
1046 asc_end:
1047     HeapFree(GetProcessHeap(), 0, want_flags);
1048     HeapFree(GetProcessHeap(), 0, buffer);
1049     HeapFree(GetProcessHeap(), 0, bin);
1050     return ret;
1051 }
1052
1053 /***********************************************************************
1054  *              CompleteAuthToken
1055  */
1056 static SECURITY_STATUS SEC_ENTRY ntlm_CompleteAuthToken(PCtxtHandle phContext,
1057  PSecBufferDesc pToken)
1058 {
1059     /* We never need to call CompleteAuthToken anyway */
1060     TRACE("%p %p\n", phContext, pToken);
1061     if (!phContext)
1062         return SEC_E_INVALID_HANDLE;
1063     
1064     return SEC_E_OK;
1065 }
1066
1067 /***********************************************************************
1068  *              DeleteSecurityContext
1069  */
1070 static SECURITY_STATUS SEC_ENTRY ntlm_DeleteSecurityContext(PCtxtHandle phContext)
1071 {
1072     SECURITY_STATUS ret;
1073
1074     TRACE("%p\n", phContext);
1075     if (phContext)
1076     {
1077         phContext->dwUpper = 0;
1078         phContext->dwLower = 0;
1079         ret = SEC_E_OK;
1080     }
1081     else
1082     {
1083         ret = SEC_E_INVALID_HANDLE;
1084     }
1085     return ret;
1086 }
1087
1088 /***********************************************************************
1089  *              QueryContextAttributesW
1090  */
1091 static SECURITY_STATUS SEC_ENTRY ntlm_QueryContextAttributesW(PCtxtHandle phContext,
1092  unsigned long ulAttribute, void *pBuffer)
1093 {
1094     TRACE("%p %ld %p\n", phContext, ulAttribute, pBuffer);
1095     if (!phContext)
1096         return SEC_E_INVALID_HANDLE;
1097
1098     switch(ulAttribute)
1099     {
1100 #define _x(x) case (x) : FIXME(#x" stub\n"); break
1101         _x(SECPKG_ATTR_ACCESS_TOKEN);
1102         _x(SECPKG_ATTR_AUTHORITY);
1103         _x(SECPKG_ATTR_DCE_INFO);
1104         case SECPKG_ATTR_FLAGS:
1105         {
1106             PSecPkgContext_Flags spcf = (PSecPkgContext_Flags)pBuffer;
1107             PNegoHelper helper = (PNegoHelper)phContext->dwLower;
1108
1109             spcf->Flags = 0;
1110             if(helper->neg_flags & NTLMSSP_NEGOTIATE_SIGN)
1111                 spcf->Flags |= ISC_RET_INTEGRITY;
1112             if(helper->neg_flags & NTLMSSP_NEGOTIATE_SEAL)
1113                 spcf->Flags |= ISC_RET_CONFIDENTIALITY;
1114             return SEC_E_OK;
1115         }
1116         _x(SECPKG_ATTR_KEY_INFO);
1117         _x(SECPKG_ATTR_LIFESPAN);
1118         _x(SECPKG_ATTR_NAMES);
1119         _x(SECPKG_ATTR_NATIVE_NAMES);
1120         _x(SECPKG_ATTR_NEGOTIATION_INFO);
1121         _x(SECPKG_ATTR_PACKAGE_INFO);
1122         _x(SECPKG_ATTR_PASSWORD_EXPIRY);
1123         _x(SECPKG_ATTR_SESSION_KEY);
1124         case SECPKG_ATTR_SIZES:
1125         {
1126             PSecPkgContext_Sizes spcs = (PSecPkgContext_Sizes)pBuffer;
1127             spcs->cbMaxToken = NTLM_MAX_BUF;
1128             spcs->cbMaxSignature = 16;
1129             spcs->cbBlockSize = 0;
1130             spcs->cbSecurityTrailer = 16;
1131             return SEC_E_OK;
1132         }
1133         _x(SECPKG_ATTR_STREAM_SIZES);
1134         _x(SECPKG_ATTR_TARGET_INFORMATION);
1135 #undef _x
1136         default:
1137             TRACE("Unknown value %ld passed for ulAttribute\n", ulAttribute);
1138     }
1139
1140     return SEC_E_UNSUPPORTED_FUNCTION;
1141 }
1142
1143 /***********************************************************************
1144  *              QueryContextAttributesA
1145  */
1146 static SECURITY_STATUS SEC_ENTRY ntlm_QueryContextAttributesA(PCtxtHandle phContext,
1147  unsigned long ulAttribute, void *pBuffer)
1148 {
1149     return ntlm_QueryContextAttributesW(phContext, ulAttribute, pBuffer);
1150 }
1151
1152 /***********************************************************************
1153  *              ImpersonateSecurityContext
1154  */
1155 static SECURITY_STATUS SEC_ENTRY ntlm_ImpersonateSecurityContext(PCtxtHandle phContext)
1156 {
1157     SECURITY_STATUS ret;
1158
1159     TRACE("%p\n", phContext);
1160     if (phContext)
1161     {
1162         ret = SEC_E_UNSUPPORTED_FUNCTION;
1163     }
1164     else
1165     {
1166         ret = SEC_E_INVALID_HANDLE;
1167     }
1168     return ret;
1169 }
1170
1171 /***********************************************************************
1172  *              RevertSecurityContext
1173  */
1174 static SECURITY_STATUS SEC_ENTRY ntlm_RevertSecurityContext(PCtxtHandle phContext)
1175 {
1176     SECURITY_STATUS ret;
1177
1178     TRACE("%p\n", phContext);
1179     if (phContext)
1180     {
1181         ret = SEC_E_UNSUPPORTED_FUNCTION;
1182     }
1183     else
1184     {
1185         ret = SEC_E_INVALID_HANDLE;
1186     }
1187     return ret;
1188 }
1189
1190 /***********************************************************************
1191  *              MakeSignature
1192  */
1193 static SECURITY_STATUS SEC_ENTRY ntlm_MakeSignature(PCtxtHandle phContext, ULONG fQOP,
1194  PSecBufferDesc pMessage, ULONG MessageSeqNo)
1195 {
1196     PNegoHelper helper;
1197     ULONG sign_version = 1;
1198
1199     TRACE("%p %ld %p %ld\n", phContext, fQOP, pMessage, MessageSeqNo);
1200     if (!phContext)
1201         return SEC_E_INVALID_HANDLE;
1202
1203     if(fQOP)
1204         FIXME("Ignoring fQOP 0x%08lx", fQOP);
1205
1206     if(MessageSeqNo)
1207         FIXME("Ignoring MessageSeqNo");
1208
1209     if(!pMessage || !pMessage->pBuffers || pMessage->cBuffers < 2 ||
1210             pMessage->pBuffers[0].BufferType != SECBUFFER_TOKEN ||
1211             !pMessage->pBuffers[0].pvBuffer)
1212         return SEC_E_INVALID_TOKEN;
1213
1214     if(pMessage->pBuffers[0].cbBuffer < 16)
1215         return SEC_E_BUFFER_TOO_SMALL;
1216
1217     helper = (PNegoHelper)phContext->dwLower;
1218     TRACE("Negotiated flags are: 0x%08lx\n", helper->neg_flags);
1219     if(helper->neg_flags & NTLMSSP_NEGOTIATE_NTLM2)
1220     {
1221         FIXME("Can't handle NTLMv2 signing yet. Aborting.\n");
1222         return SEC_E_UNSUPPORTED_FUNCTION;
1223     }
1224     if(helper->neg_flags & NTLMSSP_NEGOTIATE_SIGN)
1225     {
1226         PBYTE sig = pMessage->pBuffers[0].pvBuffer;
1227         ULONG crc = ComputeCrc32(pMessage->pBuffers[1].pvBuffer,
1228                 pMessage->pBuffers[1].cbBuffer);
1229
1230         sig[ 0] = (sign_version >>  0) & 0xff;
1231         sig[ 1] = (sign_version >>  8) & 0xff;
1232         sig[ 2] = (sign_version >> 16) & 0xff;
1233         sig[ 3] = (sign_version >> 24) & 0xff;
1234         memset(sig+4, 0, 4);
1235         sig[ 8] = (crc >>  0) & 0xff;
1236         sig[ 9] = (crc >>  8) & 0xff;
1237         sig[10] = (crc >> 16) & 0xff;
1238         sig[11] = (crc >> 24) & 0xff;
1239         sig[12] = (helper->crypt.ntlm.seq_num >>  0) & 0xff;
1240         sig[13] = (helper->crypt.ntlm.seq_num >>  8) & 0xff;
1241         sig[14] = (helper->crypt.ntlm.seq_num >> 16) & 0xff;
1242         sig[15] = (helper->crypt.ntlm.seq_num >> 24) & 0xff;
1243
1244         ++(helper->crypt.ntlm.seq_num);
1245
1246         SECUR32_arc4Process(helper->crypt.ntlm.a4i, sig+4, 12);
1247         return SEC_E_OK;
1248     }
1249
1250     if(helper->neg_flags & NTLMSSP_NEGOTIATE_KEY_EXCHANGE)
1251     {
1252         FIXME("Can't handle encrypted session key yet. Aborting.\n");
1253         return SEC_E_UNSUPPORTED_FUNCTION;
1254     }
1255
1256     if(helper->neg_flags & NTLMSSP_NEGOTIATE_ALWAYS_SIGN || helper->neg_flags == 0)
1257     {
1258         TRACE("Generating dummy signature\n");
1259         /* A dummy signature is 0x01 followed by 15 bytes of 0x00 */
1260         memset(pMessage->pBuffers[0].pvBuffer, 0, 16);
1261         memset(pMessage->pBuffers[0].pvBuffer, 0x01, 1);
1262         pMessage->pBuffers[0].cbBuffer = 16;
1263         return SEC_E_OK;
1264     }
1265
1266     return SEC_E_UNSUPPORTED_FUNCTION;
1267 }
1268
1269 /***********************************************************************
1270  *              VerifySignature
1271  */
1272 static SECURITY_STATUS SEC_ENTRY ntlm_VerifySignature(PCtxtHandle phContext,
1273  PSecBufferDesc pMessage, ULONG MessageSeqNo, PULONG pfQOP)
1274 {
1275     PNegoHelper helper;
1276     ULONG fQOP = 0;
1277
1278     TRACE("%p %p %ld %p\n", phContext, pMessage, MessageSeqNo, pfQOP);
1279     if(!phContext)
1280         return SEC_E_INVALID_HANDLE;
1281
1282     if(!pMessage || !pMessage->pBuffers || pMessage->cBuffers < 2 ||
1283             pMessage->pBuffers[0].BufferType != SECBUFFER_TOKEN ||
1284             !pMessage->pBuffers[0].pvBuffer)
1285         return SEC_E_INVALID_TOKEN;
1286
1287     if(pMessage->pBuffers[0].cbBuffer < 16)
1288         return SEC_E_BUFFER_TOO_SMALL;
1289
1290     if(MessageSeqNo)
1291         FIXME("Ignoring MessageSeqNo\n");
1292
1293     helper = (PNegoHelper)phContext->dwLower;
1294     TRACE("Negotiated flags: 0x%08lx\n", helper->neg_flags);
1295
1296     if(helper->neg_flags & NTLMSSP_NEGOTIATE_NTLM2)
1297     {
1298         FIXME("Can't handle NTLMv2 signing yet. Aborting.\n");
1299         return SEC_E_UNSUPPORTED_FUNCTION;
1300     }
1301
1302     if(helper->neg_flags & NTLMSSP_NEGOTIATE_SIGN)
1303     {
1304         SecBufferDesc local_desc;
1305         SecBuffer     local_buff[2];
1306         BYTE          local_sig[16];
1307
1308         local_desc.ulVersion = SECBUFFER_VERSION;
1309         local_desc.cBuffers = 2;
1310         local_desc.pBuffers = local_buff;
1311         local_buff[0].BufferType = SECBUFFER_TOKEN;
1312         local_buff[0].cbBuffer = 16;
1313         local_buff[0].pvBuffer = local_sig;
1314         local_buff[1].BufferType = SECBUFFER_DATA;
1315         local_buff[1].cbBuffer = pMessage->pBuffers[1].cbBuffer;
1316         local_buff[1].pvBuffer = pMessage->pBuffers[1].pvBuffer;
1317
1318         ntlm_MakeSignature(phContext, fQOP, &local_desc, MessageSeqNo);
1319
1320         if(memcmp(((PBYTE)local_buff[0].pvBuffer) + 8, ((PBYTE)pMessage->pBuffers[0].pvBuffer) + 8, 8))
1321             return SEC_E_MESSAGE_ALTERED;
1322
1323         return SEC_E_OK;
1324     }
1325
1326     if(helper->neg_flags & NTLMSSP_NEGOTIATE_KEY_EXCHANGE)
1327     {
1328         FIXME("Can't handle encrypted session keys yet. Aborting.\n");
1329         return SEC_E_UNSUPPORTED_FUNCTION;
1330     }
1331
1332     if(helper->neg_flags & NTLMSSP_NEGOTIATE_ALWAYS_SIGN || helper->neg_flags == 0)
1333     {
1334         const BYTE dummy_sig[] = {0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1335             0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
1336         TRACE("Assuming dummy signature.\n");
1337         if(memcmp(pMessage->pBuffers[0].pvBuffer, dummy_sig, sizeof(dummy_sig)) != 0)
1338         {
1339             TRACE("Failed to verify the packet signature. Not a dummy signature?\n");
1340             return SEC_E_MESSAGE_ALTERED;
1341         }
1342         else
1343         {
1344             pfQOP = &fQOP;
1345             return SEC_E_OK;
1346         }
1347     }
1348
1349     return SEC_E_UNSUPPORTED_FUNCTION;
1350 }
1351
1352 /***********************************************************************
1353  *             FreeCredentialsHandle
1354  */
1355 static SECURITY_STATUS SEC_ENTRY ntlm_FreeCredentialsHandle(
1356         PCredHandle phCredential)
1357 {
1358     SECURITY_STATUS ret;
1359
1360     if(phCredential){
1361         PNegoHelper helper = (PNegoHelper) phCredential->dwLower;
1362         phCredential->dwUpper = 0;
1363         phCredential->dwLower = 0;
1364         HeapFree(GetProcessHeap(), 0, helper->session_key);
1365         cleanup_helper(helper);
1366         ret = SEC_E_OK;
1367     }
1368     else
1369         ret = SEC_E_OK;
1370     
1371     return ret;
1372 }
1373
1374 /***********************************************************************
1375  *             EncryptMessage
1376  */
1377 static SECURITY_STATUS SEC_ENTRY ntlm_EncryptMessage(PCtxtHandle phContext,
1378         ULONG fQOP, PSecBufferDesc pMessage, ULONG MessageSeqNo)
1379 {
1380     PNegoHelper helper;
1381     TRACE("(%p %ld %p %ld)\n", phContext, fQOP, pMessage, MessageSeqNo);
1382
1383     if(!phContext)
1384         return SEC_E_INVALID_HANDLE;
1385
1386     if(fQOP)
1387         FIXME("Ignoring fQOP\n");
1388
1389     if(MessageSeqNo)
1390         FIXME("Ignoring MessageSeqNo\n");
1391
1392     if(!pMessage || !pMessage->pBuffers || pMessage->cBuffers < 2 ||
1393             pMessage->pBuffers[0].BufferType != SECBUFFER_TOKEN ||
1394             !pMessage->pBuffers[0].pvBuffer)
1395         return SEC_E_INVALID_TOKEN;
1396
1397     if(pMessage->pBuffers[0].cbBuffer < 16)
1398         return SEC_E_BUFFER_TOO_SMALL;
1399
1400     helper = (PNegoHelper) phContext->dwLower;
1401
1402     if(helper->neg_flags & NTLMSSP_NEGOTIATE_NTLM2)
1403     {
1404         FIXME("Can't handle NTLMv2 encryption yet, aborting\n");
1405         return SEC_E_UNSUPPORTED_FUNCTION;
1406     }
1407     else
1408     {
1409         PBYTE sig = pMessage->pBuffers[0].pvBuffer;
1410         ULONG crc = ComputeCrc32(pMessage->pBuffers[1].pvBuffer,
1411                 pMessage->pBuffers[1].cbBuffer);
1412         ULONG sign_version = 1l;
1413
1414         sig[ 0] = (sign_version >>  0) & 0xff;
1415         sig[ 1] = (sign_version >>  8) & 0xff;
1416         sig[ 2] = (sign_version >> 16) & 0xff;
1417         sig[ 3] = (sign_version >> 24) & 0xff;
1418         memset(sig+4, 0, 4);
1419         sig[ 8] = (crc >>  0) & 0xff;
1420         sig[ 9] = (crc >>  8) & 0xff;
1421         sig[10] = (crc >> 16) & 0xff;
1422         sig[11] = (crc >> 24) & 0xff;
1423         sig[12] = (helper->crypt.ntlm.seq_num >>  0) & 0xff;
1424         sig[13] = (helper->crypt.ntlm.seq_num >>  8) & 0xff;
1425         sig[14] = (helper->crypt.ntlm.seq_num >> 16) & 0xff;
1426         sig[15] = (helper->crypt.ntlm.seq_num >> 24) & 0xff;
1427
1428         SECUR32_arc4Process(helper->crypt.ntlm.a4i, pMessage->pBuffers[1].pvBuffer,
1429                 pMessage->pBuffers[1].cbBuffer);
1430         SECUR32_arc4Process(helper->crypt.ntlm.a4i, sig+4, 12);
1431
1432         if(helper->neg_flags & NTLMSSP_NEGOTIATE_ALWAYS_SIGN || helper->neg_flags == 0)
1433             memset(sig+4, 0, 4);
1434
1435         ++(helper->crypt.ntlm.seq_num);
1436
1437     }
1438
1439     return SEC_E_OK;
1440 }
1441
1442 /***********************************************************************
1443  *             DecryptMessage
1444  */
1445 static SECURITY_STATUS SEC_ENTRY ntlm_DecryptMessage(PCtxtHandle phContext,
1446         PSecBufferDesc pMessage, ULONG MessageSeqNo, PULONG pfQOP)
1447 {
1448     SECURITY_STATUS ret;
1449     ULONG ntlmssp_flags_save;
1450     PNegoHelper helper;
1451     TRACE("(%p %p %ld %p)\n", phContext, pMessage, MessageSeqNo, pfQOP);
1452
1453     if(!phContext)
1454         return SEC_E_INVALID_HANDLE;
1455
1456     if(MessageSeqNo)
1457         FIXME("Ignoring MessageSeqNo\n");
1458
1459     if(!pMessage || !pMessage->pBuffers || pMessage->cBuffers < 2 ||
1460             pMessage->pBuffers[0].BufferType != SECBUFFER_TOKEN ||
1461             !pMessage->pBuffers[0].pvBuffer)
1462         return SEC_E_INVALID_TOKEN;
1463
1464     if(pMessage->pBuffers[0].cbBuffer < 16)
1465         return SEC_E_BUFFER_TOO_SMALL;
1466
1467     helper = (PNegoHelper) phContext->dwLower;
1468
1469     if(helper->neg_flags & NTLMSSP_NEGOTIATE_NTLM2)
1470     {
1471         FIXME("Can't handle NTLMv2 encryption yet, aborting\n");
1472         return SEC_E_UNSUPPORTED_FUNCTION;
1473     }
1474     else
1475     {
1476         SECUR32_arc4Process(helper->crypt.ntlm.a4i,
1477                 pMessage->pBuffers[1].pvBuffer, pMessage->pBuffers[1].cbBuffer);
1478     }
1479
1480     /* Make sure we use a session key for the signature check, EncryptMessage
1481      * always does that, even in the dummy case */
1482     ntlmssp_flags_save = helper->neg_flags;
1483
1484     helper->neg_flags |= NTLMSSP_NEGOTIATE_SIGN;
1485     ret = ntlm_VerifySignature(phContext, pMessage, MessageSeqNo, pfQOP);
1486
1487     helper->neg_flags = ntlmssp_flags_save;
1488
1489     return ret;
1490 }
1491
1492 static SecurityFunctionTableA ntlmTableA = {
1493     1,
1494     NULL,   /* EnumerateSecurityPackagesA */
1495     ntlm_QueryCredentialsAttributesA,   /* QueryCredentialsAttributesA */
1496     ntlm_AcquireCredentialsHandleA,     /* AcquireCredentialsHandleA */
1497     ntlm_FreeCredentialsHandle,         /* FreeCredentialsHandle */
1498     NULL,   /* Reserved2 */
1499     ntlm_InitializeSecurityContextA,    /* InitializeSecurityContextA */
1500     ntlm_AcceptSecurityContext,         /* AcceptSecurityContext */
1501     ntlm_CompleteAuthToken,             /* CompleteAuthToken */
1502     ntlm_DeleteSecurityContext,         /* DeleteSecurityContext */
1503     NULL,  /* ApplyControlToken */
1504     ntlm_QueryContextAttributesA,       /* QueryContextAttributesA */
1505     ntlm_ImpersonateSecurityContext,    /* ImpersonateSecurityContext */
1506     ntlm_RevertSecurityContext,         /* RevertSecurityContext */
1507     ntlm_MakeSignature,                 /* MakeSignature */
1508     ntlm_VerifySignature,               /* VerifySignature */
1509     FreeContextBuffer,                  /* FreeContextBuffer */
1510     NULL,   /* QuerySecurityPackageInfoA */
1511     NULL,   /* Reserved3 */
1512     NULL,   /* Reserved4 */
1513     NULL,   /* ExportSecurityContext */
1514     NULL,   /* ImportSecurityContextA */
1515     NULL,   /* AddCredentialsA */
1516     NULL,   /* Reserved8 */
1517     NULL,   /* QuerySecurityContextToken */
1518     ntlm_EncryptMessage,                /* EncryptMessage */
1519     ntlm_DecryptMessage,                /* DecryptMessage */
1520     NULL,   /* SetContextAttributesA */
1521 };
1522
1523 static SecurityFunctionTableW ntlmTableW = {
1524     1,
1525     NULL,   /* EnumerateSecurityPackagesW */
1526     ntlm_QueryCredentialsAttributesW,   /* QueryCredentialsAttributesW */
1527     ntlm_AcquireCredentialsHandleW,     /* AcquireCredentialsHandleW */
1528     ntlm_FreeCredentialsHandle,         /* FreeCredentialsHandle */
1529     NULL,   /* Reserved2 */
1530     ntlm_InitializeSecurityContextW,    /* InitializeSecurityContextW */
1531     ntlm_AcceptSecurityContext,         /* AcceptSecurityContext */
1532     ntlm_CompleteAuthToken,             /* CompleteAuthToken */
1533     ntlm_DeleteSecurityContext,         /* DeleteSecurityContext */
1534     NULL,  /* ApplyControlToken */
1535     ntlm_QueryContextAttributesW,       /* QueryContextAttributesW */
1536     ntlm_ImpersonateSecurityContext,    /* ImpersonateSecurityContext */
1537     ntlm_RevertSecurityContext,         /* RevertSecurityContext */
1538     ntlm_MakeSignature,                 /* MakeSignature */
1539     ntlm_VerifySignature,               /* VerifySignature */
1540     FreeContextBuffer,                  /* FreeContextBuffer */
1541     NULL,   /* QuerySecurityPackageInfoW */
1542     NULL,   /* Reserved3 */
1543     NULL,   /* Reserved4 */
1544     NULL,   /* ExportSecurityContext */
1545     NULL,   /* ImportSecurityContextW */
1546     NULL,   /* AddCredentialsW */
1547     NULL,   /* Reserved8 */
1548     NULL,   /* QuerySecurityContextToken */
1549     ntlm_EncryptMessage,                /* EncryptMessage */
1550     ntlm_DecryptMessage,                /* DecryptMessage */
1551     NULL,   /* SetContextAttributesW */
1552 };
1553
1554 #define NTLM_COMMENT \
1555    { 'N', 'T', 'L', 'M', ' ', \
1556      'S', 'e', 'c', 'u', 'r', 'i', 't', 'y', ' ', \
1557      'P', 'a', 'c', 'k', 'a', 'g', 'e', 0}
1558
1559 static CHAR ntlm_comment_A[] = NTLM_COMMENT;
1560 static WCHAR ntlm_comment_W[] = NTLM_COMMENT;
1561
1562 #define NTLM_NAME {'N', 'T', 'L', 'M', 0}
1563
1564 static char ntlm_name_A[] = NTLM_NAME;
1565 static WCHAR ntlm_name_W[] = NTLM_NAME;
1566
1567 /* According to Windows, NTLM has the following capabilities.  */
1568 #define CAPS ( \
1569         SECPKG_FLAG_INTEGRITY | \
1570         SECPKG_FLAG_PRIVACY | \
1571         SECPKG_FLAG_TOKEN_ONLY | \
1572         SECPKG_FLAG_CONNECTION | \
1573         SECPKG_FLAG_MULTI_REQUIRED | \
1574         SECPKG_FLAG_IMPERSONATION | \
1575         SECPKG_FLAG_ACCEPT_WIN32_NAME | \
1576         SECPKG_FLAG_READONLY_WITH_CHECKSUM)
1577
1578 static const SecPkgInfoW infoW = {
1579     CAPS,
1580     1,
1581     RPC_C_AUTHN_WINNT,
1582     NTLM_MAX_BUF,
1583     ntlm_name_W,
1584     ntlm_comment_W
1585 };
1586
1587 static const SecPkgInfoA infoA = {
1588     CAPS,
1589     1,
1590     RPC_C_AUTHN_WINNT,
1591     NTLM_MAX_BUF,
1592     ntlm_name_A,
1593     ntlm_comment_A
1594 };
1595
1596 void SECUR32_initNTLMSP(void)
1597 {
1598     SECURITY_STATUS ret;
1599     PNegoHelper helper;
1600     static CHAR ntlm_auth[] = "ntlm_auth",
1601                 version[]   = "--version";
1602
1603     SEC_CHAR *args[] = {
1604         ntlm_auth,
1605         version,
1606         NULL };
1607
1608     if((ret = fork_helper(&helper, "ntlm_auth", args)) != SEC_E_OK)
1609     {
1610         /* Cheat and allocate a helper anyway, so cleanup later will work. */
1611         helper = HeapAlloc(GetProcessHeap(),0, sizeof(PNegoHelper));
1612         helper->version = -1;
1613     }
1614     else
1615         check_version(helper);
1616
1617     if(helper->version > 2)
1618     {
1619         SecureProvider *provider = SECUR32_addProvider(&ntlmTableA, &ntlmTableW, NULL);
1620         SECUR32_addPackages(provider, 1L, &infoA, &infoW);
1621     }
1622     cleanup_helper(helper);
1623 }