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