chroot/chroot_secure_chdir.c

Go to the documentation of this file.
00001 // Copyright 2006 Benedikt Böhm <hollow@gentoo.org>
00002 //
00003 // This program is free software; you can redistribute it and/or modify
00004 // it under the terms of the GNU General Public License as published by
00005 // the Free Software Foundation; either version 2 of the License, or
00006 // (at your option) any later version.
00007 //
00008 // This program is distributed in the hope that it will be useful,
00009 // but WITHOUT ANY WARRANTY; without even the implied warranty of
00010 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00011 // GNU General Public License for more details.
00012 //
00013 // You should have received a copy of the GNU General Public License
00014 // along with this program; if not, write to the
00015 // Free Software Foundation, Inc.,
00016 // 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
00017 
00018 #include <unistd.h>
00019 #include <errno.h>
00020 
00021 #include "chroot.h"
00022 #include "open.h"
00023 
00024 /* go to <dir> in <root> as root
00025 ** going into the chroot before doing chdir(dir) prevents symlink attacks
00026 ** and hence is safer */
00027 int chroot_secure_chdir(const char *root, const char *dir)
00028 {
00029         int orig_root, new_root;
00030         
00031         if ((orig_root = open_read("/")) == -1)
00032                 return -1;
00033         
00034         if (chdir(root) == -1)
00035                 return -1;
00036         
00037         if ((new_root = open_read(".")) == -1)
00038                 return -1;
00039         
00040         int dirfd;
00041         int errno_orig;
00042         
00043         /* check cwdfd */
00044         if (chroot_fd(new_root) == -1)
00045                 return -1;
00046         
00047         /* now go to dir in the chroot */
00048         if (chdir(dir) == -1)
00049                 goto err;
00050         
00051         /* save a file descriptor of the target dir */
00052         dirfd = open_read(".");
00053         
00054         if (dirfd == -1)
00055                 goto err;
00056         
00057         /* break out of the chroot */
00058         chroot_fd(orig_root);
00059         
00060         /* now go to the saved target dir (but outside the chroot) */
00061         if (fchdir(dirfd) == -1)
00062                 goto err2;
00063         
00064         close(dirfd);
00065         return 0;
00066         
00067 err2:
00068         errno_orig = errno;
00069         close(dirfd);
00070         errno = errno_orig;
00071 err:
00072         errno_orig = errno;
00073         chroot_fd(orig_root);
00074         errno = errno_orig;
00075         return -1;
00076 }

Generated on Sun Dec 3 17:45:53 2006 for lucid by  doxygen 1.5.1