Defensive Programming - Secure Programming

Defensive programming is sometimes referred to as secure programming by computer scientists who state this approach minimizes bugs. Software bugs can be potentially used by a cracker for a code injection, denial-of-service attack or other attack.

A difference between defensive programming and normal practices is that few assumptions are made by the programmer, who attempts to handle all possible error states. In short, the programmer never assumes a particular function call or library will work as advertised, and so handles it in the code. An example follows:

int risky_programming(char *input){ char str; // one more for the null character // ... strcpy(str, input); // copy input // ... }

The function will crash when the input is over 1000 characters. Some novice programmers may not feel that this is a problem, supposing that no user will enter such a long input. A programmer practicing defensive programming would not allow the bug, because if the application contains a known bug, Murphy's Law dictates that the bug will occur in use. This particular bug demonstrates a vulnerability which enables buffer overflow exploits. Here is a solution to this example:

int secure_programming(char *input){ char str; // ... strncpy(str, input, sizeof(str)); // copy input without exceeding the length of the destination str = '\0'; // if strlen(input) == sizeof(str) then strncpy won't NUL terminate // ... }

Read more about this topic:  Defensive Programming

Famous quotes containing the words secure and/or programming:

    We shall make mistakes, but they must never be mistakes which result from faintness of heart or abandonment of moral principles. I remember that my old school master Dr. Peabody said in days that seemed to us then to be secure and untroubled, he said things in life will not always run smoothly, sometimes we will be rising toward the heights and all will seem to reverse itself and start downward. The great thing to remember is that the trend of civilization itself is forever upward.
    Franklin D. Roosevelt (1882–1945)

    If there is a price to pay for the privilege of spending the early years of child rearing in the driver’s seat, it is our reluctance, our inability, to tolerate being demoted to the backseat. Spurred by our success in programming our children during the preschool years, we may find it difficult to forgo in later states the level of control that once afforded us so much satisfaction.
    Melinda M. Marshall (20th century)