Skip to content

Instantly share code, notes, and snippets.

@syjcnss
Created September 16, 2019 11:03
Show Gist options
  • Save syjcnss/23ddd7bd9498994002ccbe5456b977e3 to your computer and use it in GitHub Desktop.
Save syjcnss/23ddd7bd9498994002ccbe5456b977e3 to your computer and use it in GitHub Desktop.
#define LOG_TAG "su"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <unistd.h>
#include <time.h>
#include <pwd.h>
/*
* SU can be given a specific command to exec. UID _must_ be
* specified for this (ie argc => 3).
*
* Usage:
* su 1000
* su 1000 ls -l
*/
int main(int argc, char **argv)
{
struct passwd *pw;
int uid, gid, myuid;
/* Until we have something better, only root and the shell can use su. */
myuid = getuid();
if(argc < 2) {
uid = gid = 0;
} else {
pw = getpwnam(argv[1]);
if(pw == 0) {
uid = gid = atoi(argv[1]);
} else {
uid = pw->pw_uid;
gid = pw->pw_gid;
}
}
if(setgid(gid) || setuid(uid)) {
printf("su: permission denied\n");
return 1;
}
/* User specified command for exec. */
if (argc == 3 ) {
if (execlp(argv[2], argv[2], NULL) < 0) {
printf("su: exec failed for %s Error:%s\n", argv[2],
strerror(errno));
return -errno;
}
} else if (argc > 3) {
/* Copy the rest of the args from main. */
char *exec_args[argc - 1];
memset(exec_args, 0, sizeof(exec_args));
memcpy(exec_args, &argv[2], sizeof(exec_args));
if (execvp(argv[2], exec_args) < 0) {
printf("su: exec failed for %s Error:%s\n", argv[2],
strerror(errno));
return -errno;
}
}
/* Default exec shell. */
execlp("/system/bin/sh", "sh", NULL);
printf("su: exec failed\n");
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment