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:

    Happy the man, and happy he alone,
    He who can call today his own;
    He who, secure within, can say,
    Tomorrow, do thy worst, for I have lived today.
    John Dryden (1631–1700)

    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)