ntlm.c 65.8 KB
Newer Older
1
/*
2
 * Copyright 2005, 2006 Kai Blin
3 4 5 6 7 8 9 10 11 12 13 14 15
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * 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 19
 *
 * This file implements the NTLM security provider.
 */
20

21 22
#include <assert.h>
#include <stdarg.h>
23
#include <stdio.h>
24 25
#include "windef.h"
#include "winbase.h"
26
#include "winnls.h"
27
#include "wincred.h"
28
#include "rpc.h"
29
#include "sspi.h"
30
#include "lm.h"
31
#include "secur32_priv.h"
32
#include "hmac_md5.h"
33
#include "wine/unicode.h"
34 35
#include "wine/debug.h"

36
WINE_DEFAULT_DEBUG_CHANNEL(ntlm);
37
WINE_DECLARE_DEBUG_CHANNEL(winediag);
38

39
#define NTLM_MAX_BUF 1904
40 41
#define MIN_NTLM_AUTH_MAJOR_VERSION 3
#define MIN_NTLM_AUTH_MINOR_VERSION 0
42
#define MIN_NTLM_AUTH_MICRO_VERSION 25
43

44 45
static CHAR ntlm_auth[] = "ntlm_auth";

46 47 48 49 50 51 52 53
/***********************************************************************
 *              QueryCredentialsAttributesA
 */
static SECURITY_STATUS SEC_ENTRY ntlm_QueryCredentialsAttributesA(
        PCredHandle phCredential, ULONG ulAttribute, PVOID pBuffer)
{
    SECURITY_STATUS ret;

54
    TRACE("(%p, %d, %p)\n", phCredential, ulAttribute, pBuffer);
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74

    if(ulAttribute == SECPKG_ATTR_NAMES)
    {
        FIXME("SECPKG_CRED_ATTR_NAMES: stub\n");
        ret = SEC_E_UNSUPPORTED_FUNCTION;
    }
    else
        ret = SEC_E_UNSUPPORTED_FUNCTION;
    
    return ret;
}

/***********************************************************************
 *              QueryCredentialsAttributesW
 */
static SECURITY_STATUS SEC_ENTRY ntlm_QueryCredentialsAttributesW(
        PCredHandle phCredential, ULONG ulAttribute, PVOID pBuffer)
{
    SECURITY_STATUS ret;

75
    TRACE("(%p, %d, %p)\n", phCredential, ulAttribute, pBuffer);
76 77 78 79 80 81 82 83 84 85 86 87

    if(ulAttribute == SECPKG_ATTR_NAMES)
    {
        FIXME("SECPKG_CRED_ATTR_NAMES: stub\n");
        ret = SEC_E_UNSUPPORTED_FUNCTION;
    }
    else
        ret = SEC_E_UNSUPPORTED_FUNCTION;
    
    return ret;
}

88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
static char *ntlm_GetUsernameArg(LPCWSTR userW, INT userW_length)
{
    static const char username_arg[] = "--username=";
    char *user;
    int unixcp_size;

    unixcp_size =  WideCharToMultiByte(CP_UNIXCP, WC_NO_BEST_FIT_CHARS,
        userW, userW_length, NULL, 0, NULL, NULL) + sizeof(username_arg);
    user = HeapAlloc(GetProcessHeap(), 0, unixcp_size);
    if (!user) return NULL;
    memcpy(user, username_arg, sizeof(username_arg) - 1);
    WideCharToMultiByte(CP_UNIXCP, WC_NO_BEST_FIT_CHARS, userW, userW_length,
        user + sizeof(username_arg) - 1,
        unixcp_size - sizeof(username_arg) + 1, NULL, NULL);
    user[unixcp_size - 1] = '\0';
    return user;
}

static char *ntlm_GetDomainArg(LPCWSTR domainW, INT domainW_length)
{
    static const char domain_arg[] = "--domain=";
    char *domain;
    int unixcp_size;

    unixcp_size = WideCharToMultiByte(CP_UNIXCP, WC_NO_BEST_FIT_CHARS,
        domainW, domainW_length, NULL, 0,  NULL, NULL) + sizeof(domain_arg);
    domain = HeapAlloc(GetProcessHeap(), 0, unixcp_size);
    if (!domain) return NULL;
    memcpy(domain, domain_arg, sizeof(domain_arg) - 1);
    WideCharToMultiByte(CP_UNIXCP, WC_NO_BEST_FIT_CHARS, domainW,
        domainW_length, domain + sizeof(domain_arg) - 1,
        unixcp_size - sizeof(domain) + 1, NULL, NULL);
    domain[unixcp_size - 1] = '\0';
    return domain;
}

124 125 126
/***********************************************************************
 *              AcquireCredentialsHandleW
 */
127
SECURITY_STATUS SEC_ENTRY ntlm_AcquireCredentialsHandleW(
128 129 130
 SEC_WCHAR *pszPrincipal, SEC_WCHAR *pszPackage, ULONG fCredentialUse,
 PLUID pLogonID, PVOID pAuthData, SEC_GET_KEY_FN pGetKeyFn,
 PVOID pGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
131 132
{
    SECURITY_STATUS ret;
133
    PNtlmCredentials ntlm_cred;
134

135
    TRACE("(%s, %s, 0x%08x, %p, %p, %p, %p, %p, %p)\n",
136 137 138 139
     debugstr_w(pszPrincipal), debugstr_w(pszPackage), fCredentialUse,
     pLogonID, pAuthData, pGetKeyFn, pGetKeyArgument, phCredential, ptsExpiry);

    switch(fCredentialUse)
140
    {
141
        case SECPKG_CRED_INBOUND:
142 143 144
            ntlm_cred = HeapAlloc(GetProcessHeap(), 0, sizeof(*ntlm_cred));
            if (!ntlm_cred)
                ret = SEC_E_INSUFFICIENT_MEMORY;
145 146
            else
            {
147 148 149 150 151
                ntlm_cred->mode = NTLM_SERVER;
                ntlm_cred->username_arg = NULL;
                ntlm_cred->domain_arg = NULL;
                ntlm_cred->password = NULL;
                ntlm_cred->pwlen = 0;
152 153
                ntlm_cred->no_cached_credentials = 0;

154
                phCredential->dwUpper = fCredentialUse;
155 156
                phCredential->dwLower = (ULONG_PTR)ntlm_cred;
                ret = SEC_E_OK;
157 158 159 160
            }
            break;
        case SECPKG_CRED_OUTBOUND:
            {
161 162 163 164 165 166 167
                ntlm_cred = HeapAlloc(GetProcessHeap(), 0, sizeof(*ntlm_cred));
                if (!ntlm_cred)
                {
                    ret = SEC_E_INSUFFICIENT_MEMORY;
                    break;
                }
                ntlm_cred->mode = NTLM_CLIENT;
168 169
                ntlm_cred->username_arg = NULL;
                ntlm_cred->domain_arg = NULL;
170 171
                ntlm_cred->password = NULL;
                ntlm_cred->pwlen = 0;
172
                ntlm_cred->no_cached_credentials = 0;
173 174

                if(pAuthData != NULL)
175
                {
176
                    PSEC_WINNT_AUTH_IDENTITY_W auth_data = pAuthData;
177 178 179 180

                    TRACE("Username is %s\n", debugstr_wn(auth_data->User, auth_data->UserLength));
                    TRACE("Domain name is %s\n", debugstr_wn(auth_data->Domain, auth_data->DomainLength));

181 182
                    ntlm_cred->username_arg = ntlm_GetUsernameArg(auth_data->User, auth_data->UserLength);
                    ntlm_cred->domain_arg = ntlm_GetDomainArg(auth_data->Domain, auth_data->DomainLength);
183

184
                    if(auth_data->PasswordLength != 0)
185
                    {
186 187 188 189
                        ntlm_cred->pwlen = WideCharToMultiByte(CP_UNIXCP,
                                                               WC_NO_BEST_FIT_CHARS, auth_data->Password,
                                                               auth_data->PasswordLength, NULL, 0, NULL,
                                                               NULL);
190

191 192 193 194 195 196 197
                        ntlm_cred->password = HeapAlloc(GetProcessHeap(), 0,
                                                        ntlm_cred->pwlen);

                        WideCharToMultiByte(CP_UNIXCP, WC_NO_BEST_FIT_CHARS,
                                            auth_data->Password, auth_data->PasswordLength,
                                            ntlm_cred->password, ntlm_cred->pwlen, NULL, NULL);
                    }
198
                }
199 200 201 202 203

                phCredential->dwUpper = fCredentialUse;
                phCredential->dwLower = (ULONG_PTR)ntlm_cred;
                TRACE("ACH phCredential->dwUpper: 0x%08lx, dwLower: 0x%08lx\n",
                      phCredential->dwUpper, phCredential->dwLower);
204 205 206 207 208 209 210 211 212 213 214
                ret = SEC_E_OK;
                break;
            }
        case SECPKG_CRED_BOTH:
            FIXME("AcquireCredentialsHandle: SECPKG_CRED_BOTH stub\n");
            ret = SEC_E_UNSUPPORTED_FUNCTION;
            phCredential = NULL;
            break;
        default:
            phCredential = NULL;
            ret = SEC_E_UNKNOWN_CREDENTIALS;
215 216 217 218 219 220 221 222 223 224 225 226
    }
    return ret;
}

/***********************************************************************
 *              AcquireCredentialsHandleA
 */
static SECURITY_STATUS SEC_ENTRY ntlm_AcquireCredentialsHandleA(
 SEC_CHAR *pszPrincipal, SEC_CHAR *pszPackage, ULONG fCredentialUse,
 PLUID pLogonID, PVOID pAuthData, SEC_GET_KEY_FN pGetKeyFn,
 PVOID pGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
{
227 228 229 230 231 232 233 234
    SECURITY_STATUS ret;
    int user_sizeW, domain_sizeW, passwd_sizeW;
    
    SEC_WCHAR *user = NULL, *domain = NULL, *passwd = NULL, *package = NULL;
    
    PSEC_WINNT_AUTH_IDENTITY_W pAuthDataW = NULL;
    PSEC_WINNT_AUTH_IDENTITY_A identity  = NULL;

235
    TRACE("(%s, %s, 0x%08x, %p, %p, %p, %p, %p, %p)\n",
236 237
     debugstr_a(pszPrincipal), debugstr_a(pszPackage), fCredentialUse,
     pLogonID, pAuthData, pGetKeyFn, pGetKeyArgument, phCredential, ptsExpiry);
238 239 240 241 242
    
    if(pszPackage != NULL)
    {
        int package_sizeW = MultiByteToWideChar(CP_ACP, 0, pszPackage, -1,
                NULL, 0);
243

244 245 246 247 248 249 250 251
        package = HeapAlloc(GetProcessHeap(), 0, package_sizeW * 
                sizeof(SEC_WCHAR));
        MultiByteToWideChar(CP_ACP, 0, pszPackage, -1, package, package_sizeW);
    }

    
    if(pAuthData != NULL)
    {
252 253
        identity = pAuthData;

254 255 256 257 258 259 260 261
        if(identity->Flags == SEC_WINNT_AUTH_IDENTITY_ANSI)
        {
            pAuthDataW = HeapAlloc(GetProcessHeap(), 0, 
                    sizeof(SEC_WINNT_AUTH_IDENTITY_W));

            if(identity->UserLength != 0)
            {
                user_sizeW = MultiByteToWideChar(CP_ACP, 0, 
262
                    (LPCSTR)identity->User, identity->UserLength, NULL, 0);
263 264 265
                user = HeapAlloc(GetProcessHeap(), 0, user_sizeW * 
                        sizeof(SEC_WCHAR));
                MultiByteToWideChar(CP_ACP, 0, (LPCSTR)identity->User, 
266
                    identity->UserLength, user, user_sizeW);
267 268 269 270 271 272 273 274 275
            }
            else
            {
                user_sizeW = 0;
            }
             
            if(identity->DomainLength != 0)
            {
                domain_sizeW = MultiByteToWideChar(CP_ACP, 0, 
276
                    (LPCSTR)identity->Domain, identity->DomainLength, NULL, 0);
277 278 279
                domain = HeapAlloc(GetProcessHeap(), 0, domain_sizeW 
                    * sizeof(SEC_WCHAR));
                MultiByteToWideChar(CP_ACP, 0, (LPCSTR)identity->Domain, 
280
                    identity->DomainLength, domain, domain_sizeW);
281 282 283 284 285 286 287 288 289
            }
            else
            {
                domain_sizeW = 0;
            }

            if(identity->PasswordLength != 0)
            {
                passwd_sizeW = MultiByteToWideChar(CP_ACP, 0, 
290
                    (LPCSTR)identity->Password, identity->PasswordLength,
291 292 293 294
                    NULL, 0);
                passwd = HeapAlloc(GetProcessHeap(), 0, passwd_sizeW
                    * sizeof(SEC_WCHAR));
                MultiByteToWideChar(CP_ACP, 0, (LPCSTR)identity->Password,
295
                    identity->PasswordLength, passwd, passwd_sizeW);
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
            }
            else
            {
                passwd_sizeW = 0;
            }
            
            pAuthDataW->Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
            pAuthDataW->User = user;
            pAuthDataW->UserLength = user_sizeW;
            pAuthDataW->Domain = domain;
            pAuthDataW->DomainLength = domain_sizeW;
            pAuthDataW->Password = passwd;
            pAuthDataW->PasswordLength = passwd_sizeW;
        }
        else
        {
            pAuthDataW = (PSEC_WINNT_AUTH_IDENTITY_W)identity;
        }
    }       
    
    ret = ntlm_AcquireCredentialsHandleW(NULL, package, fCredentialUse, 
            pLogonID, pAuthDataW, pGetKeyFn, pGetKeyArgument, phCredential,
318
            ptsExpiry);
319 320 321 322 323 324 325 326 327
    
    HeapFree(GetProcessHeap(), 0, package);
    HeapFree(GetProcessHeap(), 0, user);
    HeapFree(GetProcessHeap(), 0, domain);
    HeapFree(GetProcessHeap(), 0, passwd);
    if(pAuthDataW != (PSEC_WINNT_AUTH_IDENTITY_W)identity)
        HeapFree(GetProcessHeap(), 0, pAuthDataW);
    
    return ret;
328 329
}

330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
/*************************************************************************
 *             ntlm_GetTokenBufferIndex
 * Calculates the index of the secbuffer with BufferType == SECBUFFER_TOKEN
 * Returns index if found or -1 if not found.
 */
static int ntlm_GetTokenBufferIndex(PSecBufferDesc pMessage)
{
    UINT i;

    TRACE("%p\n", pMessage);

    for( i = 0; i < pMessage->cBuffers; ++i )
    {
        if(pMessage->pBuffers[i].BufferType == SECBUFFER_TOKEN)
            return i;
    }

    return -1;
}

350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
/*************************************************************************
 *             ntlm_GetDataBufferIndex
 * Calculates the index of the first secbuffer with BufferType == SECBUFFER_DATA
 * Returns index if found or -1 if not found.
 */
static int ntlm_GetDataBufferIndex(PSecBufferDesc pMessage)
{
    UINT i;

    TRACE("%p\n", pMessage);

    for( i = 0; i < pMessage->cBuffers; ++i )
    {
        if(pMessage->pBuffers[i].BufferType == SECBUFFER_DATA)
            return i;
    }

    return -1;
}

370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
static BOOL ntlm_GetCachedCredential(const SEC_WCHAR *pszTargetName, PCREDENTIALW *cred)
{
    LPCWSTR p;
    LPCWSTR pszHost;
    LPWSTR pszHostOnly;
    BOOL ret;

    if (!pszTargetName)
        return FALSE;

    /* try to get the start of the hostname from service principal name (SPN) */
    pszHost = strchrW(pszTargetName, '/');
    if (pszHost)
    {
        /* skip slash character */
        pszHost++;

        /* find end of host by detecting start of instance port or start of referrer */
        p = strchrW(pszHost, ':');
        if (!p)
            p = strchrW(pszHost, '/');
        if (!p)
            p = pszHost + strlenW(pszHost);
    }
    else /* otherwise not an SPN, just a host */
395 396
    {
        pszHost = pszTargetName;
397
        p = pszHost + strlenW(pszHost);
398
    }
399 400 401 402 403 404 405 406 407 408 409 410 411 412

    pszHostOnly = HeapAlloc(GetProcessHeap(), 0, (p - pszHost + 1) * sizeof(WCHAR));
    if (!pszHostOnly)
        return FALSE;

    memcpy(pszHostOnly, pszHost, (p - pszHost) * sizeof(WCHAR));
    pszHostOnly[p - pszHost] = '\0';

    ret = CredReadW(pszHostOnly, CRED_TYPE_DOMAIN_PASSWORD, 0, cred);

    HeapFree(GetProcessHeap(), 0, pszHostOnly);
    return ret;
}

413
/***********************************************************************
414
 *              InitializeSecurityContextW
415
 */
416
SECURITY_STATUS SEC_ENTRY ntlm_InitializeSecurityContextW(
417
 PCredHandle phCredential, PCtxtHandle phContext, SEC_WCHAR *pszTargetName, 
418 419 420 421 422
 ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep, 
 PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext, 
 PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
{
    SECURITY_STATUS ret;
423
    PNtlmCredentials ntlm_cred;
424
    PNegoHelper helper = NULL;
425
    ULONG ctxt_attr = 0;
426
    char* buffer, *want_flags = NULL;
427 428
    PBYTE bin;
    int buffer_len, bin_len, max_len = NTLM_MAX_BUF;
429
    int token_idx;
430
    SEC_CHAR *username = NULL;
431 432
    SEC_CHAR *domain = NULL;
    SEC_CHAR *password = NULL;
433

434
    TRACE("%p %p %s 0x%08x %d %d %p %d %p %p %p %p\n", phCredential, phContext,
435
     debugstr_w(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
436
     Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
437

438 439 440 441 442 443 444 445
    /****************************************
     * When communicating with the client, there can be the
     * following reply packets:
     * YR <base64 blob>         should be sent to the server
     * PW                       should be sent back to helper with
     *                          base64 encoded password
     * AF <base64 blob>         client is done, blob should be
     *                          sent to server with KK prefixed
446 447
     * GF <string list>         A string list of negotiated flags
     * GK <base64 blob>         base64 encoded session key
448 449 450 451 452
     * BH <char reason>         something broke
     */
    /* The squid cache size is 2010 chars, and that's what ntlm_auth uses */

    if(TargetDataRep == SECURITY_NETWORK_DREP){
453
        TRACE("Setting SECURITY_NETWORK_DREP\n");
454
    }
455

456 457
    buffer = HeapAlloc(GetProcessHeap(), 0, sizeof(char) * NTLM_MAX_BUF);
    bin = HeapAlloc(GetProcessHeap(), 0, sizeof(BYTE) * NTLM_MAX_BUF);
458

459 460
    if((phContext == NULL) && (pInput == NULL))
    {
461
        static char helper_protocol[] = "--helper-protocol=ntlmssp-client-1";
462
        static CHAR credentials_argv[] = "--use-cached-creds";
463
        SEC_CHAR *client_argv[5];
464
        int pwlen = 0;
465

466
        TRACE("First time in ISC()\n");
467 468

        if(!phCredential)
469 470 471 472
        {
            ret = SEC_E_INVALID_HANDLE;
            goto isc_end;
        }
473 474 475 476

        /* As the server side of sspi never calls this, make sure that
         * the handler is a client handler.
         */
477 478
        ntlm_cred = (PNtlmCredentials)phCredential->dwLower;
        if(ntlm_cred->mode != NTLM_CLIENT)
479
        {
480
            TRACE("Cred mode = %d\n", ntlm_cred->mode);
481 482
            ret = SEC_E_INVALID_HANDLE;
            goto isc_end;
483 484
        }

485 486
        client_argv[0] = ntlm_auth;
        client_argv[1] = helper_protocol;
487 488 489 490
        if (!ntlm_cred->username_arg && !ntlm_cred->domain_arg)
        {
            LPWKSTA_USER_INFO_1 ui = NULL;
            NET_API_STATUS status;
491
            PCREDENTIALW cred;
492

493
            if (ntlm_GetCachedCredential(pszTargetName, &cred))
494
            {
495 496 497 498 499 500 501 502 503 504 505 506
                LPWSTR p;
                p = strchrW(cred->UserName, '\\');
                if (p)
                {
                    domain = ntlm_GetDomainArg(cred->UserName, p - cred->UserName);
                    p++;
                }
                else
                {
                    domain = ntlm_GetDomainArg(NULL, 0);
                    p = cred->UserName;
                }
507

508
                username = ntlm_GetUsernameArg(p, -1);
509

510 511 512 513 514 515
                if(cred->CredentialBlobSize != 0)
                {
                    pwlen = WideCharToMultiByte(CP_UNIXCP,
                        WC_NO_BEST_FIT_CHARS, (LPWSTR)cred->CredentialBlob,
                        cred->CredentialBlobSize / sizeof(WCHAR), NULL, 0,
                        NULL, NULL);
516

517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
                    password = HeapAlloc(GetProcessHeap(), 0, pwlen);

                    WideCharToMultiByte(CP_UNIXCP, WC_NO_BEST_FIT_CHARS,
                                        (LPWSTR)cred->CredentialBlob,
                                        cred->CredentialBlobSize / sizeof(WCHAR),
                                        password, pwlen, NULL, NULL);
                }

                CredFree(cred);

                client_argv[2] = username;
                client_argv[3] = domain;
                client_argv[4] = NULL;
            }
            else
            {
                status = NetWkstaUserGetInfo(NULL, 1, (LPBYTE *)&ui);
534
                if (status != NERR_Success || ui == NULL || ntlm_cred->no_cached_credentials)
535 536 537 538 539
                {
                    ret = SEC_E_NO_CREDENTIALS;
                    goto isc_end;
                }
                username = ntlm_GetUsernameArg(ui->wkui1_username, -1);
540
                NetApiBufferFree(ui);
541

542
                TRACE("using cached credentials\n");
543 544

                client_argv[2] = username;
545
                client_argv[3] = credentials_argv;
546 547
                client_argv[4] = NULL;
            }
548 549 550 551 552 553 554
        }
        else
        {
            client_argv[2] = ntlm_cred->username_arg;
            client_argv[3] = ntlm_cred->domain_arg;
            client_argv[4] = NULL;
        }
555 556 557 558 559 560 561 562 563 564 565 566 567 568

        if((ret = fork_helper(&helper, ntlm_auth, client_argv)) != SEC_E_OK)
            goto isc_end;

        helper->mode = NTLM_CLIENT;
        helper->session_key = HeapAlloc(GetProcessHeap(), 0, 16);
        if (!helper->session_key)
        {
            cleanup_helper(helper);
            ret = SEC_E_INSUFFICIENT_MEMORY;
            goto isc_end;
        }

        /* Generate the dummy session key = MD4(MD4(password))*/
569
        if(password || ntlm_cred->password)
570 571 572 573 574 575
        {
            SEC_WCHAR *unicode_password;
            int passwd_lenW;

            TRACE("Converting password to unicode.\n");
            passwd_lenW = MultiByteToWideChar(CP_ACP, 0,
576
                                              password ? password : ntlm_cred->password,
577
                                              password ? pwlen : ntlm_cred->pwlen,
578 579 580
                                              NULL, 0);
            unicode_password = HeapAlloc(GetProcessHeap(), 0,
                                         passwd_lenW * sizeof(SEC_WCHAR));
581
            MultiByteToWideChar(CP_ACP, 0, password ? password : ntlm_cred->password,
582
                                password ? pwlen : ntlm_cred->pwlen, unicode_password, passwd_lenW);
583

584 585
            SECUR32_CreateNTLM1SessionKey((PBYTE)unicode_password,
                                          passwd_lenW * sizeof(SEC_WCHAR), helper->session_key);
586 587 588 589 590 591

            HeapFree(GetProcessHeap(), 0, unicode_password);
        }
        else
            memset(helper->session_key, 0, 16);

592
        /* Allocate space for a maximal string of
593 594 595 596 597 598
         * "SF NTLMSSP_FEATURE_SIGN NTLMSSP_FEATURE_SEAL
         * NTLMSSP_FEATURE_SESSION_KEY"
         */
        want_flags = HeapAlloc(GetProcessHeap(), 0, 73);
        if(want_flags == NULL)
        {
599
            cleanup_helper(helper);
600
            ret = SEC_E_INSUFFICIENT_MEMORY;
601
            goto isc_end;
602 603 604 605
        }
        lstrcpyA(want_flags, "SF");
        if(fContextReq & ISC_REQ_CONFIDENTIALITY)
        {
606
            if(strstr(want_flags, "NTLMSSP_FEATURE_SEAL") == NULL)
607
                lstrcatA(want_flags, " NTLMSSP_FEATURE_SEAL");
608
        }
609 610
        if(fContextReq & ISC_REQ_CONNECTION)
            ctxt_attr |= ISC_RET_CONNECTION;
611
        if(fContextReq & ISC_REQ_EXTENDED_ERROR)
612
            ctxt_attr |= ISC_RET_EXTENDED_ERROR;
613
        if(fContextReq & ISC_REQ_INTEGRITY)
614
        {
615
            if(strstr(want_flags, "NTLMSSP_FEATURE_SIGN") == NULL)
616 617
                lstrcatA(want_flags, " NTLMSSP_FEATURE_SIGN");
        }
618
        if(fContextReq & ISC_REQ_MUTUAL_AUTH)
619
            ctxt_attr |= ISC_RET_MUTUAL_AUTH;
620
        if(fContextReq & ISC_REQ_REPLAY_DETECT)
621
        {
622
            if(strstr(want_flags, "NTLMSSP_FEATURE_SIGN") == NULL)
623 624
                lstrcatA(want_flags, " NTLMSSP_FEATURE_SIGN");
        }
625
        if(fContextReq & ISC_REQ_SEQUENCE_DETECT)
626
        {
627
            if(strstr(want_flags, "NTLMSSP_FEATURE_SIGN") == NULL)
628 629
                lstrcatA(want_flags, " NTLMSSP_FEATURE_SIGN");
        }
630 631
        if(fContextReq & ISC_REQ_STREAM)
            FIXME("ISC_REQ_STREAM\n");
632 633 634 635
        if(fContextReq & ISC_REQ_USE_DCE_STYLE)
            ctxt_attr |= ISC_RET_USED_DCE_STYLE;
        if(fContextReq & ISC_REQ_DELEGATE)
            ctxt_attr |= ISC_RET_DELEGATE;
636

637 638
        /* If no password is given, try to use cached credentials. Fall back to an empty
         * password if this failed. */
639
        if(!password && !ntlm_cred->password)
640
        {
641 642
            lstrcpynA(buffer, "OK", max_len-1);
            if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
643 644
            {
                cleanup_helper(helper);
645
                goto isc_end;
646
            }
647
            /* If the helper replied with "PW", using cached credentials failed */
648 649
            if(!strncmp(buffer, "PW", 2))
            {
650
                TRACE("Using cached credentials failed.\n");
651
                lstrcpynA(buffer, "PW AA==", max_len-1);
652
            }
653
            else /* Just do a noop on the next run */
654
                lstrcpynA(buffer, "OK", max_len-1);
655 656 657 658
        }
        else
        {
            lstrcpynA(buffer, "PW ", max_len-1);
659 660
            if((ret = encodeBase64(password ? (unsigned char *)password : (unsigned char *)ntlm_cred->password,
                        password ? pwlen : ntlm_cred->pwlen, buffer+3,
661
                        max_len-3, &buffer_len)) != SEC_E_OK)
662 663
            {
                cleanup_helper(helper);
664
                goto isc_end;
665
            }
666

667
        }
668

669 670
        TRACE("Sending to helper: %s\n", debugstr_a(buffer));
        if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
671 672
        {
            cleanup_helper(helper);
673
            goto isc_end;
674
        }
675

676
        TRACE("Helper returned %s\n", debugstr_a(buffer));
677 678 679

        if(lstrlenA(want_flags) > 2)
        {
680
            TRACE("Want flags are %s\n", debugstr_a(want_flags));
681 682 683
            lstrcpynA(buffer, want_flags, max_len-1);
            if((ret = run_helper(helper, buffer, max_len, &buffer_len)) 
                    != SEC_E_OK)
684 685
            {
                cleanup_helper(helper);
686
                goto isc_end;
687
            }
688
            if(!strncmp(buffer, "BH", 2))
689
                ERR("Helper doesn't understand new command set. Expect more things to fail.\n");
690 691
        }

692
        lstrcpynA(buffer, "YR", max_len-1);
693

694
        if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
695 696
        {
            cleanup_helper(helper);
697
            goto isc_end;
698
        }
699

700
        TRACE("%s\n", buffer);
701

702 703 704 705 706
        if(strncmp(buffer, "YR ", 3) != 0)
        {
            /* Something borked */
            TRACE("Helper returned %c%c\n", buffer[0], buffer[1]);
            ret = SEC_E_INTERNAL_ERROR;
707
            cleanup_helper(helper);
708
            goto isc_end;
709 710 711
        }
        if((ret = decodeBase64(buffer+3, buffer_len-3, bin,
                        max_len-1, &bin_len)) != SEC_E_OK)
712 713
        {
            cleanup_helper(helper);
714
            goto isc_end;
715
        }
716

717
        /* put the decoded client blob into the out buffer */
718

719 720 721
        phNewContext->dwUpper = ctxt_attr;
        phNewContext->dwLower = (ULONG_PTR)helper;

722 723 724 725
        ret = SEC_I_CONTINUE_NEEDED;
    }
    else
    {
726 727
        int input_token_idx;

728 729
        /* handle second call here */
        /* encode server data to base64 */
730
        if (!pInput || ((input_token_idx = ntlm_GetTokenBufferIndex(pInput)) == -1))
731
        {
732
            ret = SEC_E_INVALID_TOKEN;
733
            goto isc_end;
734
        }
735

736
        if(!phContext)
737 738 739 740
        {
            ret = SEC_E_INVALID_HANDLE;
            goto isc_end;
        }
741 742 743 744 745 746 747 748

        /* As the server side of sspi never calls this, make sure that
         * the handler is a client handler.
         */
        helper = (PNegoHelper)phContext->dwLower;
        if(helper->mode != NTLM_CLIENT)
        {
            TRACE("Helper mode = %d\n", helper->mode);
749 750
            ret = SEC_E_INVALID_HANDLE;
            goto isc_end;
751 752
        }

753
        if (!pInput->pBuffers[input_token_idx].pvBuffer)
754 755
        {
            ret = SEC_E_INTERNAL_ERROR;
756
            goto isc_end;
757
        }
758

759
        if(pInput->pBuffers[input_token_idx].cbBuffer > max_len)
760
        {
761
            TRACE("pInput->pBuffers[%d].cbBuffer is: %d\n",
762
                    input_token_idx,
763
                    pInput->pBuffers[input_token_idx].cbBuffer);
764
            ret = SEC_E_INVALID_TOKEN;
765
            goto isc_end;
766 767
        }
        else
768
            bin_len = pInput->pBuffers[input_token_idx].cbBuffer;
769

770
        memcpy(bin, pInput->pBuffers[input_token_idx].pvBuffer, bin_len);
771

772
        lstrcpynA(buffer, "TT ", max_len-1);
773

774 775
        if((ret = encodeBase64(bin, bin_len, buffer+3,
                        max_len-3, &buffer_len)) != SEC_E_OK)
776
            goto isc_end;
777

778
        TRACE("Server sent: %s\n", debugstr_a(buffer));
779

780 781
        /* send TT base64 blob to ntlm_auth */
        if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
782
            goto isc_end;
783

784
        TRACE("Helper replied: %s\n", debugstr_a(buffer));
785

786 787 788 789
        if( (strncmp(buffer, "KK ", 3) != 0) &&
                (strncmp(buffer, "AF ", 3) !=0))
        {
            TRACE("Helper returned %c%c\n", buffer[0], buffer[1]);
790
            ret = SEC_E_INVALID_TOKEN;
791
            goto isc_end;
792
        }
793

794 795 796 797
        /* decode the blob and send it to server */
        if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len,
                        &bin_len)) != SEC_E_OK)
        {
798
            goto isc_end;
799 800
        }

801 802 803 804 805 806 807 808
        phNewContext->dwUpper = ctxt_attr;
        phNewContext->dwLower = (ULONG_PTR)helper;

        ret = SEC_E_OK;
    }

    /* put the decoded client blob into the out buffer */

809
    if (!pOutput || ((token_idx = ntlm_GetTokenBufferIndex(pOutput)) == -1))
810
    {
811
        TRACE("no SECBUFFER_TOKEN buffer could be found\n");
812
        ret = SEC_E_BUFFER_TOO_SMALL;
813 814 815 816 817 818
        if ((phContext == NULL) && (pInput == NULL))
        {
            cleanup_helper(helper);
            phNewContext->dwUpper = 0;
            phNewContext->dwLower = 0;
        }
819
        goto isc_end;
820 821
    }

822 823
    if (fContextReq & ISC_REQ_ALLOCATE_MEMORY)
    {
824
        pOutput->pBuffers[token_idx].pvBuffer = HeapAlloc(GetProcessHeap(), 0, bin_len);
825 826 827
        pOutput->pBuffers[token_idx].cbBuffer = bin_len;
    }
    else if (pOutput->pBuffers[token_idx].cbBuffer < bin_len)
828 829 830
    {
        TRACE("out buffer is NULL or has not enough space\n");
        ret = SEC_E_BUFFER_TOO_SMALL;
831 832 833 834 835 836
        if ((phContext == NULL) && (pInput == NULL))
        {
            cleanup_helper(helper);
            phNewContext->dwUpper = 0;
            phNewContext->dwLower = 0;
        }
837 838 839
        goto isc_end;
    }

840
    if (!pOutput->pBuffers[token_idx].pvBuffer)
841 842 843
    {
        TRACE("out buffer is NULL\n");
        ret = SEC_E_INTERNAL_ERROR;
844 845 846 847 848 849
        if ((phContext == NULL) && (pInput == NULL))
        {
            cleanup_helper(helper);
            phNewContext->dwUpper = 0;
            phNewContext->dwLower = 0;
        }
850 851 852
        goto isc_end;
    }

853 854
    pOutput->pBuffers[token_idx].cbBuffer = bin_len;
    memcpy(pOutput->pBuffers[token_idx].pvBuffer, bin, bin_len);
855 856 857

    if(ret == SEC_E_OK)
    {
858 859 860
        TRACE("Getting negotiated flags\n");
        lstrcpynA(buffer, "GF", max_len - 1);
        if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
861
            goto isc_end;
862 863 864

        if(buffer_len < 3)
        {
865
            TRACE("No flags negotiated.\n");
866
            helper->neg_flags = 0l;
867 868 869 870
        }
        else
        {
            TRACE("Negotiated %s\n", debugstr_a(buffer));
871 872
            sscanf(buffer + 3, "%x", &(helper->neg_flags));
            TRACE("Stored 0x%08x as flags\n", helper->neg_flags);
873 874 875 876 877
        }

        TRACE("Getting session key\n");
        lstrcpynA(buffer, "GK", max_len - 1);
        if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
878
            goto isc_end;
879

880
        if(strncmp(buffer, "BH", 2) == 0)
881
            TRACE("No key negotiated.\n");
882 883 884 885
        else if(strncmp(buffer, "GK ", 3) == 0)
        {
            if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len, 
                            &bin_len)) != SEC_E_OK)
886
            {
887
                TRACE("Failed to decode session key\n");
888
            }
889
            TRACE("Session key is %s\n", debugstr_a(buffer+3));
890
            HeapFree(GetProcessHeap(), 0, helper->session_key);
891
            helper->session_key = HeapAlloc(GetProcessHeap(), 0, bin_len);
892
            if(!helper->session_key)
893
            {
894
                ret = SEC_E_INSUFFICIENT_MEMORY;
895
                goto isc_end;
896
            }
897
            memcpy(helper->session_key, bin, bin_len);
898
        }
899

900 901 902
        helper->crypt.ntlm.a4i = SECUR32_arc4Alloc();
        SECUR32_arc4Init(helper->crypt.ntlm.a4i, helper->session_key, 16);
        helper->crypt.ntlm.seq_num = 0l;
903
        SECUR32_CreateNTLM2SubKeys(helper);
904 905 906
        helper->crypt.ntlm2.send_a4i = SECUR32_arc4Alloc();
        helper->crypt.ntlm2.recv_a4i = SECUR32_arc4Alloc();
        SECUR32_arc4Init(helper->crypt.ntlm2.send_a4i,
907
                         helper->crypt.ntlm2.send_seal_key, 16);
908
        SECUR32_arc4Init(helper->crypt.ntlm2.recv_a4i,
909
                         helper->crypt.ntlm2.recv_seal_key, 16);
910 911
        helper->crypt.ntlm2.send_seq_no = 0l;
        helper->crypt.ntlm2.recv_seq_no = 0l;
912
    }
913

914
isc_end:
915
    HeapFree(GetProcessHeap(), 0, username);
916 917
    HeapFree(GetProcessHeap(), 0, domain);
    HeapFree(GetProcessHeap(), 0, password);
918
    HeapFree(GetProcessHeap(), 0, want_flags);
919 920
    HeapFree(GetProcessHeap(), 0, buffer);
    HeapFree(GetProcessHeap(), 0, bin);
921 922 923 924
    return ret;
}

/***********************************************************************
925
 *              InitializeSecurityContextA
926
 */
927 928
static SECURITY_STATUS SEC_ENTRY ntlm_InitializeSecurityContextA(
 PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR *pszTargetName,
929 930 931 932 933
 ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep, 
 PSecBufferDesc pInput,ULONG Reserved2, PCtxtHandle phNewContext, 
 PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
{
    SECURITY_STATUS ret;
934
    SEC_WCHAR *target = NULL;
935

936
    TRACE("%p %p %s %d %d %d %p %d %p %p %p %p\n", phCredential, phContext,
937
     debugstr_a(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
938
     Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
939 940

    if(pszTargetName != NULL)
941
    {
942 943 944 945 946 947
        int target_size = MultiByteToWideChar(CP_ACP, 0, pszTargetName,
            strlen(pszTargetName)+1, NULL, 0);
        target = HeapAlloc(GetProcessHeap(), 0, target_size *
                sizeof(SEC_WCHAR));
        MultiByteToWideChar(CP_ACP, 0, pszTargetName, strlen(pszTargetName)+1,
            target, target_size);
948
    }
949 950 951 952 953 954

    ret = ntlm_InitializeSecurityContextW(phCredential, phContext, target,
            fContextReq, Reserved1, TargetDataRep, pInput, Reserved2,
            phNewContext, pOutput, pfContextAttr, ptsExpiry);

    HeapFree(GetProcessHeap(), 0, target);
955 956 957 958 959 960
    return ret;
}

/***********************************************************************
 *              AcceptSecurityContext
 */
961
SECURITY_STATUS SEC_ENTRY ntlm_AcceptSecurityContext(
962 963 964 965 966
 PCredHandle phCredential, PCtxtHandle phContext, PSecBufferDesc pInput,
 ULONG fContextReq, ULONG TargetDataRep, PCtxtHandle phNewContext, 
 PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
{
    SECURITY_STATUS ret;
967
    char *buffer, *want_flags = NULL;
968 969 970 971
    PBYTE bin;
    int buffer_len, bin_len, max_len = NTLM_MAX_BUF;
    ULONG ctxt_attr = 0;
    PNegoHelper helper;
972
    PNtlmCredentials ntlm_cred;
973

974
    TRACE("%p %p %p %d %d %p %p %p %p\n", phCredential, phContext, pInput,
975 976
     fContextReq, TargetDataRep, phNewContext, pOutput, pfContextAttr,
     ptsExpiry);
977 978 979 980 981 982 983 984 985 986

    buffer = HeapAlloc(GetProcessHeap(), 0, sizeof(char) * NTLM_MAX_BUF);
    bin    = HeapAlloc(GetProcessHeap(),0, sizeof(BYTE) * NTLM_MAX_BUF);

    if(TargetDataRep == SECURITY_NETWORK_DREP){
        TRACE("Using SECURITY_NETWORK_DREP\n");
    }

    if(phContext == NULL)
    {
987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
        static CHAR server_helper_protocol[] = "--helper-protocol=squid-2.5-ntlmssp";
        SEC_CHAR *server_argv[] = { ntlm_auth,
            server_helper_protocol,
            NULL };

        if (!phCredential)
        {
            ret = SEC_E_INVALID_HANDLE;
            goto asc_end;
        }

        ntlm_cred = (PNtlmCredentials)phCredential->dwLower;

        if(ntlm_cred->mode != NTLM_SERVER)
        {
            ret = SEC_E_INVALID_HANDLE;
            goto asc_end;
        }

1006 1007
        /* This is the first call to AcceptSecurityHandle */
        if(pInput == NULL)
1008
        {
1009 1010
            ret = SEC_E_INCOMPLETE_MESSAGE;
            goto asc_end;
1011 1012
        }

1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
        if(pInput->cBuffers < 1)
        {
            ret = SEC_E_INCOMPLETE_MESSAGE;
            goto asc_end;
        }

        if(pInput->pBuffers[0].cbBuffer > max_len)
        {
            ret = SEC_E_INVALID_TOKEN;
            goto asc_end;
        }
        else
            bin_len = pInput->pBuffers[0].cbBuffer;

1027 1028 1029 1030 1031 1032 1033 1034
        if( (ret = fork_helper(&helper, ntlm_auth, server_argv)) !=
            SEC_E_OK)
        {
            ret = SEC_E_INTERNAL_ERROR;
            goto asc_end;
        }
        helper->mode = NTLM_SERVER;

1035
        /* Handle all the flags */
1036 1037 1038 1039 1040
        want_flags = HeapAlloc(GetProcessHeap(), 0, 73);
        if(want_flags == NULL)
        {
            TRACE("Failed to allocate memory for the want_flags!\n");
            ret = SEC_E_INSUFFICIENT_MEMORY;
1041
            cleanup_helper(helper);
1042 1043 1044
            goto asc_end;
        }
        lstrcpyA(want_flags, "SF");
1045
        if(fContextReq & ASC_REQ_ALLOCATE_MEMORY)
1046
        {
1047
            FIXME("ASC_REQ_ALLOCATE_MEMORY stub\n");
1048
        }
1049
        if(fContextReq & ASC_REQ_CONFIDENTIALITY)
1050
        {
1051
            lstrcatA(want_flags, " NTLMSSP_FEATURE_SEAL");
1052
        }
1053
        if(fContextReq & ASC_REQ_CONNECTION)
1054 1055
        {
            /* This is default, so we'll enable it */
1056
            lstrcatA(want_flags, " NTLMSSP_FEATURE_SESSION_KEY");
1057
            ctxt_attr |= ASC_RET_CONNECTION;
1058
        }
1059
        if(fContextReq & ASC_REQ_EXTENDED_ERROR)
1060
        {
1061
            FIXME("ASC_REQ_EXTENDED_ERROR stub\n");
1062
        }
1063
        if(fContextReq & ASC_REQ_INTEGRITY)
1064
        {
1065
            lstrcatA(want_flags, " NTLMSSP_FEATURE_SIGN");
1066
        }
1067
        if(fContextReq & ASC_REQ_MUTUAL_AUTH)
1068
        {
1069
            FIXME("ASC_REQ_MUTUAL_AUTH stub\n");
1070
        }
1071
        if(fContextReq & ASC_REQ_REPLAY_DETECT)
1072
        {
1073
            FIXME("ASC_REQ_REPLAY_DETECT stub\n");
1074 1075 1076
        }
        if(fContextReq & ISC_REQ_SEQUENCE_DETECT)
        {
1077
            FIXME("ASC_REQ_SEQUENCE_DETECT stub\n");
1078 1079 1080
        }
        if(fContextReq & ISC_REQ_STREAM)
        {
1081
            FIXME("ASC_REQ_STREAM stub\n");
1082 1083 1084
        }
        /* Done with the flags */

1085 1086 1087 1088 1089 1090
        if(lstrlenA(want_flags) > 3)
        {
            TRACE("Server set want_flags: %s\n", debugstr_a(want_flags));
            lstrcpynA(buffer, want_flags, max_len - 1);
            if((ret = run_helper(helper, buffer, max_len, &buffer_len)) !=
                    SEC_E_OK)
1091 1092
            {
                cleanup_helper(helper);
1093
                goto asc_end;
1094
            }
1095 1096 1097 1098
            if(!strncmp(buffer, "BH", 2))
                TRACE("Helper doesn't understand new command set\n");
        }

1099 1100 1101 1102 1103 1104 1105 1106
        /* This is the YR request from the client, encode to base64 */

        memcpy(bin, pInput->pBuffers[0].pvBuffer, bin_len);

        lstrcpynA(buffer, "YR ", max_len-1);

        if((ret = encodeBase64(bin, bin_len, buffer+3, max_len-3,
                    &buffer_len)) != SEC_E_OK)
1107
        {
1108
            cleanup_helper(helper);
1109 1110
            goto asc_end;
        }
1111

1112
        TRACE("Client sent: %s\n", debugstr_a(buffer));
1113

1114 1115 1116
        if((ret = run_helper(helper, buffer, max_len, &buffer_len)) !=
                    SEC_E_OK)
        {
1117
            cleanup_helper(helper);
1118 1119
            goto asc_end;
        }
1120

1121 1122
        TRACE("Reply from ntlm_auth: %s\n", debugstr_a(buffer));
        /* The expected answer is TT <base64 blob> */
1123

1124 1125 1126
        if(strncmp(buffer, "TT ", 3) != 0)
        {
            ret = SEC_E_INTERNAL_ERROR;
1127
            cleanup_helper(helper);
1128 1129
            goto asc_end;
        }
1130

1131 1132 1133
        if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len,
                        &bin_len)) != SEC_E_OK)
        {
1134
            cleanup_helper(helper);
1135 1136
            goto asc_end;
        }
1137

1138 1139 1140 1141
        /* send this to the client */
        if(pOutput == NULL)
        {
            ret = SEC_E_INSUFFICIENT_MEMORY;
1142
            cleanup_helper(helper);
1143 1144
            goto asc_end;
        }
1145

1146 1147 1148
        if(pOutput->cBuffers < 1)
        {
            ret = SEC_E_INSUFFICIENT_MEMORY;
1149
            cleanup_helper(helper);
1150 1151
            goto asc_end;
        }
1152

1153 1154 1155 1156
        pOutput->pBuffers[0].cbBuffer = bin_len;
        pOutput->pBuffers[0].BufferType = SECBUFFER_DATA;
        memcpy(pOutput->pBuffers[0].pvBuffer, bin, bin_len);
        ret = SEC_I_CONTINUE_NEEDED;
1157

1158 1159 1160 1161 1162 1163 1164 1165 1166
    }
    else
    {
        /* we expect a KK request from client */
        if(pInput == NULL)
        {
            ret = SEC_E_INCOMPLETE_MESSAGE;
            goto asc_end;
        }
1167

1168 1169 1170 1171 1172 1173
        if(pInput->cBuffers < 1)
        {
            ret = SEC_E_INCOMPLETE_MESSAGE;
            goto asc_end;
        }

1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
        if(!phContext)
        {
            ret = SEC_E_INVALID_HANDLE;
            goto asc_end;
        }

        helper = (PNegoHelper)phContext->dwLower;

        if(helper->mode != NTLM_SERVER)
        {
            ret = SEC_E_INVALID_HANDLE;
            goto asc_end;
        }

1188 1189 1190 1191
        if(pInput->pBuffers[0].cbBuffer > max_len)
        {
            ret = SEC_E_INVALID_TOKEN;
            goto asc_end;
1192 1193
        }
        else
1194 1195 1196 1197 1198 1199 1200 1201
            bin_len = pInput->pBuffers[0].cbBuffer;

        memcpy(bin, pInput->pBuffers[0].pvBuffer, bin_len);

        lstrcpynA(buffer, "KK ", max_len-1);

        if((ret = encodeBase64(bin, bin_len, buffer+3, max_len-3,
                    &buffer_len)) != SEC_E_OK)
1202
        {
1203 1204
            goto asc_end;
        }
1205

1206
        TRACE("Client sent: %s\n", debugstr_a(buffer));
1207

1208 1209 1210 1211 1212
        if((ret = run_helper(helper, buffer, max_len, &buffer_len)) !=
                    SEC_E_OK)
        {
            goto asc_end;
        }
1213

1214
        TRACE("Reply from ntlm_auth: %s\n", debugstr_a(buffer));
1215

1216 1217 1218 1219
        /* At this point, we get a NA if the user didn't authenticate, but a BH
         * if ntlm_auth could not connect to winbindd. Apart from running Wine
         * as root, there is no way to fix this for now, so just handle this as
         * a failed login. */
1220 1221 1222
        if(strncmp(buffer, "AF ", 3) != 0)
        {
            if(strncmp(buffer, "NA ", 3) == 0)
1223
            {
1224 1225
                ret = SEC_E_LOGON_DENIED;
                goto asc_end;
1226
            }
1227
            else
1228
            {
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
                size_t ntlm_pipe_err_len = strlen("BH NT_STATUS_ACCESS_DENIED");

                if( (buffer_len >= ntlm_pipe_err_len) &&
                    (strncmp(buffer, "BH NT_STATUS_ACCESS_DENIED",
                             ntlm_pipe_err_len) == 0))
                {
                    TRACE("Connection to winbindd failed\n");
                    ret = SEC_E_LOGON_DENIED;
                }
                else
                    ret = SEC_E_INTERNAL_ERROR;

1241
                goto asc_end;
1242 1243
            }
        }
1244
        pOutput->pBuffers[0].cbBuffer = 0;
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257

        TRACE("Getting negotiated flags\n");
        lstrcpynA(buffer, "GF", max_len - 1);
        if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
            goto asc_end;

        if(buffer_len < 3)
        {
            TRACE("No flags negotiated, or helper does not support GF command\n");
        }
        else
        {
            TRACE("Negotiated %s\n", debugstr_a(buffer));
1258 1259
            sscanf(buffer + 3, "%x", &(helper->neg_flags));
            TRACE("Stored 0x%08x as flags\n", helper->neg_flags);
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
        }

        TRACE("Getting session key\n");
        lstrcpynA(buffer, "GK", max_len - 1);
        if((ret = run_helper(helper, buffer, max_len, &buffer_len)) != SEC_E_OK)
            goto asc_end;

        if(buffer_len < 3)
            TRACE("Helper does not support GK command\n");
        else
        {
            if(strncmp(buffer, "BH ", 3) == 0)
            {
                TRACE("Helper sent %s\n", debugstr_a(buffer+3));
1274
                HeapFree(GetProcessHeap(), 0, helper->session_key);
1275
                helper->session_key = HeapAlloc(GetProcessHeap(), 0, 16);
1276 1277 1278 1279 1280
                if (!helper->session_key)
                {
                    ret = SEC_E_INSUFFICIENT_MEMORY;
                    goto asc_end;
                }
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
                /*FIXME: Generate the dummy session key = MD4(MD4(password))*/
                memset(helper->session_key, 0 , 16);
            }
            else if(strncmp(buffer, "GK ", 3) == 0)
            {
                if((ret = decodeBase64(buffer+3, buffer_len-3, bin, max_len, 
                                &bin_len)) != SEC_E_OK)
                {
                    TRACE("Failed to decode session key\n");
                }
                TRACE("Session key is %s\n", debugstr_a(buffer+3));
1292
                HeapFree(GetProcessHeap(), 0, helper->session_key);
1293
                helper->session_key = HeapAlloc(GetProcessHeap(), 0, 16);
1294 1295
                if(!helper->session_key)
                {
1296
                    ret = SEC_E_INSUFFICIENT_MEMORY;
1297 1298
                    goto asc_end;
                }
1299
                memcpy(helper->session_key, bin, 16);
1300 1301
            }
        }
1302 1303 1304
        helper->crypt.ntlm.a4i = SECUR32_arc4Alloc();
        SECUR32_arc4Init(helper->crypt.ntlm.a4i, helper->session_key, 16);
        helper->crypt.ntlm.seq_num = 0l;
1305
    }
1306 1307 1308 1309 1310

    phNewContext->dwUpper = ctxt_attr;
    phNewContext->dwLower = (ULONG_PTR)helper;

asc_end:
1311
    HeapFree(GetProcessHeap(), 0, want_flags);
1312 1313
    HeapFree(GetProcessHeap(), 0, buffer);
    HeapFree(GetProcessHeap(), 0, bin);
1314 1315 1316 1317 1318 1319 1320 1321 1322
    return ret;
}

/***********************************************************************
 *              CompleteAuthToken
 */
static SECURITY_STATUS SEC_ENTRY ntlm_CompleteAuthToken(PCtxtHandle phContext,
 PSecBufferDesc pToken)
{
1323
    /* We never need to call CompleteAuthToken anyway */
1324
    TRACE("%p %p\n", phContext, pToken);
1325 1326 1327 1328
    if (!phContext)
        return SEC_E_INVALID_HANDLE;
    
    return SEC_E_OK;
1329 1330 1331 1332 1333
}

/***********************************************************************
 *              DeleteSecurityContext
 */
1334
SECURITY_STATUS SEC_ENTRY ntlm_DeleteSecurityContext(PCtxtHandle phContext)
1335
{
1336
    PNegoHelper helper;
1337 1338

    TRACE("%p\n", phContext);
1339 1340 1341 1342 1343 1344 1345 1346 1347
    if (!phContext)
        return SEC_E_INVALID_HANDLE;

    helper = (PNegoHelper)phContext->dwLower;

    phContext->dwUpper = 0;
    phContext->dwLower = 0;

    SECUR32_arc4Cleanup(helper->crypt.ntlm.a4i);
1348 1349 1350 1351 1352 1353
    SECUR32_arc4Cleanup(helper->crypt.ntlm2.send_a4i);
    SECUR32_arc4Cleanup(helper->crypt.ntlm2.recv_a4i);
    HeapFree(GetProcessHeap(), 0, helper->crypt.ntlm2.send_sign_key);
    HeapFree(GetProcessHeap(), 0, helper->crypt.ntlm2.send_seal_key);
    HeapFree(GetProcessHeap(), 0, helper->crypt.ntlm2.recv_sign_key);
    HeapFree(GetProcessHeap(), 0, helper->crypt.ntlm2.recv_seal_key);
1354

1355 1356
    cleanup_helper(helper);

1357
    return SEC_E_OK;
1358 1359 1360 1361 1362
}

/***********************************************************************
 *              QueryContextAttributesW
 */
1363
SECURITY_STATUS SEC_ENTRY ntlm_QueryContextAttributesW(PCtxtHandle phContext,
1364
 ULONG ulAttribute, void *pBuffer)
1365
{
1366
    TRACE("%p %d %p\n", phContext, ulAttribute, pBuffer);
1367 1368 1369 1370
    if (!phContext)
        return SEC_E_INVALID_HANDLE;

    switch(ulAttribute)
1371
    {
1372 1373 1374 1375
#define _x(x) case (x) : FIXME(#x" stub\n"); break
        _x(SECPKG_ATTR_ACCESS_TOKEN);
        _x(SECPKG_ATTR_AUTHORITY);
        _x(SECPKG_ATTR_DCE_INFO);
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387
        case SECPKG_ATTR_FLAGS:
        {
            PSecPkgContext_Flags spcf = (PSecPkgContext_Flags)pBuffer;
            PNegoHelper helper = (PNegoHelper)phContext->dwLower;

            spcf->Flags = 0;
            if(helper->neg_flags & NTLMSSP_NEGOTIATE_SIGN)
                spcf->Flags |= ISC_RET_INTEGRITY;
            if(helper->neg_flags & NTLMSSP_NEGOTIATE_SEAL)
                spcf->Flags |= ISC_RET_CONFIDENTIALITY;
            return SEC_E_OK;
        }
1388 1389 1390 1391 1392 1393 1394 1395 1396
        _x(SECPKG_ATTR_KEY_INFO);
        _x(SECPKG_ATTR_LIFESPAN);
        _x(SECPKG_ATTR_NAMES);
        _x(SECPKG_ATTR_NATIVE_NAMES);
        _x(SECPKG_ATTR_NEGOTIATION_INFO);
        _x(SECPKG_ATTR_PACKAGE_INFO);
        _x(SECPKG_ATTR_PASSWORD_EXPIRY);
        _x(SECPKG_ATTR_SESSION_KEY);
        case SECPKG_ATTR_SIZES:
1397 1398 1399 1400 1401 1402 1403 1404
        {
            PSecPkgContext_Sizes spcs = (PSecPkgContext_Sizes)pBuffer;
            spcs->cbMaxToken = NTLM_MAX_BUF;
            spcs->cbMaxSignature = 16;
            spcs->cbBlockSize = 0;
            spcs->cbSecurityTrailer = 16;
            return SEC_E_OK;
        }
1405 1406 1407 1408
        _x(SECPKG_ATTR_STREAM_SIZES);
        _x(SECPKG_ATTR_TARGET_INFORMATION);
#undef _x
        default:
1409
            TRACE("Unknown value %d passed for ulAttribute\n", ulAttribute);
1410
    }
1411 1412

    return SEC_E_UNSUPPORTED_FUNCTION;
1413 1414 1415 1416 1417
}

/***********************************************************************
 *              QueryContextAttributesA
 */
1418
SECURITY_STATUS SEC_ENTRY ntlm_QueryContextAttributesA(PCtxtHandle phContext,
1419
 ULONG ulAttribute, void *pBuffer)
1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461
{
    return ntlm_QueryContextAttributesW(phContext, ulAttribute, pBuffer);
}

/***********************************************************************
 *              ImpersonateSecurityContext
 */
static SECURITY_STATUS SEC_ENTRY ntlm_ImpersonateSecurityContext(PCtxtHandle phContext)
{
    SECURITY_STATUS ret;

    TRACE("%p\n", phContext);
    if (phContext)
    {
        ret = SEC_E_UNSUPPORTED_FUNCTION;
    }
    else
    {
        ret = SEC_E_INVALID_HANDLE;
    }
    return ret;
}

/***********************************************************************
 *              RevertSecurityContext
 */
static SECURITY_STATUS SEC_ENTRY ntlm_RevertSecurityContext(PCtxtHandle phContext)
{
    SECURITY_STATUS ret;

    TRACE("%p\n", phContext);
    if (phContext)
    {
        ret = SEC_E_UNSUPPORTED_FUNCTION;
    }
    else
    {
        ret = SEC_E_INVALID_HANDLE;
    }
    return ret;
}

1462 1463 1464
/***********************************************************************
 *             ntlm_CreateSignature
 * As both MakeSignature and VerifySignature need this, but different keys
1465
 * are needed for NTLM2, the logic goes into a helper function.
1466 1467 1468 1469 1470
 * To ensure maximal reusability, we can specify the direction as NTLM_SEND for
 * signing/encrypting and NTLM_RECV for verfying/decrypting. When encrypting,
 * the signature is encrypted after the message was encrypted, so
 * CreateSignature shouldn't do it. In this case, encrypt_sig can be set to
 * false.
1471 1472
 */
static SECURITY_STATUS ntlm_CreateSignature(PNegoHelper helper, PSecBufferDesc pMessage,
1473
        int token_idx, SignDirection direction, BOOL encrypt_sig)
1474 1475 1476
{
    ULONG sign_version = 1;
    UINT i;
1477
    PBYTE sig;
1478 1479
    TRACE("%p, %p, %d, %d, %d\n", helper, pMessage, token_idx, direction,
            encrypt_sig);
1480 1481

    sig = pMessage->pBuffers[token_idx].pvBuffer;
1482

1483
    if(helper->neg_flags & NTLMSSP_NEGOTIATE_NTLM2 &&
1484
            helper->neg_flags & NTLMSSP_NEGOTIATE_SIGN)
1485
    {
1486 1487 1488 1489
        BYTE digest[16];
        BYTE seq_no[4];
        HMAC_MD5_CTX hmac_md5_ctx;

1490
        TRACE("Signing NTLM2 style\n");
1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518

        if(direction == NTLM_SEND)
        {
            seq_no[0] = (helper->crypt.ntlm2.send_seq_no >>  0) & 0xff;
            seq_no[1] = (helper->crypt.ntlm2.send_seq_no >>  8) & 0xff;
            seq_no[2] = (helper->crypt.ntlm2.send_seq_no >> 16) & 0xff;
            seq_no[3] = (helper->crypt.ntlm2.send_seq_no >> 24) & 0xff;

            ++(helper->crypt.ntlm2.send_seq_no);

            HMACMD5Init(&hmac_md5_ctx, helper->crypt.ntlm2.send_sign_key, 16);
        }
        else
        {
            seq_no[0] = (helper->crypt.ntlm2.recv_seq_no >>  0) & 0xff;
            seq_no[1] = (helper->crypt.ntlm2.recv_seq_no >>  8) & 0xff;
            seq_no[2] = (helper->crypt.ntlm2.recv_seq_no >> 16) & 0xff;
            seq_no[3] = (helper->crypt.ntlm2.recv_seq_no >> 24) & 0xff;

            ++(helper->crypt.ntlm2.recv_seq_no);

            HMACMD5Init(&hmac_md5_ctx, helper->crypt.ntlm2.recv_sign_key, 16);
        }

        HMACMD5Update(&hmac_md5_ctx, seq_no, 4);
        for( i = 0; i < pMessage->cBuffers; ++i )
        {
            if(pMessage->pBuffers[i].BufferType & SECBUFFER_DATA)
1519
                HMACMD5Update(&hmac_md5_ctx, pMessage->pBuffers[i].pvBuffer,
1520 1521 1522 1523 1524
                        pMessage->pBuffers[i].cbBuffer);
        }

        HMACMD5Final(&hmac_md5_ctx, digest);

1525
        if(encrypt_sig && helper->neg_flags & NTLMSSP_NEGOTIATE_KEY_EXCHANGE)
1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
        {
            if(direction == NTLM_SEND)
                SECUR32_arc4Process(helper->crypt.ntlm2.send_a4i, digest, 8);
            else
                SECUR32_arc4Process(helper->crypt.ntlm2.recv_a4i, digest, 8);
        }

        /* The NTLM2 signature is the sign version */
        sig[ 0] = (sign_version >>  0) & 0xff;
        sig[ 1] = (sign_version >>  8) & 0xff;
        sig[ 2] = (sign_version >> 16) & 0xff;
        sig[ 3] = (sign_version >> 24) & 0xff;
        /* The first 8 bytes of the digest */
        memcpy(sig+4, digest, 8);
        /* And the sequence number */
        memcpy(sig+12, seq_no, 4);

        pMessage->pBuffers[token_idx].cbBuffer = 16;

        return SEC_E_OK;
1546
    }
1547
    if(helper->neg_flags & NTLMSSP_NEGOTIATE_SIGN)
1548
    {
1549
        ULONG crc = 0U;
1550
        TRACE("Signing NTLM1 style\n");
1551 1552 1553 1554 1555 1556 1557 1558 1559

        for(i=0; i < pMessage->cBuffers; ++i)
        {
            if(pMessage->pBuffers[i].BufferType & SECBUFFER_DATA)
            {
                crc = ComputeCrc32(pMessage->pBuffers[i].pvBuffer,
                    pMessage->pBuffers[i].cbBuffer, crc);
            }
        }
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576

        sig[ 0] = (sign_version >>  0) & 0xff;
        sig[ 1] = (sign_version >>  8) & 0xff;
        sig[ 2] = (sign_version >> 16) & 0xff;
        sig[ 3] = (sign_version >> 24) & 0xff;
        memset(sig+4, 0, 4);
        sig[ 8] = (crc >>  0) & 0xff;
        sig[ 9] = (crc >>  8) & 0xff;
        sig[10] = (crc >> 16) & 0xff;
        sig[11] = (crc >> 24) & 0xff;
        sig[12] = (helper->crypt.ntlm.seq_num >>  0) & 0xff;
        sig[13] = (helper->crypt.ntlm.seq_num >>  8) & 0xff;
        sig[14] = (helper->crypt.ntlm.seq_num >> 16) & 0xff;
        sig[15] = (helper->crypt.ntlm.seq_num >> 24) & 0xff;

        ++(helper->crypt.ntlm.seq_num);

1577 1578
        if(encrypt_sig)
            SECUR32_arc4Process(helper->crypt.ntlm.a4i, sig+4, 12);
1579
        return SEC_E_OK;
1580
    }
1581

1582
    if(helper->neg_flags & NTLMSSP_NEGOTIATE_ALWAYS_SIGN || helper->neg_flags == 0)
1583
    {
1584
        TRACE("Creating a dummy signature.\n");
1585
        /* A dummy signature is 0x01 followed by 15 bytes of 0x00 */
1586 1587 1588
        memset(pMessage->pBuffers[token_idx].pvBuffer, 0, 16);
        memset(pMessage->pBuffers[token_idx].pvBuffer, 0x01, 1);
        pMessage->pBuffers[token_idx].cbBuffer = 16;
1589 1590 1591 1592
        return SEC_E_OK;
    }

    return SEC_E_UNSUPPORTED_FUNCTION;
1593 1594
}

1595 1596 1597
/***********************************************************************
 *              MakeSignature
 */
1598 1599
SECURITY_STATUS SEC_ENTRY ntlm_MakeSignature(PCtxtHandle phContext,
    ULONG fQOP, PSecBufferDesc pMessage, ULONG MessageSeqNo)
1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624
{
    PNegoHelper helper;
    int token_idx;

    TRACE("%p %d %p %d\n", phContext, fQOP, pMessage, MessageSeqNo);
    if (!phContext)
        return SEC_E_INVALID_HANDLE;

    if(fQOP)
        FIXME("Ignoring fQOP 0x%08x\n", fQOP);

    if(MessageSeqNo)
        FIXME("Ignoring MessageSeqNo\n");

    if(!pMessage || !pMessage->pBuffers || pMessage->cBuffers < 2)
        return SEC_E_INVALID_TOKEN;

    /* If we didn't find a SECBUFFER_TOKEN type buffer */
    if((token_idx = ntlm_GetTokenBufferIndex(pMessage)) == -1)
        return SEC_E_INVALID_TOKEN;

    if(pMessage->pBuffers[token_idx].cbBuffer < 16)
        return SEC_E_BUFFER_TOO_SMALL;

    helper = (PNegoHelper)phContext->dwLower;
1625
    TRACE("Negotiated flags are: 0x%08x\n", helper->neg_flags);
1626

1627
    return ntlm_CreateSignature(helper, pMessage, token_idx, NTLM_SEND, TRUE);
1628 1629
}

1630 1631 1632
/***********************************************************************
 *              VerifySignature
 */
1633 1634
SECURITY_STATUS SEC_ENTRY ntlm_VerifySignature(PCtxtHandle phContext,
    PSecBufferDesc pMessage, ULONG MessageSeqNo, PULONG pfQOP)
1635
{
1636 1637
    PNegoHelper helper;
    ULONG fQOP = 0;
1638
    UINT i;
1639
    int token_idx;
1640
    SECURITY_STATUS ret;
1641 1642 1643
    SecBufferDesc local_desc;
    PSecBuffer     local_buff;
    BYTE          local_sig[16];
1644

1645
    TRACE("%p %p %d %p\n", phContext, pMessage, MessageSeqNo, pfQOP);
1646 1647 1648
    if(!phContext)
        return SEC_E_INVALID_HANDLE;

1649 1650 1651
    if(!pMessage || !pMessage->pBuffers || pMessage->cBuffers < 2)
        return SEC_E_INVALID_TOKEN;

1652
    if((token_idx = ntlm_GetTokenBufferIndex(pMessage)) == -1)
1653 1654
        return SEC_E_INVALID_TOKEN;

1655
    if(pMessage->pBuffers[token_idx].cbBuffer < 16)
1656 1657 1658 1659 1660 1661
        return SEC_E_BUFFER_TOO_SMALL;

    if(MessageSeqNo)
        FIXME("Ignoring MessageSeqNo\n");

    helper = (PNegoHelper)phContext->dwLower;
1662
    TRACE("Negotiated flags: 0x%08x\n", helper->neg_flags);
1663

1664
    local_buff = HeapAlloc(GetProcessHeap(), 0, pMessage->cBuffers * sizeof(SecBuffer));
1665

1666 1667 1668
    local_desc.ulVersion = SECBUFFER_VERSION;
    local_desc.cBuffers = pMessage->cBuffers;
    local_desc.pBuffers = local_buff;
1669

1670
    for(i=0; i < pMessage->cBuffers; ++i)
1671
    {
1672
        if(pMessage->pBuffers[i].BufferType == SECBUFFER_TOKEN)
1673
        {
1674 1675 1676
            local_buff[i].BufferType = SECBUFFER_TOKEN;
            local_buff[i].cbBuffer = 16;
            local_buff[i].pvBuffer = local_sig;
1677 1678 1679
        }
        else
        {
1680 1681 1682
            local_buff[i].BufferType = pMessage->pBuffers[i].BufferType;
            local_buff[i].cbBuffer = pMessage->pBuffers[i].cbBuffer;
            local_buff[i].pvBuffer = pMessage->pBuffers[i].pvBuffer;
1683 1684 1685
        }
    }

1686
    if((ret = ntlm_CreateSignature(helper, &local_desc, token_idx, NTLM_RECV, TRUE)) != SEC_E_OK)
1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699
        return ret;

    if(memcmp(((PBYTE)local_buff[token_idx].pvBuffer) + 8,
                ((PBYTE)pMessage->pBuffers[token_idx].pvBuffer) + 8, 8))
        ret = SEC_E_MESSAGE_ALTERED;
    else
        ret = SEC_E_OK;

    HeapFree(GetProcessHeap(), 0, local_buff);
    pfQOP = &fQOP;

    return ret;

1700 1701
}

1702 1703 1704
/***********************************************************************
 *             FreeCredentialsHandle
 */
1705
SECURITY_STATUS SEC_ENTRY ntlm_FreeCredentialsHandle(PCredHandle phCredential)
1706 1707
{
    SECURITY_STATUS ret;
1708

1709
    if(phCredential){
1710
        PNtlmCredentials ntlm_cred = (PNtlmCredentials) phCredential->dwLower;
1711 1712
        phCredential->dwUpper = 0;
        phCredential->dwLower = 0;
1713 1714 1715 1716 1717
        if (ntlm_cred->password)
            memset(ntlm_cred->password, 0, ntlm_cred->pwlen);
        HeapFree(GetProcessHeap(), 0, ntlm_cred->password);
        HeapFree(GetProcessHeap(), 0, ntlm_cred->username_arg);
        HeapFree(GetProcessHeap(), 0, ntlm_cred->domain_arg);
1718
        HeapFree(GetProcessHeap(), 0, ntlm_cred);
1719 1720 1721 1722 1723 1724 1725
        ret = SEC_E_OK;
    }
    else
        ret = SEC_E_OK;
    
    return ret;
}
1726

1727 1728 1729
/***********************************************************************
 *             EncryptMessage
 */
1730 1731
SECURITY_STATUS SEC_ENTRY ntlm_EncryptMessage(PCtxtHandle phContext,
    ULONG fQOP, PSecBufferDesc pMessage, ULONG MessageSeqNo)
1732
{
1733
    PNegoHelper helper;
1734
    int token_idx, data_idx;
1735

1736
    TRACE("(%p %d %p %d)\n", phContext, fQOP, pMessage, MessageSeqNo);
1737 1738 1739 1740

    if(!phContext)
        return SEC_E_INVALID_HANDLE;

1741 1742 1743 1744 1745 1746
    if(fQOP)
        FIXME("Ignoring fQOP\n");

    if(MessageSeqNo)
        FIXME("Ignoring MessageSeqNo\n");

1747
    if(!pMessage || !pMessage->pBuffers || pMessage->cBuffers < 2)
1748 1749
        return SEC_E_INVALID_TOKEN;

1750
    if((token_idx = ntlm_GetTokenBufferIndex(pMessage)) == -1)
1751 1752
        return SEC_E_INVALID_TOKEN;

1753 1754 1755
    if((data_idx = ntlm_GetDataBufferIndex(pMessage)) ==-1 )
        return SEC_E_INVALID_TOKEN;

1756
    if(pMessage->pBuffers[token_idx].cbBuffer < 16)
1757 1758 1759 1760
        return SEC_E_BUFFER_TOO_SMALL;

    helper = (PNegoHelper) phContext->dwLower;

1761 1762 1763 1764 1765
    if(helper->neg_flags & NTLMSSP_NEGOTIATE_NTLM2 && 
            helper->neg_flags & NTLMSSP_NEGOTIATE_SEAL)
    { 
        ntlm_CreateSignature(helper, pMessage, token_idx, NTLM_SEND, FALSE);
        SECUR32_arc4Process(helper->crypt.ntlm2.send_a4i,
1766
                pMessage->pBuffers[data_idx].pvBuffer,
1767
                pMessage->pBuffers[data_idx].cbBuffer);
1768 1769 1770 1771

        if(helper->neg_flags & NTLMSSP_NEGOTIATE_KEY_EXCHANGE)
            SECUR32_arc4Process(helper->crypt.ntlm2.send_a4i,
                    ((BYTE *)pMessage->pBuffers[token_idx].pvBuffer)+4, 8);
1772 1773 1774
    }
    else
    {
1775 1776
        PBYTE sig;
        ULONG save_flags;
1777

1778 1779 1780 1781 1782 1783
        /* EncryptMessage always produces real signatures, so make sure
         * NTLMSSP_NEGOTIATE_SIGN is set*/
        save_flags = helper->neg_flags;
        helper->neg_flags |= NTLMSSP_NEGOTIATE_SIGN;
        ntlm_CreateSignature(helper, pMessage, token_idx, NTLM_SEND, FALSE);
        helper->neg_flags = save_flags;
1784

1785
        sig = pMessage->pBuffers[token_idx].pvBuffer;
1786

1787 1788 1789
        SECUR32_arc4Process(helper->crypt.ntlm.a4i,
                pMessage->pBuffers[data_idx].pvBuffer,
                pMessage->pBuffers[data_idx].cbBuffer);
1790 1791 1792 1793 1794 1795
        SECUR32_arc4Process(helper->crypt.ntlm.a4i, sig+4, 12);

        if(helper->neg_flags & NTLMSSP_NEGOTIATE_ALWAYS_SIGN || helper->neg_flags == 0)
            memset(sig+4, 0, 4);
    }
    return SEC_E_OK;
1796 1797 1798 1799 1800
}

/***********************************************************************
 *             DecryptMessage
 */
1801 1802
SECURITY_STATUS SEC_ENTRY ntlm_DecryptMessage(PCtxtHandle phContext,
    PSecBufferDesc pMessage, ULONG MessageSeqNo, PULONG pfQOP)
1803
{
1804 1805
    SECURITY_STATUS ret;
    ULONG ntlmssp_flags_save;
1806
    PNegoHelper helper;
1807
    int token_idx, data_idx;
1808
    TRACE("(%p %p %d %p)\n", phContext, pMessage, MessageSeqNo, pfQOP);
1809 1810 1811 1812

    if(!phContext)
        return SEC_E_INVALID_HANDLE;

1813 1814 1815
    if(MessageSeqNo)
        FIXME("Ignoring MessageSeqNo\n");

1816 1817 1818
    if(!pMessage || !pMessage->pBuffers || pMessage->cBuffers < 2)
        return SEC_E_INVALID_TOKEN;

1819
    if((token_idx = ntlm_GetTokenBufferIndex(pMessage)) == -1)
1820 1821
        return SEC_E_INVALID_TOKEN;

1822 1823 1824
    if((data_idx = ntlm_GetDataBufferIndex(pMessage)) ==-1)
        return SEC_E_INVALID_TOKEN;

1825
    if(pMessage->pBuffers[token_idx].cbBuffer < 16)
1826 1827 1828 1829
        return SEC_E_BUFFER_TOO_SMALL;

    helper = (PNegoHelper) phContext->dwLower;

1830
    if(helper->neg_flags & NTLMSSP_NEGOTIATE_NTLM2 && helper->neg_flags & NTLMSSP_NEGOTIATE_SEAL)
1831
    {
1832
        SECUR32_arc4Process(helper->crypt.ntlm2.recv_a4i,
1833 1834
                pMessage->pBuffers[data_idx].pvBuffer,
                pMessage->pBuffers[data_idx].cbBuffer);
1835 1836 1837 1838
    }
    else
    {
        SECUR32_arc4Process(helper->crypt.ntlm.a4i,
1839 1840
                pMessage->pBuffers[data_idx].pvBuffer,
                pMessage->pBuffers[data_idx].cbBuffer);
1841 1842
    }

1843 1844 1845 1846 1847 1848 1849 1850 1851 1852
    /* Make sure we use a session key for the signature check, EncryptMessage
     * always does that, even in the dummy case */
    ntlmssp_flags_save = helper->neg_flags;

    helper->neg_flags |= NTLMSSP_NEGOTIATE_SIGN;
    ret = ntlm_VerifySignature(phContext, pMessage, MessageSeqNo, pfQOP);

    helper->neg_flags = ntlmssp_flags_save;

    return ret;
1853 1854
}

1855
static const SecurityFunctionTableA ntlmTableA = {
1856 1857 1858 1859
    1,
    NULL,   /* EnumerateSecurityPackagesA */
    ntlm_QueryCredentialsAttributesA,   /* QueryCredentialsAttributesA */
    ntlm_AcquireCredentialsHandleA,     /* AcquireCredentialsHandleA */
1860
    ntlm_FreeCredentialsHandle,         /* FreeCredentialsHandle */
1861 1862 1863 1864 1865
    NULL,   /* Reserved2 */
    ntlm_InitializeSecurityContextA,    /* InitializeSecurityContextA */
    ntlm_AcceptSecurityContext,         /* AcceptSecurityContext */
    ntlm_CompleteAuthToken,             /* CompleteAuthToken */
    ntlm_DeleteSecurityContext,         /* DeleteSecurityContext */
1866
    NULL,  /* ApplyControlToken */
1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880
    ntlm_QueryContextAttributesA,       /* QueryContextAttributesA */
    ntlm_ImpersonateSecurityContext,    /* ImpersonateSecurityContext */
    ntlm_RevertSecurityContext,         /* RevertSecurityContext */
    ntlm_MakeSignature,                 /* MakeSignature */
    ntlm_VerifySignature,               /* VerifySignature */
    FreeContextBuffer,                  /* FreeContextBuffer */
    NULL,   /* QuerySecurityPackageInfoA */
    NULL,   /* Reserved3 */
    NULL,   /* Reserved4 */
    NULL,   /* ExportSecurityContext */
    NULL,   /* ImportSecurityContextA */
    NULL,   /* AddCredentialsA */
    NULL,   /* Reserved8 */
    NULL,   /* QuerySecurityContextToken */
1881 1882
    ntlm_EncryptMessage,                /* EncryptMessage */
    ntlm_DecryptMessage,                /* DecryptMessage */
1883 1884 1885
    NULL,   /* SetContextAttributesA */
};

1886
static const SecurityFunctionTableW ntlmTableW = {
1887 1888 1889 1890
    1,
    NULL,   /* EnumerateSecurityPackagesW */
    ntlm_QueryCredentialsAttributesW,   /* QueryCredentialsAttributesW */
    ntlm_AcquireCredentialsHandleW,     /* AcquireCredentialsHandleW */
1891
    ntlm_FreeCredentialsHandle,         /* FreeCredentialsHandle */
1892 1893 1894 1895 1896
    NULL,   /* Reserved2 */
    ntlm_InitializeSecurityContextW,    /* InitializeSecurityContextW */
    ntlm_AcceptSecurityContext,         /* AcceptSecurityContext */
    ntlm_CompleteAuthToken,             /* CompleteAuthToken */
    ntlm_DeleteSecurityContext,         /* DeleteSecurityContext */
1897
    NULL,  /* ApplyControlToken */
1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911
    ntlm_QueryContextAttributesW,       /* QueryContextAttributesW */
    ntlm_ImpersonateSecurityContext,    /* ImpersonateSecurityContext */
    ntlm_RevertSecurityContext,         /* RevertSecurityContext */
    ntlm_MakeSignature,                 /* MakeSignature */
    ntlm_VerifySignature,               /* VerifySignature */
    FreeContextBuffer,                  /* FreeContextBuffer */
    NULL,   /* QuerySecurityPackageInfoW */
    NULL,   /* Reserved3 */
    NULL,   /* Reserved4 */
    NULL,   /* ExportSecurityContext */
    NULL,   /* ImportSecurityContextW */
    NULL,   /* AddCredentialsW */
    NULL,   /* Reserved8 */
    NULL,   /* QuerySecurityContextToken */
1912 1913
    ntlm_EncryptMessage,                /* EncryptMessage */
    ntlm_DecryptMessage,                /* DecryptMessage */
1914 1915 1916
    NULL,   /* SetContextAttributesW */
};

1917 1918 1919 1920 1921 1922 1923 1924 1925
#define NTLM_COMMENT \
   { 'N', 'T', 'L', 'M', ' ', \
     'S', 'e', 'c', 'u', 'r', 'i', 't', 'y', ' ', \
     'P', 'a', 'c', 'k', 'a', 'g', 'e', 0}

static CHAR ntlm_comment_A[] = NTLM_COMMENT;
static WCHAR ntlm_comment_W[] = NTLM_COMMENT;

#define NTLM_NAME {'N', 'T', 'L', 'M', 0}
1926

1927 1928 1929 1930 1931
static char ntlm_name_A[] = NTLM_NAME;
static WCHAR ntlm_name_W[] = NTLM_NAME;

/* According to Windows, NTLM has the following capabilities.  */
#define CAPS ( \
1932 1933 1934 1935 1936 1937 1938 1939 1940 1941
    SECPKG_FLAG_INTEGRITY  | \
    SECPKG_FLAG_PRIVACY    | \
    SECPKG_FLAG_TOKEN_ONLY | \
    SECPKG_FLAG_CONNECTION | \
    SECPKG_FLAG_MULTI_REQUIRED    | \
    SECPKG_FLAG_IMPERSONATION     | \
    SECPKG_FLAG_ACCEPT_WIN32_NAME | \
    SECPKG_FLAG_NEGOTIABLE        | \
    SECPKG_FLAG_LOGON             | \
    SECPKG_FLAG_RESTRICTED_TOKENS )
1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959

static const SecPkgInfoW infoW = {
    CAPS,
    1,
    RPC_C_AUTHN_WINNT,
    NTLM_MAX_BUF,
    ntlm_name_W,
    ntlm_comment_W
};

static const SecPkgInfoA infoA = {
    CAPS,
    1,
    RPC_C_AUTHN_WINNT,
    NTLM_MAX_BUF,
    ntlm_name_A,
    ntlm_comment_A
};
1960

1961 1962
SecPkgInfoA *ntlm_package_infoA = (SecPkgInfoA *)&infoA;
SecPkgInfoW *ntlm_package_infoW = (SecPkgInfoW *)&infoW;
1963

1964
void SECUR32_initNTLMSP(void)
1965
{
1966
    PNegoHelper helper;
1967
    static CHAR version[] = "--version";
1968 1969

    SEC_CHAR *args[] = {
1970 1971
        ntlm_auth,
        version,
1972 1973
        NULL };

1974
    if(fork_helper(&helper, ntlm_auth, args) != SEC_E_OK)
1975
        helper = NULL;
1976 1977 1978
    else
        check_version(helper);

1979 1980 1981 1982 1983 1984 1985
    if( helper &&
        ((helper->major >  MIN_NTLM_AUTH_MAJOR_VERSION) ||
         (helper->major == MIN_NTLM_AUTH_MAJOR_VERSION  &&
          helper->minor >  MIN_NTLM_AUTH_MINOR_VERSION) ||
         (helper->major == MIN_NTLM_AUTH_MAJOR_VERSION  &&
          helper->minor == MIN_NTLM_AUTH_MINOR_VERSION  &&
          helper->micro >= MIN_NTLM_AUTH_MICRO_VERSION)) )
1986
    {
1987
        SecureProvider *provider = SECUR32_addProvider(&ntlmTableA, &ntlmTableW, NULL);
1988
        SECUR32_addPackages(provider, 1L, ntlm_package_infoA, ntlm_package_infoW);
1989
    }
1990 1991
    else
    {
1992 1993 1994 1995 1996 1997 1998
        ERR_(winediag)("%s was not found or is outdated. "
                       "Make sure that ntlm_auth >= %d.%d.%d is in your path. "
                       "Usually, you can find it in the winbind package of your distribution.\n",
                       ntlm_auth,
                       MIN_NTLM_AUTH_MAJOR_VERSION,
                       MIN_NTLM_AUTH_MINOR_VERSION,
                       MIN_NTLM_AUTH_MICRO_VERSION);
1999

2000
    }
2001
    cleanup_helper(helper);
2002
}