...
A security flaw exists in the code shown below resulting from the absence of proper canonicalization measures on the file path. This allows an attacker to traverse the filesystem and possibly write to a file of his choice, with the privileges of the vulnerable program. For example, it may be possible to overwrite the password file (such as the /etc/passwd
, common to many POSIX based systems) or a device file such as the mouse which in turn can aid further exploitation or cause a denial of service to occur.
Code Block | ||
---|---|---|
| ||
/* Program running with elevated privileges where argv[1] and argv[2] isare supplied by the user */ char x[100]; FILE *fp = fopen(argv[1],"w"); /* argv[2] is also specified by the user and may be "foo:*:100:200:8A-74(home):/home/foo:/usr/bin/sh"; * or some other specially crafted input */ char x[100]; strncpy(x,argv[2],100); x[100] = '\0'; fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fp); /* Write operation to an unintended file like /etc/passwd gets executed */ |
Wiki Markup |
---|
An attacker can control the value of {{argv\[1\]}} and consequently access any resource on the filesystem. |
...
Another essential step is to drop superuser privileges permanently after these calls so as to be in agreement with the principle of least privilege. The chroot()
system call is not secure against the superuser changing the current root directory (if privileges are not dropped) and may be ineffective if the current working directory is not set to the new root directory immediately following the call to chroot()
. Successful jail creation prevents unintentional filesystem access even if an attacker gives malicious input, such as through command line arguments.
Code Block | ||
---|---|---|
| ||
/* * Make sure that the ~/chroot/jail directory exists within the current working directory * Also assign appropriate permissions to the directory to restrict access * Close all filesystem descriptors to outside resources lest they escape the jail */ if (setuid(0) == -1) { /* ReportHandle that setuid failed and note the errno value Error */ } if (chroot("~/chroot/jail") == -1) { /* OperationHandle failed, handle error Error */ } if (chdir("/") == -1) { /* Operation failed, handle errorHandle Error */ } /* Drop privileges permanently to those of the file owner */ */ if (setgid(getgid()) == -1) { /* Handle Error */ } if (setuid(getuid()) == -1) { /* OperationHandle failed, handle error Error */ } /* Perform unprivileged operations */ FILE* fp = fopen(argv[1], "w"); |
...