2012年7月15日星期日
StdRegProv.Vbs
'这是一篇远程操作注册表的脚本.在已知ip,username,password的情况下.
'本文参考,改编自:http://www.44342.com/vbscript-f902-t8710-p1.htm
'用c++用了两天的时间,获取的内容却为为空,用脚本2分钟搞定.
'made at 2012.07.15
On Error Resume Next '相当于编译语言的异常处理.
Set objLocator = CreateObject("WbemScripting.SWbemLocator")
Set objService = objLocator.ConnectServer("10.101.0.133", "Root\DEFAULT","administrator", "123456")
Set objRegistry = objService.Get("StdRegProv")
strKeyPath = "SOFTWARE\Microsoft\Windows NT\CurrentVersion"
strValueName = "ProductName"
const HKEY_LOCAL_MACHINE = &H80000002
objRegistry.GetStringValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,strValue
WScript.Echo strValue
strValueName = "InstallDate"
objRegistry.GetDWORDValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,strValue
WScript.Echo strValue
'made by correy.
2012年7月7日星期六
Win32_QuickFixEngineering.Vbs
'好久没有写脚本了.
'这是在已知ip,域名,用户名,密码的情况下通过wmi获取远程电脑上的补丁的信息.
'made at 2012.07.07
'email:kouleguan at hotmail dot com
'homepage:http://correy.webs.com
On Error Resume Next
strComputer = "10.101.0.133"
Set objSWbemLocator = CreateObject("WbemScripting.SWbemLocator")
Set objSWbemServices = objSWbemLocator.ConnectServer(strComputer, "root\cimv2", "administrator", "123456", , "ntlmdomain:dp-correy-2003")
Set colSwbemObjectSet = objSWbemServices.ExecQuery("Select * from Win32_QuickFixEngineering")
For Each objItem in colSwbemObjectSet
Wscript.Echo "//////////////////////////////////////////////////////////////////////////"
Wscript.Echo "HotFixID: " & objItem.HotFixID '此值是"File 1"时,下面的就是kbXXXXXXXX,并且出重复.
Wscript.Echo "ServicePackInEffect: " & objItem.ServicePackInEffect
Next
'made by correy.
2012年7月5日星期四
LookupAccountName.Cpp
/*
sid一个神秘的东西,本想是获取或者枚举用户和它的关系.
这里有两个从微软搬过来的函数,
一个是从句柄获得sid,这个好像有问题,难道是我使用的问题.
一个是从(用户)名字获取sid.这个经试验是好的.
这里主要用了两个函数:GetTokenInformation,LookupAccountNameW
因为用GetTokenInformation的函数获取的东西好像有点问题,所以此文就命名为:LookupAccountName.Cpp.
*/
#include "stdafx.h"
#include <windows.h>
#include "D:\Program Files\Microsoft Visual Studio 9.0\SmartDevices\SDK\Smartphone2003\Include\mq.h"
#include <Sddl.h>
#pragma comment(lib, "advapi32.lib")
//http://msdn.microsoft.com/en-us/library/windows/desktop/aa446670(v=vs.85).aspx
BOOL GetLogonSID (HANDLE hToken, PSID *ppsid)
{
BOOL bSuccess = FALSE;
DWORD dwIndex;
DWORD dwLength = 0;
PTOKEN_GROUPS ptg = NULL;
if (NULL == ppsid)// Verify the parameter passed in is not NULL.
goto Cleanup;
if (!GetTokenInformation(// Get required buffer size and allocate the TOKEN_GROUPS buffer.
hToken, // handle to the access token
TokenGroups, // get information about the token's groups
(LPVOID) ptg, // pointer to TOKEN_GROUPS buffer
0, // size of buffer
&dwLength // receives required buffer size
))
{
if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
goto Cleanup;
ptg = (PTOKEN_GROUPS)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, dwLength);
if (ptg == NULL)
goto Cleanup;
}
if (!GetTokenInformation(hToken,TokenGroups,(LPVOID) ptg,dwLength,&dwLength)) {// Get the token group information from the access token.
goto Cleanup;
}
// Loop through the groups to find the logon SID.
for (dwIndex = 0; dwIndex < ptg->GroupCount; dwIndex++) //这个没有大括号.
if ((ptg->Groups[dwIndex].Attributes & SE_GROUP_LOGON_ID) == SE_GROUP_LOGON_ID)
{ // Found the logon SID; make a copy of it.
dwLength = GetLengthSid(ptg->Groups[dwIndex].Sid);
*ppsid = (PSID) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwLength);
if (*ppsid == NULL)
goto Cleanup;
if (!CopySid(dwLength, *ppsid, ptg->Groups[dwIndex].Sid))
{
HeapFree(GetProcessHeap(), 0, (LPVOID)*ppsid);
goto Cleanup;
}
break;
}
bSuccess = TRUE;
Cleanup:
if (ptg != NULL)// Free the buffer for the token groups.
HeapFree(GetProcessHeap(), 0, (LPVOID)ptg);
return bSuccess;
}
//这个不要了.
//VOID FreeLogonSID (PSID *ppsid)
//{
// HeapFree(GetProcessHeap(), 0, (LPVOID)*ppsid);
//}
//http://msdn.microsoft.com/en-us/library/windows/desktop/ms707085(v=vs.85).aspx
//还有一个函数:CreateQSecDescriptor
HRESULT GetSid(LPCWSTR wszAccName,PSID * ppSid) //此函数,还可以精简,我没有精简.
{
if (wszAccName == NULL || ppSid == NULL) {// Validate the input parameters.
return MQ_ERROR_INVALID_PARAMETER;
}
// Create buffers that may be large enough.If a buffer is too small, the count parameter will be set to the size needed.
const DWORD INITIAL_SIZE = 32;
DWORD cbSid = 0;
DWORD dwSidBufferSize = INITIAL_SIZE;
DWORD cchDomainName = 0;
DWORD dwDomainBufferSize = INITIAL_SIZE;
WCHAR * wszDomainName = NULL;
SID_NAME_USE eSidType;
DWORD dwErrorCode = 0;
HRESULT hr = MQ_OK;
*ppSid = (PSID) new BYTE[dwSidBufferSize];// Create buffers for the SID and the domain name.
if (*ppSid == NULL) {
return MQ_ERROR_INSUFFICIENT_RESOURCES;
}
memset(*ppSid, 0, dwSidBufferSize);
wszDomainName = new WCHAR[dwDomainBufferSize];
if (wszDomainName == NULL) {
return MQ_ERROR_INSUFFICIENT_RESOURCES;
}
memset(wszDomainName, 0, dwDomainBufferSize*sizeof(WCHAR));
for ( ; ; )// Obtain the SID for the account name passed.
{ // Set the count variables to the buffer sizes and retrieve the SID.
cbSid = dwSidBufferSize;
cchDomainName = dwDomainBufferSize;
if (LookupAccountNameW(
NULL, // Computer name. NULL for the local computer
wszAccName,
*ppSid, // Pointer to the SID buffer. Use NULL to get the size needed,
&cbSid, // Size of the SID buffer needed.
wszDomainName, // wszDomainName,//这个还能获取域名.
&cchDomainName,
&eSidType)) //其实这个函数就是返回sid和域名用的别的没啥,不要多想,下面的是垃圾,加上更完美.
{
if (IsValidSid(*ppSid) == FALSE)
{
wprintf(L"The SID for %s is invalid.\n", wszAccName);
dwErrorCode = MQ_ERROR;
}
break;
}
dwErrorCode = GetLastError();
if (dwErrorCode == ERROR_INSUFFICIENT_BUFFER) // Check if one of the buffers was too small.
{
if (cbSid > dwSidBufferSize)
{ // Reallocate memory for the SID buffer.
wprintf(L"The SID buffer was too small. It will be reallocated.\n");
FreeSid(*ppSid);
*ppSid = (PSID) new BYTE[cbSid];
if (*ppSid == NULL)
{
return MQ_ERROR_INSUFFICIENT_RESOURCES;
}
memset(*ppSid, 0, cbSid);
dwSidBufferSize = cbSid;
}
if (cchDomainName > dwDomainBufferSize)
{ // Reallocate memory for the domain name buffer.
wprintf(L"The domain name buffer was too small. It will be reallocated.\n");
delete [] wszDomainName;
wszDomainName = new WCHAR[cchDomainName];
if (wszDomainName == NULL)
{
return MQ_ERROR_INSUFFICIENT_RESOURCES;
}
memset(wszDomainName, 0, cchDomainName*sizeof(WCHAR));
dwDomainBufferSize = cchDomainName;
}
}
else
{
wprintf(L"LookupAccountNameW failed. GetLastError returned: %d\n", dwErrorCode);
hr = HRESULT_FROM_WIN32(dwErrorCode);
break;
}
}
delete [] wszDomainName;
return hr;
}
//http://msdn.microsoft.com/en-us/library/windows/desktop/aa379554(v=vs.85).aspx
#define MAX_NAME 256
BOOL SearchTokenGroupsForSID (VOID) //这个暂时放这里.不做讨论.
{
DWORD i, dwSize = 0, dwResult = 0;
HANDLE hToken;
PTOKEN_GROUPS pGroupInfo;
SID_NAME_USE SidType;
char lpName[MAX_NAME];
char lpDomain[MAX_NAME];
PSID pSID = NULL;
SID_IDENTIFIER_AUTHORITY SIDAuth = SECURITY_NT_AUTHORITY;
// Open a handle to the access token for the calling process.
if (!OpenProcessToken( GetCurrentProcess(), TOKEN_QUERY, &hToken ))
{
printf( "OpenProcessToken Error %u\n", GetLastError() );
return FALSE;
}
// Call GetTokenInformation to get the buffer size.
if(!GetTokenInformation(hToken, TokenGroups, NULL, dwSize, &dwSize))
{
dwResult = GetLastError();
if( dwResult != ERROR_INSUFFICIENT_BUFFER ) {
printf( "GetTokenInformation Error %u\n", dwResult );
return FALSE;
}
}
// Allocate the buffer.
pGroupInfo = (PTOKEN_GROUPS) GlobalAlloc( GPTR, dwSize );
// Call GetTokenInformation again to get the group information.
if(! GetTokenInformation(hToken, TokenGroups, pGroupInfo, dwSize, &dwSize ) )
{
printf( "GetTokenInformation Error %u\n", GetLastError() );
return FALSE;
}
// Create a SID for the BUILTIN\Administrators group.
if(! AllocateAndInitializeSid( &SIDAuth, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &pSID) )
{
printf( "AllocateAndInitializeSid Error %u\n", GetLastError() );
return FALSE;
}
// Loop through the group SIDs looking for the administrator SID.
for(i=0; i<pGroupInfo->GroupCount; i++)
{
if ( EqualSid(pSID, pGroupInfo->Groups[i].Sid) )
{ // Lookup the account name and print it.
dwSize = MAX_NAME;
if( !LookupAccountSid( NULL, pGroupInfo->Groups[i].Sid, (LPWSTR)lpName, &dwSize, (LPWSTR)lpDomain, &dwSize, &SidType ) ) //此函数能实现根据sid获取用户名的功能,进而可以想办法利用此函数进行枚举.
{
dwResult = GetLastError();
if( dwResult == ERROR_NONE_MAPPED )
strcpy_s (lpName, dwSize, "NONE_MAPPED" );
else
{
printf("LookupAccountSid Error %u\n", GetLastError());
return FALSE;
}
}
printf( "Current user is a member of the %s\\%s group\n", lpDomain, lpName );
// Find out whether the SID is enabled in the token.
if (pGroupInfo->Groups[i].Attributes & SE_GROUP_ENABLED)
printf("The group SID is enabled.\n");
else if (pGroupInfo->Groups[i].Attributes & SE_GROUP_USE_FOR_DENY_ONLY)
printf("The group SID is a deny-only SID.\n");
else
printf("The group SID is not enabled.\n");
}
}
if (pSID)
FreeSid(pSID);
if ( pGroupInfo )
GlobalFree( pGroupInfo );
return TRUE;
}
//更多的还有http://msdn.microsoft.com/en-us/library/windows/desktop/aa379608(v=vs.85).aspx
int _tmain(int argc, _TCHAR* argv[])
{
wchar_t sz_UserNamew[260] = {0};
int len = sizeof(sz_UserNamew);
GetUserName(sz_UserNamew,(LPDWORD)&len);
LPWSTR * wsz_sid = (LPWSTR *)HeapAlloc(GetProcessHeap(), 0, 0x200);
PSID * ppSid = (PSID *)HeapAlloc(GetProcessHeap(), 0, 0x200);
GetSid(sz_UserNamew,ppSid);//Administrator,Defaultapppool应该有枚举的办法.NetUserEnum,但不全.特殊的没有.
bool b = ConvertSidToStringSid(*ppSid,(LPWSTR *)wsz_sid);
int x = GetLastError();
MessageBox(0,(LPCWSTR)(* ( int *)wsz_sid),0,0);
RtlZeroMemory(wsz_sid,0x200);
RtlZeroMemory(ppSid,0x200);
HANDLE hToken;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY_SOURCE | TOKEN_QUERY, &hToken)) return( FALSE );
GetLogonSID(hToken,ppSid);//字面意思是登录的sid,用的是当前进程或者线程的句柄.
b = ConvertSidToStringSid(*ppSid,(LPWSTR *)wsz_sid);
x = GetLastError();
MessageBox(0,(LPCWSTR)(* ( int *)wsz_sid),0,0);//得到的这个值在注册表中找不到.HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
HeapFree(GetProcessHeap(), 0, wsz_sid);
HeapFree(GetProcessHeap(), 0, ppSid);
SearchTokenGroupsForSID();
return 0;
}
//made by correy.
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
参考:Microsoft SDKs\Windows\v7.1\Samples\security\authorization\textsid这个工程.
获取当前用户(进程的)SID更简单.其实也就这么简单.
made at 2013.10.10
*/
#include <windows.h>
#include <Sddl.h>
int _tmain()
{
#define MY_BUFSIZE 256 // all allocations should be dynamic
HANDLE hToken;
BYTE buf[MY_BUFSIZE];
PTOKEN_USER ptgUser = (PTOKEN_USER)buf;
DWORD cbBuffer=MY_BUFSIZE;
BOOL bSuccess;
// obtain current process token
if(!OpenProcessToken(
GetCurrentProcess(), // target current process
TOKEN_QUERY, // TOKEN_QUERY access
&hToken // resultant hToken
)) {
return 1;
}
// obtain user identified by current process' access token
bSuccess = GetTokenInformation(
hToken, // identifies access token
TokenUser, // TokenUser info type
ptgUser, // retrieved info buffer
cbBuffer, // size of buffer passed-in
&cbBuffer // required buffer size
);
CloseHandle(hToken);
if(!bSuccess) {
return 1;
}
LPWSTR lpSid = NULL;
ConvertSidToStringSid(ptgUser->User.Sid, &lpSid);
//这时已经获取到了,可以查看了.
LocalFree(lpSid);
return 1;
}
sid一个神秘的东西,本想是获取或者枚举用户和它的关系.
这里有两个从微软搬过来的函数,
一个是从句柄获得sid,这个好像有问题,难道是我使用的问题.
一个是从(用户)名字获取sid.这个经试验是好的.
这里主要用了两个函数:GetTokenInformation,LookupAccountNameW
因为用GetTokenInformation的函数获取的东西好像有点问题,所以此文就命名为:LookupAccountName.Cpp.
*/
#include "stdafx.h"
#include <windows.h>
#include "D:\Program Files\Microsoft Visual Studio 9.0\SmartDevices\SDK\Smartphone2003\Include\mq.h"
#include <Sddl.h>
#pragma comment(lib, "advapi32.lib")
//http://msdn.microsoft.com/en-us/library/windows/desktop/aa446670(v=vs.85).aspx
BOOL GetLogonSID (HANDLE hToken, PSID *ppsid)
{
BOOL bSuccess = FALSE;
DWORD dwIndex;
DWORD dwLength = 0;
PTOKEN_GROUPS ptg = NULL;
if (NULL == ppsid)// Verify the parameter passed in is not NULL.
goto Cleanup;
if (!GetTokenInformation(// Get required buffer size and allocate the TOKEN_GROUPS buffer.
hToken, // handle to the access token
TokenGroups, // get information about the token's groups
(LPVOID) ptg, // pointer to TOKEN_GROUPS buffer
0, // size of buffer
&dwLength // receives required buffer size
))
{
if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
goto Cleanup;
ptg = (PTOKEN_GROUPS)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, dwLength);
if (ptg == NULL)
goto Cleanup;
}
if (!GetTokenInformation(hToken,TokenGroups,(LPVOID) ptg,dwLength,&dwLength)) {// Get the token group information from the access token.
goto Cleanup;
}
// Loop through the groups to find the logon SID.
for (dwIndex = 0; dwIndex < ptg->GroupCount; dwIndex++) //这个没有大括号.
if ((ptg->Groups[dwIndex].Attributes & SE_GROUP_LOGON_ID) == SE_GROUP_LOGON_ID)
{ // Found the logon SID; make a copy of it.
dwLength = GetLengthSid(ptg->Groups[dwIndex].Sid);
*ppsid = (PSID) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwLength);
if (*ppsid == NULL)
goto Cleanup;
if (!CopySid(dwLength, *ppsid, ptg->Groups[dwIndex].Sid))
{
HeapFree(GetProcessHeap(), 0, (LPVOID)*ppsid);
goto Cleanup;
}
break;
}
bSuccess = TRUE;
Cleanup:
if (ptg != NULL)// Free the buffer for the token groups.
HeapFree(GetProcessHeap(), 0, (LPVOID)ptg);
return bSuccess;
}
//这个不要了.
//VOID FreeLogonSID (PSID *ppsid)
//{
// HeapFree(GetProcessHeap(), 0, (LPVOID)*ppsid);
//}
//http://msdn.microsoft.com/en-us/library/windows/desktop/ms707085(v=vs.85).aspx
//还有一个函数:CreateQSecDescriptor
HRESULT GetSid(LPCWSTR wszAccName,PSID * ppSid) //此函数,还可以精简,我没有精简.
{
if (wszAccName == NULL || ppSid == NULL) {// Validate the input parameters.
return MQ_ERROR_INVALID_PARAMETER;
}
// Create buffers that may be large enough.If a buffer is too small, the count parameter will be set to the size needed.
const DWORD INITIAL_SIZE = 32;
DWORD cbSid = 0;
DWORD dwSidBufferSize = INITIAL_SIZE;
DWORD cchDomainName = 0;
DWORD dwDomainBufferSize = INITIAL_SIZE;
WCHAR * wszDomainName = NULL;
SID_NAME_USE eSidType;
DWORD dwErrorCode = 0;
HRESULT hr = MQ_OK;
*ppSid = (PSID) new BYTE[dwSidBufferSize];// Create buffers for the SID and the domain name.
if (*ppSid == NULL) {
return MQ_ERROR_INSUFFICIENT_RESOURCES;
}
memset(*ppSid, 0, dwSidBufferSize);
wszDomainName = new WCHAR[dwDomainBufferSize];
if (wszDomainName == NULL) {
return MQ_ERROR_INSUFFICIENT_RESOURCES;
}
memset(wszDomainName, 0, dwDomainBufferSize*sizeof(WCHAR));
for ( ; ; )// Obtain the SID for the account name passed.
{ // Set the count variables to the buffer sizes and retrieve the SID.
cbSid = dwSidBufferSize;
cchDomainName = dwDomainBufferSize;
if (LookupAccountNameW(
NULL, // Computer name. NULL for the local computer
wszAccName,
*ppSid, // Pointer to the SID buffer. Use NULL to get the size needed,
&cbSid, // Size of the SID buffer needed.
wszDomainName, // wszDomainName,//这个还能获取域名.
&cchDomainName,
&eSidType)) //其实这个函数就是返回sid和域名用的别的没啥,不要多想,下面的是垃圾,加上更完美.
{
if (IsValidSid(*ppSid) == FALSE)
{
wprintf(L"The SID for %s is invalid.\n", wszAccName);
dwErrorCode = MQ_ERROR;
}
break;
}
dwErrorCode = GetLastError();
if (dwErrorCode == ERROR_INSUFFICIENT_BUFFER) // Check if one of the buffers was too small.
{
if (cbSid > dwSidBufferSize)
{ // Reallocate memory for the SID buffer.
wprintf(L"The SID buffer was too small. It will be reallocated.\n");
FreeSid(*ppSid);
*ppSid = (PSID) new BYTE[cbSid];
if (*ppSid == NULL)
{
return MQ_ERROR_INSUFFICIENT_RESOURCES;
}
memset(*ppSid, 0, cbSid);
dwSidBufferSize = cbSid;
}
if (cchDomainName > dwDomainBufferSize)
{ // Reallocate memory for the domain name buffer.
wprintf(L"The domain name buffer was too small. It will be reallocated.\n");
delete [] wszDomainName;
wszDomainName = new WCHAR[cchDomainName];
if (wszDomainName == NULL)
{
return MQ_ERROR_INSUFFICIENT_RESOURCES;
}
memset(wszDomainName, 0, cchDomainName*sizeof(WCHAR));
dwDomainBufferSize = cchDomainName;
}
}
else
{
wprintf(L"LookupAccountNameW failed. GetLastError returned: %d\n", dwErrorCode);
hr = HRESULT_FROM_WIN32(dwErrorCode);
break;
}
}
delete [] wszDomainName;
return hr;
}
//http://msdn.microsoft.com/en-us/library/windows/desktop/aa379554(v=vs.85).aspx
#define MAX_NAME 256
BOOL SearchTokenGroupsForSID (VOID) //这个暂时放这里.不做讨论.
{
DWORD i, dwSize = 0, dwResult = 0;
HANDLE hToken;
PTOKEN_GROUPS pGroupInfo;
SID_NAME_USE SidType;
char lpName[MAX_NAME];
char lpDomain[MAX_NAME];
PSID pSID = NULL;
SID_IDENTIFIER_AUTHORITY SIDAuth = SECURITY_NT_AUTHORITY;
// Open a handle to the access token for the calling process.
if (!OpenProcessToken( GetCurrentProcess(), TOKEN_QUERY, &hToken ))
{
printf( "OpenProcessToken Error %u\n", GetLastError() );
return FALSE;
}
// Call GetTokenInformation to get the buffer size.
if(!GetTokenInformation(hToken, TokenGroups, NULL, dwSize, &dwSize))
{
dwResult = GetLastError();
if( dwResult != ERROR_INSUFFICIENT_BUFFER ) {
printf( "GetTokenInformation Error %u\n", dwResult );
return FALSE;
}
}
// Allocate the buffer.
pGroupInfo = (PTOKEN_GROUPS) GlobalAlloc( GPTR, dwSize );
// Call GetTokenInformation again to get the group information.
if(! GetTokenInformation(hToken, TokenGroups, pGroupInfo, dwSize, &dwSize ) )
{
printf( "GetTokenInformation Error %u\n", GetLastError() );
return FALSE;
}
// Create a SID for the BUILTIN\Administrators group.
if(! AllocateAndInitializeSid( &SIDAuth, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &pSID) )
{
printf( "AllocateAndInitializeSid Error %u\n", GetLastError() );
return FALSE;
}
// Loop through the group SIDs looking for the administrator SID.
for(i=0; i<pGroupInfo->GroupCount; i++)
{
if ( EqualSid(pSID, pGroupInfo->Groups[i].Sid) )
{ // Lookup the account name and print it.
dwSize = MAX_NAME;
if( !LookupAccountSid( NULL, pGroupInfo->Groups[i].Sid, (LPWSTR)lpName, &dwSize, (LPWSTR)lpDomain, &dwSize, &SidType ) ) //此函数能实现根据sid获取用户名的功能,进而可以想办法利用此函数进行枚举.
{
dwResult = GetLastError();
if( dwResult == ERROR_NONE_MAPPED )
strcpy_s (lpName, dwSize, "NONE_MAPPED" );
else
{
printf("LookupAccountSid Error %u\n", GetLastError());
return FALSE;
}
}
printf( "Current user is a member of the %s\\%s group\n", lpDomain, lpName );
// Find out whether the SID is enabled in the token.
if (pGroupInfo->Groups[i].Attributes & SE_GROUP_ENABLED)
printf("The group SID is enabled.\n");
else if (pGroupInfo->Groups[i].Attributes & SE_GROUP_USE_FOR_DENY_ONLY)
printf("The group SID is a deny-only SID.\n");
else
printf("The group SID is not enabled.\n");
}
}
if (pSID)
FreeSid(pSID);
if ( pGroupInfo )
GlobalFree( pGroupInfo );
return TRUE;
}
//更多的还有http://msdn.microsoft.com/en-us/library/windows/desktop/aa379608(v=vs.85).aspx
int _tmain(int argc, _TCHAR* argv[])
{
wchar_t sz_UserNamew[260] = {0};
int len = sizeof(sz_UserNamew);
GetUserName(sz_UserNamew,(LPDWORD)&len);
LPWSTR * wsz_sid = (LPWSTR *)HeapAlloc(GetProcessHeap(), 0, 0x200);
PSID * ppSid = (PSID *)HeapAlloc(GetProcessHeap(), 0, 0x200);
GetSid(sz_UserNamew,ppSid);//Administrator,Defaultapppool应该有枚举的办法.NetUserEnum,但不全.特殊的没有.
bool b = ConvertSidToStringSid(*ppSid,(LPWSTR *)wsz_sid);
int x = GetLastError();
MessageBox(0,(LPCWSTR)(* ( int *)wsz_sid),0,0);
RtlZeroMemory(wsz_sid,0x200);
RtlZeroMemory(ppSid,0x200);
HANDLE hToken;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY_SOURCE | TOKEN_QUERY, &hToken)) return( FALSE );
GetLogonSID(hToken,ppSid);//字面意思是登录的sid,用的是当前进程或者线程的句柄.
b = ConvertSidToStringSid(*ppSid,(LPWSTR *)wsz_sid);
x = GetLastError();
MessageBox(0,(LPCWSTR)(* ( int *)wsz_sid),0,0);//得到的这个值在注册表中找不到.HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
HeapFree(GetProcessHeap(), 0, wsz_sid);
HeapFree(GetProcessHeap(), 0, ppSid);
SearchTokenGroupsForSID();
return 0;
}
//made by correy.
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
参考:Microsoft SDKs\Windows\v7.1\Samples\security\authorization\textsid这个工程.
获取当前用户(进程的)SID更简单.其实也就这么简单.
made at 2013.10.10
*/
#include <windows.h>
#include <Sddl.h>
int _tmain()
{
#define MY_BUFSIZE 256 // all allocations should be dynamic
HANDLE hToken;
BYTE buf[MY_BUFSIZE];
PTOKEN_USER ptgUser = (PTOKEN_USER)buf;
DWORD cbBuffer=MY_BUFSIZE;
BOOL bSuccess;
// obtain current process token
if(!OpenProcessToken(
GetCurrentProcess(), // target current process
TOKEN_QUERY, // TOKEN_QUERY access
&hToken // resultant hToken
)) {
return 1;
}
// obtain user identified by current process' access token
bSuccess = GetTokenInformation(
hToken, // identifies access token
TokenUser, // TokenUser info type
ptgUser, // retrieved info buffer
cbBuffer, // size of buffer passed-in
&cbBuffer // required buffer size
);
CloseHandle(hToken);
if(!bSuccess) {
return 1;
}
LPWSTR lpSid = NULL;
ConvertSidToStringSid(ptgUser->User.Sid, &lpSid);
//这时已经获取到了,可以查看了.
LocalFree(lpSid);
return 1;
}
IoRegisterFsRegistrationChange.C
/*
IoRegisterFsRegistrationChange这个函数,大多数人都知道.
在文件过滤驱动中大多用到,也都知道字面的意思.
本人笨拙,要刨根问底,进一步知晓,只有我编写代码,调试并查看效果,我才算掌握这个函数.
与其说回调,不如说:在一般的情况下是枚举(文件系统相关的).这是不正确但形象的说明.
这个函数费了我半天的时间.
*/
//#include <ntddk.h>
#include <Ntifs.h>
VOID DriverNotificationRoutine(__in PDEVICE_OBJECT DeviceObject,__in BOOLEAN FsActive)
{
if (FsActive)
{
DbgPrint("/////////////////////////////////////////////////////////////////////////\n");
DbgPrint("the file system has registered\n"); //\n后面不能有空格,不然会蓝屏.
DbgPrint("本设备对象所在的驱动对象的驱动名字:%wZ \n",&DeviceObject->DriverObject->DriverName);//\FileSystem\Fs_Rec重复出现好几次.
if(DeviceObject->NextDevice) //不判断会蓝屏.因为有的没有.
{
DbgPrint("本设备对象的下一个设备对象的驱动对象的驱动名字:%wZ \n",&DeviceObject->NextDevice->DriverObject->DriverName);
}
if (DeviceObject->AttachedDevice)
{
DbgPrint("本设备对象的附加设备对象的所在驱动的驱动的名字:%wZ \n",&DeviceObject->AttachedDevice->DriverObject->DriverName);
}
//这个和第一个显示的是一样的.就是:&DeviceObject->DriverObject->DriverName,注释掉,不显示了.
//DbgPrint("本设备对象的扩展信息中的驱动对象的驱动名字:%wZ \n",&DeviceObject->DeviceObjectExtension->DeviceObject->DriverObject->DriverName);
}
else
{
DbgPrint("the file system has unregistered\n");
}
}
VOID Unload(PDRIVER_OBJECT DriverObject)
{
IoUnregisterFsRegistrationChange(DriverObject, DriverNotificationRoutine);
}
NTSTATUS DriverEntry(PDRIVER_OBJECT DriverObject, PUNICODE_STRING pRegistryPath)
{
_asm int 3
DriverObject->DriverUnload = Unload;
IoRegisterFsRegistrationChange(DriverObject, DriverNotificationRoutine);
return STATUS_SUCCESS;
}
//made at 2012.06.29
SystemModuleInformation.C
/*
ZwQuerySystemInformation这个函数在应用层也可以使用,功能十分强大,以前是未公开的,现在是半公开的,因为内核中没有这个函数的声明.
本文修改自kmdkit的第六篇教程.以前把c/c++改为asm,现在是把asm改为c/c++.
看似简单的一个事情,费了我一天的时间.
win 7 32测试通过.
made at 2012.06.23
*/
#include <ntddk.h>
//下面的结构摘自:http://undocumented.ntinternals.net/UserMode/Undocumented%20Functions/System%20Information/SYSTEM_INFORMATION_CLASS.html
typedef enum _SYSTEM_INFORMATION_CLASS {
SystemBasicInformation,
SystemProcessorInformation,
SystemPerformanceInformation,
SystemTimeOfDayInformation,
SystemPathInformation,
SystemProcessInformation,
SystemCallCountInformation,
SystemDeviceInformation,
SystemProcessorPerformanceInformation,
SystemFlagsInformation,
SystemCallTimeInformation,
SystemModuleInformation,
SystemLocksInformation,
SystemStackTraceInformation,
SystemPagedPoolInformation,
SystemNonPagedPoolInformation,
SystemHandleInformation,
SystemObjectInformation,
SystemPageFileInformation,
SystemVdmInstemulInformation,
SystemVdmBopInformation,
SystemFileCacheInformation,
SystemPoolTagInformation,
SystemInterruptInformation,
SystemDpcBehaviorInformation,
SystemFullMemoryInformation,
SystemLoadGdiDriverInformation,
SystemUnloadGdiDriverInformation,
SystemTimeAdjustmentInformation,
SystemSummaryMemoryInformation,
SystemNextEventIdInformation,
SystemEventIdsInformation,
SystemCrashDumpInformation,
SystemExceptionInformation,
SystemCrashDumpStateInformation,
SystemKernelDebuggerInformation,
SystemContextSwitchInformation,
SystemRegistryQuotaInformation,
SystemExtendServiceTableInformation,
SystemPrioritySeperation,
SystemPlugPlayBusInformation,
SystemDockInformation,
SystemPowerInformation1,//提示重复定义,后面加一个1.
SystemProcessorSpeedInformation,
SystemCurrentTimeZoneInformation,
SystemLookasideInformation
} SYSTEM_INFORMATION_CLASS, *PSYSTEM_INFORMATION_CLASS;
//摘自微软:http://msdn.microsoft.com/en-us/library/windows/desktop/ms725506(v=vs.85).aspx
//NTSTATUS NTAPI ZwQuerySystemInformation( //WINAPI改为NTAPI或者去掉编译没有问题.
// __in SYSTEM_INFORMATION_CLASS SystemInformationClass,
// __inout PVOID SystemInformation,
// __in ULONG SystemInformationLength,
// __out_opt PULONG ReturnLength
// );
//下面的摘自:http://undocumented.ntinternals.net/UserMode/Undocumented%20Functions/System%20Information/NtQuerySystemInformation.html
NTSYSAPI
NTSTATUS
NTAPI
ZwQuerySystemInformation(//把Nt修改为Zw.
IN SYSTEM_INFORMATION_CLASS SystemInformationClass,
OUT PVOID SystemInformation,
IN ULONG SystemInformationLength,
OUT PULONG ReturnLength OPTIONAL );
//未公开的结构,搜索自网络:http://alter.org.ua/docs/nt_kernel/procaddr/#samples, kmdkit也有.
//与http://undocumented.ntinternals.net/UserMode/Structures/SYSTEM_MODULE_INFORMATION.html的不同.
//typedef struct _SYSTEM_MODULE_INFORMATION {
// ULONG ModulesCount;
// SYSTEM_MODULE Modules[0];
//} SYSTEM_MODULE_INFORMATION, *PSYSTEM_MODULE_INFORMATION;
typedef struct SYSTEM_MODULE_INFORMATION {
ULONG Reserved[2];
PVOID Base;
ULONG Size;
ULONG Flags;
USHORT Index;
USHORT Unknown;
USHORT LoadCount;
USHORT ModuleNameOffset;
CHAR ImageName[256];
} SYSTEM_MODULE_INFORMATION, *PSYSTEM_MODULE_INFORMATION;
VOID Unload(PDRIVER_OBJECT DriverObject){}
NTSTATUS DriverEntry(PDRIVER_OBJECT DriverObject, PUNICODE_STRING pRegistryPath)
{
ULONG cb = 0;
PSYSTEM_MODULE_INFORMATION p;
PVOID p0;
int dwNumModules;
int i;
LPSTR name;
_asm int 3
DriverObject->DriverUnload = Unload; //写在前面是确保顺利卸载.
ZwQuerySystemInformation(11,& p, 0, & cb);//#define SystemModuleInformation 11
if (cb == 0) return 0;
p = (PSYSTEM_MODULE_INFORMATION)ExAllocatePool( PagedPool, cb);
if (p == 0) return 0;
p0 = (PVOID)p;//这两个变量定义的别扭,但可以使用.
if (ZwQuerySystemInformation(11, p, cb, & cb) != 0)
{
ExFreePool( p);
return 0;
}
dwNumModules = *(int *) p;
(int *) p += 1;//指针加4个字节.
for (i = 0;i<dwNumModules;i++)
{
name = (LPSTR)(p->ImageName + p->ModuleNameOffset);
if (_strnicmp(name,"ntoskrnl.exe",strlen("ntoskrnl.exe")) == 0)
{//If your system has PAE - "ntkrnlpa.exe"
DbgPrint("%s base: %08X size: %08X\n",name,p->Base,p->Size);
}
if (_strnicmp(name,"ntkrnlpa.exe",strlen("ntkrnlpa.exe")) == 0)
{//; If you have multiprocessor system use "ntkrnlmp.exe".
DbgPrint("%s base: %08X size: %08X\n",name,p->Base,p->Size);
}
if (_strnicmp(name,"ntkrpamp.exe",strlen("ntkrpamp.exe")) == 0)
{//Multiprocessor + PAE - "ntkrpamp.exe"
DbgPrint("%s base: %08X size: %08X\n",name,p->Base,p->Size);
}
//ntice.sys,不知道啥玩意,不显示了.
DbgPrint("%s base: %08X size: %08X\n",name,p->Base,p->Size);//我要看看全部的是啥玩意.
(unsigned char *)p += sizeof (SYSTEM_MODULE_INFORMATION);
}
ExFreePool( p0);
return STATUS_SUCCESS;
//返回STATUS_DEVICE_CONFIGURATION_ERROR,也加载成功,也不需要卸载函数了,也能再次加载.
}
//made by correy
\\KnownDlls\\KnownDllPath.C
/* 本文整理自网络, 起源于WinObjEx.exe的无聊的使用. 大家都知道如何获取:%windir% = %SystemRoot% 今天的是获取:%WINDIR%\system32,注意获得的路径的后面是不带\的. 注释:%system%在2003和win 7上是无效的,别的没有测试. 注意还有个路径:L"\\KnownDlls\\KnownDllPath",这个只存在于64位的系统。 */ #include <ntddk.h> VOID OnUnload(PDRIVER_OBJECT DriverObject){} NTSTATUS DriverEntry(__in PDRIVER_OBJECT pDriverObject,__in PUNICODE_STRING pRegistryPath) {//方法一: ULONG ActualLength; HANDLE LinkHandle; WCHAR NameBuffer[128];//这个可能定义的小了. OBJECT_ATTRIBUTES ObjectAttributes; UNICODE_STRING LinkString, NameString; _asm int 3 LinkString.Buffer = NameBuffer; LinkString.MaximumLength = sizeof(NameBuffer); RtlZeroMemory(NameBuffer, sizeof(NameBuffer)); RtlInitUnicodeString(&NameString, L"\\KnownDlls\\KnownDllPath");//不可以用//,不然会ZwOpenSymbolicLinkObject调用失败.就是得到的句柄为0. InitializeObjectAttributes(&ObjectAttributes, &NameString, OBJ_KERNEL_HANDLE, NULL, NULL); ZwOpenSymbolicLinkObject(&LinkHandle, SYMBOLIC_LINK_QUERY, &ObjectAttributes); ZwQuerySymbolicLinkObject(LinkHandle, &LinkString, &ActualLength);//LinkString就是想要的值. KdPrint(("KnownDllPath: %wZ \n",&LinkString)); ZwClose(LinkHandle); //////////////////////////////////////////////////////////////////////////////////////////////////////// //方法二: { NTSTATUS ZwOpenDirectoryObject( __out PHANDLE DirectoryHandle, __in ACCESS_MASK DesiredAccess, __in POBJECT_ATTRIBUTES ObjectAttributes); UNICODE_STRING usDirName,usSymbolicName,usSymbolic; OBJECT_ATTRIBUTES ObjDir,ObjSymbolic; WCHAR wchBuffer[128]; HANDLE hDir,hSymbolic; RtlInitUnicodeString (&usDirName,L"\\KnownDlls"); InitializeObjectAttributes( &ObjDir,&usDirName,OBJ_CASE_INSENSITIVE|OBJ_KERNEL_HANDLE,NULL,NULL); ZwOpenDirectoryObject ( &hDir,DIRECTORY_QUERY,&ObjDir); RtlInitUnicodeString (&usSymbolicName , L"KnownDllPath"); InitializeObjectAttributes(&ObjSymbolic,&usSymbolicName,OBJ_CASE_INSENSITIVE|OBJ_KERNEL_HANDLE,hDir,NULL); ZwOpenSymbolicLinkObject (&hSymbolic,GENERIC_READ,&ObjSymbolic); usSymbolic.Buffer = wchBuffer; usSymbolic.MaximumLength = 256*sizeof(WCHAR); usSymbolic.Length =0; ZwQuerySymbolicLinkObject ( hSymbolic,&usSymbolic,NULL); KdPrint(("KnownDllPath: %wZ \n",&usSymbolic)); } pDriverObject->DriverUnload = OnUnload; return 0; } //made by correy ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* 在驱动中把dos-name转换nt-name. made at 20140605. */ #include <ntifs.h> #include <windef.h> #define TAG 'tset' //test DRIVER_UNLOAD Unload; VOID Unload(__in PDRIVER_OBJECT DriverObject) { } #pragma INITCODE DRIVER_INITIALIZE DriverEntry; NTSTATUS DriverEntry(__in struct _DRIVER_OBJECT * DriverObject, __in PUNICODE_STRING RegistryPath) { ULONG ActualLength; HANDLE LinkHandle = 0; WCHAR NameBuffer[128];//这个可能定义的小了. OBJECT_ATTRIBUTES ObjectAttributes; UNICODE_STRING LinkString, NameString; NTSTATUS status = STATUS_SUCCESS; KdBreakPoint(); DriverObject->DriverUnload = Unload; LinkString.Buffer = NameBuffer; LinkString.MaximumLength = sizeof(NameBuffer); RtlZeroMemory(NameBuffer, sizeof(NameBuffer)); RtlInitUnicodeString(&NameString, L"\\??\\c:");//注意格式。 InitializeObjectAttributes(&ObjectAttributes, &NameString, OBJ_KERNEL_HANDLE, NULL, NULL); status = ZwOpenSymbolicLinkObject(&LinkHandle, SYMBOLIC_LINK_QUERY | GENERIC_READ , &ObjectAttributes); status = ZwQuerySymbolicLinkObject(LinkHandle, &LinkString, &ActualLength); KdPrint(("%wZ \n",&LinkString));//得到的值形如:"\Device\HarddiskVolume1"。 ZwClose(LinkHandle); return 0; }
WinHttpReadData.Cpp
/*
以前接触网络的时候,认为用户层用socket足矣(其实还有比socket更底层的),别的都不用,这样停止了几年.
后来发现有一些操作,还是用高级的好.
这就知道了.WinINet和WinHTTP等.
好像WinHTTP是WinINet的子集(IWinHttpRequest又是WinHTTP的子集),但比WinINet效率高,还可以用于服务器.
以前也知道点,但没有具体深入.
前几天算是开始了,费了一个多月的时间才把下面的小问题搞定.
下面的代码来自:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa384104(v=vs.85).aspx
等.
并加一些注释.没有精简.
再说一下:
看似简单的几个函数,如果不深刻理解总是出错的.
原因在于示例程序可以运行,修改别的就不行了.
注意参数的设置:如端口,协议等.一定要配合.
下面的代码经过简单的修改,可以成功的访问:
www.microsoft.com
www.baidu.com
www.google.com.hk 注释:访问www.google.com,得到的数据不是我们想要的,可能又转到了:www.google.com.hk
www.126.com
*/
#include <windows.h>
#include <Winhttp.h>
#pragma comment(lib, "Winhttp.lib")
void wmain(void)
{
DWORD dwSize = 0;
DWORD dwDownloaded = 0;
LPSTR pszOutBuffer;
BOOL bResults = FALSE;
HINTERNET hSession = NULL,
hConnect = NULL,
hRequest = NULL;
// Use WinHttpOpen to obtain a session handle.
hSession = WinHttpOpen( L"WinHTTP Example/1.0",
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, //WINHTTP_ACCESS_TYPE_NO_PROXY WINHTTP_ACCESS_TYPE_DEFAULT_PROXY
WINHTTP_NO_PROXY_NAME, //#define WINHTTP_NO_PROXY_NAME NULL
WINHTTP_NO_PROXY_BYPASS, 0);//#define WINHTTP_NO_PROXY_BYPASS NULL
// Specify an HTTP server.
if (hSession)
{
DWORD data;
DWORD dwSize = sizeof(DWORD);
WinHttpSetTimeouts( hSession, 60000000, 60000000, 60000000, 60000000);//我这台电脑上的原始值是:60000ms,设置大点,防止因为这个而出现错误.
// Use WinHttpQueryOption to retrieve internet options.
if (WinHttpQueryOption( hSession,
WINHTTP_OPTION_CONNECT_TIMEOUT,
&data, &dwSize))
{
printf("Connection timeout: %u ms\n\n",data); //60000ms
}
else
{
printf( "Error %u in WinHttpQueryOption.\n",
GetLastError());
}
// When finished, release the HINTERNET handle.
// WinHttpCloseHandle(hSession);
//以上这几行代码也摘抄自msdn .
hConnect = WinHttpConnect( hSession, L"correy.webs.com", //www.microsoft.com www.baidu.com www.google.com.hk 支持L"220.181.112.143"格式.不要加http://和https://
INTERNET_DEFAULT_HTTP_PORT, 0); //INTERNET_DEFAULT_HTTP_PORT INTERNET_DEFAULT_HTTPS_PORT //设置端口,注意要和协议匹配.
}
// Create an HTTP request handle.
if (hConnect)
hRequest = WinHttpOpenRequest( hConnect, L"GET", NULL,//可以改为"POST","HEAD".等.
NULL, //Pointer to a string that contains the HTTP version. If this parameter is NULL, the function uses HTTP/1.1.
WINHTTP_NO_REFERER, //还可以写具体的相对位置.如果没有,可以设置为WINHTTP_NO_REFERER
WINHTTP_DEFAULT_ACCEPT_TYPES, //see Media Types defined by IANA at http://www.iana.org/assignments/media-types/.
WINHTTP_FLAG_REFRESH);//WINHTTP_FLAG_REFRESH WINHTTP_FLAG_SECURE 设置协议, 注意要和端口匹配.
// Send a request.
if (hRequest)
bResults = WinHttpSendRequest( hRequest,//这个很费时间.
WINHTTP_NO_ADDITIONAL_HEADERS,
0, WINHTTP_NO_REQUEST_DATA, 0,
0, 0); //用GetLastError返回的错误码,结合函数说明在头文件里面查,msdn上也有的.
int x = ERROR_WINHTTP_CANNOT_CONNECT; //goto definition用的.
//具体的查看信息是:http://msdn.microsoft.com/en-us/library/windows/desktop/aa383770(v=vs.85).aspx
// End the request.
if (bResults)
bResults = WinHttpReceiveResponse( hRequest, NULL); //ERROR_WINHTTP_CANNOT_CONNECT
// Keep checking for data until there is nothing left.
if (bResults)
{
do
{
// Check for available data.
dwSize = 0;
if (!WinHttpQueryDataAvailable( hRequest, &dwSize))
{
printf( "Error %u in WinHttpQueryDataAvailable.\n",
GetLastError());
break;
}
// No more available data.
if (!dwSize)
break;
// Allocate space for the buffer.
pszOutBuffer = new char[dwSize+1];
if (!pszOutBuffer)
{
printf("Out of memory\n");
break;
}
// Read the Data.
ZeroMemory(pszOutBuffer, dwSize+1);
if (!WinHttpReadData( hRequest, (LPVOID)pszOutBuffer,
dwSize, &dwDownloaded))
{
printf( "Error %u in WinHttpReadData.\n", GetLastError());
}
else
{
printf("%s", pszOutBuffer);
}
// Free the memory allocated to the buffer.
delete [] pszOutBuffer;
// This condition should never be reached since WinHttpQueryDataAvailable
// reported that there are bits to read.
if (!dwDownloaded)
break;
} while (dwSize > 0);
}
else
{
// Report any errors.
printf( "Error %d has occurred.\n", GetLastError() );
}
// Close any open handles.
if (hRequest) WinHttpCloseHandle(hRequest);
if (hConnect) WinHttpCloseHandle(hConnect);
if (hSession) WinHttpCloseHandle(hSession);
}
//made by correy
minifilter.c
/*
最简单的minifilter.
修改自wdk的nullFilter.c.
安装的办法可以用.inf
也可以编程操作注册表的办法,但我还没有实现.
*/
#include <fltKernel.h>
PFLT_FILTER FilterHandle;
NTSTATUS NullUnload (__in FLT_FILTER_UNLOAD_FLAGS Flags)
{ //这个也可以不要的.
DbgPrint("minifilter stop");//方便net stop或者fltmc load或者sc stop查询.
FltUnregisterFilter( FilterHandle );
return STATUS_SUCCESS;
}
FLT_REGISTRATION FilterRegistration = {sizeof(FLT_REGISTRATION),FLT_REGISTRATION_VERSION,0,0,0,NullUnload,0,0,0,0,0,0,0};
NTSTATUS DriverEntry (__in PDRIVER_OBJECT DriverObject,__in PUNICODE_STRING RegistryPath)
{
DbgPrint("minifilter entry");//方便net start或者fltmc unload或者sc stop查询.
FltRegisterFilter( DriverObject,&FilterRegistration,&FilterHandle );
FltStartFiltering( FilterHandle );
return 0;
}
//made at 2012.05.20
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//下面的精简自wdk的passThrough.c
#include <fltKernel.h>
PFLT_FILTER gFilterHandle;
ULONG_PTR OperationStatusCtx = 1;
ULONG gTraceFlags = 1;
#define PT_DBG_PRINT( _dbgLevel, _string ) (FlagOn(gTraceFlags,(_dbgLevel)) ? DbgPrint _string : ((int)0))
VOID PtOperationStatusCallback (__in PCFLT_RELATED_OBJECTS FltObjects,__in PFLT_IO_PARAMETER_BLOCK ParameterSnapshot,__in NTSTATUS OperationStatus,__in PVOID RequesterContext)
{
PT_DBG_PRINT( 1,("PassThrough!PtOperationStatusCallback: Entered\n") );
PT_DBG_PRINT( 2,("PassThrough!PtOperationStatusCallback: Status=%08x ctx=%p IrpMj=%02x.%02x \"%s\"\n",
OperationStatus,RequesterContext,ParameterSnapshot->MajorFunction,ParameterSnapshot->MinorFunction,
FltGetIrpName(ParameterSnapshot->MajorFunction)) );
}
BOOLEAN PtDoRequestOperationStatus(__in PFLT_CALLBACK_DATA Data)
{
PFLT_IO_PARAMETER_BLOCK iopb = Data->Iopb;
return (BOOLEAN)(((iopb->MajorFunction == IRP_MJ_FILE_SYSTEM_CONTROL) &&
((iopb->Parameters.FileSystemControl.Common.FsControlCode == FSCTL_REQUEST_FILTER_OPLOCK) ||
(iopb->Parameters.FileSystemControl.Common.FsControlCode == FSCTL_REQUEST_BATCH_OPLOCK) ||
(iopb->Parameters.FileSystemControl.Common.FsControlCode == FSCTL_REQUEST_OPLOCK_LEVEL_1) ||
(iopb->Parameters.FileSystemControl.Common.FsControlCode == FSCTL_REQUEST_OPLOCK_LEVEL_2))) ||
((iopb->MajorFunction == IRP_MJ_DIRECTORY_CONTROL) && (iopb->MinorFunction == IRP_MN_NOTIFY_CHANGE_DIRECTORY)));
}
FLT_PREOP_CALLBACK_STATUS PtPreOperationPassThrough (__inout PFLT_CALLBACK_DATA Data,__in PCFLT_RELATED_OBJECTS FltObjects,__deref_out_opt PVOID *CompletionContext)
{
NTSTATUS status;
PT_DBG_PRINT( 1,("PassThrough!PtPreOperationPassThrough: Entered\n") );
if (PtDoRequestOperationStatus( Data ))
{
status = FltRequestOperationStatusCallback( Data,PtOperationStatusCallback,(PVOID)(++OperationStatusCtx) );
if (!NT_SUCCESS(status))
{
PT_DBG_PRINT( 2,("PassThrough!PtPreOperationPassThrough: FltRequestOperationStatusCallback Failed, status=%08x\n",status) );
}
}
return FLT_PREOP_SUCCESS_WITH_CALLBACK;
}
FLT_POSTOP_CALLBACK_STATUS PtPostOperationPassThrough (__inout PFLT_CALLBACK_DATA Data,__in PCFLT_RELATED_OBJECTS FltObjects,
__in_opt PVOID CompletionContext,__in FLT_POST_OPERATION_FLAGS Flags)
{
PT_DBG_PRINT( 1,("PassThrough!PtPostOperationPassThrough: Entered\n") );
return FLT_POSTOP_FINISHED_PROCESSING;
}
FLT_PREOP_CALLBACK_STATUS PtPreOperationNoPostOperationPassThrough (__inout PFLT_CALLBACK_DATA Data,__in PCFLT_RELATED_OBJECTS FltObjects,__deref_out_opt PVOID *CompletionContext)
{
PT_DBG_PRINT( 1,("PassThrough!PtPreOperationNoPostOperationPassThrough: Entered\n") );
return FLT_PREOP_SUCCESS_NO_CALLBACK;
}
CONST FLT_OPERATION_REGISTRATION Callbacks[] = {//用编程的办法,实现,只有一处是特殊的.
{ IRP_MJ_CREATE, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_CREATE_NAMED_PIPE, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_CLOSE, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_READ, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_WRITE, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_QUERY_INFORMATION, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_SET_INFORMATION, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_QUERY_EA, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_SET_EA, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_FLUSH_BUFFERS, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_QUERY_VOLUME_INFORMATION, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_SET_VOLUME_INFORMATION, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_DIRECTORY_CONTROL, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_FILE_SYSTEM_CONTROL, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_DEVICE_CONTROL, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_INTERNAL_DEVICE_CONTROL, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_SHUTDOWN, 0, PtPreOperationNoPostOperationPassThrough, NULL }, //post operations not supported
{ IRP_MJ_LOCK_CONTROL, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_CLEANUP, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_CREATE_MAILSLOT, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_QUERY_SECURITY, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_SET_SECURITY, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_QUERY_QUOTA, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_SET_QUOTA, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_PNP, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_ACQUIRE_FOR_SECTION_SYNCHRONIZATION, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_RELEASE_FOR_SECTION_SYNCHRONIZATION, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_ACQUIRE_FOR_MOD_WRITE, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_RELEASE_FOR_MOD_WRITE, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_ACQUIRE_FOR_CC_FLUSH, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_RELEASE_FOR_CC_FLUSH, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_FAST_IO_CHECK_IF_POSSIBLE, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_NETWORK_QUERY_OPEN, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_MDL_READ, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_MDL_READ_COMPLETE, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_PREPARE_MDL_WRITE, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_MDL_WRITE_COMPLETE, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_VOLUME_MOUNT, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_VOLUME_DISMOUNT, 0, PtPreOperationPassThrough, PtPostOperationPassThrough },
{ IRP_MJ_OPERATION_END }
};
#pragma PAGEDCODE
NTSTATUS PtInstanceSetup (__in PCFLT_RELATED_OBJECTS FltObjects,__in FLT_INSTANCE_SETUP_FLAGS Flags,__in DEVICE_TYPE VolumeDeviceType,__in FLT_FILESYSTEM_TYPE VolumeFilesystemType)
{
PT_DBG_PRINT( 1,("PassThrough!PtInstanceSetup: Entered\n") );
return STATUS_SUCCESS;
}
#pragma PAGEDCODE
NTSTATUS PtInstanceQueryTeardown (__in PCFLT_RELATED_OBJECTS FltObjects,__in FLT_INSTANCE_QUERY_TEARDOWN_FLAGS Flags)
{
PT_DBG_PRINT( 1,("PassThrough!PtInstanceQueryTeardown: Entered\n") );
return STATUS_SUCCESS;
}
#pragma PAGEDCODE
VOID PtInstanceTeardownStart (__in PCFLT_RELATED_OBJECTS FltObjects,__in FLT_INSTANCE_TEARDOWN_FLAGS Flags)
{
PT_DBG_PRINT( 1, ("PassThrough!PtInstanceTeardownStart: Entered\n") );
}
#pragma PAGEDCODE
VOID PtInstanceTeardownComplete (__in PCFLT_RELATED_OBJECTS FltObjects,__in FLT_INSTANCE_TEARDOWN_FLAGS Flags)
{
PT_DBG_PRINT( 1,("PassThrough!PtInstanceTeardownComplete: Entered\n") );
}
#pragma PAGEDCODE
NTSTATUS PtUnload (__in FLT_FILTER_UNLOAD_FLAGS Flags)
{
PT_DBG_PRINT( 1,("PassThrough!PtUnload: Entered\n") );
FltUnregisterFilter( gFilterHandle );
return STATUS_SUCCESS;
}
CONST FLT_REGISTRATION FilterRegistration = {
sizeof( FLT_REGISTRATION ), // Size
FLT_REGISTRATION_VERSION, // Version
0, // Flags
NULL, // Context
Callbacks, // Operation callbacks
PtUnload, // MiniFilterUnload
PtInstanceSetup, // InstanceSetup
PtInstanceQueryTeardown, // InstanceQueryTeardown
PtInstanceTeardownStart, // InstanceTeardownStart
PtInstanceTeardownComplete, // InstanceTeardownComplete
NULL, // GenerateFileName
NULL, // GenerateDestinationFileName
NULL // NormalizeNameComponent
};
#pragma INITCODE
NTSTATUS DriverEntry (__in PDRIVER_OBJECT DriverObject,__in PUNICODE_STRING RegistryPath)
{
PT_DBG_PRINT( 1,("PassThrough!DriverEntry: Entered\n") );
FltRegisterFilter( DriverObject, &FilterRegistration,&gFilterHandle );
FltStartFiltering( gFilterHandle );
return 0;
}
//made by correy
WinVerifyTrust.Cpp
/*
检查一个pe文件是不是一个有效的数字签名。
开始以为用检查pe文件结构的办法就能实现,可是这个办法不全面,易出错。
还是用这个方便,安全。
本文修改自msdn.
*/
#include <windows.h>
#include <Softpub.h>
#pragma comment (lib, "wintrust")
BOOL VerifyEmbeddedSignature(LPCWSTR pwszSourceFile)
{
WINTRUST_FILE_INFO FileData;
memset(&FileData, 0, sizeof(FileData));
FileData.cbStruct = sizeof(WINTRUST_FILE_INFO);
FileData.pcwszFilePath = pwszSourceFile;
FileData.hFile = NULL;
FileData.pgKnownSubject = NULL;
WINTRUST_DATA WinTrustData;
memset(&WinTrustData, 0, sizeof(WinTrustData));
WinTrustData.cbStruct = sizeof(WinTrustData);
WinTrustData.pPolicyCallbackData = NULL;// Use default code signing EKU.
WinTrustData.pSIPClientData = NULL;// No data to pass to SIP.
WinTrustData.dwUIChoice = WTD_UI_NONE;// Disable WVT UI.
WinTrustData.fdwRevocationChecks = WTD_REVOKE_NONE; // No revocation checking.
WinTrustData.dwUnionChoice = WTD_CHOICE_FILE;// Verify an embedded signature on a file.
WinTrustData.dwStateAction = 0;// Default verification.
WinTrustData.hWVTStateData = NULL;// Not applicable for default verification of embedded signature.
WinTrustData.pwszURLReference = NULL;// Not used.
WinTrustData.dwUIContext = 0;
WinTrustData.pFile = &FileData;// Set pFile.
GUID WVTPolicyGUID = WINTRUST_ACTION_GENERIC_VERIFY_V2;
LONG lStatus = WinVerifyTrust(NULL,&WVTPolicyGUID,&WinTrustData);// 真正的开始.
if (ERROR_SUCCESS == lStatus)
{
MessageBox(0,L"The file you selected is signed and the signature was verified.",0,0);
}
else
{
MessageBox(0,L"其他的众多的失败之一",0,0);
return false;
}
return true;
}
int _tmain(int argc, _TCHAR* argv[])
{
VerifyEmbeddedSignature(L"E:\\signature\\exe.exe");
return 0;
}
订阅:
博文 (Atom)