input validation for user input strings with cin?

Discussion in 'Computer Programming, Emulation, and Game Modding' started by StackMasher, Dec 23, 2016.

  1. StackMasher
    OP

    StackMasher GBAtemp Regular

    Member
    104
    51
    Nov 29, 2016
    I'm writing an emulator and I have this shell style debugging thing where you enter commands like step etc. But there's a buffer overflow vulnerability and I'm not sure how to fix it. cin extracts the string into a buffer of size 10, but the user can enter strings larger than that. How can I put some sort of restriction on the size of the strings?
     
  2. FAST6191

    FAST6191 Techromancer

    pip Reporter
    23,193
    8,944
    Nov 21, 2005
    While most people that can help might guess you are working in C++ (cin being a function associated with it more than most other things I can think of offhand) you may still wish to state it.

    If you are writing an emulator, typically considered one of the harder things you can do as a programmer, I would have hoped you already covered input string sanitisation. That said if it is the sort of thing that motivates you to learn programming then so be it, same deal if it is a simpler system like chip8.

    When you say restriction on the strings do you mean at the input (think the classic enter characters and then when it hits the limit it changes the last entered value) or just I don't need buffer overflows? For the former then you are on your own for that one (it is not hard though) but for the latter then what is the matter with a basic pre parser like strlen? http://www.cplusplus.com/reference/cstring/strlen/
    You then just do a strlen on the input, then say if the result <10 print a string saying how about trying something shorter, else call the parser.

    Option two. Chop it off. Not ideal as an error message is better than some unexpected behaviour because a command got cut short, however if it was only for something that did not get parsed then it is easier.
     
  3. StackMasher
    OP

    StackMasher GBAtemp Regular

    Member
    104
    51
    Nov 29, 2016
    I'm aware of doing proper bounds checking and things like that, I just wasn't sure how to implement it with cin since it's quite abstract and it just pukes out whatever there is in stdin up until the first \n. I ended up doing this:
    Code:
    //Extract the user input a character at a time
    char curChar;       
    for (int i{}; i<20; ++i)
    {
        cin >> std::noskipws >> curChar;
        if (i==19 && curChar!='\n')
        {
            cerr << "[!] Command too long" << endl;
        }
        if (i==19 || curChar=='\n')
        {
            command[i]='\0';
            break;
        }
        command[i]=curChar;
    }