Secure C++ Programming
I am starting to learn C++ and I am trying to ensure that I learn how to write secure code in C++ straight from the beginning.
I am already aware that with C++ there is always the chance of a buffer overflow by not validating the user input before putting it into an array (for example putting a string into a char array). I also know that C++ doesn't have any built in methods for stopping the data being added to the array (therefore C++ allowing myVar[200] to be written when the variable was created as char myVar[150]; ) I am aware that you're able to use a variable type string to hold user input as the size of the array is adjusted according to the user input, but this still I believe can be exploited to produce a buffer overflow (I am not certain how though).
My questions are; How can I go about validating the user input to prevent allowing for a buffer overflow to occur. What other security problems should I be aware of when coding with C++?
Thank you for any help you're able to provide in advance
Regards Satal Keto :ninja:
From an article on searchsecurity:
Qualify all user input
To qualify all user input in home-grown applications, first make sure the input string is a valid length. For example, suppose your program is designed to accept 50 characters of text and add them to a database. If the user enters 75 characters, then they have entered more text than the database record can accommodate, and who knows what will happen next. User input should be designed so when a user enters a text string, the length of the string is compared against the maximum allowed input and truncated if necessary.
So, one simple way is to store the input in a temporary variable and check its length before using it in the application. If the input isn't valid, just let them re-enter a valid one.
EDIT: I found a great article about buffer overflows (and how to prevent them), you should really read this: http://www.ibm.com/developerworks/linux/library/l-sp4.html
if youre using std io, use cin.getLine() and specify a number of characters allowed to be inputted. this prevents BoF in many cases. if you use printf or sprintf, always make sure that if you use a variable, use a format before it e.g. use printf("%s",var) instead of printf(var); this prevents format string exploits :) and thats as much as i know lol