Search This Blog

6.07.2021

Changing users with SUID and setuid/setgid

 Doing the Linux privilege escalation room on TryHackMe reminded me of a trick I've used in the past.  I haven't used it for nefarious purposes, only to get around a web script being run as the woefully unprivileged apache user, when it needed to run as a more privileged user.  It could easily be used as a good pentesting exploit.  I DO NOT endorse using this for evil.  Only use this for good, people.

It uses what I call a run stub.  It's a C wrapper that launches the script, but only after it changes the UID/GID to the desired higher-privileged user.  The run stub has to have SUID permissions and be owned by root.  So, chmod u+s runstub after compiling runstub.c into runstub.  The permissions listing should say: -rwsr-xr-x root root.

Below is the code: 

#include <stdio.h> 
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>

int uid;
int gid;
char runprog[512];
int main(int argc, char *argv[])
{
setgid(<gid>); /* <gid> is whatever GID you want to switch to */
setuid(<uid>);  /* <uid> is whatever UID you want to switch to */
snprintf(runprog, 512, "/path/to/script %s", argv[1]);  /* runprog is the buffer, 512 is the size of the buffer, the rest is the script you're trying to run and any arguments you want to pass to it, specified on the run stub's command line */
system(runprog);
return 0;
}

The two magic parts here are setuid()/setgid(), which *nix uses to switch users and groups in things like sudo and su, and system().  The snprintf() line formats the command into a string that can be passed to system(), which executes commands.

So, use your powers for good, and happy hacking.

No comments:

Post a Comment