📄 ntlmauth.cpp
字号:
/*____________________________________________________________________________*\
Copyright (c) 1997-2000 John Roy, Holger Zimmermann. All rights reserved.
These sources, libraries and applications are
FREE FOR COMMERCIAL AND NON-COMMERCIAL USE
as long as the following conditions are adhered to.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHORS OR ITS CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
*____________________________________________________________________________*|
*
* $Source: /cvsroot/pi3web/Pi3Web_200/Source/HTTP/NtlmAuth.cpp,v $
* $Date: 2003/05/13 18:42:03 $
*
Description:
NTLM authentication module for Windows NT.
\*____________________________________________________________________________*/
/* $SourceTop:$ */
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <iostream.h>
#if WIN32
#include <windows.h>
#define SECURITY_WIN32
#define WIN32_CHICAGO
#include "sspi.h"
#include "issperr.h"
#endif // WIN32
#include "HandBase.h"
#include "PIStrStr.h"
#include "PIString.h"
#include "Pi3API.h"
#include "PiAPI.h"
#include "uuencode.h"
#if WIN32
/*____________________________________________________________________________*\
*
Description:
\*____________________________________________________________________________*/
/*
#define D { cerr << __FILE__ << ", " << __LINE__ << endl; }
*/
#define D
/*____________________________________________________________________________*\
*
Description:
\*____________________________________________________________________________*/
#define KEY_CONF_REALM "Realm"
#define KEY_INT_CONVSTATE "NtlmConvState"
#define NTLM_AUTH_TYPE "NTLM"
#define CS_HTTP_CHALLENGE 0
#define CS_NTLM_CHALLENGE 1
#define CS_NTLM_RESPONSE 2
/*____________________________________________________________________________*\
*
Description:
Documentation
\*____________________________________________________________________________*/
#if 0
/*
** HTML documentation for this handler
*/
/*___+++HTMLDOC_BEGIN+++___*/
Name:
NtlmAuth
Description:
Provide NTLM (challenge response) authentication. Use with Win32 only.
Options:
<H5>Overview</H5>
<TABLE BORDER=1>
<TH>Option
<TH>Default
<TH>Values
<TH>Short Description
<TH>Example(s)
<TR>
<TD>Realm
<TD>+
<TD>A string
<TD>Realm to authenticate
<TD>Realm="Admin"
</TABLE>
<STRONG>-</STRONG> in the <IT>default</IT> indicates no default<BR>
<STRONG>+</STRONG> in the <IT>default</IT> indicates the field is mandatory<BR>
<H4>Description of Options</H4>
<H5>
Realm
</H5>
Realm to be authenticated by this handler.
Phase:
CHECKAUTH
Returns:
PIAPI_COMPLETED if authentication passed. INT_REDIRECT if the
status was set to 401 to challenge, PIAPI_CONTINUE if this
handler choose to take no action and PIAPI_ERROR if this handler
was invoked for a phase other than CHECKAUTH.
Note:
Example:
<PRE>
<Object>
Name NtlmAuth
Class NtlmAuthClass
</Object>
<Object>
...
Handle NtlmAuth
...
</Object>
</PRE>
/*___+++HTMLDOC_END+++___*/
#endif
// Change the following define statement to use "Kerberos"
// For Windows 2000, it could also be "Negotiate" to choose the best
// possible package available to both client and server.
#define PACKAGE_NAME "NTLM"
// #define NT_DLL_NAME "secur32.dll"
// #define TOKEN_SOURCE_NAME "Pi3Web_NtlmAuth"
#define wVerRequested 0x0101
// #include "security.h"
/*____________________________________________________________________________*\
*
Class:
Description:
\*____________________________________________________________________________*/
class NtlmAuth : public HandlerBaseHTTP
{
private:
PIString sRealm;
PBYTE g_pInBuf;
PBYTE g_pOutBuf;
BOOL _fHaveCredHandle;
BOOL _fHaveCtxtHandle;
DWORD g_cbMaxToken;
TimeStamp Lifetime;
HINSTANCE g_hLib;
PSecurityFunctionTable g_pFuncs;
CredHandle _hcred;
SecHandle _hctxt;
const char *pfkConvState; /* Lookup key for the conversation state */
BOOL InitPackage ( PIOStrStream os )
{
OSVERSIONINFO VerInfo;
CHAR lpszDLL[MAX_PATH];
FARPROC pInit;
SECURITY_STATUS ss;
PSecPkgInfo pkgInfo;
ULONG cPackages;
SecPkgInfo *ppPackageInfo;
//
// Find out which security DLL to use, depending on
// whether we are on NT or Win95
//
VerInfo.dwOSVersionInfoSize = sizeof( OSVERSIONINFO );
if ( !GetVersionEx( &VerInfo )) // If this fails, something has gone wrong
{
os << "Unable to retrieve version info." << ends;
return FALSE;
}
if ( VerInfo.dwPlatformId == VER_PLATFORM_WIN32_NT )
{
strcpy( lpszDLL, "security.dll" );
}
else if ( VerInfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS )
{
strcpy( lpszDLL, "secur32.dll" );
}
else
{
os << "Unknown or invalid Platform-ID." << ends;
return FALSE;
};
//--------------------------------------------------------------------
// Load the SSPI Library Load and initialize a security package.
if ( !(g_hLib = LoadLibrary( lpszDLL )))
{
os << "Could not load the dll '" << lpszDLL << "'." << ends;
return FALSE;
};
if ( !(pInit = GetProcAddress( g_hLib, SECURITY_ENTRYPOINT )))
{
os << "Could not get security initialization routine." << ends;
return FALSE;
};
if ( !(g_pFuncs = (PSecurityFunctionTable) pInit()))
{
os << "Could not initialize the security package." << ends;
return FALSE;
};
//--------------------------------------------------------------------
// List the available security packages.
ss = g_pFuncs->EnumerateSecurityPackages(
&cPackages,
&ppPackageInfo );
if ( !SEC_SUCCESS(ss) )
{
os << "Could not list available security packages." << ends;
return FALSE;
};
//--------------------------------------------------------------------
// Query the security package for the maximum token length..
ss = g_pFuncs->QuerySecurityPackageInfo (PACKAGE_NAME, &pkgInfo);
if ( !(SEC_SUCCESS(ss)) )
{
os << "Could not query selected package information." << ends;
return FALSE;
};
g_cbMaxToken = pkgInfo->cbMaxToken;
g_pFuncs->FreeContextBuffer (pkgInfo);
ss = g_pFuncs->AcquireCredentialsHandle (
NULL, // Use the default principal
PACKAGE_NAME,
SECPKG_CRED_INBOUND,
NULL, // Use the current LOGON id
NULL,
NULL,
NULL,
&_hcred,
&Lifetime );
if ( SEC_SUCCESS (ss) )
{
_fHaveCredHandle = TRUE;
}
else
{
os << "Could not acquire credentials handle." << ends;
return FALSE;
};
return TRUE;
};
BOOL ResetConversation( PIHTTP *pPIHTTP )
{
PIDB_replace( pPIHTTP->pConnectionDB, PIDBTYPE_OPAQUE, pfkConvState,
(void *)CS_HTTP_CHALLENGE, PIDBFLAG_FASTKEY );
if ( _fHaveCtxtHandle )
{
SECURITY_STATUS ss;
ss = g_pFuncs->DeleteSecurityContext( &_hctxt );
};
_fHaveCtxtHandle = FALSE;
return TRUE;
};
//--------------------------------------------------------------------
// Define RevertContext.
// Revert to the original server context.
// Return TRUE is successful, otherwise, FALSE.
BOOL RevertContext (DWORD dwKey)
{
SECURITY_STATUS ss;
ss = g_pFuncs->RevertSecurityContext( &_hctxt );
if (!(SEC_SUCCESS(ss)))
{
// HANDLE_ERROR("Revert to original context failed.");
};
return(TRUE);
};
protected:
int Parameter( const char *pVariable, const char *pValue,
const char *pWhere )
{
assert( pVariable && pValue );
PIOStrStream os;
os << pWhere << "NtlmAuth: ";
if ( !PIUtil_stricmp( pVariable, KEY_CONF_REALM ) )
{
sRealm = (const char *)pValue;
if (!InitPackage( os ))
{
os << "Security package not initialized." << ends;
CONFIG_ERR( Object(), os.str() );
return 0;
}
else
{
g_pOutBuf = (PBYTE)PIUtil_malloc( g_cbMaxToken );
g_pInBuf = (PBYTE)PIUtil_malloc( g_cbMaxToken );
};
}
else
{
os << "Unknown directive '" << pVariable << "'" << ends;
CONFIG_ERR( Object(), os.str() );
return 0;
};
return 1;
};
public:
NtlmAuth( PIObject *pObject, int iArgc, const char *ppArgv[] )
: HandlerBaseHTTP( pObject ),
sRealm( 0 ),
g_pOutBuf( NULL ),
g_pInBuf( NULL ),
_fHaveCredHandle( FALSE ),
_fHaveCtxtHandle( FALSE ),
g_cbMaxToken( 0 ),
pfkConvState( PIDB_getFastKey( KEY_INT_CONVSTATE, PIDBTYPE_STRING ))
{
ReadParameters( iArgc, ppArgv );
};
~NtlmAuth()
{
if ( _fHaveCredHandle )
{
g_pFuncs->FreeCredentialHandle( &_hcred );
};
if ( g_pOutBuf ) PIUtil_free( g_pOutBuf );
if ( g_pInBuf ) PIUtil_free( g_pInBuf );
};
int Handle( int iPhase, PIHTTP &tPIHTTP, PIIOBuffer &tB )
{
int iConvState = CS_HTTP_CHALLENGE;
#define HANDLE_ERROR( code, where ) \
if ( code ) { \
HTTPCore_logError( &tPIHTTP, \
"NtlmAuth: SSPI error no %Xh in '%s'.", code, where ); \
} else { \
HTTPCore_logError( &tPIHTTP, \
"NtlmAuth: Error occured in SSPI: %s", where ); \
}; \
ResetConversation( &tPIHTTP ); \
return HTTPUtil_doHTTPError( &tPIHTTP, ST_INTERNALERROR );
#define HANDLE_REDIR \
if ( void *pLength = PIDB_lookup( tPIHTTP.pRequestDB, PIDBTYPE_RFC822, \
KEY_HTTP_CONTENTLENGTH, 0 )) { \
int iLen; \
const char *pBuf = PIIOBuffer_read( &tB, &iLen ); \
int toRead = atoi((const char *)pLength) - iLen; \
while( toRead ) { \
pBuf = PIIOBuffer_read( &tB, &iLen ); \
toRead -= iLen; \
} \
} \
tPIHTTP.iStatus = ST_UNAUTHORIZED; \
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -