Support 64bit systems
[schsh.git] / schsh
1 #!/usr/bin/python
2 #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
3 # Configuration
4 shell = None # set to "/bin/bash" or similar to allow shell access
5 allowCommands = ["scp", "rsync", "/usr/lib/openssh/sftp-server"]
6 commandPaths = ["/usr/bin", "/bin"]
7
8 # END of Configuration
9 #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
10 # DO NOT TOUCH ANYTHING BELOW THIS LINE
11
12 import logging, logging.handlers
13 import os, sys, shlex, pwd
14
15 logger = logging.getLogger("schsh")
16 logger.setLevel(logging.INFO)
17 logger.addHandler(logging.handlers.SysLogHandler(address = '/dev/log',
18                                                 facility = logging.handlers.SysLogHandler.LOG_AUTH))
19
20 def get_username():
21     return pwd.getpwuid(os.getuid()).pw_name
22
23 def log(msg, lvl = logging.INFO):
24         logger.log(lvl, "%s[%d]: <%s> %s" % ("schsh", os.getpid(), get_username(), msg))
25
26 def logquit(msg):
27         log(msg, logging.ERROR)
28         sys.exit(1)
29
30 def addPath(prog):
31         if prog.startswith("/"):
32                 return prog
33         # look for it in the paths
34         for path in commandPaths:
35                 fullprog = os.path.join(path, prog)
36                 if os.path.exists(fullprog):
37                         return fullprog
38         return None
39
40 # parse arguments
41 run = []
42 if len(sys.argv) == 1:
43         if shell is None:
44                 print "No shell for you!"
45                 logquit("Shell access not allowed")
46         else:
47                 run = [shell]
48 elif len(sys.argv) == 3 and sys.argv[1] == "-c":
49         # check if the command is allowed, and add path
50         run = shlex.split(sys.argv[2])
51         if len(run) > 0 and run[0] in allowCommands:
52                 run[0] = addPath(run[0])
53                 log("Running '"+str(run)+"'")
54         else:
55                 print "You are not allowed to run this command."
56                 logquit("Attempt to run invalid command '"+sys.argv[2]+"'")
57 else:
58         logquit("Invalid arguments for schsh: "+str(sys.argv))
59
60 assert len(run) > 0
61 os.execl("/usr/bin/schroot", "/usr/bin/schroot", "-c", "schsh-"+get_username(), "-d", "/data", "--", *run)