From 5ee9402b7d721e9436f92f4ca9137b1a693ef065 Mon Sep 17 00:00:00 2001 From: Alkis Christidis Date: Tue, 23 May 2017 18:17:13 +0300 Subject: [PATCH] Added SEH exception handling when calling the shellcode, so that the compiler doesn't die in case of an error --- ShellcodeCompiler/DebugUtils.cpp | 18 +++++++-- ShellcodeCompiler/SEHUtils.h | 38 +++++++++++++++++++ ShellcodeCompiler/ShellcodeCompiler.vcxproj | 2 + .../ShellcodeCompiler.vcxproj.filters | 3 ++ 4 files changed, 58 insertions(+), 3 deletions(-) create mode 100644 ShellcodeCompiler/SEHUtils.h diff --git a/ShellcodeCompiler/DebugUtils.cpp b/ShellcodeCompiler/DebugUtils.cpp index 8364ddd..7e8586b 100644 --- a/ShellcodeCompiler/DebugUtils.cpp +++ b/ShellcodeCompiler/DebugUtils.cpp @@ -1,8 +1,11 @@ #include "DebugUtils.h" +#include "SEHUtils.h" // Dump all data - debug purposes + + void DebugUtils::DumpAllData() { cout << endl; @@ -53,7 +56,16 @@ void DebugUtils::TestShellcode(string p_sFilename) } // Copy shellcode and execute it - - memcpy(sc, p, size); - (*(int(*)()) sc)(); + try + { + _set_se_translator(CxxTranslateSehException); + memcpy(sc, p, size); + (*(int(*)()) sc)(); + } + catch (const seh_exception& e) + { + cout << "Error when executing shellcode: " + << e.what() << endl; + } } + diff --git a/ShellcodeCompiler/SEHUtils.h b/ShellcodeCompiler/SEHUtils.h new file mode 100644 index 0000000..59385e0 --- /dev/null +++ b/ShellcodeCompiler/SEHUtils.h @@ -0,0 +1,38 @@ +#ifndef SEHUTILIS_H +#define SEHUTILIS_H +#include +#include + +struct seh_exception : public std::exception +{ + seh_exception(const char* message, DWORD code) : exception(message), m_code(code) {} + + DWORD Code() const { return m_code; } + +private: + const DWORD m_code; +}; + +void CxxTranslateSehException(unsigned int, EXCEPTION_POINTERS* pointers) +{ + DWORD exceptionCode = pointers->ExceptionRecord->ExceptionCode; + const char* msg = nullptr; + + switch (exceptionCode) { + case EXCEPTION_ACCESS_VIOLATION: + msg = "Access violation."; + break; + case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: + msg = "Out of bound access."; + break; + case EXCEPTION_ILLEGAL_INSTRUCTION: + msg = "Illegal instruction."; + break; + default: + break; + } + throw seh_exception(msg, exceptionCode); +} + + +#endif diff --git a/ShellcodeCompiler/ShellcodeCompiler.vcxproj b/ShellcodeCompiler/ShellcodeCompiler.vcxproj index 0c4fe0b..f53714b 100644 --- a/ShellcodeCompiler/ShellcodeCompiler.vcxproj +++ b/ShellcodeCompiler/ShellcodeCompiler.vcxproj @@ -134,6 +134,7 @@ true true NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + Async Console @@ -157,6 +158,7 @@ + diff --git a/ShellcodeCompiler/ShellcodeCompiler.vcxproj.filters b/ShellcodeCompiler/ShellcodeCompiler.vcxproj.filters index 8bf45e7..f09e405 100644 --- a/ShellcodeCompiler/ShellcodeCompiler.vcxproj.filters +++ b/ShellcodeCompiler/ShellcodeCompiler.vcxproj.filters @@ -63,6 +63,9 @@ Header Files + + Header Files +