shell32: Add Fonts to user's shell folders list.
[wine] / dlls / secur32 / ntlm.c
1 /*
2  * Copyright 2005 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 "windef.h"
24 #include "winbase.h"
25 #include "winnls.h"
26 #include "rpc.h"
27 #include "sspi.h"
28 #include "lm.h"
29 #include "secur32_priv.h"
30 #include "wine/debug.h"
31
32 WINE_DEFAULT_DEBUG_CHANNEL(secur32);
33
34 #define NTLM_MAX_BUF 2010
35
36
37 /***********************************************************************
38  *              QueryCredentialsAttributesA
39  */
40 static SECURITY_STATUS SEC_ENTRY ntlm_QueryCredentialsAttributesA(
41         PCredHandle phCredential, ULONG ulAttribute, PVOID pBuffer)
42 {
43     SECURITY_STATUS ret;
44
45     TRACE("(%p, %ld, %p)\n", phCredential, ulAttribute, pBuffer);
46
47     if(ulAttribute == SECPKG_ATTR_NAMES)
48     {
49         FIXME("SECPKG_CRED_ATTR_NAMES: stub\n");
50         ret = SEC_E_UNSUPPORTED_FUNCTION;
51     }
52     else
53         ret = SEC_E_UNSUPPORTED_FUNCTION;
54     
55     return ret;
56 }
57
58 /***********************************************************************
59  *              QueryCredentialsAttributesW
60  */
61 static SECURITY_STATUS SEC_ENTRY ntlm_QueryCredentialsAttributesW(
62         PCredHandle phCredential, ULONG ulAttribute, PVOID pBuffer)
63 {
64     SECURITY_STATUS ret;
65
66     TRACE("(%p, %ld, %p)\n", phCredential, ulAttribute, pBuffer);
67
68     if(ulAttribute == SECPKG_ATTR_NAMES)
69     {
70         FIXME("SECPKG_CRED_ATTR_NAMES: stub\n");
71         ret = SEC_E_UNSUPPORTED_FUNCTION;
72     }
73     else
74         ret = SEC_E_UNSUPPORTED_FUNCTION;
75     
76     return ret;
77 }
78
79 /***********************************************************************
80  *              AcquireCredentialsHandleW
81  */
82 static SECURITY_STATUS SEC_ENTRY ntlm_AcquireCredentialsHandleW(
83  SEC_WCHAR *pszPrincipal, SEC_WCHAR *pszPackage, ULONG fCredentialUse,
84  PLUID pLogonID, PVOID pAuthData, SEC_GET_KEY_FN pGetKeyFn,
85  PVOID pGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
86 {
87     SECURITY_STATUS ret;
88     PNegoHelper helper = NULL;
89     
90     SEC_CHAR *client_user_arg = NULL;
91     SEC_CHAR *client_domain_arg = NULL;
92     SEC_WCHAR *username = NULL, *domain = NULL;
93     
94     SEC_CHAR *client_argv[5];
95     SEC_CHAR *server_argv[] = { "ntlm_auth",
96         "--helper-protocol=squid-2.5-ntlmssp",
97         NULL };
98
99     TRACE("(%s, %s, 0x%08lx, %p, %p, %p, %p, %p, %p)\n",
100      debugstr_w(pszPrincipal), debugstr_w(pszPackage), fCredentialUse,
101      pLogonID, pAuthData, pGetKeyFn, pGetKeyArgument, phCredential, ptsExpiry);
102
103
104     switch(fCredentialUse)
105     {
106         case SECPKG_CRED_INBOUND:
107             if( (ret = fork_helper(&helper, "ntlm_auth", server_argv)) !=
108                     SEC_E_OK)
109             {
110                 phCredential = NULL;
111                 break;
112             }
113             else
114             {
115                 helper->mode = NTLM_SERVER;
116                 phCredential->dwUpper = fCredentialUse;
117                 phCredential->dwLower = (DWORD)helper;
118             }
119             ret = SEC_E_OK;
120             break;
121         case SECPKG_CRED_OUTBOUND:
122             {
123                 static const char username_arg[] = "--username=";
124                 static const char domain_arg[] = "--domain=";
125                 int unixcp_size;
126
127                 if(pAuthData == NULL)
128                 {
129                     LPWKSTA_USER_INFO_1 ui = NULL;
130                     NET_API_STATUS status;
131
132                     status = NetWkstaUserGetInfo(NULL, 1, (LPBYTE *)&ui);
133                     if (status != NERR_Success || ui == NULL)
134                     {
135                         ret = SEC_E_NO_CREDENTIALS;
136                         phCredential = NULL;
137                         break;
138                     }
139                     
140                     username = HeapAlloc(GetProcessHeap(), 0, 
141                             (lstrlenW(ui->wkui1_username)+1) * 
142                             sizeof(SEC_WCHAR));
143                     lstrcpyW(username, ui->wkui1_username);
144                         
145                     /* same for the domain */
146                     domain = HeapAlloc(GetProcessHeap(), 0, 
147                             (lstrlenW(ui->wkui1_logon_domain)+1) * 
148                             sizeof(SEC_WCHAR));
149                     lstrcpyW(domain, ui->wkui1_logon_domain);
150                     NetApiBufferFree(ui);
151                 }
152                 else
153                 {
154                     PSEC_WINNT_AUTH_IDENTITY_W auth_data = 
155                         (PSEC_WINNT_AUTH_IDENTITY_W)pAuthData;
156
157                     if (!auth_data->UserLength || !auth_data->DomainLength)
158                     {
159                         ret = SEC_E_NO_CREDENTIALS;
160                         phCredential = NULL;
161                         break;
162                     }
163                     /* Get username and domain from pAuthData */
164                     username = HeapAlloc(GetProcessHeap(), 0, 
165                             (auth_data->UserLength + 1) * sizeof(SEC_WCHAR));
166                     lstrcpyW(username, auth_data->User);
167
168                     domain = HeapAlloc(GetProcessHeap(), 0,
169                             (auth_data->DomainLength + 1) * sizeof(SEC_WCHAR));
170                     lstrcpyW(domain, auth_data->Domain);
171                 }
172                 TRACE("Username is %s\n", debugstr_w(username));
173                 unixcp_size =  WideCharToMultiByte(CP_UNIXCP, WC_NO_BEST_FIT_CHARS,
174                         username, -1, NULL, 0, NULL, NULL) + sizeof(username_arg);
175                 client_user_arg = HeapAlloc(GetProcessHeap(), 0, unixcp_size);
176                 lstrcpyA(client_user_arg, username_arg);
177                 WideCharToMultiByte(CP_UNIXCP, WC_NO_BEST_FIT_CHARS, username, -1,
178                         client_user_arg + sizeof(username_arg) - 1, 
179                         unixcp_size - sizeof(username_arg) + 1, NULL, NULL);
180
181                 TRACE("Domain name is %s\n", debugstr_w(domain));
182                 unixcp_size = WideCharToMultiByte(CP_UNIXCP, WC_NO_BEST_FIT_CHARS,
183                         domain, -1, NULL, 0,  NULL, NULL) + sizeof(domain_arg);
184                 client_domain_arg = HeapAlloc(GetProcessHeap(), 0, unixcp_size);
185                 lstrcpyA(client_domain_arg, domain_arg);
186                 WideCharToMultiByte(CP_UNIXCP, WC_NO_BEST_FIT_CHARS, domain,
187                         -1, client_domain_arg + sizeof(domain_arg) - 1, 
188                         unixcp_size - sizeof(domain) + 1, NULL, NULL);
189
190                 client_argv[0] = "ntlm_auth";
191                 client_argv[1] = "--helper-protocol=ntlmssp-client-1";
192                 client_argv[2] = client_user_arg;
193                 client_argv[3] = client_domain_arg;
194                 client_argv[4] = NULL;
195
196                 if((ret = fork_helper(&helper, "ntlm_auth", client_argv)) != 
197                         SEC_E_OK)
198                 {
199                     phCredential = NULL;
200                     break;
201                 }
202                 else
203                 {
204                     helper->mode = NTLM_CLIENT;
205
206                     if(pAuthData != NULL)
207                     {
208                         PSEC_WINNT_AUTH_IDENTITY_W auth_data = 
209                            (PSEC_WINNT_AUTH_IDENTITY_W)pAuthData;
210
211                         if(auth_data->PasswordLength != 0)
212                         {
213                             helper->pwlen = WideCharToMultiByte(CP_UNIXCP, 
214                                 WC_NO_BEST_FIT_CHARS, auth_data->Password, 
215                                 auth_data->PasswordLength+1, NULL, 0, NULL, NULL);
216                         
217                             helper->password = HeapAlloc(GetProcessHeap(), 0, 
218                                     helper->pwlen);
219
220                             WideCharToMultiByte(CP_UNIXCP, WC_NO_BEST_FIT_CHARS,
221                                 auth_data->Password, auth_data->PasswordLength+1,
222                                 helper->password, helper->pwlen, NULL, NULL);
223                         }
224                     }
225            
226                     phCredential->dwUpper = fCredentialUse;
227                     phCredential->dwLower = (DWORD)helper;
228                     TRACE("ACH phCredential->dwUpper: 0x%08lx, dwLower: 0x%08lx\n",
229                             phCredential->dwUpper, phCredential->dwLower);
230                 }
231                 ret = SEC_E_OK;
232                 break;
233             }
234         case SECPKG_CRED_BOTH:
235             FIXME("AcquireCredentialsHandle: SECPKG_CRED_BOTH stub\n");
236             ret = SEC_E_UNSUPPORTED_FUNCTION;
237             phCredential = NULL;
238             break;
239         default:
240             phCredential = NULL;
241             ret = SEC_E_UNKNOWN_CREDENTIALS;
242     }
243     
244
245     HeapFree(GetProcessHeap(), 0, client_user_arg);
246     HeapFree(GetProcessHeap(), 0, client_domain_arg);
247     HeapFree(GetProcessHeap(), 0, username);
248     HeapFree(GetProcessHeap(), 0, domain);
249
250     return ret;
251 }
252
253 /***********************************************************************
254  *              AcquireCredentialsHandleA
255  */
256 static SECURITY_STATUS SEC_ENTRY ntlm_AcquireCredentialsHandleA(
257  SEC_CHAR *pszPrincipal, SEC_CHAR *pszPackage, ULONG fCredentialUse,
258  PLUID pLogonID, PVOID pAuthData, SEC_GET_KEY_FN pGetKeyFn,
259  PVOID pGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
260 {
261     SECURITY_STATUS ret;
262     int user_sizeW, domain_sizeW, passwd_sizeW;
263     
264     SEC_WCHAR *user = NULL, *domain = NULL, *passwd = NULL, *package = NULL;
265     
266     PSEC_WINNT_AUTH_IDENTITY_W pAuthDataW = NULL;
267     PSEC_WINNT_AUTH_IDENTITY_A identity  = NULL;
268
269     TRACE("(%s, %s, 0x%08lx, %p, %p, %p, %p, %p, %p)\n",
270      debugstr_a(pszPrincipal), debugstr_a(pszPackage), fCredentialUse,
271      pLogonID, pAuthData, pGetKeyFn, pGetKeyArgument, phCredential, ptsExpiry);
272     
273     if(pszPackage != NULL)
274     {
275         int package_sizeW = MultiByteToWideChar(CP_ACP, 0, pszPackage, -1,
276                 NULL, 0);
277
278         package = HeapAlloc(GetProcessHeap(), 0, package_sizeW * 
279                 sizeof(SEC_WCHAR));
280         MultiByteToWideChar(CP_ACP, 0, pszPackage, -1, package, package_sizeW);
281     }
282
283     
284     if(pAuthData != NULL)
285     {
286         identity = (PSEC_WINNT_AUTH_IDENTITY_A)pAuthData;
287         
288         if(identity->Flags == SEC_WINNT_AUTH_IDENTITY_ANSI)
289         {
290             pAuthDataW = HeapAlloc(GetProcessHeap(), 0, 
291                     sizeof(SEC_WINNT_AUTH_IDENTITY_W));
292
293             if(identity->UserLength != 0)
294             {
295                 user_sizeW = MultiByteToWideChar(CP_ACP, 0, 
296                     (LPCSTR)identity->User, identity->UserLength+1, NULL, 0);
297                 user = HeapAlloc(GetProcessHeap(), 0, user_sizeW * 
298                         sizeof(SEC_WCHAR));
299                 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)identity->User, 
300                     identity->UserLength+1, user, user_sizeW);
301             }
302             else
303             {
304                 user_sizeW = 0;
305             }
306              
307             if(identity->DomainLength != 0)
308             {
309                 domain_sizeW = MultiByteToWideChar(CP_ACP, 0, 
310                     (LPCSTR)identity->Domain, identity->DomainLength+1, NULL, 0);
311                 domain = HeapAlloc(GetProcessHeap(), 0, domain_sizeW 
312                     * sizeof(SEC_WCHAR));
313                 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)identity->Domain, 
314                     identity->DomainLength+1, domain, domain_sizeW);
315             }
316             else
317             {
318                 domain_sizeW = 0;
319             }
320
321             if(identity->PasswordLength != 0)
322             {
323                 passwd_sizeW = MultiByteToWideChar(CP_ACP, 0, 
324                     (LPCSTR)identity->Password, identity->PasswordLength+1, 
325                     NULL, 0);
326                 passwd = HeapAlloc(GetProcessHeap(), 0, passwd_sizeW
327                     * sizeof(SEC_WCHAR));
328                 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)identity->Password,
329                     identity->PasswordLength+1, passwd, passwd_sizeW);
330             }
331             else
332             {
333                 passwd_sizeW = 0;
334             }
335             
336             pAuthDataW->Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
337             pAuthDataW->User = user;
338             pAuthDataW->UserLength = user_sizeW;
339             pAuthDataW->Domain = domain;
340             pAuthDataW->DomainLength = domain_sizeW;
341             pAuthDataW->Password = passwd;
342             pAuthDataW->PasswordLength = passwd_sizeW;
343         }
344         else
345         {
346             pAuthDataW = (PSEC_WINNT_AUTH_IDENTITY_W)identity;
347         }
348     }       
349     
350     ret = ntlm_AcquireCredentialsHandleW(NULL, package, fCredentialUse, 
351             pLogonID, pAuthDataW, pGetKeyFn, pGetKeyArgument, phCredential,
352             ptsExpiry);
353     
354     HeapFree(GetProcessHeap(), 0, package);
355     HeapFree(GetProcessHeap(), 0, user);
356     HeapFree(GetProcessHeap(), 0, domain);
357     HeapFree(GetProcessHeap(), 0, passwd);
358     if(pAuthDataW != (PSEC_WINNT_AUTH_IDENTITY_W)identity)
359         HeapFree(GetProcessHeap(), 0, pAuthDataW);
360     
361     return ret;
362 }
363
364 /***********************************************************************
365  *              InitializeSecurityContextW
366  */
367 static SECURITY_STATUS SEC_ENTRY ntlm_InitializeSecurityContextW(
368  PCredHandle phCredential, PCtxtHandle phContext, SEC_WCHAR *pszTargetName, 
369  ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep, 
370  PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext, 
371  PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
372 {
373     SECURITY_STATUS ret;
374     PNegoHelper helper;
375     ULONG ctxt_attr = 0;
376     char* buffer;
377     PBYTE bin;
378     int buffer_len, bin_len, max_len = NTLM_MAX_BUF;
379
380     TRACE("%p %p %s %ld %ld %ld %p %ld %p %p %p %p\n", phCredential, phContext,
381      debugstr_w(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
382      Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
383
384     if(!phCredential)
385         return SEC_E_INVALID_HANDLE;
386
387     /* As the server side of sspi never calls this, make sure that
388      * the handler is a client handler.
389      */
390     helper = (PNegoHelper)phCredential->dwLower;
391     if(helper->mode != NTLM_CLIENT)
392     {
393         TRACE("Helper mode = %d\n", helper->mode);
394         return SEC_E_INVALID_HANDLE;
395     }
396
397     /****************************************
398      * When communicating with the client, there can be the
399      * following reply packets:
400      * YR <base64 blob>         should be sent to the server
401      * PW                       should be sent back to helper with
402      *                          base64 encoded password
403      * AF <base64 blob>         client is done, blob should be
404      *                          sent to server with KK prefixed
405      * BH <char reason>         something broke
406      */
407     /* The squid cache size is 2010 chars, and that's what ntlm_auth uses */
408
409     if (pszTargetName)
410     {
411         TRACE("According to a MS whitepaper pszTargetName is ignored.\n");
412     }
413     /* Handle all the flags */
414     if(fContextReq & ISC_REQ_CONFIDENTIALITY)
415     {
416         FIXME("InitializeSecurityContext(): ISC_REQ_CONFIDENTIALITY stub\n");
417     }
418     if(fContextReq & ISC_REQ_CONNECTION)
419     {
420         /* This is default, so we'll enable it */
421         ctxt_attr |= ISC_RET_CONNECTION;
422     }
423     if(fContextReq & ISC_REQ_EXTENDED_ERROR)
424         FIXME("ISC_REQ_EXTENDED_ERROR\n");
425     if(fContextReq & ISC_REQ_INTEGRITY)
426         FIXME("ISC_REQ_INTEGRITY\n");
427     if(fContextReq & ISC_REQ_MUTUAL_AUTH)
428         FIXME("ISC_REQ_MUTUAL_AUTH\n");
429     if(fContextReq & ISC_REQ_REPLAY_DETECT)
430         FIXME("ISC_REQ_REPLAY_DETECT\n");
431     if(fContextReq & ISC_REQ_SEQUENCE_DETECT)
432         FIXME("ISC_REQ_SEQUENCE_DETECT\n");
433     if(fContextReq & ISC_REQ_STREAM)
434         FIXME("ISC_REQ_STREAM\n");
435
436     /* Done with the flags */
437     if(TargetDataRep == SECURITY_NETWORK_DREP){
438         FIXME("Don't know how to do SECURITY_NETWORK_DREP\n");
439         return SEC_E_UNSUPPORTED_FUNCTION;
440     }
441
442     buffer = HeapAlloc(GetProcessHeap(), 0, sizeof(char) * NTLM_MAX_BUF);
443     bin = HeapAlloc(GetProcessHeap(), 0, sizeof(BYTE) * NTLM_MAX_BUF);
444
445     if((phContext == NULL) && (pInput == NULL))
446     {
447         TRACE("First time in ISC()\n");
448         /* Request a challenge request from ntlm_auth */
449         if(helper->password == NULL)
450         {
451             FIXME("Using empty password for now.\n");
452             lstrcpynA(buffer, "PW AA==", max_len-1);
453         }
454         else
455         {
456             lstrcpynA(buffer, "PW ", max_len-1);
457             if((ret = encodeBase64((unsigned char*)helper->password,
458                         helper->pwlen-2, buffer+3,
459                         max_len-3, &buffer_len)) != SEC_E_OK)
460             {
461                 TRACE("Deleting password!\n");
462                 memset(helper->password, 0, helper->pwlen-2);
463                 HeapFree(GetProcessHeap(), 0, helper->password);
464                 goto end;
465             }
466
467         }
468
469         TRACE("Sending to helper: %s\n", debugstr_a(buffer));
470         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
471             goto end;
472
473         TRACE("Helper returned %s\n", debugstr_a(buffer));
474         lstrcpynA(buffer, "YR", max_len-1);
475
476         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
477             goto end;
478
479         TRACE("%s\n", buffer);
480
481         if(strncmp(buffer, "YR ", 3) != 0)
482         {
483             /* Something borked */
484             TRACE("Helper returned %c%c\n", buffer[0], buffer[1]);
485             ret = SEC_E_INTERNAL_ERROR;
486             goto end;
487         }
488         if((ret = decodeBase64(buffer+3, buffer_len-3, bin,
489                         max_len-1, &bin_len)) != SEC_E_OK)
490             goto end;
491
492         /* put the decoded client blob into the out buffer */
493
494         ret = SEC_I_CONTINUE_NEEDED;
495     }
496     else
497     {
498         /* handle second call here */
499         /* encode server data to base64 */
500         if (!pInput || !pInput->cBuffers)
501         {
502             ret = SEC_E_INCOMPLETE_MESSAGE;
503             goto end;
504         }
505
506         if (!pInput->pBuffers[0].pvBuffer)
507         {
508             ret = SEC_E_INTERNAL_ERROR;
509             goto end;
510         }
511
512         if(pInput->pBuffers[0].cbBuffer > max_len)
513         {
514             TRACE("pInput->pBuffers[0].cbBuffer is: %ld\n",
515                     pInput->pBuffers[0].cbBuffer);
516             ret = SEC_E_INVALID_TOKEN;
517             goto end;
518         }
519         else
520             bin_len = pInput->pBuffers[0].cbBuffer;
521
522         memcpy(bin, pInput->pBuffers[0].pvBuffer, bin_len);
523
524         lstrcpynA(buffer, "TT ", max_len-1);
525
526         if((ret = encodeBase64(bin, bin_len, buffer+3,
527                         max_len-3, &buffer_len)) != SEC_E_OK)
528             goto end;
529
530         TRACE("Server sent: %s\n", debugstr_a(buffer));
531
532         /* send TT base64 blob to ntlm_auth */
533         if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
534             goto end;
535
536         TRACE("Helper replied: %s\n", debugstr_a(buffer));
537
538         if( (strncmp(buffer, "KK ", 3) != 0) &&
539                 (strncmp(buffer, "AF ", 3) !=0))
540         {
541             TRACE("Helper returned %c%c\n", buffer[0], buffer[1]);
542             HeapFree(GetProcessHeap(), 0, buffer);
543             HeapFree(GetProcessHeap(), 0, bin);
544             return SEC_E_INVALID_TOKEN;
545         }
546
547         /* decode the blob and send it to server */
548         if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len,
549                         &bin_len)) != SEC_E_OK)
550         {
551             HeapFree(GetProcessHeap(), 0, buffer);
552             HeapFree(GetProcessHeap(), 0, bin);
553             return ret;
554         }
555
556         phNewContext->dwUpper = ctxt_attr;
557         phNewContext->dwLower = ret;
558
559         ret = SEC_E_OK;
560     }
561
562     /* put the decoded client blob into the out buffer */
563
564     if (fContextReq & ISC_REQ_ALLOCATE_MEMORY)
565     {
566         if (pOutput)
567         {
568             pOutput->cBuffers = 1;
569             pOutput->pBuffers[0].pvBuffer = SECUR32_ALLOC(bin_len);
570             pOutput->pBuffers[0].cbBuffer = bin_len;
571         }
572     }
573
574     if (!pOutput || !pOutput->cBuffers || pOutput->pBuffers[0].cbBuffer < bin_len)
575     {
576         TRACE("out buffer is NULL or has not enough space\n");
577         ret = SEC_E_BUFFER_TOO_SMALL;
578         goto end;
579     }
580
581     if (!pOutput->pBuffers[0].pvBuffer)
582     {
583         TRACE("out buffer is NULL\n");
584         ret = SEC_E_INTERNAL_ERROR;
585         goto end;
586     }
587
588     pOutput->pBuffers[0].cbBuffer = bin_len;
589     pOutput->pBuffers[0].BufferType = SECBUFFER_DATA;
590     memcpy(pOutput->pBuffers[0].pvBuffer, bin, bin_len);
591
592     if(ret != SEC_I_CONTINUE_NEEDED)
593     {
594         TRACE("Deleting password!\n");
595         if(helper->password)
596             memset(helper->password, 0, helper->pwlen-2);
597         HeapFree(GetProcessHeap(), 0, helper->password);
598     }
599 end:
600     HeapFree(GetProcessHeap(), 0, buffer);
601     HeapFree(GetProcessHeap(), 0, bin);
602     return ret;
603 }
604
605 /***********************************************************************
606  *              InitializeSecurityContextA
607  */
608 static SECURITY_STATUS SEC_ENTRY ntlm_InitializeSecurityContextA(
609  PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR *pszTargetName,
610  ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep, 
611  PSecBufferDesc pInput,ULONG Reserved2, PCtxtHandle phNewContext, 
612  PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
613 {
614     SECURITY_STATUS ret;
615
616     TRACE("%p %p %s %ld %ld %ld %p %ld %p %p %p %p\n", phCredential, phContext,
617      debugstr_a(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
618      Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
619     
620     if (phCredential)
621     {
622         SEC_WCHAR *target = NULL;
623         if(pszTargetName != NULL)
624         {
625             int target_size = MultiByteToWideChar(CP_ACP, 0, pszTargetName, 
626                 strlen(pszTargetName)+1, NULL, 0);
627             target = HeapAlloc(GetProcessHeap(), 0, target_size * 
628                     sizeof(SEC_WCHAR));
629             MultiByteToWideChar(CP_ACP, 0, pszTargetName, strlen(pszTargetName)+1,
630                 target, target_size);
631         }
632         
633         ret = ntlm_InitializeSecurityContextW(phCredential, phContext, target, 
634                 fContextReq, Reserved1, TargetDataRep, pInput, Reserved2,
635                 phNewContext, pOutput, pfContextAttr, ptsExpiry);
636         
637         HeapFree(GetProcessHeap(), 0, target);
638     }
639     else
640     {
641         ret = SEC_E_INVALID_HANDLE;
642     }
643     return ret;
644 }
645
646 /***********************************************************************
647  *              AcceptSecurityContext
648  */
649 static SECURITY_STATUS SEC_ENTRY ntlm_AcceptSecurityContext(
650  PCredHandle phCredential, PCtxtHandle phContext, PSecBufferDesc pInput,
651  ULONG fContextReq, ULONG TargetDataRep, PCtxtHandle phNewContext, 
652  PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
653 {
654     SECURITY_STATUS ret;
655
656     TRACE("%p %p %p %ld %ld %p %p %p %p\n", phCredential, phContext, pInput,
657      fContextReq, TargetDataRep, phNewContext, pOutput, pfContextAttr,
658      ptsExpiry);
659     if (phCredential)
660     {
661         PNegoHelper helper = (PNegoHelper)phCredential->dwLower;
662         /* Max size of input data is 2010 byte, as that's the maximum size 
663          * ntlm_auth will handle*/
664         char *buffer = HeapAlloc(GetProcessHeap(), 0, 
665                 sizeof(char) * NTLM_MAX_BUF);
666         PBYTE bin = HeapAlloc(GetProcessHeap(),0, sizeof(BYTE) * NTLM_MAX_BUF);
667         int buffer_len, bin_len, max_len = NTLM_MAX_BUF;
668         ULONG ctxt_attr = 0;
669
670         if(helper->mode != NTLM_SERVER)
671         {
672             HeapFree(GetProcessHeap(), 0, buffer);
673             HeapFree(GetProcessHeap(), 0, bin);
674             return SEC_E_INVALID_HANDLE;
675         }
676
677         /* Handle all the flags */
678         if(fContextReq & ISC_REQ_ALLOCATE_MEMORY)
679         {
680             FIXME("AcceptSecurityContext(): ISC_REQ_ALLOCATE_MEMORY stub\n");
681         }
682         if(fContextReq & ISC_REQ_CONFIDENTIALITY)
683         {
684             FIXME("AcceptSecurityContext(): ISC_REQ_CONFIDENTIALITY stub\n");
685         }
686         if(fContextReq & ISC_REQ_CONNECTION)
687         {
688             /* This is default, so we'll enable it */
689             ctxt_attr |= ISC_RET_CONNECTION;
690         }
691         if(fContextReq & ISC_REQ_EXTENDED_ERROR)
692         {
693             FIXME("AcceptSecurityContext(): ISC_REQ_EXTENDED_ERROR stub\n");
694         }
695         if(fContextReq & ISC_REQ_INTEGRITY)
696         {
697             FIXME("AcceptSecurityContext(): ISC_REQ_INTEGRITY stub\n");
698         }
699         if(fContextReq & ISC_REQ_MUTUAL_AUTH)
700         {
701             FIXME("AcceptSecurityContext(): ISC_REQ_MUTUAL_AUTH stub\n");
702         }
703         if(fContextReq & ISC_REQ_REPLAY_DETECT)
704         {
705             FIXME("AcceptSecurityContext(): ISC_REQ_REPLAY_DETECT stub\n");
706         }
707         if(fContextReq & ISC_REQ_SEQUENCE_DETECT)
708         {
709             FIXME("AcceptSecurityContext(): ISC_REQ_SEQUENCE_DETECT stub\n");
710         }
711         if(fContextReq & ISC_REQ_STREAM)
712         {
713             FIXME("AcceptSecurityContext(): ISC_REQ_STREAM stub\n");
714         }
715         /* Done with the flags */
716         if(TargetDataRep == SECURITY_NETWORK_DREP){
717             FIXME("Don't know how to do SECURITY_NETWORK_DREP\n");
718             HeapFree(GetProcessHeap(), 0, buffer);
719             HeapFree(GetProcessHeap(), 0, bin);
720             return SEC_E_UNSUPPORTED_FUNCTION;
721         }
722
723         
724         if(phContext == NULL)
725         {
726             /* This is the first call to AcceptSecurityHandle */
727             if(pInput == NULL)
728             {
729                 HeapFree(GetProcessHeap(), 0, buffer);
730                 HeapFree(GetProcessHeap(), 0, bin);
731                 return SEC_E_INCOMPLETE_MESSAGE;
732             }
733             
734             if(pInput->cBuffers < 1)
735             {
736                 HeapFree(GetProcessHeap(), 0, buffer);
737                 HeapFree(GetProcessHeap(), 0, bin);
738                 return SEC_E_INCOMPLETE_MESSAGE;
739             }
740
741             if(pInput->pBuffers[0].cbBuffer > max_len)
742             {
743                 HeapFree(GetProcessHeap(), 0, buffer);
744                 HeapFree(GetProcessHeap(), 0, bin);
745                 return SEC_E_INVALID_TOKEN;
746             }
747             else
748                 bin_len = pInput->pBuffers[0].cbBuffer;
749
750             /* This is the YR request from the client, encode to base64 */
751             
752             memcpy(bin, pInput->pBuffers[0].pvBuffer, bin_len);
753
754             lstrcpynA(buffer, "YR ", max_len-1);
755
756             if((ret = encodeBase64(bin, bin_len, buffer+3, max_len-3,
757                         &buffer_len)) != SEC_E_OK)
758             {
759                 HeapFree(GetProcessHeap(), 0, buffer);
760                 HeapFree(GetProcessHeap(), 0, bin);
761                 return ret;
762             }
763             
764             TRACE("Client sent: %s\n", debugstr_a(buffer));
765             
766             if((ret = run_helper(helper, buffer, max_len, &buffer_len)) !=
767                         SEC_E_OK)
768             {
769                 HeapFree(GetProcessHeap(), 0, buffer);
770                 HeapFree(GetProcessHeap(), 0, bin);
771                 return ret;
772             }
773
774             TRACE("Reply from ntlm_auth: %s\n", debugstr_a(buffer));
775             /* The expected answer is TT <base64 blob> */
776
777             if(strncmp(buffer, "TT ", 3) != 0)
778             {
779                 HeapFree(GetProcessHeap(), 0, buffer);
780                 HeapFree(GetProcessHeap(), 0, bin);
781                 return SEC_E_INVALID_TOKEN;
782             }
783
784             if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len,
785                             &bin_len)) != SEC_E_OK)
786             {
787                 HeapFree(GetProcessHeap(), 0, buffer);
788                 HeapFree(GetProcessHeap(), 0, bin);
789                 return ret;
790             }
791             
792             /* send this to the client */
793             if(pOutput == NULL)
794             {
795                 HeapFree(GetProcessHeap(), 0, buffer);
796                 HeapFree(GetProcessHeap(), 0, bin);
797                 return SEC_E_INSUFFICIENT_MEMORY;
798             }
799
800             if(pOutput->cBuffers < 1)
801             {
802                 HeapFree(GetProcessHeap(), 0, buffer);
803                 HeapFree(GetProcessHeap(), 0, bin);
804                 return SEC_E_INSUFFICIENT_MEMORY;
805             }
806
807             pOutput->pBuffers[0].cbBuffer = bin_len;
808             pOutput->pBuffers[0].BufferType = SECBUFFER_DATA;
809             memcpy(pOutput->pBuffers[0].pvBuffer, bin, bin_len);
810             ret = SEC_I_CONTINUE_NEEDED;
811             
812         }
813         else
814         {
815             /* we expect a KK request from client */
816             if(pInput == NULL)
817             {
818                 HeapFree(GetProcessHeap(), 0, buffer);
819                 HeapFree(GetProcessHeap(), 0, bin);
820                 return SEC_E_INCOMPLETE_MESSAGE;
821             }
822             
823             if(pInput->cBuffers < 1)
824             {
825                 HeapFree(GetProcessHeap(), 0, buffer);
826                 HeapFree(GetProcessHeap(), 0, bin);
827                 return SEC_E_INCOMPLETE_MESSAGE;
828             }
829
830             if(pInput->pBuffers[0].cbBuffer > max_len)
831             {
832                 HeapFree(GetProcessHeap(), 0, buffer);
833                 HeapFree(GetProcessHeap(), 0, bin);
834                 return SEC_E_INVALID_TOKEN;
835             }
836             else
837                 bin_len = pInput->pBuffers[0].cbBuffer;
838
839             memcpy(bin, pInput->pBuffers[0].pvBuffer, bin_len);
840
841             lstrcpynA(buffer, "KK ", max_len-1);
842
843             if((ret = encodeBase64(bin, bin_len, buffer+3, max_len-3,
844                         &buffer_len)) != SEC_E_OK)
845             {
846                 HeapFree(GetProcessHeap(), 0, buffer);
847                 HeapFree(GetProcessHeap(), 0, bin);
848                 return ret;
849             }
850             
851             TRACE("Client sent: %s\n", debugstr_a(buffer));
852             
853             if((ret = run_helper(helper, buffer, max_len, &buffer_len)) !=
854                         SEC_E_OK)
855             {
856                 HeapFree(GetProcessHeap(), 0, buffer);
857                 HeapFree(GetProcessHeap(), 0, bin);
858                 return ret;
859             }
860
861             TRACE("Reply from ntlm_auth: %s\n", debugstr_a(buffer));
862             
863             if(strncmp(buffer, "AF ", 3) != 0)
864             {
865                 if(strncmp(buffer, "NA ", 3) == 0)
866                 {
867                     HeapFree(GetProcessHeap(), 0, buffer);
868                     HeapFree(GetProcessHeap(), 0, bin);
869                     return SEC_E_LOGON_DENIED;
870                 }
871                 else
872                 {
873                     HeapFree(GetProcessHeap(), 0, buffer);
874                     HeapFree(GetProcessHeap(), 0, bin);
875                     return SEC_E_INVALID_TOKEN;
876                 }
877             }
878             
879             ret = SEC_E_OK;
880         }
881         
882         phNewContext->dwUpper = ctxt_attr;
883         phNewContext->dwLower = ret;
884         HeapFree(GetProcessHeap(), 0, buffer);
885         HeapFree(GetProcessHeap(), 0, bin);
886
887     }
888     else
889     {
890         ret = SEC_E_INVALID_HANDLE;
891     }
892     return ret;
893 }
894
895 /***********************************************************************
896  *              CompleteAuthToken
897  */
898 static SECURITY_STATUS SEC_ENTRY ntlm_CompleteAuthToken(PCtxtHandle phContext,
899  PSecBufferDesc pToken)
900 {
901     SECURITY_STATUS ret;
902
903     TRACE("%p %p\n", phContext, pToken);
904     if (phContext)
905     {
906         ret = SEC_E_UNSUPPORTED_FUNCTION;
907     }
908     else
909     {
910         ret = SEC_E_INVALID_HANDLE;
911     }
912     return ret;
913 }
914
915 /***********************************************************************
916  *              DeleteSecurityContext
917  */
918 static SECURITY_STATUS SEC_ENTRY ntlm_DeleteSecurityContext(PCtxtHandle phContext)
919 {
920     SECURITY_STATUS ret;
921
922     TRACE("%p\n", phContext);
923     if (phContext)
924     {
925         phContext->dwUpper = 0;
926         phContext->dwLower = 0;
927         ret = SEC_E_OK;
928     }
929     else
930     {
931         ret = SEC_E_INVALID_HANDLE;
932     }
933     return ret;
934 }
935
936 /***********************************************************************
937  *              QueryContextAttributesW
938  */
939 static SECURITY_STATUS SEC_ENTRY ntlm_QueryContextAttributesW(PCtxtHandle phContext,
940  unsigned long ulAttribute, void *pBuffer)
941 {
942     SECURITY_STATUS ret;
943
944     /* FIXME: From reading wrapper.h, I think the dwUpper part of a context is
945      * the SecurePackage part and the dwLower part is the actual context 
946      * handle. It should be easy to extract the context attributes from that.
947      */
948     TRACE("%p %ld %p\n", phContext, ulAttribute, pBuffer);
949     if (phContext)
950     {
951         ret = SEC_E_UNSUPPORTED_FUNCTION;
952     }
953     else
954     {
955         ret = SEC_E_INVALID_HANDLE;
956     }
957     return ret;
958 }
959
960 /***********************************************************************
961  *              QueryContextAttributesA
962  */
963 static SECURITY_STATUS SEC_ENTRY ntlm_QueryContextAttributesA(PCtxtHandle phContext,
964  unsigned long ulAttribute, void *pBuffer)
965 {
966     return ntlm_QueryContextAttributesW(phContext, ulAttribute, pBuffer);
967 }
968
969 /***********************************************************************
970  *              ImpersonateSecurityContext
971  */
972 static SECURITY_STATUS SEC_ENTRY ntlm_ImpersonateSecurityContext(PCtxtHandle phContext)
973 {
974     SECURITY_STATUS ret;
975
976     TRACE("%p\n", phContext);
977     if (phContext)
978     {
979         ret = SEC_E_UNSUPPORTED_FUNCTION;
980     }
981     else
982     {
983         ret = SEC_E_INVALID_HANDLE;
984     }
985     return ret;
986 }
987
988 /***********************************************************************
989  *              RevertSecurityContext
990  */
991 static SECURITY_STATUS SEC_ENTRY ntlm_RevertSecurityContext(PCtxtHandle phContext)
992 {
993     SECURITY_STATUS ret;
994
995     TRACE("%p\n", phContext);
996     if (phContext)
997     {
998         ret = SEC_E_UNSUPPORTED_FUNCTION;
999     }
1000     else
1001     {
1002         ret = SEC_E_INVALID_HANDLE;
1003     }
1004     return ret;
1005 }
1006
1007 /***********************************************************************
1008  *              MakeSignature
1009  */
1010 static SECURITY_STATUS SEC_ENTRY ntlm_MakeSignature(PCtxtHandle phContext, ULONG fQOP,
1011  PSecBufferDesc pMessage, ULONG MessageSeqNo)
1012 {
1013     SECURITY_STATUS ret;
1014
1015     TRACE("%p %ld %p %ld\n", phContext, fQOP, pMessage, MessageSeqNo);
1016     if (phContext)
1017     {
1018         ret = SEC_E_UNSUPPORTED_FUNCTION;
1019     }
1020     else
1021     {
1022         ret = SEC_E_INVALID_HANDLE;
1023     }
1024     return ret;
1025 }
1026
1027 /***********************************************************************
1028  *              VerifySignature
1029  */
1030 static SECURITY_STATUS SEC_ENTRY ntlm_VerifySignature(PCtxtHandle phContext,
1031  PSecBufferDesc pMessage, ULONG MessageSeqNo, PULONG pfQOP)
1032 {
1033     SECURITY_STATUS ret;
1034
1035     TRACE("%p %p %ld %p\n", phContext, pMessage, MessageSeqNo, pfQOP);
1036     if (phContext)
1037     {
1038         ret = SEC_E_UNSUPPORTED_FUNCTION;
1039     }
1040     else
1041     {
1042         ret = SEC_E_INVALID_HANDLE;
1043     }
1044     return ret;
1045 }
1046
1047 /***********************************************************************
1048  *             FreeCredentialsHandle
1049  */
1050 static SECURITY_STATUS SEC_ENTRY ntlm_FreeCredentialsHandle(
1051         PCredHandle phCredential)
1052 {
1053     SECURITY_STATUS ret;
1054
1055     if(phCredential){
1056         PNegoHelper helper = (PNegoHelper) phCredential->dwLower;
1057         phCredential->dwUpper = 0;
1058         phCredential->dwLower = 0;
1059         cleanup_helper(helper);
1060         ret = SEC_E_OK;
1061     }
1062     else
1063         ret = SEC_E_OK;
1064     
1065     return ret;
1066 }
1067
1068 static SecurityFunctionTableA ntlmTableA = {
1069     1,
1070     NULL,   /* EnumerateSecurityPackagesA */
1071     ntlm_QueryCredentialsAttributesA,   /* QueryCredentialsAttributesA */
1072     ntlm_AcquireCredentialsHandleA,     /* AcquireCredentialsHandleA */
1073     ntlm_FreeCredentialsHandle,         /* FreeCredentialsHandle */
1074     NULL,   /* Reserved2 */
1075     ntlm_InitializeSecurityContextA,    /* InitializeSecurityContextA */
1076     ntlm_AcceptSecurityContext,         /* AcceptSecurityContext */
1077     ntlm_CompleteAuthToken,             /* CompleteAuthToken */
1078     ntlm_DeleteSecurityContext,         /* DeleteSecurityContext */
1079     NULL,  /* ApplyControlToken */
1080     ntlm_QueryContextAttributesA,       /* QueryContextAttributesA */
1081     ntlm_ImpersonateSecurityContext,    /* ImpersonateSecurityContext */
1082     ntlm_RevertSecurityContext,         /* RevertSecurityContext */
1083     ntlm_MakeSignature,                 /* MakeSignature */
1084     ntlm_VerifySignature,               /* VerifySignature */
1085     FreeContextBuffer,                  /* FreeContextBuffer */
1086     NULL,   /* QuerySecurityPackageInfoA */
1087     NULL,   /* Reserved3 */
1088     NULL,   /* Reserved4 */
1089     NULL,   /* ExportSecurityContext */
1090     NULL,   /* ImportSecurityContextA */
1091     NULL,   /* AddCredentialsA */
1092     NULL,   /* Reserved8 */
1093     NULL,   /* QuerySecurityContextToken */
1094     NULL,   /* EncryptMessage */
1095     NULL,   /* DecryptMessage */
1096     NULL,   /* SetContextAttributesA */
1097 };
1098
1099 static SecurityFunctionTableW ntlmTableW = {
1100     1,
1101     NULL,   /* EnumerateSecurityPackagesW */
1102     ntlm_QueryCredentialsAttributesW,   /* QueryCredentialsAttributesW */
1103     ntlm_AcquireCredentialsHandleW,     /* AcquireCredentialsHandleW */
1104     ntlm_FreeCredentialsHandle,         /* FreeCredentialsHandle */
1105     NULL,   /* Reserved2 */
1106     ntlm_InitializeSecurityContextW,    /* InitializeSecurityContextW */
1107     ntlm_AcceptSecurityContext,         /* AcceptSecurityContext */
1108     ntlm_CompleteAuthToken,             /* CompleteAuthToken */
1109     ntlm_DeleteSecurityContext,         /* DeleteSecurityContext */
1110     NULL,  /* ApplyControlToken */
1111     ntlm_QueryContextAttributesW,       /* QueryContextAttributesW */
1112     ntlm_ImpersonateSecurityContext,    /* ImpersonateSecurityContext */
1113     ntlm_RevertSecurityContext,         /* RevertSecurityContext */
1114     ntlm_MakeSignature,                 /* MakeSignature */
1115     ntlm_VerifySignature,               /* VerifySignature */
1116     FreeContextBuffer,                  /* FreeContextBuffer */
1117     NULL,   /* QuerySecurityPackageInfoW */
1118     NULL,   /* Reserved3 */
1119     NULL,   /* Reserved4 */
1120     NULL,   /* ExportSecurityContext */
1121     NULL,   /* ImportSecurityContextW */
1122     NULL,   /* AddCredentialsW */
1123     NULL,   /* Reserved8 */
1124     NULL,   /* QuerySecurityContextToken */
1125     NULL,   /* EncryptMessage */
1126     NULL,   /* DecryptMessage */
1127     NULL,   /* SetContextAttributesW */
1128 };
1129
1130 #define NTLM_COMMENT \
1131    { 'N', 'T', 'L', 'M', ' ', \
1132      'S', 'e', 'c', 'u', 'r', 'i', 't', 'y', ' ', \
1133      'P', 'a', 'c', 'k', 'a', 'g', 'e', 0}
1134
1135 static CHAR ntlm_comment_A[] = NTLM_COMMENT;
1136 static WCHAR ntlm_comment_W[] = NTLM_COMMENT;
1137
1138 #define NTLM_NAME {'N', 'T', 'L', 'M', 0}
1139
1140 static char ntlm_name_A[] = NTLM_NAME;
1141 static WCHAR ntlm_name_W[] = NTLM_NAME;
1142
1143 /* According to Windows, NTLM has the following capabilities.  */
1144 #define CAPS ( \
1145         SECPKG_FLAG_INTEGRITY | \
1146         SECPKG_FLAG_PRIVACY | \
1147         SECPKG_FLAG_TOKEN_ONLY | \
1148         SECPKG_FLAG_CONNECTION | \
1149         SECPKG_FLAG_MULTI_REQUIRED | \
1150         SECPKG_FLAG_IMPERSONATION | \
1151         SECPKG_FLAG_ACCEPT_WIN32_NAME | \
1152         SECPKG_FLAG_READONLY_WITH_CHECKSUM)
1153
1154 static const SecPkgInfoW infoW = {
1155     CAPS,
1156     1,
1157     RPC_C_AUTHN_WINNT,
1158     NTLM_MAX_BUF,
1159     ntlm_name_W,
1160     ntlm_comment_W
1161 };
1162
1163 static const SecPkgInfoA infoA = {
1164     CAPS,
1165     1,
1166     RPC_C_AUTHN_WINNT,
1167     NTLM_MAX_BUF,
1168     ntlm_name_A,
1169     ntlm_comment_A
1170 };
1171
1172 void SECUR32_initNTLMSP(void)
1173 {   
1174     SECURITY_STATUS ret;
1175     PNegoHelper helper;
1176
1177     SEC_CHAR *args[] = {
1178         "ntlm_auth",
1179         "--version",
1180         NULL };
1181
1182     if((ret = fork_helper(&helper, "ntlm_auth", args)) != SEC_E_OK)
1183     {
1184         /* Cheat and allocate a helper anyway, so cleanup later will work. */
1185         helper = HeapAlloc(GetProcessHeap,0, sizeof(PNegoHelper));
1186         helper->version = -1;
1187     }
1188     else
1189         check_version(helper);
1190
1191     if(helper->version > 2)
1192     {
1193         SecureProvider *provider = SECUR32_addProvider(&ntlmTableA, &ntlmTableW, NULL);
1194         SECUR32_addPackages(provider, 1L, &infoA, &infoW);
1195     }
1196     cleanup_helper(helper);
1197 }