OSDN Git Service

Add support for process protection (prevents from loading untrustworthy DLLs with...
authors_kawamoto <s_kawamoto@users.sourceforge.jp>
Thu, 29 Sep 2011 09:12:38 +0000 (18:12 +0900)
committers_kawamoto <s_kawamoto@users.sourceforge.jp>
Thu, 29 Sep 2011 09:12:38 +0000 (18:12 +0900)
Fix bugs of UTF-8 to UTF-16 API bridge.

15 files changed:
FFFTP.vc90.vcproj
FFFTP.vcproj
FFFTP_Eng_Release/FFFTP.exe
FFFTP_English.vc90.vcproj
FFFTP_English.vcproj
Release/FFFTP.exe
config.h
connect.c
getput.c
main.c
mbswrapper.c
mbswrapper.h
protectprocess.c [new file with mode: 0644]
protectprocess.h [new file with mode: 0644]
socketwrapper.c

index 6ea6f40..ba3fc8b 100644 (file)
                        <Tool
                                Name="VCLinkerTool"
                                AdditionalOptions="/MACHINE:I386"
-                               AdditionalDependencies="wsock32.lib comctl32.lib winmm.lib htmlhelp.lib"
+                               AdditionalDependencies="wsock32.lib comctl32.lib winmm.lib rasapi32.lib htmlhelp.lib sfc.lib wintrust.lib"
                                OutputFile=".\Debug\FFFTP.exe"
                                LinkIncremental="2"
                                SuppressStartupBanner="true"
                                GenerateManifest="false"
+                               DelayLoadDLLs="advapi32.dll;comctl32.dll;comdlg32.dll;gdi32.dll;sfc.dll;shell32.dll;ole32.dll;user32.dll;winmm.dll;wintrust.dll;wsock32.dll"
                                GenerateDebugInformation="true"
                                ProgramDatabaseFile=".\Debug\FFFTP.pdb"
                                SubSystem="2"
                        <Tool
                                Name="VCLinkerTool"
                                AdditionalOptions="/MACHINE:I386"
-                               AdditionalDependencies="wsock32.lib comctl32.lib winmm.lib RASAPI32.LIB htmlhelp.lib"
+                               AdditionalDependencies="wsock32.lib comctl32.lib winmm.lib rasapi32.lib htmlhelp.lib sfc.lib wintrust.lib"
                                OutputFile=".\Release\FFFTP.exe"
                                LinkIncremental="1"
                                SuppressStartupBanner="true"
                                GenerateManifest="false"
+                               DelayLoadDLLs="advapi32.dll;comctl32.dll;comdlg32.dll;gdi32.dll;sfc.dll;shell32.dll;ole32.dll;user32.dll;winmm.dll;wintrust.dll;wsock32.dll"
                                ProgramDatabaseFile=".\Release\FFFTP.pdb"
                                SubSystem="2"
                                RandomizedBaseAddress="1"
                                >
                        </File>
                        <File
+                               RelativePath=".\protectprocess.c"
+                               >
+                       </File>
+                       <File
                                RelativePath=".\ras.c"
                                >
                        </File>
                                >
                        </File>
                        <File
+                               RelativePath=".\protectprocess.h"
+                               >
+                       </File>
+                       <File
                                RelativePath=".\Resource\resource.h"
                                >
                        </File>
index ad16916..0d6d0c0 100644 (file)
                        <Tool\r
                                Name="VCLinkerTool"\r
                                AdditionalOptions="/MACHINE:I386"\r
-                               AdditionalDependencies="wsock32.lib comctl32.lib winmm.lib htmlhelp.lib"\r
+                               AdditionalDependencies="wsock32.lib comctl32.lib winmm.lib rasapi32.lib htmlhelp.lib sfc.lib wintrust.lib"\r
                                OutputFile=".\Debug\FFFTP.exe"\r
                                LinkIncremental="2"\r
                                SuppressStartupBanner="true"\r
                                GenerateManifest="false"\r
+                               DelayLoadDLLs="advapi32.dll;comctl32.dll;comdlg32.dll;gdi32.dll;sfc.dll;shell32.dll;ole32.dll;user32.dll;winmm.dll;wintrust.dll;wsock32.dll"\r
                                GenerateDebugInformation="true"\r
                                ProgramDatabaseFile=".\Debug\FFFTP.pdb"\r
                                SubSystem="2"\r
                        <Tool\r
                                Name="VCLinkerTool"\r
                                AdditionalOptions="/MACHINE:I386"\r
-                               AdditionalDependencies="wsock32.lib comctl32.lib winmm.lib RASAPI32.LIB htmlhelp.lib"\r
+                               AdditionalDependencies="wsock32.lib comctl32.lib winmm.lib rasapi32.lib htmlhelp.lib sfc.lib wintrust.lib"\r
                                OutputFile=".\Release\FFFTP.exe"\r
                                LinkIncremental="1"\r
                                SuppressStartupBanner="true"\r
                                GenerateManifest="false"\r
+                               DelayLoadDLLs="advapi32.dll;comctl32.dll;comdlg32.dll;gdi32.dll;sfc.dll;shell32.dll;ole32.dll;user32.dll;winmm.dll;wintrust.dll;wsock32.dll"\r
                                ProgramDatabaseFile=".\Release\FFFTP.pdb"\r
                                SubSystem="2"\r
                        />\r
                                >\r
                        </File>\r
                        <File\r
+                               RelativePath=".\protectprocess.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
                                RelativePath=".\ras.c"\r
                                >\r
                        </File>\r
                                >\r
                        </File>\r
                        <File\r
+                               RelativePath=".\protectprocess.h"\r
+                               >\r
+                       </File>\r
+                       <File\r
                                RelativePath=".\Resource\resource.h"\r
                                >\r
                        </File>\r
index 1269981..7e3b85c 100644 (file)
Binary files a/FFFTP_Eng_Release/FFFTP.exe and b/FFFTP_Eng_Release/FFFTP.exe differ
index 3226993..7b7a568 100644 (file)
                        <Tool
                                Name="VCLinkerTool"
                                AdditionalOptions="/MACHINE:I386"
-                               AdditionalDependencies="wsock32.lib comctl32.lib winmm.lib htmlhelp.lib"
+                               AdditionalDependencies="wsock32.lib comctl32.lib winmm.lib rasapi32.lib htmlhelp.lib sfc.lib wintrust.lib"
                                OutputFile=".\FFFTP_Eng_Debug\FFFTP.exe"
                                LinkIncremental="2"
                                SuppressStartupBanner="true"
                                GenerateManifest="false"
+                               DelayLoadDLLs="advapi32.dll;comctl32.dll;comdlg32.dll;gdi32.dll;sfc.dll;shell32.dll;ole32.dll;user32.dll;winmm.dll;wintrust.dll;wsock32.dll"
                                GenerateDebugInformation="true"
                                ProgramDatabaseFile=".\FFFTP_Eng_Debug\FFFTP.pdb"
                                SubSystem="2"
                        <Tool
                                Name="VCLinkerTool"
                                AdditionalOptions="/MACHINE:I386"
-                               AdditionalDependencies="wsock32.lib comctl32.lib winmm.lib htmlhelp.lib"
+                               AdditionalDependencies="wsock32.lib comctl32.lib winmm.lib rasapi32.lib htmlhelp.lib sfc.lib wintrust.lib"
                                OutputFile=".\FFFTP_Eng_Release\FFFTP.exe"
                                LinkIncremental="1"
                                SuppressStartupBanner="true"
                                GenerateManifest="false"
+                               DelayLoadDLLs="advapi32.dll;comctl32.dll;comdlg32.dll;gdi32.dll;sfc.dll;shell32.dll;ole32.dll;user32.dll;winmm.dll;wintrust.dll;wsock32.dll"
                                ProgramDatabaseFile=".\FFFTP_Eng_Release\FFFTP.pdb"
                                SubSystem="2"
                                RandomizedBaseAddress="1"
                                >
                        </File>
                        <File
+                               RelativePath=".\protectprocess.c"
+                               >
+                       </File>
+                       <File
                                RelativePath=".\ras.c"
                                >
                        </File>
                                >
                        </File>
                        <File
+                               RelativePath=".\protectprocess.h"
+                               >
+                       </File>
+                       <File
                                RelativePath=".\Resource_eng\resource.h"
                                >
                        </File>
                        RelativePath=".\Resource_eng\ffftp.exe.manifest"
                        >
                        <FileConfiguration
-                               Name="Release|Win32"
+                               Name="Debug|Win32"
+                               ExcludedFromBuild="true"
                                >
                                <Tool
                                        Name="VCCustomBuildTool"
                                />
                        </FileConfiguration>
                        <FileConfiguration
-                               Name="Debug|Win32"
-                               ExcludedFromBuild="true"
+                               Name="Release|Win32"
                                >
                                <Tool
                                        Name="VCCustomBuildTool"
index d2c99af..6eaf128 100644 (file)
                        <Tool\r
                                Name="VCLinkerTool"\r
                                AdditionalOptions="/MACHINE:I386"\r
-                               AdditionalDependencies="wsock32.lib comctl32.lib winmm.lib htmlhelp.lib"\r
+                               AdditionalDependencies="wsock32.lib comctl32.lib winmm.lib rasapi32.lib htmlhelp.lib sfc.lib wintrust.lib"\r
                                OutputFile=".\FFFTP_Eng_Debug\FFFTP.exe"\r
                                LinkIncremental="2"\r
                                SuppressStartupBanner="true"\r
                                GenerateManifest="false"\r
+                               DelayLoadDLLs="advapi32.dll;comctl32.dll;comdlg32.dll;gdi32.dll;sfc.dll;shell32.dll;ole32.dll;user32.dll;winmm.dll;wintrust.dll;wsock32.dll"\r
                                GenerateDebugInformation="true"\r
                                ProgramDatabaseFile=".\FFFTP_Eng_Debug\FFFTP.pdb"\r
                                SubSystem="2"\r
                        <Tool\r
                                Name="VCLinkerTool"\r
                                AdditionalOptions="/MACHINE:I386"\r
-                               AdditionalDependencies="wsock32.lib comctl32.lib winmm.lib htmlhelp.lib"\r
+                               AdditionalDependencies="wsock32.lib comctl32.lib winmm.lib rasapi32.lib htmlhelp.lib sfc.lib wintrust.lib"\r
                                OutputFile=".\FFFTP_Eng_Release\FFFTP.exe"\r
                                LinkIncremental="1"\r
                                SuppressStartupBanner="true"\r
                                GenerateManifest="false"\r
+                               DelayLoadDLLs="advapi32.dll;comctl32.dll;comdlg32.dll;gdi32.dll;sfc.dll;shell32.dll;ole32.dll;user32.dll;winmm.dll;wintrust.dll;wsock32.dll"\r
                                ProgramDatabaseFile=".\FFFTP_Eng_Release\FFFTP.pdb"\r
                                SubSystem="2"\r
                        />\r
                                >\r
                        </File>\r
                        <File\r
+                               RelativePath=".\protectprocess.c"\r
+                               >\r
+                       </File>\r
+                       <File\r
                                RelativePath=".\ras.c"\r
                                >\r
                        </File>\r
                                >\r
                        </File>\r
                        <File\r
+                               RelativePath=".\protectprocess.h"\r
+                               >\r
+                       </File>\r
+                       <File\r
                                RelativePath=".\Resource_eng\resource.h"\r
                                >\r
                        </File>\r
index 76f86a8..1a39387 100644 (file)
Binary files a/Release/FFFTP.exe and b/Release/FFFTP.exe differ
index 79ca376..4ac18ff 100644 (file)
--- a/config.h
+++ b/config.h
@@ -7,6 +7,8 @@
 #include "mbswrapper.h"\r
 // OpenSSL用ソケットラッパーを使用する\r
 #include "socketwrapper.h"\r
+// プロセスをDLL Injectionから保護する\r
+#include "protectprocess.h"\r
 // 使用するCPUを1個に限定する(マルチコアCPUの特定環境下でファイル通信中にクラッシュするバグ対策)\r
 #define DISABLE_MULTI_CPUS\r
 // ファイル転送用のネットワークバッファを無効にする(通信中止後にリモートのディレクトリが表示されないバグ対策)\r
index 7259032..9798a44 100644 (file)
--- a/connect.c
+++ b/connect.c
@@ -1092,8 +1092,8 @@ int AskShareProh(void)
        int Sts;\r
 \r
        Sts = YES;\r
-       if(CmdCtrlSocket == TrnCtrlSocket)\r
-               Sts = NO;\r
+//     if(CmdCtrlSocket == TrnCtrlSocket)\r
+//             Sts = NO;\r
 \r
        return(Sts);\r
 }\r
index d7e00c2..be0d5db 100644 (file)
--- a/getput.c
+++ b/getput.c
@@ -120,6 +120,8 @@ static HANDLE hListAccMutex;                        /* 転送ファイルアクセス用ミューテ
 \r
 static int TransFiles = 0;                             /* 転送待ちファイル数 */\r
 static TRANSPACKET *TransPacketBase = NULL;    /* 転送ファイルリスト */\r
+// 同時接続対応\r
+static TRANSPACKET *NextTransPacketBase = NULL;\r
 \r
 // 同時接続対応\r
 //static int Canceled;         /* 中止フラグ YES/NO */\r
@@ -373,6 +375,9 @@ void AddTransFileList(TRANSPACKET *Pkt)
                        PostMessage(GetMainHwnd(), WM_CHANGE_COND, 0, 0);\r
                }\r
        }\r
+       // 同時接続対応\r
+       if(NextTransPacketBase == NULL)\r
+               NextTransPacketBase = TransPacketBase;\r
        ReleaseMutex(hListAccMutex);\r
 \r
        return;\r
@@ -413,6 +418,9 @@ void AppendTransFileList(TRANSPACKET *Pkt)
                        Pos = Pos->Next;\r
                Pos->Next = Pkt;\r
        }\r
+       // 同時接続対応\r
+       if(NextTransPacketBase == NULL)\r
+               NextTransPacketBase = TransPacketBase;\r
 \r
        while(Pkt != NULL)\r
        {\r
@@ -507,6 +515,8 @@ static void EraseTransFileList(void)
                }\r
        }\r
        TransPacketBase = NotDel;\r
+       // 同時接続対応\r
+       NextTransPacketBase = TransPacketBase;\r
        TransFiles = 0;\r
        PostMessage(GetMainHwnd(), WM_CHANGE_COND, 0, 0);\r
        ReleaseMutex(hListAccMutex);\r
@@ -611,8 +621,10 @@ static ULONG WINAPI TransferThread(void *Dummy)
        char Tmp[FMAX_PATH+1];\r
        int CwdSts;\r
        int GoExit;\r
-       int Down;\r
-       int Up;\r
+//     int Down;\r
+//     int Up;\r
+       static int Down;\r
+       static int Up;\r
        int DelNotify;\r
        int ThreadCount;\r
        SOCKET CmdSkt;\r
@@ -650,6 +662,12 @@ static ULONG WINAPI TransferThread(void *Dummy)
 //             Canceled = NO;\r
                Canceled[ThreadCount] = NO;\r
 \r
+               while(TransPacketBase != NULL && strcmp(TransPacketBase->Cmd, "") == 0)\r
+               {\r
+                       Pos = TransPacketBase;\r
+                       TransPacketBase = TransPacketBase->Next;\r
+                       free(Pos);\r
+               }\r
                NewCmdSkt = AskCmdCtrlSkt();\r
                if(TransPacketBase && NewCmdSkt != INVALID_SOCKET && ThreadCount < AskMaxThreadCount())\r
                {\r
@@ -682,10 +700,10 @@ static ULONG WINAPI TransferThread(void *Dummy)
                }\r
                CmdSkt = NewCmdSkt;\r
 //             if(TransPacketBase != NULL)\r
-               if(TrnSkt != INVALID_SOCKET && TransPacketBase != NULL)\r
+               if(TrnSkt != INVALID_SOCKET && NextTransPacketBase != NULL)\r
                {\r
-                       Pos = TransPacketBase;\r
-                       TransPacketBase = TransPacketBase->Next;\r
+                       Pos = NextTransPacketBase;\r
+                       NextTransPacketBase = NextTransPacketBase->Next;\r
                        // ディレクトリ操作は非同期で行わない\r
 //                     ReleaseMutex(hListAccMutex);\r
                        if(hWndTrans == NULL)\r
@@ -1003,6 +1021,7 @@ static ULONG WINAPI TransferThread(void *Dummy)
                                        for(i = 0; i < MAX_DATA_CONNECTION; i++)\r
                                                Canceled[i] = YES;\r
                                        EraseTransFileList();\r
+                                       Pos = NULL;\r
                                }\r
                                else\r
                                {\r
@@ -1032,7 +1051,8 @@ static ULONG WINAPI TransferThread(void *Dummy)
                        }\r
                        if(hWndTrans != NULL)\r
                                SendMessage(hWndTrans, WM_SET_PACKET, 0, 0);\r
-                       free(Pos);\r
+                       if(Pos != NULL)\r
+                               strcpy(Pos->Cmd, "");\r
                }\r
 //             else\r
                else if(TransPacketBase == NULL)\r
@@ -1047,20 +1067,20 @@ static ULONG WINAPI TransferThread(void *Dummy)
                                        DestroyWindow(hWndTrans);\r
                                        hWndTrans = NULL;\r
 \r
-                                       if(GoExit == YES)\r
-                                       {\r
-                                               SoundPlay(SND_TRANS);\r
-\r
-                                               if(AskAutoExit() == NO)\r
-                                               {\r
-                                                       if(Down == YES)\r
-                                                               PostMessage(GetMainHwnd(), WM_REFRESH_LOCAL_FLG, 0, 0);\r
-                                                       if(Up == YES)\r
-                                                               PostMessage(GetMainHwnd(), WM_REFRESH_REMOTE_FLG, 0, 0);\r
-                                               }\r
-                                               Down = NO;\r
-                                               Up = NO;\r
-                                       }\r
+//                                     if(GoExit == YES)\r
+//                                     {\r
+//                                             SoundPlay(SND_TRANS);\r
+//\r
+//                                             if(AskAutoExit() == NO)\r
+//                                             {\r
+//                                                     if(Down == YES)\r
+//                                                             PostMessage(GetMainHwnd(), WM_REFRESH_LOCAL_FLG, 0, 0);\r
+//                                                     if(Up == YES)\r
+//                                                             PostMessage(GetMainHwnd(), WM_REFRESH_REMOTE_FLG, 0, 0);\r
+//                                             }\r
+//                                             Down = NO;\r
+//                                             Up = NO;\r
+//                                     }\r
                                }\r
                        }\r
                        BackgrndMessageProc();\r
@@ -1068,6 +1088,16 @@ static ULONG WINAPI TransferThread(void *Dummy)
 \r
                        if(GoExit == YES)\r
                        {\r
+                               SoundPlay(SND_TRANS);\r
+                               if(AskAutoExit() == NO)\r
+                               {\r
+                                       if(Down == YES)\r
+                                               PostMessage(GetMainHwnd(), WM_REFRESH_LOCAL_FLG, 0, 0);\r
+                                       if(Up == YES)\r
+                                               PostMessage(GetMainHwnd(), WM_REFRESH_REMOTE_FLG, 0, 0);\r
+                               }\r
+                               Down = NO;\r
+                               Up = NO;\r
                                PostMessage(GetMainHwnd(), WM_COMMAND, MAKEWPARAM(MENU_AUTO_EXIT, 0), 0);\r
                                GoExit = NO;\r
                        }\r
diff --git a/main.c b/main.c
index 704be47..b6cef18 100644 (file)
--- a/main.c
+++ b/main.c
@@ -232,6 +232,34 @@ int PASCAL WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLi
        int Ret;\r
        BOOL Sts;\r
 \r
+       // プロセス保護\r
+#ifdef ENABLE_PROCESS_PROTECTION\r
+       BOOL bProtect;\r
+       char* pCommand;\r
+       char Option[FMAX_PATH+1];\r
+       bProtect = FALSE;\r
+       pCommand = lpszCmdLine;\r
+       while(pCommand = GetToken(pCommand, Option))\r
+       {\r
+               if(strcmp(Option, "--protect") == 0)\r
+               {\r
+                       bProtect = TRUE;\r
+                       break;\r
+               }\r
+       }\r
+       InitializeLoadLibraryHook();\r
+       if(bProtect)\r
+       {\r
+#ifndef _DEBUG\r
+               if(IsDebuggerPresent() || RestartProtectedProcess(" --restart"))\r
+                       return 0;\r
+#endif\r
+               // DLLの検証の前にロードされている必要があるDLL\r
+               LoadLibrary("shell32.dll");\r
+               EnableLoadLibraryHook(TRUE);\r
+       }\r
+#endif\r
+\r
 #ifdef DISABLE_MULTI_CPUS\r
        SetProcessAffinityMask(GetCurrentProcess(), 1);\r
 #endif\r
@@ -244,6 +272,7 @@ int PASCAL WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLi
 \r
        InitCommonControls();\r
 \r
+       // FTPS対応\r
 #ifdef USE_OPENSSL\r
        LoadOpenSSL();\r
 #endif\r
@@ -277,6 +306,7 @@ int PASCAL WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLi
                Ret = Msg.wParam;\r
        }\r
     UnregisterClass(FtpClassStr, hInstFtp);\r
+       // FTPS対応\r
 #ifdef USE_OPENSSL\r
        FreeOpenSSL();\r
 #endif\r
@@ -1697,6 +1727,15 @@ static int AnalyzeComLine(char *Str, int *AutoConnect, int *CmdOption, char *unc
                        {\r
                                hHelpWin = HtmlHelp(NULL, AskHelpFilePath(), HH_HELP_CONTEXT, IDH_HELP_TOPIC_0000024);\r
                        }\r
+                       // プロセス保護\r
+#ifdef ENABLE_PROCESS_PROTECTION\r
+                       else if(strcmp(Tmp, "--restart") == 0)\r
+                       {\r
+                       }\r
+                       else if(strcmp(Tmp, "--protect") == 0)\r
+                       {\r
+                       }\r
+#endif\r
                        else\r
                        {\r
                                SetTaskMsg(MSGJPN180, Tmp);\r
index 585a26b..74a63d9 100644 (file)
@@ -1,4 +1,4 @@
-// mbswrapper.cpp
+// mbswrapper.c
 // Copyright (C) 2011 Suguru Kawamoto
 // マルチバイト文字ワイド文字APIラッパー
 // マルチバイト文字はUTF-8、ワイド文字はUTF-16であるものとする
@@ -40,6 +40,16 @@ int WtoM(LPSTR pDst, int size, LPCWSTR pSrc, int count)
        return WideCharToMultiByte(CP_UTF8, 0, pSrc, count, NULL, 0, NULL, NULL);
 }
 
+// Shift_JIS文字列からワイド文字列へ変換
+int AtoW(LPWSTR pDst, int size, LPCSTR pSrc, int count)
+{
+       if(pSrc < (LPCSTR)0x00010000 || pSrc == (LPCSTR)~0)
+               return 0;
+       if(pDst)
+               return MultiByteToWideChar(CP_ACP, 0, pSrc, count, pDst, size);
+       return MultiByteToWideChar(CP_ACP, 0, pSrc, count, NULL, 0);
+}
+
 // ワイド文字列からShift_JIS文字列へ変換
 int WtoA(LPSTR pDst, int size, LPCWSTR pSrc, int count)
 {
@@ -179,6 +189,24 @@ int WtoMMultiString(LPSTR pDst, int size, LPCWSTR pSrc)
        return i;
 }
 
+// NULL区切りShift_JIS文字列からワイド文字列へ変換
+int AtoWMultiString(LPWSTR pDst, int size, LPCSTR pSrc)
+{
+       int i;
+       if(pSrc < (LPCSTR)0x00010000 || pSrc == (LPCSTR)~0)
+               return 0;
+       if(!pDst)
+               return GetMultiStringLengthA(pSrc);
+       i = 0;
+       while(*pSrc != '\0')
+       {
+               i += MultiByteToWideChar(CP_ACP, 0, pSrc, -1, pDst + i, size - i - 1);
+               pSrc += strlen(pSrc) + 1;
+       }
+       pDst[i] = L'\0';
+       return i;
+}
+
 // NULL区切りワイド文字列からShift_JIS文字列へ変換
 int WtoAMultiString(LPSTR pDst, int size, LPCWSTR pSrc)
 {
@@ -319,6 +347,24 @@ char* DuplicateWtoM(LPCWSTR lpString, int c)
        return p;
 }
 
+// メモリを確保してShift_JIS文字列からワイド文字列へ変換
+wchar_t* DuplicateAtoW(LPCSTR lpString, int c)
+{
+       wchar_t* p;
+       int i;
+       if(lpString < (LPCSTR)0x00010000 || lpString == (LPCSTR)~0)
+               return (wchar_t*)lpString;
+       if(c < 0)
+               c = strlen(lpString);
+       p = AllocateStringW(AtoW(NULL, 0, lpString, c) + 1);
+       if(p)
+       {
+               i = AtoW(p, 65535, lpString, c);
+               p[i] = L'\0';
+       }
+       return p;
+}
+
 // メモリを確保してワイド文字列からShift_JIS文字列へ変換
 char* DuplicateWtoA(LPCWSTR lpString, int c)
 {
@@ -351,6 +397,7 @@ void FreeDuplicatedString(void* p)
 // マルチバイト文字バッファ pm%d
 // 引数バッファ a%d
 
+#pragma warning(disable:4102)
 #define START_ROUTINE                                  do{
 #define END_ROUTINE                                            }while(0);end_of_routine:
 #define QUIT_ROUTINE                                   goto end_of_routine;
@@ -367,6 +414,18 @@ END_ROUTINE
        return r;
 }
 
+HMODULE LoadLibraryM(LPCSTR lpLibFileName)
+{
+       HMODULE r = NULL;
+       wchar_t* pw0 = NULL;
+START_ROUTINE
+       pw0 = DuplicateMtoW(lpLibFileName, -1);
+       r = LoadLibraryW(pw0);
+END_ROUTINE
+       FreeDuplicatedString(pw0);
+       return r;
+}
+
 HANDLE CreateFileM(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile)
 {
        HANDLE r = INVALID_HANDLE_VALUE;
@@ -886,11 +945,24 @@ END_ROUTINE
        return r;
 }
 
+LPSTR GetCommandLineM()
+{
+       LPSTR r = 0;
+       static char* pm0 = NULL;
+START_ROUTINE
+       if(!pm0)
+               pm0 = DuplicateWtoM(GetCommandLineW(), -1);
+       r = pm0;
+END_ROUTINE
+       return r;
+}
+
 DWORD GetCurrentDirectoryM(DWORD nBufferLength, LPSTR lpBuffer)
 {
        DWORD r = 0;
        wchar_t* pw0 = NULL;
 START_ROUTINE
+       // TODO: バッファが不十分な場合に必要なサイズを返す
        pw0 = AllocateStringW(nBufferLength * 4);
        GetCurrentDirectoryW(nBufferLength * 4, pw0);
        WtoM(lpBuffer, nBufferLength, pw0, -1);
@@ -1130,7 +1202,7 @@ START_ROUTINE
                        pwPage[i].pfnDlgProc = v0->ppsp[i].pfnDlgProc;
                        pwPage[i].lParam = v0->ppsp[i].lParam;
                        // TODO: pfnCallback
-                       pwPage[i].pfnCallback = v0->ppsp[i].pfnCallback;
+                       pwPage[i].pfnCallback = (LPFNPSPCALLBACKW)v0->ppsp[i].pfnCallback;
                        pwPage[i].pcRefParent = v0->ppsp[i].pcRefParent;
 //                     pwPage[i].pszHeaderTitle = DuplicateMtoW(v0->ppsp[i].pszHeaderTitle, -1);
 //                     pwPage[i].pszHeaderSubTitle = DuplicateMtoW(v0->ppsp[i].pszHeaderSubTitle, -1);
@@ -1144,21 +1216,21 @@ START_ROUTINE
        a0.pfnCallback = v0->pfnCallback;
        r = PropertySheetW(&a0);
        if(a0.dwFlags & PSH_USEICONID)
-               FreeDuplicatedString(a0.pszIcon);
-       FreeDuplicatedString(a0.pszCaption);
-       FreeDuplicatedString(a0.pStartPage);
+               FreeDuplicatedString((void*)a0.pszIcon);
+       FreeDuplicatedString((void*)a0.pszCaption);
+       FreeDuplicatedString((void*)a0.pStartPage);
        if(pwPage)
        {
                for(i = 0; i < v0->nPages; i++)
                {
-                       FreeDuplicatedString(pwPage[i].pszTemplate);
+                       FreeDuplicatedString((void*)pwPage[i].pszTemplate);
                        if(pwPage[i].dwFlags & PSP_USEICONID)
-                               FreeDuplicatedString(pwPage[i].pszIcon);
+                               FreeDuplicatedString((void*)pwPage[i].pszIcon);
                        if(pwPage[i].dwFlags & PSP_USETITLE)
-                               FreeDuplicatedString(pwPage[i].pszTitle);
-//                     FreeDuplicatedString(pwPage[i].pszHeaderTitle);
-//                     FreeDuplicatedString(pwPage[i].pszHeaderSubTitle);
-//                     FreeDuplicatedString(pwPage[i].pszbmHeader);
+                               FreeDuplicatedString((void*)pwPage[i].pszTitle);
+//                     FreeDuplicatedString((void*)pwPage[i].pszHeaderTitle);
+//                     FreeDuplicatedString((void*)pwPage[i].pszHeaderSubTitle);
+//                     FreeDuplicatedString((void*)pwPage[i].pszbmHeader);
                }
                free(pwPage);
        }
@@ -1601,7 +1673,7 @@ START_ROUTINE
        v0->nFontType = a0.nFontType;
        if(pwlf)
                free(pwlf);
-       FreeDuplicatedString(a0.lpTemplateName);
+       FreeDuplicatedString((void*)a0.lpTemplateName);
        FreeDuplicatedString(a0.lpszStyle);
 END_ROUTINE
        FreeDuplicatedString(pw0);
@@ -1704,7 +1776,7 @@ START_ROUTINE
        if(wr)
        {
                *wr = L'\0';
-               r = _Str + WtoM(NULL, 0, pw0, -1) - 1;
+               r = (unsigned char*)_Str + WtoM(NULL, 0, pw0, -1) - 1;
        }
 END_ROUTINE
        FreeDuplicatedString(pw0);
@@ -1723,7 +1795,7 @@ START_ROUTINE
        if(wr)
        {
                *wr = L'\0';
-               r = _Str + WtoM(NULL, 0, pw0, -1) - 1;
+               r = (unsigned char*)_Str + WtoM(NULL, 0, pw0, -1) - 1;
        }
 END_ROUTINE
        FreeDuplicatedString(pw0);
@@ -1743,7 +1815,7 @@ START_ROUTINE
        if(wr)
        {
                *wr = L'\0';
-               r = _Str + WtoM(NULL, 0, pw0, -1) - 1;
+               r = (unsigned char*)_Str + WtoM(NULL, 0, pw0, -1) - 1;
        }
 END_ROUTINE
        FreeDuplicatedString(pw0);
@@ -1835,7 +1907,7 @@ START_ROUTINE
        if(wr)
        {
                *wr = L'\0';
-               r = _Str + WtoM(NULL, 0, pw0, -1) - 1;
+               r = (unsigned char*)_Str + WtoM(NULL, 0, pw0, -1) - 1;
        }
 END_ROUTINE
        FreeDuplicatedString(pw0);
index cb4f3ab..3ca2f26 100644 (file)
@@ -14,6 +14,9 @@
 #undef WinMain
 #define WinMain WinMainM
 int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow);
+#undef LoadLibrary
+#define LoadLibrary LoadLibraryM
+HMODULE LoadLibraryM(LPCSTR lpLibFileName);
 #undef CreateFile
 #define CreateFile CreateFileM
 HANDLE CreateFileM(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile);
@@ -62,6 +65,9 @@ BOOL SetWindowTextM(HWND hWnd, LPCSTR lpString);
 #undef DragQueryFile
 #define DragQueryFile DragQueryFileM
 UINT DragQueryFileM(HDROP hDrop, UINT iFile, LPSTR lpszFile, UINT cch);
+#undef GetCommandLine
+#define GetCommandLine GetCommandLineM
+LPSTR GetCommandLineM();
 #undef GetCurrentDirectory
 #define GetCurrentDirectory GetCurrentDirectoryM
 DWORD GetCurrentDirectoryM(DWORD nBufferLength, LPSTR lpBuffer);
@@ -204,15 +210,17 @@ FILE * fopenM(const char * _Filename, const char * _Mode);
 
 int MtoW(LPWSTR pDst, int size, LPCSTR pSrc, int count);
 int WtoM(LPSTR pDst, int size, LPCWSTR pSrc, int count);
+int AtoW(LPWSTR pDst, int size, LPCSTR pSrc, int count);
 int WtoA(LPSTR pDst, int size, LPCWSTR pSrc, int count);
 int TerminateStringM(LPSTR lpString, int size);
 int TerminateStringW(LPWSTR lpString, int size);
-int TerminateStringA(LPWSTR lpString, int size);
+int TerminateStringA(LPSTR lpString, int size);
 size_t GetMultiStringLengthM(LPCSTR lpString);
 size_t GetMultiStringLengthW(LPCWSTR lpString);
-size_t GetMultiStringLengthA(LPCWSTR lpString);
+size_t GetMultiStringLengthA(LPCSTR lpString);
 int MtoWMultiString(LPWSTR pDst, int size, LPCSTR pSrc);
 int WtoMMultiString(LPSTR pDst, int size, LPCWSTR pSrc);
+int AtoWMultiString(LPWSTR pDst, int size, LPCSTR pSrc);
 int WtoAMultiString(LPSTR pDst, int size, LPCWSTR pSrc);
 char* AllocateStringM(int size);
 wchar_t* AllocateStringW(int size);
@@ -222,6 +230,7 @@ wchar_t* DuplicateMtoWBuffer(LPCSTR lpString, int c, int size);
 wchar_t* DuplicateMtoWMultiString(LPCSTR lpString);
 wchar_t* DuplicateMtoWMultiStringBuffer(LPCSTR lpString, int size);
 char* DuplicateWtoM(LPCWSTR lpString, int c);
+wchar_t* DuplicateAtoW(LPCSTR lpString, int c);
 char* DuplicateWtoA(LPCWSTR lpString, int c);
 void FreeDuplicatedString(void* p);
 
diff --git a/protectprocess.c b/protectprocess.c
new file mode 100644 (file)
index 0000000..1492bc6
--- /dev/null
@@ -0,0 +1,576 @@
+// protectprocess.c
+// Copyright (C) 2011 Suguru Kawamoto
+// \83v\83\8d\83Z\83X\82Ì\95Û\8cì
+
+// \8e\9f\82Ì\92\86\82©\82ç1\8cÂ\82Ì\82Ý\97L\8cø\82É\82·\82é
+// \83t\83b\83N\90æ\82Ì\8aÖ\90\94\82Ì\83R\81[\83h\82ð\8f\91\82«\8a·\82¦\82é
+// \91S\82Ä\82Ì\8cÄ\82Ñ\8fo\82µ\82ð\83t\83b\83N\89Â\94\\82¾\82ª\8c´\97\9d\93I\82É\93ñ\8fd\8cÄ\82Ñ\8fo\82µ\82É\91Î\89\9e\82Å\82«\82È\82¢
+#define USE_CODE_HOOK
+// \83t\83b\83N\90æ\82Ì\8aÖ\90\94\82Ì\83C\83\93\83|\81[\83g\83A\83h\83\8c\83X\83e\81[\83u\83\8b\82ð\8f\91\82«\8a·\82¦\82é
+// \93ñ\8fd\8cÄ\82Ñ\8fo\82µ\82ª\89Â\94\\82¾\82ª\8cÄ\82Ñ\8fo\82µ\95û\96@\82É\82æ\82Á\82Ä\82Í\83t\83b\83N\82ð\89ñ\94ð\82³\82ê\82é
+//#define USE_IAT_HOOK
+
+// \83t\83b\83N\91Î\8fÛ\82Ì\8aÖ\90\94\96¼ %s
+// \83t\83b\83N\91Î\8fÛ\82Ì\8c^ _%s
+// \83t\83b\83N\91Î\8fÛ\82Ì\83|\83C\83\93\83^ p_%s
+// \83t\83b\83N\97p\82Ì\8aÖ\90\94\96¼ h_%s
+// \83t\83b\83N\91Î\8fÛ\82Ì\83R\81[\83h\82Ì\83o\83b\83N\83A\83b\83v c_%s
+
+#define _WIN32_WINNT 0x0600
+
+#include <tchar.h>
+#include <windows.h>
+#include <ntsecapi.h>
+#include <wincrypt.h>
+#include <wintrust.h>
+#include <softpub.h>
+#include <aclapi.h>
+#include <sfc.h>
+#ifdef USE_IAT_HOOK
+#include <tlhelp32.h>
+#include <dbghelp.h>
+#endif
+
+#define DO_NOT_REPLACE
+#include "protectprocess.h"
+#include "mbswrapper.h"
+
+#ifdef USE_IAT_HOOK
+#pragma comment(lib, "dbghelp.lib")
+#endif
+
+#ifdef USE_CODE_HOOK
+#if defined(_X86_)
+#define HOOK_JUMP_CODE_LENGTH 5
+#elif defined(_AMD64_)
+#define HOOK_JUMP_CODE_LENGTH 14
+#endif
+#endif
+
+BOOL HookFunctionInCode(void* pOriginal, void* pNew, void* pBackupCode, BOOL bRestore);
+
+// \95Ï\90\94\82Ì\90é\8c¾
+#ifdef USE_CODE_HOOK
+#define HOOK_FUNCTION_VAR(name) _##name p_##name;BYTE c_##name[HOOK_JUMP_CODE_LENGTH * 2];
+#endif
+#ifdef USE_IAT_HOOK
+#define HOOK_FUNCTION_VAR(name) _##name p_##name;
+#endif
+// \8aÖ\90\94\83|\83C\83\93\83^\82ð\8eæ\93¾
+#define GET_FUNCTION(h, name) p_##name = (_##name)GetProcAddress(h, #name)
+// \83t\83b\83N\91Î\8fÛ\82Ì\83R\81[\83h\82ð\92u\8a·\82µ\82Ä\83t\83b\83N\82ð\8aJ\8en
+#define SET_HOOK_FUNCTION(name) HookFunctionInCode(p_##name, h_##name, &c_##name, FALSE)
+// \83t\83b\83N\91Î\8fÛ\82ð\8cÄ\82Ñ\8fo\82·\91O\82É\91Î\8fÛ\82Ì\83R\81[\83h\82ð\95\9c\8c³
+#define START_HOOK_FUNCTION(name) HookFunctionInCode(p_##name, h_##name, &c_##name, TRUE)
+// \83t\83b\83N\91Î\8fÛ\82ð\8cÄ\82Ñ\8fo\82µ\82½\8cã\82É\91Î\8fÛ\82Ì\83R\81[\83h\82ð\92u\8a·
+#define END_HOOK_FUNCTION(name) HookFunctionInCode(p_##name, h_##name, NULL, FALSE)
+
+HOOK_FUNCTION_VAR(LoadLibraryA)
+HOOK_FUNCTION_VAR(LoadLibraryW)
+HOOK_FUNCTION_VAR(LoadLibraryExA)
+HOOK_FUNCTION_VAR(LoadLibraryExW)
+
+// \83h\83L\83\85\83\81\83\93\83g\82ª\96³\82¢\82½\82ß\8c´\88ö\82Í\95s\96¾\82¾\82ª\91æ2\88ø\90\94\82Í\83|\83C\83\93\83^\82Å\82È\82¢\82Æ\83G\83\89\81[\82É\82È\82é\8fê\8d\87\82ª\82 \82é
+//typedef NTSTATUS (WINAPI* _LdrLoadDll)(LPCWSTR, DWORD, UNICODE_STRING*, HMODULE*);
+typedef NTSTATUS (WINAPI* _LdrLoadDll)(LPCWSTR, DWORD*, UNICODE_STRING*, HMODULE*);
+// \83h\83L\83\85\83\81\83\93\83g\82ª\96³\82¢\82½\82ß\8c´\88ö\82Í\95s\96¾\82¾\82ª\91æ2\88ø\90\94\82Í\83|\83C\83\93\83^\82Å\82È\82¢\82Æ\83G\83\89\81[\82É\82È\82é\8fê\8d\87\82ª\82 \82é
+//typedef NTSTATUS (WINAPI* _LdrGetDllHandle)(LPCWSTR, DWORD, UNICODE_STRING*, HMODULE*);
+typedef NTSTATUS (WINAPI* _LdrGetDllHandle)(LPCWSTR, DWORD*, UNICODE_STRING*, HMODULE*);
+typedef NTSTATUS (WINAPI* _LdrAddRefDll)(DWORD, HMODULE);
+
+_LdrLoadDll p_LdrLoadDll;
+_LdrGetDllHandle p_LdrGetDllHandle;
+_LdrAddRefDll p_LdrAddRefDll;
+
+#define MAX_MD5_HASH_TABLE 16
+
+BYTE g_MD5HashTable[MAX_MD5_HASH_TABLE][16];
+
+// \88È\89º\83t\83b\83N\8aÖ\90\94
+// \83t\83b\83N\91Î\8fÛ\82ð\8cÄ\82Ñ\8fo\82·\8fê\8d\87\82Í\91O\8cã\82ÅSTART_HOOK_FUNCTION\82ÆEND_HOOK_FUNCTION\82ð\8eÀ\8ds\82·\82é\95K\97v\82ª\82 \82é
+
+HMODULE WINAPI h_LoadLibraryA(LPCSTR lpLibFileName)
+{
+       HMODULE r = NULL;
+       if(GetModuleHandleA(lpLibFileName) || IsModuleTrustedA(lpLibFileName))
+       {
+               wchar_t* pw0 = NULL;
+               pw0 = DuplicateAtoW(lpLibFileName, -1);
+               r = System_LoadLibrary(pw0, NULL, 0);
+               FreeDuplicatedString(pw0);
+       }
+       return r;
+}
+
+HMODULE WINAPI h_LoadLibraryW(LPCWSTR lpLibFileName)
+{
+       HMODULE r = NULL;
+       if(GetModuleHandleW(lpLibFileName) || IsModuleTrustedW(lpLibFileName))
+               r = System_LoadLibrary(lpLibFileName, NULL, 0);
+       return r;
+}
+
+HMODULE WINAPI h_LoadLibraryExA(LPCSTR lpLibFileName, HANDLE hFile, DWORD dwFlags)
+{
+       HMODULE r = NULL;
+       if(GetModuleHandleA(lpLibFileName) || IsModuleTrustedA(lpLibFileName))
+       {
+               wchar_t* pw0 = NULL;
+               pw0 = DuplicateAtoW(lpLibFileName, -1);
+               r = System_LoadLibrary(pw0, hFile, dwFlags);
+               FreeDuplicatedString(pw0);
+       }
+       return r;
+}
+
+HMODULE WINAPI h_LoadLibraryExW(LPCWSTR lpLibFileName, HANDLE hFile, DWORD dwFlags)
+{
+       HMODULE r = NULL;
+       if(GetModuleHandleW(lpLibFileName) || IsModuleTrustedW(lpLibFileName))
+               r = System_LoadLibrary(lpLibFileName, hFile, dwFlags);
+       return r;
+}
+
+// \88È\89º\83w\83\8b\83p\81[\8aÖ\90\94
+
+BOOL GetMD5HashOfFile(LPCWSTR Filename, void* pHash)
+{
+       BOOL bResult;
+       HCRYPTPROV hProv;
+       HCRYPTHASH hHash;
+       HANDLE hFile;
+       DWORD Size;
+       void* pData;
+       DWORD dw;
+       bResult = FALSE;
+       if(CryptAcquireContextW(&hProv, NULL, NULL, PROV_RSA_FULL, 0) || CryptAcquireContextW(&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET))
+       {
+               if(CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash))
+               {
+                       if((hFile = CreateFileW(Filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) != INVALID_HANDLE_VALUE)
+                       {
+                               Size = GetFileSize(hFile, NULL);
+                               if(pData = VirtualAlloc(NULL, Size, MEM_COMMIT, PAGE_READWRITE))
+                               {
+                                       VirtualLock(pData, Size);
+                                       if(ReadFile(hFile, pData, Size, &dw, NULL))
+                                       {
+                                               if(CryptHashData(hHash, (BYTE*)pData, Size, 0))
+                                               {
+                                                       dw = 16;
+                                                       if(CryptGetHashParam(hHash, HP_HASHVAL, (BYTE*)pHash, &dw, 0))
+                                                               bResult = TRUE;
+                                               }
+                                       }
+                                       VirtualUnlock(pData, Size);
+                                       VirtualFree(pData, Size, MEM_DECOMMIT);
+                               }
+                               CloseHandle(hFile);
+                       }
+                       CryptDestroyHash(hHash);
+               }
+               CryptReleaseContext(hProv, 0);
+       }
+       return bResult;
+}
+
+#ifdef USE_CODE_HOOK
+BOOL HookFunctionInCode(void* pOriginal, void* pNew, void* pBackupCode, BOOL bRestore)
+{
+       BOOL bResult;
+       DWORD Protect;
+#if defined(_X86_)
+       BYTE JumpCode[HOOK_JUMP_CODE_LENGTH] = {0xe9, 0x00, 0x00, 0x00, 0x00};
+       size_t Relative;
+       Relative = (size_t)pNew - (size_t)pOriginal - HOOK_JUMP_CODE_LENGTH;
+       memcpy(&JumpCode[1], &Relative, 4);
+       bResult = FALSE;
+       if(bRestore)
+       {
+               if(VirtualProtect(pOriginal, HOOK_JUMP_CODE_LENGTH, PAGE_EXECUTE_READWRITE, &Protect))
+               {
+                       memcpy(pOriginal, pBackupCode, HOOK_JUMP_CODE_LENGTH);
+                       VirtualProtect(pOriginal, HOOK_JUMP_CODE_LENGTH, Protect, &Protect);
+                       bResult = TRUE;
+               }
+       }
+       else
+       {
+               if(pBackupCode)
+                       memcpy(pBackupCode, pOriginal, HOOK_JUMP_CODE_LENGTH);
+               if(VirtualProtect(pOriginal, HOOK_JUMP_CODE_LENGTH, PAGE_EXECUTE_READWRITE, &Protect))
+               {
+                       memcpy(pOriginal, &JumpCode, HOOK_JUMP_CODE_LENGTH);
+                       VirtualProtect(pOriginal, HOOK_JUMP_CODE_LENGTH, Protect, &Protect);
+                       bResult = TRUE;
+               }
+       }
+#elif defined(_AMD64_)
+       BYTE JumpCode[HOOK_JUMP_CODE_LENGTH] = {0xff, 0x25, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+       size_t Absolute;
+       Absolute = (size_t)pOriginal;
+       memcpy(&JumpCode[6], &Absolute, 8);
+       bResult = FALSE;
+       if(bRestore)
+       {
+               if(VirtualProtect(pOriginal, HOOK_JUMP_CODE_LENGTH, PAGE_EXECUTE_READWRITE, &Protect))
+               {
+                       memcpy(pOriginal, pBackupCode, HOOK_JUMP_CODE_LENGTH);
+                       VirtualProtect(pOriginal, HOOK_JUMP_CODE_LENGTH, Protect, &Protect);
+                       bResult = TRUE;
+               }
+       }
+       else
+       {
+               if(pBackupCode)
+                       memcpy(pBackupCode, pOriginal, HOOK_JUMP_CODE_LENGTH);
+               if(VirtualProtect(pOriginal, HOOK_JUMP_CODE_LENGTH, PAGE_EXECUTE_READWRITE, &Protect))
+               {
+                       memcpy(pOriginal, &JumpCode, HOOK_JUMP_CODE_LENGTH);
+                       VirtualProtect(pOriginal, HOOK_JUMP_CODE_LENGTH, Protect, &Protect);
+                       bResult = TRUE;
+               }
+       }
+#endif
+       return bResult;
+}
+#endif
+
+#ifdef USE_IAT_HOOK
+BOOL HookFunctionInIAT(void* pOriginal, void* pNew)
+{
+       BOOL bResult;
+       HANDLE hSnapshot;
+       MODULEENTRY32 me;
+       BOOL bFound;
+       IMAGE_IMPORT_DESCRIPTOR* piid;
+       ULONG Size;
+       IMAGE_THUNK_DATA* pitd;
+       DWORD Protect;
+       bResult = FALSE;
+       if((hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetCurrentProcessId())) != INVALID_HANDLE_VALUE)
+       {
+               me.dwSize = sizeof(MODULEENTRY32);
+               if(Module32First(hSnapshot, &me))
+               {
+                       bFound = FALSE;
+                       do
+                       {
+                               if(piid = (IMAGE_IMPORT_DESCRIPTOR*)ImageDirectoryEntryToData(me.hModule, TRUE, IMAGE_DIRECTORY_ENTRY_IMPORT, &Size))
+                               {
+                                       while(!bFound && piid->Name != 0)
+                                       {
+                                               pitd = (IMAGE_THUNK_DATA*)((BYTE*)me.hModule + piid->FirstThunk);
+                                               while(!bFound && pitd->u1.Function != 0)
+                                               {
+                                                       if((void*)pitd->u1.Function == pOriginal)
+                                                       {
+                                                               bFound = TRUE;
+                                                               if(VirtualProtect(&pitd->u1.Function, sizeof(void*), PAGE_EXECUTE_READWRITE, &Protect))
+                                                               {
+                                                                       memcpy(&pitd->u1.Function, &pNew, sizeof(void*));
+                                                                       VirtualProtect(&pitd->u1.Function, sizeof(void*), Protect, &Protect);
+                                                                       bResult = TRUE;
+                                                               }
+                                                       }
+                                                       pitd++;
+                                               }
+                                               piid++;
+                                       }
+                               }
+                       }
+                       while(!bFound && Module32Next(hSnapshot, &me));
+               }
+               CloseHandle(hSnapshot);
+       }
+       return bResult;
+}
+#endif
+
+// kernel32.dll\82ÌLoadLibraryExW\91\8a\93\96\82Ì\8aÖ\90\94
+HMODULE System_LoadLibrary(LPCWSTR lpLibFileName, HANDLE hFile, DWORD dwFlags)
+{
+       HMODULE r = NULL;
+       UNICODE_STRING us;
+       us.Length = sizeof(wchar_t) * wcslen(lpLibFileName);
+       us.MaximumLength = sizeof(wchar_t) * (wcslen(lpLibFileName) + 1);
+       us.Buffer = (PWSTR)lpLibFileName;
+       if(dwFlags & LOAD_LIBRARY_AS_DATAFILE)
+       {
+//             if(p_LdrGetDllHandle(NULL, dwFlags, &us, &r) == 0)
+               if(p_LdrGetDllHandle(NULL, &dwFlags, &us, &r) == 0)
+               {
+                       if(p_LdrAddRefDll)
+                               p_LdrAddRefDll(0, r);
+               }
+               else
+               {
+                       dwFlags |= DONT_RESOLVE_DLL_REFERENCES;
+//                     if(p_LdrLoadDll(NULL, dwFlags, &us, &r) == 0)
+                       if(p_LdrLoadDll(NULL, &dwFlags, &us, &r) == 0)
+                       {
+                       }
+                       else
+                               r = NULL;
+               }
+       }
+       else
+       {
+//             if(p_LdrGetDllHandle(NULL, dwFlags, &us, &r) == 0)
+               if(p_LdrGetDllHandle(NULL, &dwFlags, &us, &r) == 0)
+               {
+                       if(p_LdrAddRefDll)
+                               p_LdrAddRefDll(0, r);
+               }
+//             else if(p_LdrLoadDll(NULL, dwFlags, &us, &r) == 0)
+               else if(p_LdrLoadDll(NULL, &dwFlags, &us, &r) == 0)
+               {
+               }
+               else
+                       r = NULL;
+       }
+       return r;
+}
+
+// DLL\82Ì\83n\83b\83V\83\85\82ð\93o\98^
+BOOL RegisterModuleMD5Hash(void* pHash)
+{
+       BOOL bResult;
+       BYTE NullHash[16] = {0};
+       int i;
+       bResult = FALSE;
+       if(FindModuleMD5Hash(pHash))
+               bResult = TRUE;
+       else
+       {
+               i = 0;
+               while(i < MAX_MD5_HASH_TABLE)
+               {
+                       if(memcmp(&g_MD5HashTable[i], &NullHash, 16) == 0)
+                       {
+                               memcpy(&g_MD5HashTable[i], pHash, 16);
+                               bResult = TRUE;
+                               break;
+                       }
+                       i++;
+               }
+       }
+       return bResult;
+}
+
+// DLL\82Ì\83n\83b\83V\83\85\82Ì\93o\98^\82ð\89ð\8f\9c
+BOOL UnregisterModuleMD5Hash(void* pHash)
+{
+       BOOL bResult;
+       BYTE NullHash[16] = {0};
+       int i;
+       bResult = FALSE;
+       i = 0;
+       while(i < MAX_MD5_HASH_TABLE)
+       {
+               if(memcmp(&g_MD5HashTable[i], pHash, 16) == 0)
+               {
+                       memcpy(&g_MD5HashTable[i], &NullHash, 16);
+                       bResult = TRUE;
+                       break;
+               }
+               i++;
+       }
+       return bResult;
+}
+
+// DLL\82Ì\83n\83b\83V\83\85\82ð\8c\9f\8dõ
+BOOL FindModuleMD5Hash(void* pHash)
+{
+       BOOL bResult;
+       int i;
+       bResult = FALSE;
+       i = 0;
+       while(i < MAX_MD5_HASH_TABLE)
+       {
+               if(memcmp(&g_MD5HashTable[i], pHash, 16) == 0)
+               {
+                       bResult = TRUE;
+                       break;
+               }
+               i++;
+       }
+       return bResult;
+}
+
+// DLL\82ð\8am\94F
+// \83n\83b\83V\83\85\82ª\93o\98^\82³\82ê\82Ä\82¢\82é\81AAuthenticode\8f\90\96¼\82ª\82³\82ê\82Ä\82¢\82é\81A\82Ü\82½\82ÍWFP\82É\82æ\82é\95Û\8cì\89º\82É\82 \82é\82±\82Æ\82ð\8am\94F
+BOOL IsModuleTrustedA(LPCSTR Filename)
+{
+       BOOL r = FALSE;
+       wchar_t* pw0 = NULL;
+       pw0 = DuplicateAtoW(Filename, -1);
+       r = IsModuleTrustedW(pw0);
+       FreeDuplicatedString(pw0);
+       return r;
+}
+
+// DLL\82ð\8am\94F
+// \83n\83b\83V\83\85\82ª\93o\98^\82³\82ê\82Ä\82¢\82é\81AAuthenticode\8f\90\96¼\82ª\82³\82ê\82Ä\82¢\82é\81A\82Ü\82½\82ÍWFP\82É\82æ\82é\95Û\8cì\89º\82É\82 \82é\82±\82Æ\82ð\8am\94F
+BOOL IsModuleTrustedW(LPCWSTR Filename)
+{
+       BOOL bResult;
+       WCHAR Path[MAX_PATH];
+       LPWSTR p;
+       BYTE Hash[16];
+       GUID g = WINTRUST_ACTION_GENERIC_VERIFY_V2;
+       WINTRUST_FILE_INFO wfi;
+       WINTRUST_DATA wd;
+       bResult = FALSE;
+       if(wcsrchr(Filename, '.') > wcsrchr(Filename, '\\'))
+       {
+               if(SearchPathW(NULL, Filename, NULL, MAX_PATH, Path, &p) > 0)
+                       Filename = Path;
+       }
+       else
+       {
+               if(SearchPathW(NULL, Filename, L".dll", MAX_PATH, Path, &p) > 0)
+                       Filename = Path;
+       }
+       if(GetMD5HashOfFile(Filename, &Hash))
+       {
+               if(FindModuleMD5Hash(&Hash))
+                       bResult = TRUE;
+       }
+       if(!bResult)
+       {
+               ZeroMemory(&wfi, sizeof(WINTRUST_FILE_INFO));
+               wfi.cbStruct = sizeof(WINTRUST_FILE_INFO);
+               wfi.pcwszFilePath = Filename;
+               ZeroMemory(&wd, sizeof(WINTRUST_DATA));
+               wd.cbStruct = sizeof(WINTRUST_DATA);
+               wd.dwUIChoice = WTD_UI_NONE;
+               wd.dwUnionChoice = WTD_CHOICE_FILE;
+               wd.pFile = &wfi;
+               if(WinVerifyTrust((HWND)INVALID_HANDLE_VALUE, &g, &wd) == ERROR_SUCCESS)
+                       bResult = TRUE;
+       }
+       if(!bResult)
+       {
+               if(SfcIsFileProtected(NULL, Filename))
+                       bResult = TRUE;
+       }
+//     if(!bResult)
+//     {
+//             WCHAR Temp[MAX_PATH + 128];
+//             _swprintf(Temp, L"Untrusted module was detected! \"%s\"\n", Filename);
+//             OutputDebugStringW(Temp);
+//     }
+       return bResult;
+}
+
+// \8aÖ\90\94\83|\83C\83\93\83^\82ð\8eg\97p\89Â\94\\82È\8fó\91Ô\82É\8f\89\8aú\89»
+BOOL InitializeLoadLibraryHook()
+{
+       HMODULE hModule;
+       hModule = GetModuleHandleW(L"kernel32.dll");
+       GET_FUNCTION(hModule, LoadLibraryA);
+       GET_FUNCTION(hModule, LoadLibraryW);
+       GET_FUNCTION(hModule, LoadLibraryExA);
+       GET_FUNCTION(hModule, LoadLibraryExW);
+       hModule = GetModuleHandleW(L"ntdll.dll");
+       GET_FUNCTION(hModule, LdrLoadDll);
+       GET_FUNCTION(hModule, LdrGetDllHandle);
+       GET_FUNCTION(hModule, LdrAddRefDll);
+       return TRUE;
+}
+
+// SetWindowsHookEx\91Î\8dô
+// DLL Injection\82³\82ê\82½\8fê\8d\87\82Í\8fã\82Ìh_LoadLibrary\8cn\8aÖ\90\94\82Å\83g\83\89\83b\83v\89Â\94\
+BOOL EnableLoadLibraryHook(BOOL bEnable)
+{
+       if(bEnable)
+       {
+               // \8c\9f\8fØ\82É\95K\97v\82ÈDLL\82Ì\92x\89\84\93Ç\82Ý\8d\9e\82Ý\89ñ\94ð
+               IsModuleTrustedA("");
+#ifdef USE_CODE_HOOK
+               SET_HOOK_FUNCTION(LoadLibraryA);
+               SET_HOOK_FUNCTION(LoadLibraryW);
+               SET_HOOK_FUNCTION(LoadLibraryExA);
+               SET_HOOK_FUNCTION(LoadLibraryExW);
+#endif
+#ifdef USE_IAT_HOOK
+               HookFunctionInIAT(p_LoadLibraryA, h_LoadLibraryA);
+               HookFunctionInIAT(p_LoadLibraryW, h_LoadLibraryW);
+               HookFunctionInIAT(p_LoadLibraryExA, h_LoadLibraryExA);
+               HookFunctionInIAT(p_LoadLibraryExW, h_LoadLibraryExW);
+#endif
+       }
+       else
+       {
+#ifdef USE_CODE_HOOK
+               END_HOOK_FUNCTION(LoadLibraryA);
+               END_HOOK_FUNCTION(LoadLibraryW);
+               END_HOOK_FUNCTION(LoadLibraryExA);
+               END_HOOK_FUNCTION(LoadLibraryExW);
+#endif
+#ifdef USE_IAT_HOOK
+               HookFunctionInIAT(h_LoadLibraryA, p_LoadLibraryA);
+               HookFunctionInIAT(h_LoadLibraryW, p_LoadLibraryW);
+               HookFunctionInIAT(h_LoadLibraryExA, p_LoadLibraryExA);
+               HookFunctionInIAT(h_LoadLibraryExW, p_LoadLibraryExW);
+#endif
+       }
+       return TRUE;
+}
+
+// ReadProcessMemory\81AWriteProcessMemory\81ACreateRemoteThread\91Î\8dô
+// TerminateProcess\82Ì\82Ý\8b\96\89Â
+BOOL RestartProtectedProcess(LPCTSTR Keyword)
+{
+       BOOL bResult;
+       ACL* pACL;
+       SID_IDENTIFIER_AUTHORITY sia = SECURITY_WORLD_SID_AUTHORITY;
+       PSID pSID;
+       SECURITY_DESCRIPTOR sd;
+       TCHAR* CommandLine;
+       SECURITY_ATTRIBUTES sa;
+       STARTUPINFO si;
+       PROCESS_INFORMATION pi;
+       bResult = FALSE;
+       if(_tcslen(GetCommandLine()) >= _tcslen(Keyword) && _tcscmp(GetCommandLine() + _tcslen(GetCommandLine()) - _tcslen(Keyword), Keyword) == 0)
+               return FALSE;
+       if(pACL = (ACL*)malloc(sizeof(ACL) + 1024))
+       {
+               if(InitializeAcl(pACL, sizeof(ACL) + 1024, ACL_REVISION))
+               {
+                       if(AllocateAndInitializeSid(&sia, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &pSID))
+                       {
+                               if(AddAccessAllowedAce(pACL, ACL_REVISION, PROCESS_TERMINATE, pSID))
+                               {
+                                       if(InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION))
+                                       {
+                                               if(SetSecurityDescriptorDacl(&sd, TRUE, pACL, FALSE))
+                                               {
+                                                       if(CommandLine = (TCHAR*)malloc(sizeof(TCHAR) * (_tcslen(GetCommandLine()) + _tcslen(Keyword) + 1)))
+                                                       {
+                                                               _tcscpy(CommandLine, GetCommandLine());
+                                                               _tcscat(CommandLine, Keyword);
+                                                               sa.nLength = sizeof(SECURITY_ATTRIBUTES);
+                                                               sa.lpSecurityDescriptor = &sd;
+                                                               sa.bInheritHandle = FALSE;
+                                                               GetStartupInfo(&si);
+                                                               if(CreateProcess(NULL, CommandLine, &sa, NULL, FALSE, 0, NULL, NULL, &si, &pi))
+                                                               {
+                                                                       CloseHandle(pi.hThread);
+                                                                       CloseHandle(pi.hProcess);
+                                                                       bResult = TRUE;
+                                                               }
+                                                               free(CommandLine);
+                                                       }
+                                               }
+                                       }
+                               }
+                               FreeSid(pSID);
+                       }
+               }
+               free(pACL);
+       }
+       return bResult;
+}
+
diff --git a/protectprocess.h b/protectprocess.h
new file mode 100644 (file)
index 0000000..2cff761
--- /dev/null
@@ -0,0 +1,58 @@
+// protectprocess.h
+// Copyright (C) 2011 Suguru Kawamoto
+// \83v\83\8d\83Z\83X\82Ì\95Û\8cì
+
+#ifndef __PROTECTPROCESS_H__
+#define __PROTECTPROCESS_H__
+
+#define ENABLE_PROCESS_PROTECTION
+
+// \8e\9f\82Ì\92\86\82©\82ç1\8cÂ\82Ì\82Ý\97L\8cø\82É\82·\82é
+// \83t\83b\83N\90æ\82Ì\8aÖ\90\94\82Ì\83R\81[\83h\82ð\8f\91\82«\8a·\82¦\82é
+// \91S\82Ä\82Ì\8cÄ\82Ñ\8fo\82µ\82ð\83t\83b\83N\89Â\94\\82¾\82ª\8c´\97\9d\93I\82É\93ñ\8fd\8cÄ\82Ñ\8fo\82µ\82É\91Î\89\9e\82Å\82«\82È\82¢
+#define USE_CODE_HOOK
+// \83t\83b\83N\90æ\82Ì\8aÖ\90\94\82Ì\83C\83\93\83|\81[\83g\83A\83h\83\8c\83X\83e\81[\83u\83\8b\82ð\8f\91\82«\8a·\82¦\82é
+// \93ñ\8fd\8cÄ\82Ñ\8fo\82µ\82ª\89Â\94\\82¾\82ª\8cÄ\82Ñ\8fo\82µ\95û\96@\82É\82æ\82Á\82Ä\82Í\83t\83b\83N\82ð\89ñ\94ð\82³\82ê\82é
+//#define USE_IAT_HOOK
+
+typedef HMODULE (WINAPI* _LoadLibraryA)(LPCSTR);
+typedef HMODULE (WINAPI* _LoadLibraryW)(LPCWSTR);
+typedef HMODULE (WINAPI* _LoadLibraryExA)(LPCSTR, HANDLE, DWORD);
+typedef HMODULE (WINAPI* _LoadLibraryExW)(LPCWSTR, HANDLE, DWORD);
+
+#ifndef DO_NOT_REPLACE
+
+#ifdef USE_IAT_HOOK
+
+// \95Ï\90\94\82Ì\90é\8c¾
+#define EXTERN_HOOK_FUNCTION_VAR(name) extern _##name p_##name;
+
+#undef LoadLibraryA
+#define LoadLibraryA p_LoadLibraryA
+EXTERN_HOOK_FUNCTION_VAR(LoadLibraryA)
+#undef LoadLibraryW
+#define LoadLibraryW p_LoadLibraryW
+EXTERN_HOOK_FUNCTION_VAR(LoadLibraryW)
+#undef LoadLibraryExA
+#define LoadLibraryExA p_LoadLibraryExA
+EXTERN_HOOK_FUNCTION_VAR(LoadLibraryExA)
+#undef LoadLibraryExW
+#define LoadLibraryExW p_LoadLibraryExW
+EXTERN_HOOK_FUNCTION_VAR(LoadLibraryExW)
+
+#endif
+
+#endif
+
+HMODULE System_LoadLibrary(LPCWSTR lpLibFileName, HANDLE hFile, DWORD dwFlags);
+BOOL RegisterModuleMD5Hash(void* pHash);
+BOOL UnregisterModuleMD5Hash(void* pHash);
+BOOL FindModuleMD5Hash(void* pHash);
+BOOL IsModuleTrustedA(LPCSTR Filename);
+BOOL IsModuleTrustedW(LPCWSTR Filename);
+BOOL InitializeLoadLibraryHook();
+BOOL EnableLoadLibraryHook(BOOL bEnable);
+BOOL RestartProtectedProcess(LPCTSTR Keyword);
+
+#endif
+
index 3159e93..68382dc 100644 (file)
@@ -1,15 +1,18 @@
-// socketwrapper.cpp
+// socketwrapper.c
 // Copyright (C) 2011 Suguru Kawamoto
 // ソケットラッパー
 // socket関連関数をOpenSSL用に置換
 // コンパイルにはOpenSSLのヘッダーファイルが必要
 // 実行にはOpenSSLのDLLが必要
 
+#define _WIN32_WINNT 0x0600
+
 #include <windows.h>
 #include <mmsystem.h>
 #include <openssl/ssl.h>
 
 #include "socketwrapper.h"
+#include "protectprocess.h"
 
 typedef void (__cdecl* _SSL_load_error_strings)();
 typedef int (__cdecl* _SSL_library_init)();
@@ -65,6 +68,13 @@ BOOL LoadOpenSSL()
 {
        if(g_bOpenSSLLoaded)
                return FALSE;
+#ifdef ENABLE_PROCESS_PROTECTION
+       // ssleay32.dll 1.0.0e
+       // libssl32.dll 1.0.0e
+       RegisterModuleMD5Hash("\x8B\xA3\xB7\xB3\xCE\x2E\x4F\x07\x8C\xB8\x93\x7D\x77\xE1\x09\x3A");
+       // libeay32.dll 1.0.0e
+       RegisterModuleMD5Hash("\xA6\x4C\xAF\x9E\xF3\xDC\xFC\x68\xAE\xCA\xCC\x61\xD2\xF6\x70\x8B");
+#endif
        g_hOpenSSL = LoadLibrary("ssleay32.dll");
        if(!g_hOpenSSL)
                g_hOpenSSL = LoadLibrary("libssl32.dll");