简体   繁体   中英

C++ const std:string& security when passing to a third-party API

I have a third party API that expects me to pass a std::string by reference. It says it is accepting it with const . That pretty much means nothing because it can just cast the memory pointer to a non-const char* and modify my string.

Check the code below with an example.

Should I be concerned/suspicious about third-party APIs that ask me to pass a const std::string& (by const reference) instead of a std::string (by value)?

They told me it is because they want to avoid string copying as the strings can be long. Am I being paranoid or it makes sense?

class Blah {

public:
    static void testBlah(const string& s) {
        char* blah = (char*) s.c_str(); // cast away from const char*
        blah[1] = 'b';
    }
};

int main() {

    cout << "!!!Hello There !!!" << endl; // prints !!!Hello World!!!

    const string s = "xxx"; // NOTE THE CONST !!!

    Blah::testBlah(s);

    cout << s << endl; // prints "xbx"

    return 0;
}

Just wrap it in your own trusted class:

#include <iostream>

class Blah {

public:
    static void testBlah(const std::string& s)
    {
        char* blah = (char*)s.c_str(); // cast away from const char*
        blah[1] = 'b';
    }
};

class Safe_Blah {
public:
    static void testBlah(const std::string s)
    {
        Blah::testBlah(s);
    }
};

int main()
{

    std::cout << "!!!Hello There !!!" << std::endl; // prints !!!Hello World!!!

    const std::string s = "xxx"; // NOTE THE CONST !!!

    //Blah::testBlah(s);
    Safe_Blah::testBlah(s);

    std::cout << s.c_str() << std::endl; // now prints "xxx"

    return 0;
}

An API that accept const& to an object is giving out a promise to not modify that object. While, yes, the library may be nefarious and modify it anyway, doing so would be breaking the promise. If the object you passed to it is defined as const , modifying it would be undefined behavior . From the library developer perspective, this would be very bad . Basically, the library devs would be inviting Chutulhu to come and break their users applications in arbitrary, random, unspecified and unpredictable ways.

When it comes to not trusting your library, you lose. C++ API's are not "safe" in any conceivable way in terms of security from an attacker that controls a library you call. When you call a function that is in a library, you pass control of execution over to that library. That library will then have access to read and write all of the memory of your application and may if it so chose, replace the whole lot with it's own thing. So if you're worried about a library doing evil stuff behind your back, you're pretty much out of luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM