Secure coding: Difference between revisions

Content deleted Content added
Monkbot (talk | contribs)
m Task 18 (cosmetic): eval 3 templates: del empty params (2×);
mNo edit summary
Line 13:
An example of a [[C (programming language)|C]] program prone to a buffer overflow is<syntaxhighlight lang="c++">
int vulnerable_function(char * large_user_input) {
char dst[SMALL];
strcpy(dst, large_user_input);
}
</syntaxhighlight>If the user input is larger than the destination buffer, a buffer overflow will occur.
Line 20:
To fix this unsafe program, use strncpy to prevent a possible buffer overflow.<syntaxhighlight lang="c++">
int secure_function(char * user_input) {
char dst[BUF_SIZE];
// copy a maximum of BUF_SIZE bytes
strncpy(dst, user_input, BUF_SIZE);
}
</syntaxhighlight>Another secure alternative is to dynamically allocate memory on the heap using [[malloc]].<syntaxhighlight lang="c++">
char * secure_copy(char * src) {
size_t len = strlen(src);
char * dst = (char *) malloc(len + 1);
if (dst != NULL) {
strncpy(dst, src, len);
// append null terminator
dst[len] = '\0';
}
}
return dst;
}
</syntaxhighlight>In the above code snippet, the program attempts to copy the contents of '''''src''''' into '''''dst,''''' while also checking the return value of malloc to ensure that enough memory was able to be allocated for the destination buffer.
Line 66:
</syntaxhighlight>
 
== Path Traversaltraversal prevention ==
Path Traversaltraversal is a vulnerability whereby paths provided from an untrusted source are interpreted in such a way that unauthorised file access is possible.
 
For example, consider a script that fetches an article by taking a filename, which is then read by the script and [[Parse|parsed]]. Such a script might use the following hypothetical URL to retrieve an article about [[dog food]]:
<nowiki>httphttps://www.example.net/cgi-bin/article.sh?name=dogfood.html</nowiki>
If the script has no input checking, instead trusting that the filename is always valid, a [[malicious user]] could forge a URL to retrieve configuration files from the webserver:
<nowiki>httphttps://www.example.net/cgi-bin/article.sh?name=../../../../../etc/passwd</nowiki>
Depending on the script, this may expose the [[Passwd#Password file|/etc/passwd]] file, which on [[Unix-like]] systems contains (among others) [[User identifier (Unix)|user IDs]], their [[Username|login names]], [[home directory]] paths and [[Operating system shell|shells]]. (See [[SQL injection]] for a similar attack.)