Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Defensive programming
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
== Secure programming == {{main|Secure coding}} Secure programming is the subset of defensive programming concerned with [[computer security]]. Security is the concern, not necessarily safety or availability (the [[software]] may be allowed to fail in certain ways). As with all kinds of defensive programming, avoiding bugs is a primary objective; however, the motivation is not as much to reduce the likelihood of failure in normal operation (as if safety were the concern), but to reduce the attack surface β the programmer must assume that the software might be misused actively to reveal bugs, and that bugs could be exploited maliciously. <syntaxhighlight lang="c">int risky_programming(char *input) { char str[1000]; // ... strcpy(str, input); // Copy input. // ... }</syntaxhighlight> The function will result in undefined behavior when the input is over 1000 characters. Some programmers may not feel that this is a problem, supposing that no user will enter such a long input. This particular bug demonstrates a vulnerability which enables [[buffer overflow]] [[exploit (computer security)|exploit]]s. Here is a solution to this example: <syntaxhighlight lang="c">int secure_programming(char *input) { char str[1000+1]; // One more for the null character. // ... // Copy input without exceeding the length of the destination. strncpy(str, input, sizeof(str)); // If strlen(input) >= sizeof(str) then strncpy won't null terminate. // We counter this by always setting the last character in the buffer to NUL, // effectively cropping the string to the maximum length we can handle. // One can also decide to explicitly abort the program if strlen(input) is // too long. str[sizeof(str) - 1] = '\0'; // ... }</syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)