【问题标题】:Compile-time string encryption编译时字符串加密
【发布时间】:2011-11-08 09:17:00
【问题描述】:

我不希望逆向工程师在我的应用程序中读取硬编码字符串的纯文本。简单的解决方案是使用简单的XOR-Encryption。问题是我需要一个转换器,在我的应用程序中它看起来像这样:

//Before (unsecure)
char * cString = "Helllo Stackoverflow!";
//After (secure)
char * cString = XStr( 0x06, 0x15, 0x9D, 0xD5FBF3CC, 0xCDCD83F7, 0xD1C7C4C3, 0xC6DCCEDE, 0xCBC2C0C7, 0x90000000 ).c();

是否有可能通过使用类似的结构来维护干净的代码

//Before (unsecure)
char * cString = "Helllo Stackoverflow!";
//After (secure)
char * cString = CRYPT("Helllo Stackoverflow!");

它也应该适用于相当长的字符串(1000 个字符?:-))。提前谢谢你

【问题讨论】:

  • 嗯,试一试有用吗?
  • @Brian 当然不是。问题很明确:是否有一种机制(可能使用宏)来使它工作?这根本不是一个愚蠢的问题——据我所知,没有确切的解决方案,但您可以使用模板非常接近。
  • 请记住,这种加密很容易被破解;当您的程序启动时,“cString”的内容将是未加密的,并且任何有权访问您的 RAM 的人都可以看到。这还不包括 XOR 本身很容易破解。
  • @Billy:我知道,但您不会使用调试器找到字符串,因为它无法与普通内存分离。这已经是我想要的了。
  • 不幸的是,C++ 没有完整的依赖类型,因此模板机制不能分解字符串(当然,预处理器也不能分解它们,因为它不拆分标记)。最好的办法是在生成的文件中外部定义它们。

标签: c++ encryption macros reverse-engineering


【解决方案1】:

完美的解决方案确实存在,就是这样。

我也认为这是不可能的,尽管它很简单,但人们编写了解决方案,您需要一个自定义工具来扫描构建的文件,然后扫描字符串并像这样加密字符串,这还不错但是我想要一个从 Visual Studio 编译的包,现在可以了!

您需要的是C++ 11(Visual Studio 2015 Update 1 开箱即用)

神奇的发生在这个新命令constexpr

神奇地发生在这个#define

#define XorString( String ) ( CXorString<ConstructIndexList<sizeof( String ) - 1>::Result>( String ).decrypt() )

它不会在编译时解密 XorString,仅在运行时,但它只会在编译时加密字符串,因此字符串不会出现在可执行文件中

printf(XorString( "this string is hidden!" ));

它会打印出"this string is hidden!",但你不会在可执行文件中找到它作为字符串!请自行查看Microsoft Sysinternals Strings程序下载链接:https://technet.microsoft.com/en-us/sysinternals/strings.aspx

完整的源代码很大,但可以很容易地包含在一个头文件中。但也是非常随机的,所以加密的字符串输出总是会改变每次新的编译,种子会根据编译时间而改变,非常可靠,完美的解决方案。

创建一个名为XorString.h的文件

#pragma once

//-------------------------------------------------------------//
// "Malware related compile-time hacks with C++11" by LeFF   //
// You can use this code however you like, I just don't really //
// give a shit, but if you feel some respect for me, please //
// don't cut off this comment when copy-pasting... ;-)       //
//-------------------------------------------------------------//

////////////////////////////////////////////////////////////////////
template <int X> struct EnsureCompileTime {
    enum : int {
        Value = X
    };
};
////////////////////////////////////////////////////////////////////


////////////////////////////////////////////////////////////////////
//Use Compile-Time as seed
#define Seed ((__TIME__[7] - '0') * 1  + (__TIME__[6] - '0') * 10  + \
              (__TIME__[4] - '0') * 60   + (__TIME__[3] - '0') * 600 + \
              (__TIME__[1] - '0') * 3600 + (__TIME__[0] - '0') * 36000)
////////////////////////////////////////////////////////////////////


////////////////////////////////////////////////////////////////////
constexpr int LinearCongruentGenerator(int Rounds) {
    return 1013904223 + 1664525 * ((Rounds> 0) ? LinearCongruentGenerator(Rounds - 1) : Seed & 0xFFFFFFFF);
}
#define Random() EnsureCompileTime<LinearCongruentGenerator(10)>::Value //10 Rounds
#define RandomNumber(Min, Max) (Min + (Random() % (Max - Min + 1)))
////////////////////////////////////////////////////////////////////


////////////////////////////////////////////////////////////////////
template <int... Pack> struct IndexList {};
////////////////////////////////////////////////////////////////////


////////////////////////////////////////////////////////////////////
template <typename IndexList, int Right> struct Append;
template <int... Left, int Right> struct Append<IndexList<Left...>, Right> {
    typedef IndexList<Left..., Right> Result;
};
////////////////////////////////////////////////////////////////////


////////////////////////////////////////////////////////////////////
template <int N> struct ConstructIndexList {
    typedef typename Append<typename ConstructIndexList<N - 1>::Result, N - 1>::Result Result;
};
template <> struct ConstructIndexList<0> {
    typedef IndexList<> Result;
};
////////////////////////////////////////////////////////////////////


////////////////////////////////////////////////////////////////////
const char XORKEY = static_cast<char>(RandomNumber(0, 0xFF));
constexpr char EncryptCharacter(const char Character, int Index) {
    return Character ^ (XORKEY + Index);
}

template <typename IndexList> class CXorString;
template <int... Index> class CXorString<IndexList<Index...> > {
private:
    char Value[sizeof...(Index) + 1];
public:
    constexpr CXorString(const char* const String)
    : Value{ EncryptCharacter(String[Index], Index)... } {}

    char* decrypt() {
        for(int t = 0; t < sizeof...(Index); t++) {
            Value[t] = Value[t] ^ (XORKEY + t);
        }
        Value[sizeof...(Index)] = '\0';
        return Value;
    }

    char* get() {
        return Value;
    }
};
#define XorS(X, String) CXorString<ConstructIndexList<sizeof(String)-1>::Result> X(String)
#define XorString( String ) ( CXorString<ConstructIndexList<sizeof( String ) - 1>::Result>( String ).decrypt() )
////////////////////////////////////////////////////////////////////

更新的代码如下,这是一个更好的版本,支持 char 和 wchar_t 字符串!

#pragma once
#include <string>
#include <array>
#include <cstdarg>

#define BEGIN_NAMESPACE( x ) namespace x {
#define END_NAMESPACE }

BEGIN_NAMESPACE(XorCompileTime)

constexpr auto time = __TIME__;
constexpr auto seed = static_cast< int >(time[7]) + static_cast< int >(time[6]) * 10 + static_cast< int >(time[4]) * 60 + static_cast< int >(time[3]) * 600 + static_cast< int >(time[1]) * 3600 + static_cast< int >(time[0]) * 36000;

// 1988, Stephen Park and Keith Miller
// "Random Number Generators: Good Ones Are Hard To Find", considered as "minimal standard"
// Park-Miller 31 bit pseudo-random number generator, implemented with G. Carta's optimisation:
// with 32-bit math and without division

template < int N >
struct RandomGenerator
{
private:
    static constexpr unsigned a = 16807; // 7^5
    static constexpr unsigned m = 2147483647; // 2^31 - 1

    static constexpr unsigned s = RandomGenerator< N - 1 >::value;
    static constexpr unsigned lo = a * (s & 0xFFFF); // Multiply lower 16 bits by 16807
    static constexpr unsigned hi = a * (s >> 16); // Multiply higher 16 bits by 16807
    static constexpr unsigned lo2 = lo + ((hi & 0x7FFF) << 16); // Combine lower 15 bits of hi with lo's upper bits
    static constexpr unsigned hi2 = hi >> 15; // Discard lower 15 bits of hi
    static constexpr unsigned lo3 = lo2 + hi;

public:
    static constexpr unsigned max = m;
    static constexpr unsigned value = lo3 > m ? lo3 - m : lo3;
};

template <>
struct RandomGenerator< 0 >
{
    static constexpr unsigned value = seed;
};

template < int N, int M >
struct RandomInt
{
    static constexpr auto value = RandomGenerator< N + 1 >::value % M;
};

template < int N >
struct RandomChar
{
    static const char value = static_cast< char >(1 + RandomInt< N, 0x7F - 1 >::value);
};

template < size_t N, int K, typename Char >
struct XorString
{
private:
    const char _key;
    std::array< Char, N + 1 > _encrypted;

    constexpr Char enc(Char c) const
    {
        return c ^ _key;
    }

    Char dec(Char c) const
    {
        return c ^ _key;
    }

public:
    template < size_t... Is >
    constexpr __forceinline XorString(const Char* str, std::index_sequence< Is... >) : _key(RandomChar< K >::value), _encrypted{ enc(str[Is])... }
    {
    }

    __forceinline decltype(auto) decrypt(void)
    {
        for (size_t i = 0; i < N; ++i) {
            _encrypted[i] = dec(_encrypted[i]);
        }
        _encrypted[N] = '\0';
        return _encrypted.data();
    }
};

//--------------------------------------------------------------------------------
//-- Note: XorStr will __NOT__ work directly with functions like printf.
//         To work with them you need a wrapper function that takes a const char*
//         as parameter and passes it to printf and alike.
//
//         The Microsoft Compiler/Linker is not working correctly with variadic 
//         templates!
//  
//         Use the functions below or use std::cout (and similar)!
//--------------------------------------------------------------------------------

static auto w_printf = [](const char* fmt, ...) {
    va_list args;
    va_start(args, fmt);
    vprintf_s(fmt, args);
    va_end(args);
};

static auto w_printf_s = [](const char* fmt, ...) {
    va_list args;
    va_start(args, fmt);
    vprintf_s(fmt, args);
    va_end(args);
};

static auto w_sprintf = [](char* buf, const char* fmt, ...) {
    va_list args;
    va_start(args, fmt);
    vsprintf(buf, fmt, args);
    va_end(args);
};

static auto w_sprintf_ret = [](char* buf, const char* fmt, ...) {
    int ret;
    va_list args;
    va_start(args, fmt);
    ret = vsprintf(buf, fmt, args);
    va_end(args);
    return ret;
};

static auto w_sprintf_s = [](char* buf, size_t buf_size, const char* fmt, ...) {
    va_list args;
    va_start(args, fmt);
    vsprintf_s(buf, buf_size, fmt, args);
    va_end(args);
};

static auto w_sprintf_s_ret = [](char* buf, size_t buf_size, const char* fmt, ...) {
    int ret;
    va_list args;
    va_start(args, fmt);
    ret = vsprintf_s(buf, buf_size, fmt, args);
    va_end(args);
    return ret;
};

//Old functions before I found out about wrapper functions.
//#define XorStr( s ) ( XorCompileTime::XorString< sizeof(s)/sizeof(char) - 1, __COUNTER__, char >( s, std::make_index_sequence< sizeof(s)/sizeof(char) - 1>() ).decrypt() )
//#define XorStrW( s ) ( XorCompileTime::XorString< sizeof(s)/sizeof(wchar_t) - 1, __COUNTER__, wchar_t >( s, std::make_index_sequence< sizeof(s)/sizeof(wchar_t) - 1>() ).decrypt() )

//Wrapper functions to work in all functions below
#define XorStr( s ) []{ constexpr XorCompileTime::XorString< sizeof(s)/sizeof(char) - 1, __COUNTER__, char > expr( s, std::make_index_sequence< sizeof(s)/sizeof(char) - 1>() ); return expr; }().decrypt()
#define XorStrW( s ) []{ constexpr XorCompileTime::XorString< sizeof(s)/sizeof(wchar_t) - 1, __COUNTER__, wchar_t > expr( s, std::make_index_sequence< sizeof(s)/sizeof(wchar_t) - 1>() ); return expr; }().decrypt()

END_NAMESPACE

【讨论】:

  • 不保证字符串会被“加密”。编译器可能会在运行时对其进行加密,或者删除此 encrypt().decrypt() 因为实际上它是无操作的。
【解决方案2】:

This blog 为 C++ 中的编译时字符串散列提供了一种解决方案。我想原理是一样的。不幸的是,您必须为每个字符串长度创建一个 Makro。

【讨论】:

  • 谢谢,我还要等一下,也许有一个解决方案也适用于动态长度。
  • 有趣的博客条目。但它相当复杂,而且对用户并不友好 :) 我更喜欢使用解析器...查看我的答案
  • @Listing:不,但原则是一样的。而不是散列字符串,您必须对其应用加密。有很多加密算法供您使用。我相信您可以根据自己的需要调整示例。
  • 该博客仅演示了 优化器 如何将表达式折叠为常量。但是计算出的哈希值不是编译时间常数(可以用作模板非类型参数等)。因此,输入字符串是否出现在数据段中仍然取决于优化器/编译器。如果我理解 OP 正确,那么他想要一种方法来保证他的敏感输入字符串不会出现在二进制文件中。
  • @Listing:在 C++11 和 C++14 中,使用 constexpr 方法将允许您为此使用常规方法;他们可以做的事情有一些限制,但加密(没有随机值)应该在他们的范围内。
【解决方案3】:

我的首选解决方案:

// some header
extern char const* const MyString;

// some generated source
char const* const MyString = "aioghaiogeubeisbnuvs";

然后使用您最喜欢的脚本语言生成这个源文件,您可以在其中存储“加密”资源。

【讨论】:

  • +1:这也允许使用比 XOR 更复杂的加密方法。
【解决方案4】:

这是一个迟到的答案,但我确信有更好的解决方案。

请参考已接受的答案here

基本上,它展示了如何使用ADVobfuscator 库来混淆字符串,如下所示:

#include "MetaString.h"

using namespace std;
using namespace andrivet::ADVobfuscator;

void Example()
{
    /* Example 1 */

    // here, the string is compiled in an obfuscated form, and
    // it's only deobfuscated at runtime, at the very moment of its use
    cout << OBFUSCATED("Now you see me") << endl;

    /* Example 2 */

    // here, we store the obfuscated string into an object to
    // deobfuscate whenever we need to
    auto narrator = DEF_OBFUSCATED("Tyler Durden");

    // note: although the function is named `decrypt()`, it's still deobfuscation
    cout << narrator.decrypt() << endl;
}

【讨论】:

    【解决方案5】:

    我认为你必须做类似使用 gettext (i18n) 时所做的事情:

    • 使用像 CRYPT 这样的宏。
    • 使用在找到 CRYPT 时对字符串进行加密的解析器。
    • 编写一个解密函数,由您的宏调用。

    对于 gettext,您使用用于生成 i18ned 字符串字典并调用 gettext 函数的 _() 宏。

    顺便说一句,你也必须管理 i18n :),你需要类似的东西:

    _CRYPT_()
    _CRYPT_I18N_()
    

    您必须使用构建系统对其进行管理,以使其可维护。我用 gettext 做到这一点...

    我的 2 美分

    【讨论】:

    • 所以你认为使用标准解析器的普通c++定义是不可能的?
    • @Listing:我不这么认为,但我对此并没有投入太多。我所知道的是,国际化是通过这种方式完成的。我想如果有人找到了一种使用预处理器的方法,它就会被使用......但你永远不知道:)
    【解决方案6】:

    如果您愿意使用 C++11 功能,可以使用可变参数模板对可变长度字符串进行编译时加密,例如 this

    另请参阅this,您可能会发现它的解释更好。

    【讨论】:

    • 不幸的是,您可以利用多字节字符对字符进行分组,从而一次将它们分组 4 个。
    • @Matthieu:我实际上同意,尽管tbh,字符串的编译时加密是浪费时间(散列有点不同),因为任何值得他们盐的人都可以一次解密并使用RVA将两者联系起来。
    • 我同意,这里加密基本没用。
    【解决方案7】:

    如果人们对简单的字符串加密感兴趣。我编写了一个代码示例,描述了使用 MACRO 进行字符串自我解密和标记。提供了一个外部加密代码来修补二进制文件(因此在程序编译后对字符串进行加密)。字符串在内存中一次解密一个。

    http://www.sevagas.com/?String-encryption-using-macro-and

    这不会阻止带有调试器的反向器最终找到字符串,但会阻止字符串从可执行文件和内存转储中列出。

    【讨论】:

      【解决方案8】:

      我无法编译它,编译器抛出无数错误,我正在寻找其他快速字符串加密的解决方案,并发现了这个小玩具https://www.stringencrypt.com(不难,第一个结果是谷歌的字符串加密关键字)。

      这就是它的工作原理:

      1. 你输入标签名称说 sString
      2. 你输入字符串内容
      3. 你点击加密
      4. 它获取字符串并对其进行加密
      5. 生成 C++ 解密源代码(支持多种其他语言)
      6. 您将此 sn-p 粘贴到您的代码中

      示例字符串“StackOverflow 太棒了!”,输出代码(每次生成的代码都略有不同)。它同时支持 ANSI (char) 和 UNICODE (wchar_t) 类型的字符串

      ANSI 输出:

      // encrypted with https://www.stringencrypt.com (v1.1.0) [C/C++]
      // sString = "StackOverflow is awesome!"
      unsigned char sString[26] = { 0xE3, 0x84, 0x2D, 0x08, 0xDF, 0x6E, 0x0B, 0x87,
                                    0x51, 0xCF, 0xA2, 0x07, 0xDE, 0xCF, 0xBF, 0x73,
                                    0x1C, 0xFC, 0xA7, 0x32, 0x7D, 0x64, 0xCE, 0xBD,
                                    0x25, 0xD8 };
      
      for (unsigned int bIFLw = 0, YivfL = 0; bIFLw < 26; bIFLw++)
      {
              YivfL = sString[bIFLw];
              YivfL -= bIFLw;
              YivfL = ~YivfL;
              YivfL = (((YivfL & 0xFF) >> 7) | (YivfL << 1)) & 0xFF;
              YivfL ++;
              YivfL ^= 0x67;
              YivfL = (((YivfL & 0xFF) >> 6) | (YivfL << 2)) & 0xFF;
              YivfL += bIFLw;
              YivfL += 0x0F;
              YivfL = ((YivfL << 4) | ( (YivfL & 0xFF) >> 4)) & 0xFF;
              YivfL ^= 0xDA;
              YivfL += bIFLw;
              YivfL ++;
              sString[bIFLw] = YivfL;
      }
      
      printf(sString);
      

      UNICODE 输出:

      // encrypted with https://www.stringencrypt.com (v1.1.0) [C/C++]
      // sString = "StackOverflow is awesome!"
      wchar_t sString[26] = { 0x13A6, 0xA326, 0x9AA6, 0x5AA5, 0xEBA7, 0x9EA7, 0x6F27, 0x55A6,
                              0xEB24, 0xD624, 0x9824, 0x58A3, 0x19A5, 0xBD25, 0x62A5, 0x56A4,
                              0xFC2A, 0xC9AA, 0x93AA, 0x49A9, 0xDFAB, 0x9EAB, 0x9CAB, 0x45AA,
                              0x23CE, 0x614F };
      
      for (unsigned int JCBjr = 0, XNEPI = 0; JCBjr < 26; JCBjr++)
      {
              XNEPI = sString[JCBjr];
              XNEPI -= 0x5D75;
              XNEPI = (((XNEPI & 0xFFFF) >> 14) | (XNEPI << 2)) & 0xFFFF;
              XNEPI = ~XNEPI;
              XNEPI -= 0xA6E5;
              XNEPI ^= JCBjr;
              XNEPI = (((XNEPI & 0xFFFF) >> 10) | (XNEPI << 6)) & 0xFFFF;
              XNEPI --;
              XNEPI ^= 0x9536;
              XNEPI += JCBjr;
              XNEPI = ((XNEPI << 1) | ( (XNEPI & 0xFFFF) >> 15)) & 0xFFFF;
              sString[JCBjr] = XNEPI;
      }
      
      wprintf(sString);
      

      现在我知道它可能不是完美的解决方案,但它适用于我和我的编译器。

      【讨论】:

        猜你喜欢
        • 2011-10-19
        • 2011-05-05
        • 1970-01-01
        • 2021-02-24
        • 2016-04-22
        • 1970-01-01
        • 2011-06-25
        • 1970-01-01
        • 2015-10-21
        相关资源
        最近更新 更多