如何安全地清除 std::string?

2022-01-21 00:00:00 string passwords c++ secure-coding

如何在 std::string 中存储敏感数据(例如:密码)?

How does one store sensitive data (ex: passwords) in std::string?

我有一个应用程序,它提示用户输入密码并在连接设置期间将其传递给下游服务器.我想在建立连接后安全地清除密码值.

I have an application which prompts the user for a password and passes it to a downstream server during connection setup. I want to securely clear the password value after the connection has been established.

如果我将密码存储为 char * 数组,我可以使用像 SecureZeroMemory 从进程内存中删除敏感数据.但是,我想在我的代码中避免使用 char 数组,并且正在为 std::string?

If I store the password as a char * array, I can use APIs like SecureZeroMemory to get rid of the sensitive data from the process memory. However, I want to avoid char arrays in my code and am looking for something similar for std::string?

推荐答案

基于给出的答案 这里,我写了一个分配器来安全地零内存.

Based on the answer given here, I wrote an allocator to securely zero memory.

#include <string>
#include <windows.h>

namespace secure
{
  template <class T> class allocator : public std::allocator<T>
  {
  public:

    template<class U> struct rebind { typedef allocator<U> other; };
    allocator() throw() {}
    allocator(const allocator &) throw() {}
    template <class U> allocator(const allocator<U>&) throw() {}

    void deallocate(pointer p, size_type num)
    {
      SecureZeroMemory((void *)p, num);
      std::allocator<T>::deallocate(p, num);
    }
  };

  typedef std::basic_string<char, std::char_traits<char>, allocator<char> > string;
}

int main()
{
  {
    secure::string bar("bar");
    secure::string longbar("baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaar");
  }
}

然而,事实证明,根据 std::string 的实现方式,分配器可能甚至不会为小值调用.例如,在我的代码中,deallocate 甚至不会为字符串 bar 调用(在 Visual Studio 上).

However, it turns out, depending on how std::string is implemented, it is possible that the allocator isn't even invoked for small values. In my code, for example, the deallocate doesn't even get called for the string bar (on Visual Studio).

因此,答案是我们不能使用 std::string 来存储敏感数据.当然,我们可以选择编写一个处理用例的新类,但我对使用定义的 std::string 特别感兴趣.

The answer, then, is that we cannot use std::string to store sensitive data. Of course, we have the option to write a new class that handles the use case, but I was specifically interested in using std::string as defined.

感谢大家的帮助!

相关文章