Advertisement
Guest User

Untitled

a guest
Jul 18th, 2018
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.05 KB | None | 0 0
  1. #include <iostream>
  2. #include <sstream>
  3.  
  4. #include <cerrno>
  5. #include <cstring>
  6.  
  7. #include <sys/stat.h>
  8. #include <sys/mount.h>
  9. #include <sys/syscall.h>
  10. #include <sched.h>
  11.  
  12. #include <cstdio>
  13. #include <cstdlib>
  14.  
  15. #include <unistd.h>
  16.  
  17. #define OLD_ROOT "oldroot"
  18.  
  19. using namespace std;
  20.  
  21. int main(int argc, char* argv[]) {
  22.   if(argc != 2) {
  23.     cerr << "First argument is the template for the root" << endl;
  24.     return -1;
  25.   }
  26.   string template_root(argv[1]);
  27.  
  28.   // Generate tmpfs directory
  29.   stringstream ss;
  30.   ss << "tmpfs_" << template_root;
  31.   string tmpfs = ss.str();
  32.  
  33.   struct stat st;
  34.   if(stat(tmpfs.c_str(),&st) == 0) {
  35.     cerr << tmpfs << " already exists!" << endl;
  36.     return -1;
  37.   }
  38.  
  39.   if(mkdir(tmpfs.c_str(),644) != 0) {
  40.     perror("mkdir");
  41.     return -1;
  42.   }
  43.  
  44.   // Mount tmpfs
  45.   if(mount("none", tmpfs.c_str(), "tmpfs", 0, "mode=0644,uid=65534,size=10M") != 0) {
  46.     perror("mount");
  47.     return 1;
  48.   }
  49.  
  50.   // Copy content
  51.   ss.str("");
  52.   ss.clear();
  53.   ss << "cp -r " << template_root << "/* " << tmpfs;
  54.   system(ss.str().c_str());
  55.  
  56.   // Create mount namespace
  57.   if(unshare(CLONE_NEWNS) < 0) {
  58.     perror("unshare");
  59.     return 1;
  60.   }
  61.  
  62.   // Make old root MS_SLAVE
  63.   // Using the syscall directly is not easy since it requires
  64.   // reading the /etc/fstab
  65.   if(system("mount --make-rslave /") != 0) {
  66.     perror("mount");
  67.     return 1;
  68.   }
  69.  
  70.   // Change directory
  71.   chdir(tmpfs.c_str());
  72.  
  73.   // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  74.   // This command leads to EBUSY of the pivot_root.
  75.   // Without it, everything works fine
  76.   chroot(".");
  77.  
  78.   // Move to new root file system
  79.   if(mkdir(OLD_ROOT,644) != 0) {
  80.     perror("mkdir");
  81.     return -1;
  82.   }
  83.   if(syscall(SYS_pivot_root,".",OLD_ROOT) < 0) {
  84.     perror("pivot_root");
  85.     return 1;
  86.   }
  87.  
  88.   // Remove old mount
  89.   if(umount2(OLD_ROOT,MNT_DETACH) != 0) {
  90.     perror("umount");
  91.     return 1;
  92.   }
  93.   if(rmdir(OLD_ROOT) != 0) {
  94.     perror("rmdir");
  95.     return 1;
  96.   }
  97.  
  98.   // Enter shell - only for testing
  99.   execl("/bin/bash","-i",NULL);
  100.  
  101.   return 0;
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement