src/encryptionprovider.py
author ft
Tue, 08 Apr 2014 11:39:52 +0200
changeset 1 ad15a8882cac
parent 0 35acc83f4749
child 5 21d27339c811
permissions -rwxr-xr-x
Implemented getdevices, mount and umount
changed from /bin/bash to /bin/sh
     1 #!/usr/bin/python
     2 
     3 import subprocess
     4 import web
     5 import netifaces
     6 import argparse
     7 import thread
     8 import time
     9 import os
    10 import sys
    11 import ConfigParser
    12 import logging
    13 from passwordreceiver import *
    14 
    15 MINOPTS = { "Main" : ["LogFile", "LogLevel", "MountScript", "UmountScript", "InitScript", "GetDevicesScript", "Keyfile"]}
    16 
    17 #CONFIG_FILE="/etc/enryptionprovider/encryptionprovider.cfg"
    18 CONFIG_FILE="/home/spawn/workspace_python/encryptionprovider/config/encryptionprovider.cfg"
    19 CONFIG_NOT_READABLE = "Configfile is not readable"
    20 CONFIG_WRONG = "Something is wrong with the config"
    21 CONFIG_MISSING = "Section: \"%s\" Option: \"%s\" in configfile is missing"
    22 
    23 def checkMinimumOptions (config):
    24     for section, options in MINOPTS.iteritems ():
    25         for option in options:
    26             if (config.has_option(section, option) == False):
    27                 print (CONFIG_MISSING % (section, option))
    28                 exit (129)
    29     
    30     
    31 def loadConfig ():
    32     configfile = CONFIG_FILE
    33     config = ConfigParser.SafeConfigParser ()
    34 
    35     if ((os.path.exists (configfile) == False) or (os.path.isfile (configfile) == False) or (os.access (configfile, os.R_OK) == False)):
    36         print (CONFIG_NOT_READABLE)
    37         exit (1)
    38 
    39     try:
    40         config.read (CONFIG_FILE)
    41     except Exception, e:
    42         print (CONFIG_WRONG)
    43         print ("Error: %s" % (e))
    44         exit (1)
    45 
    46     checkMinimumOptions (config)
    47     return config
    48 
    49 def initLog (config):
    50     global LOG
    51     logfile = config.get("Main", "LogFile")
    52     
    53     numeric_level = getattr(logging, config.get("Main", "LogLevel").upper(), None)
    54     if not isinstance(numeric_level, int):
    55         raise ValueError('Invalid log level: %s' % loglevel)
    56 
    57     # ToDo move log level and maybe other things to config file
    58     logging.basicConfig(
    59                         level = numeric_level,
    60                         format = "%(asctime)s %(name)-12s %(funcName)-15s %(levelname)-8s %(message)s",
    61                         datefmt = "%Y-%m-%d %H:%M:%S",
    62                         filename = logfile,
    63                         filemode = "a+",
    64     )
    65     LOG = logging.getLogger("fuse_main")
    66     
    67     
    68     
    69     
    70 def runExternalScripts (command):
    71     LOG.debug ("Run external Script: %s" %(command,))
    72     
    73     if (os.path.isfile (command[0]) == False):
    74         LOG.error ("File does not exist: %s" %((command[0]),))
    75         sys.stderr.write("File does not exist: %s\n" %((command[0]),))
    76         exit (1)
    77     
    78     process = subprocess.Popen( command, stdout=subprocess.PIPE, stderr=subprocess.PIPE )
    79     retcode = process.wait()
    80     ( stdout, stderr ) = process.communicate()
    81     
    82     return { "retcode" : retcode, "stdout" : stdout, "stderr" : stderr }
    83     
    84     
    85 def getDevices (script):
    86     command = [script];
    87     result = runExternalScripts (command);
    88     
    89     if (result["retcode"] != 0):
    90         LOG.error ("Retcode: %s" %(result["retcode"],))
    91         LOG.error ("stdout: %s" %(result["stdout"],))
    92         LOG.error ("stderr: %s" %(result["stderr"],))
    93         sys.stderr.write("%s" %(result["stderr"],))
    94         exit (1)
    95     
    96     #print ("%s" %(result["stdout"],))
    97     # don't use print here, because of the extra newline
    98     sys.stdout.write ("%s" %(result["stdout"],))
    99 
   100 
   101 def umountDevice (script, device):
   102     command = [script, device];
   103     result = runExternalScripts (command);
   104     
   105     if (result["retcode"] != 0):
   106         LOG.error ("Retcode: %s" %(result["retcode"],))
   107         LOG.error ("stdout: %s" %(result["stdout"],))
   108         LOG.error ("stderr: %s" %(result["stderr"],))
   109         sys.stderr.write("%s" %(result["stderr"],))
   110         exit (1)
   111         
   112     #print ("%s" %(result["stdout"],))
   113     # don't use print here, because of the extra newline
   114     sys.stdout.write ("%s" %(result["stdout"],))
   115     
   116 
   117 def mountDevice (script, interface, port, device, mountpoint, keyfilepath):    
   118     listener = MyRestListener (opensecurity_urls, globals(), script = script, device = device, mountpoint = mountpoint, tries = 3, keyfilepath = keyfilepath)
   119     thread.start_new_thread(listener.run, (interface, port,))
   120     
   121     #command = [script, device, mountpoint, password];
   122     #result = runExternalScripts (command);
   123     
   124     close = False
   125     while (close == False):
   126         time.sleep(1)
   127         if (os.path.ismount(mountpoint) == True):
   128             close = True
   129             LOG.info ("Stick \"%s\" was mounted sucessfully to \"%s\"" %(device, mountpoint,))
   130             sys.exit(0)
   131             
   132         if (os.path.exists(device) == False):
   133             close = True
   134             LOG.error ("Stick \"%s\" removed -> exit" %(device,))
   135             sys.exit(1)
   136 
   137 
   138 if __name__ == "__main__":
   139     
   140     parser = argparse.ArgumentParser(epilog='--mount, --umount and --initialize are mutually exclusive')
   141     group = parser.add_mutually_exclusive_group(required=True)
   142     group.add_argument('-m', '--mount', action='store', nargs=4, dest='mount', help='Mounts an encrypted device.', metavar=("interface", "port", "device", "mountpoint"))
   143     group.add_argument('-u', '--umount', action='store', nargs=1, dest='umount', help='Unmounts an encrypted device', metavar="device")
   144     group.add_argument('-i', '--initialize', action='store', nargs=4, dest='initialize', help='Initialize an device.', metavar=("interface", "port", "device", "mountpoint"))
   145     group.add_argument('-g', '--getdevices', action='store_true', dest="getdevices", help='Returns a list of all mounted encrypted devices')
   146     arguments = parser.parse_args()
   147     
   148     
   149     config = loadConfig ()
   150     initLog (config)
   151     
   152     if (arguments.getdevices):
   153         getDevices (config.get ("Main", "GetDevicesScript"))
   154         
   155     if (arguments.umount):
   156         umountDevice (config.get ("Main", "UmountScript"), arguments.umount[0])
   157     
   158     if (arguments.mount):
   159         mountDevice (config.get ("Main", "MountScript"), arguments.mount[0], int(arguments.mount[1]), arguments.mount[2], arguments.mount[3], config.get ("Main", "Keyfile"))
   160     
   161     if (arguments.initialize):
   162         print ("Init: %s" %(arguments.initialize,))