Last active
November 13, 2017 13:22
-
-
Save laurivosandi/3d08feb5fbc74aee7dea1952cea779a7 to your computer and use it in GitHub Desktop.
Illustrative and probably very buggy example of what su essentially does
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <sys/types.h> | |
#include <string.h> | |
#include <crypt.h> | |
/** | |
* Illustrative and probably very buggy example of what su essentially does | |
* | |
* To compile run: gcc switcharoo.c -o switcharoo -l crypt | |
* Set permissions: sudo chown root:root switcharoo | |
* Set suid bit: sudo chmod 4755 switcharoo | |
*/ | |
int main(int argc, char** argv) { | |
char *password = getpass("Password:"); | |
FILE *fh = fopen("/etc/shadow", "r"); | |
char line[200]; | |
fgets(line, 200, fh); // read first line, usually corresponds to root user | |
char *username = strtok(line, ":"); // extract first column | |
char *hash = strtok(NULL, ":"); // extract second column | |
printf("Hash from /etc/shadow is: %s\n", hash); | |
char *result = crypt(password, hash); // calculate hash with salt from /etc/shadow | |
printf("User supplied password results in hash: %s\n", result); | |
int ok = strcmp (result, hash) == 0; // compare hashes | |
puts(ok ? "Access granted." : "Access denied."); | |
if (ok) { | |
printf("UID before setuid: %d\n", getuid()); | |
printf("Effective UID before setuid: %d\n", geteuid()); | |
setuid(0); // set actual UID to 0 | |
printf("UID after setuid: %d\n", getuid()); | |
printf("Effective after setuid: %d\n", geteuid()); | |
system("bash"); // execute new shell with root permissions | |
return 0; | |
} else { | |
return 255; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment