13 from passwordreceiver import *
15 MINOPTS = { "Main" : ["LogFile", "LogLevel", "MountScript", "UmountScript", "InitScript", "GetDevicesScript", "Keyfile"]}
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"
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))
31 configfile = CONFIG_FILE
32 config = ConfigParser.SafeConfigParser ()
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)
39 config.read (CONFIG_FILE)
42 print ("Error: %s" % (e))
45 checkMinimumOptions (config)
50 logfile = config.get("Main", "LogFile")
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)
56 # ToDo move log level and maybe other things to config file
58 level = numeric_level,
59 format = "%(asctime)s %(name)-12s %(funcName)-15s %(levelname)-8s %(message)s",
60 datefmt = "%Y-%m-%d %H:%M:%S",
64 LOG = logging.getLogger("encryptionprovicer")
69 def runExternalScripts (command):
70 LOG.debug ("Run external Script: %s" %(command,))
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]),))
77 process = subprocess.Popen( command, stdout=subprocess.PIPE, stderr=subprocess.PIPE )
78 retcode = process.wait()
79 ( stdout, stderr ) = process.communicate()
81 return { "retcode" : retcode, "stdout" : stdout, "stderr" : stderr }
84 def getDevices (script):
86 result = runExternalScripts (command);
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"],))
95 #print ("%s" %(result["stdout"],))
96 # don't use print here, because of the extra newline
97 sys.stdout.write ("%s" %(result["stdout"],))
100 def umountDevice (script, device):
101 command = [script, device];
102 result = runExternalScripts (command);
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"],))
111 #print ("%s" %(result["stdout"],))
112 # don't use print here, because of the extra newline
113 sys.stdout.write ("%s" %(result["stdout"],))
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,))
121 while (close == False):
123 if (os.path.ismount(mountpoint) == True):
125 LOG.info ("Stick \"%s\" was mounted sucessfully to \"%s\"" %(device, mountpoint,))
128 if (os.path.exists(device) == False):
130 LOG.error ("Stick \"%s\" removed -> exit" %(device,))
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()
138 if (pipe.close() != None):
139 LOG.error ("error: %s" %(result,))
142 if (result == device):
143 LOG.debug ("Device: %s ### Result: %s ### Return: True" %(device, result,))
146 LOG.debug ("Device: %s ### Result: %s ### Return: False" %(device, result,))
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,))
155 while (close == False):
157 if (os.path.exists(device) == False):
159 LOG.info ("Stick \"%s\" removed -> exit" %(device,))
162 if __name__ == "__main__":
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()
173 config = loadConfig ()
176 if (arguments.getdevices):
177 getDevices (config.get ("Main", "GetDevicesScript"))
179 if (arguments.umount):
180 umountDevice (config.get ("Main", "UmountScript"), arguments.umount[0])
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"))
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"))