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