2 # -*- coding: utf-8 -*-
4 # ------------------------------------------------------------
5 # opensecurity_client_restful_server
7 # the OpenSecurity client RESTful server
9 # Autor: Oliver Maurhart, <oliver.maurhart@ait.ac.at>
11 # Copyright (C) 2013 AIT Austrian Institute of Technology
12 # AIT Austrian Institute of Technology GmbH
13 # Donau-City-Strasse 1 | 1220 Vienna | Austria
14 # http://www.ait.ac.at
16 # This program is free software; you can redistribute it and/or
17 # modify it under the terms of the GNU General Public License
18 # as published by the Free Software Foundation version 2.
20 # This program is distributed in the hope that it will be useful,
21 # but WITHOUT ANY WARRANTY; without even the implied warranty of
22 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 # GNU General Public License for more details.
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 51 Franklin Street, Fifth Floor,
28 # Boston, MA 02110-1301, USA.
29 # ------------------------------------------------------------
32 # ------------------------------------------------------------
59 from opensecurity_util import logger, setupLogger, OpenSecurityException
60 if sys.platform == 'win32' or sys.platform == 'cygwin':
61 from cygwin import Cygwin
64 import __init__ as opensecurity
65 from environment import Environment
68 # ------------------------------------------------------------
72 """All the URLs we know mapping to class handler"""
74 '/credentials', 'os_credentials',
75 '/keyfile', 'os_keyfile',
77 '/notification', 'os_notification',
78 '/password', 'os_password',
79 '/netmount', 'os_netmount',
80 '/netumount', 'os_netumount',
81 '/netcleanup', 'os_netcleanup',
86 # ------------------------------------------------------------
90 """lock for read/write log file"""
91 log_file_lock = threading.Lock()
93 """timer for the log file bouncer"""
94 log_file_bouncer = None
97 """The REST server object"""
101 # ------------------------------------------------------------
105 class os_credentials:
107 """OpenSecurity '/credentials' handler.
109 This is called on GET /credentials?text=TEXT.
110 Ideally this should pop up a user dialog to insert his
111 credentials based the given TEXT.
120 if not "text" in args:
121 raise web.badrequest('no text given')
124 remote_ip = web.ctx.environ['REMOTE_ADDR']
126 # create the process which queries the user
127 dlg_image = os.path.join(sys.path[0], 'opensecurity_dialog.pyw')
128 process_command = [sys.executable, dlg_image, 'credentials', args.text]
129 process = subprocess.Popen(process_command, shell = False, stdout = subprocess.PIPE)
131 # run process result handling in seprate thread (not to block main one)
132 bouncer = ProcessResultBouncer(process, remote_ip, '/credentials')
135 return 'user queried for credentials'
140 """OpenSecurity '/keyfile' handler.
142 This is called on GET /keyfile?text=TEXT.
143 Ideally this should pop up a user dialog to insert his
144 password along with a keyfile.
153 if not "text" in args:
154 raise web.badrequest('no text given')
157 remote_ip = web.ctx.environ['REMOTE_ADDR']
159 # create the process which queries the user
160 dlg_image = os.path.join(sys.path[0], 'opensecurity_dialog.pyw')
161 process_command = [sys.executable, dlg_image, 'keyfile', args.text]
162 process = subprocess.Popen(process_command, shell = False, stdout = subprocess.PIPE)
164 # run process result handling in seprate thread (not to block main one)
165 bouncer = ProcessResultBouncer(process, remote_ip, '/keyfile')
168 return 'user queried for password and keyfile'
173 """OpenSecurity '/log' handler.
175 This is called on GET or POST on the log function /log
188 args['user'] = getpass.getuser()
189 args['system'] = platform.node() + " " + platform.system() + " " + platform.release()
191 # add these to new data to log
193 log_file_name = os.path.join(Environment('OpenSecurity').log_path, 'vm_new.log')
194 log_file_lock.acquire()
195 pickle.dump(args, open(log_file_name, 'ab'))
196 log_file_lock.release()
201 class os_notification:
203 """OpenSecurity '/notification' handler.
205 This is called on GET /notification?msgtype=TYPE&text=TEXT.
206 This will pop up an OpenSecurity notifcation window
215 if not "msgtype" in args:
216 raise web.badrequest('no msgtype given')
218 if not args.msgtype in ['information', 'warning', 'critical']:
219 raise web.badrequest('Unknown value for msgtype')
222 if not "text" in args:
223 raise web.badrequest('no text given')
225 # invoke the user dialog as a subprocess
226 dlg_image = os.path.join(sys.path[0], 'opensecurity_dialog.py')
227 process_command = [sys.executable, dlg_image, 'notification-' + args.msgtype, args.text]
228 process = subprocess.Popen(process_command, shell = False, stdout = subprocess.PIPE)
235 """OpenSecurity '/password' handler.
237 This is called on GET /password?text=TEXT.
238 Ideally this should pop up a user dialog to insert his
239 password based device name.
248 if not "text" in args:
249 raise web.badrequest('no text given')
252 remote_ip = web.ctx.environ['REMOTE_ADDR']
254 # create the process which queries the user
255 dlg_image = os.path.join(sys.path[0], 'opensecurity_dialog.pyw')
256 process_command = [sys.executable, dlg_image, 'password', args.text]
257 process = subprocess.Popen(process_command, shell = False, stdout = subprocess.PIPE)
259 # run process result handling in seprate thread (not to block main one)
260 bouncer = ProcessResultBouncer(process, remote_ip, '/password')
263 return 'user queried for password'
265 def genNetworkDrive():
266 logical_drives = getLogicalDrives()
267 logger.info("Used logical drive letters: "+ str(logical_drives).strip('[]') )
268 drives = list(map(chr, range(68, 91)))
270 if drive not in logical_drives:
274 def getLogicalDrives():
275 drive_bitmask = ctypes.cdll.kernel32.GetLogicalDrives()
276 drives = list(itertools.compress(string.ascii_uppercase, map(lambda x:ord(x) - ord('0'), bin(drive_bitmask)[:1:-1])))
279 def getNetworkPath(drive):
280 return win32wnet.WNetGetConnection(drive+':')
282 def getDriveType(drive):
283 return ctypes.cdll.kernel32.GetDriveTypeW(u"%s:\\"%drive)
285 def getNetworkDrive(path):
286 for drive in getLogicalDrives():
287 #if is a network drive
288 if getDriveType(drive) == 4:
289 network_path = getNetworkPath(drive)
290 if path in network_path:
294 # handles netumount request
295 class MountNetworkDriveHandler(threading.Thread):
297 def __init__(self, net_path):
298 threading.Thread.__init__(self)
299 self.networkPath = net_path
302 drive = genNetworkDrive()
304 logger.error("Failed to assign drive letter for: " + self.networkPath)
307 logger.info("Assigned drive " + drive + " to " + self.networkPath)
309 #Check for drive availability
311 if os.path.exists(drive):
312 logger.error("Drive letter is already in use: " + drive)
315 #Check for network resource availability
317 while not os.path.exists(self.networkPath):
321 logger.info("Path not accessible: " + self.networkPath + " retrying")
324 command = 'USE ' + drive + ' ' + self.networkPath + ' /PERSISTENT:NO'
327 result = Cygwin.checkResult(Cygwin.execute('C:\\Windows\\system32\\NET', command))
334 """OpenSecurity '/netmount' handler"""
340 # we _need_ a net_resource
341 if not "net_resource" in args:
342 raise web.badrequest('no net_resource given')
344 driveHandler = MountNetworkDriveHandler(args['net_resource'])
346 driveHandler.join(None)
349 # handles netumount request
350 class UmountNetworkDriveHandler(threading.Thread):
354 def __init__(self, path):
355 threading.Thread.__init__(self)
356 self.networkPath = path
360 drive = getNetworkDrive(self.networkPath)
362 logger.info("Failed to retrieve drive letter for: " + self.networkPath + ". Successfully deleted or missing.")
366 logger.info("Unmounting drive " + drive + " for " + self.networkPath)
367 command = 'USE ' + drive + ' /DELETE /YES'
368 result = Cygwin.checkResult(Cygwin.execute('C:\\Windows\\system32\\net.exe', command))
369 if string.find(str(result[1]), 'successfully',) == -1:
370 logger.error(result[2])
376 """OpenSecurity '/netumount' handler"""
382 # we _need_ a net_resource
383 if not "net_resource" in args:
384 raise web.badrequest('no net_resource given')
386 driveHandler = UmountNetworkDriveHandler(args['net_resource'])
388 driveHandler.join(None)
393 """OpenSecurity '/netcleanup' handler"""
399 # we _need_ a net_resource
400 if not "hostonly_ip" in args:
401 raise web.badrequest('no net_resource given')
403 ip = args['hostonly_ip']
404 ip = ip[:ip.rindex('.')]
405 drives = getLogicalDrives()
407 # found network drive
408 if getDriveType(drive) == 4:
409 path = getNetworkPath(drive)
411 driveHandler = UmountNetworkDriveHandler(path)
413 driveHandler.join(None)
417 """OpenSecurity '/' handler"""
421 res = "OpenSecurity-Client RESTFul Server { \"version\": \"%s\" }" % opensecurity.__version__
423 # add some sample links
429 (copy paste this into your browser's address field after the host:port)
431 /password?text=Give+me+a+password+for+device+%22My+USB+Drive%22+(ID%3A+32090-AAA-X0)
433 (eg.: http://127.0.0.1:8090/password?text=Give+me+a+password+for+device+%22My+USB+Drive%22+(ID%3A+32090-AAA-X0))
434 NOTE: check yout taskbar, the dialog window may not pop up in front of your browser window.
437 Request a combination of user and password:
438 (copy paste this into your browser's address field after the host:port)
440 /credentials?text=Tell+the+NSA+which+credentials+to+use+in+order+to+avoid+hacking+noise+on+wire.
442 (eg.: http://127.0.0.1:8090/credentials?text=Tell+the+NSA+which+credentials+to+use+in+order+to+avoid+hacking+noise+on+wire.)
443 NOTE: check yout taskbar, the dialog window may not pop up in front of your browser window.
446 Request a combination of password and keyfile:
447 (copy paste this into your browser's address field after the host:port)
449 /keyfile?text=Your%20private%20RSA%20Keyfile%3A
451 (eg.: http://127.0.0.1:8090//keyfile?text=Your%20private%20RSA%20Keyfile%3A)
452 NOTE: check yout taskbar, the dialog window may not pop up in front of your browser window.
456 (copy paste this into your browser's address field after the host:port)
458 /application?vm=Debian+7&app=Browser
460 (e.g. http://127.0.0.1:8090/application?vm=Debian+7&app=Browser)
466 class ProcessResultBouncer(threading.Thread):
468 """A class to post the result of a given process - assuming it to be in JSON - to a REST Api."""
470 def __init__(self, process, remote_ip, resource):
474 threading.Thread.__init__(self)
475 self._process = process
476 self._remote_ip = remote_ip
477 self._resource = resource
490 # invoke the user dialog as a subprocess
491 result = self._process.communicate()[0]
492 if self._process.returncode != 0:
493 print 'user request has been aborted.'
496 # all ok, tell send request back appropriate destination
498 j = json.loads(result)
500 print 'error in password parsing'
503 # by provided a 'data' we turn this into a POST statement
504 url_addr = 'http://' + self._remote_ip + ':58080' + self._resource
505 req = urllib2.Request(url_addr, urllib.urlencode(j))
507 res = urllib2.urlopen(req)
509 print 'failed to contact: ' + url_addr
513 class RESTServerThread(threading.Thread):
515 """Thread for serving the REST API."""
517 def __init__(self, port):
520 threading.Thread.__init__(self)
536 def is_already_running(port = 8090):
538 """check if this is started twice"""
541 s = socket.create_connection(('127.0.0.1', port), 0.5)
548 def _bounce_vm_logs():
550 """grab all logs from the VMs and push them to the log servers"""
554 # pick the highest current number
556 for f in glob.iglob(os.path.join(Environment('OpenSecurity').log_path, 'vm_cur.log.*')):
558 n = f.split('.')[-1:][0]
566 # first add new vm logs to our existing one: rename the log file
567 log_file_name_new = os.path.join(Environment('OpenSecurity').log_path, 'vm_new.log')
568 log_file_name_cur = os.path.join(Environment('OpenSecurity').log_path, 'vm_cur.log.' + str(cur))
569 log_file_lock.acquire()
571 os.rename(log_file_name_new, log_file_name_cur)
572 print('new log file: ' + log_file_name_cur)
575 log_file_lock.release()
577 # now we have a list of next log files to dump
578 log_files = glob.glob(os.path.join(Environment('OpenSecurity').log_path, 'vm_cur.log.*'))
580 for log_file in log_files:
583 f = open(log_file, 'rb')
593 logger.warning('tried to delete log file (pushed to EOF) "' + log_file + '" but failed')
596 logger.warning('encountered error while pushing log file "' + log_file + '"')
599 # start bouncer again ...
600 global log_file_bouncer
601 log_file_bouncer = threading.Timer(5.0, _bounce_vm_logs)
602 log_file_bouncer.start()
606 """POST a single log to log server
608 @param log the log POST param
611 log_server_url = "http://extern.x-net.at/opensecurity/log"
613 key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, 'SOFTWARE\OpenSecurity')
614 log_server_url = str(win32api.RegQueryValueEx(key, 'LogServerURL')[0])
615 win32api.RegCloseKey(key)
617 logger.warning('Cannot open Registry HKEY_LOCAL_MACHINE\SOFTWARE\OpenSecurity and get "LogServerURL" value, using default instead')
619 # by provided a 'data' we turn this into a POST statement
620 d = urllib.urlencode(log)
621 req = urllib2.Request(log_server_url, d)
623 logger.debug('pushed log to server: ' + str(log_server_url))
628 """Start the REST server"""
632 # start the VM-log bouncer timer
633 global log_file_bouncer
634 log_file_bouncer = threading.Timer(5.0, _bounce_vm_logs)
635 log_file_bouncer.start()
637 # trick the web.py server
638 sys.argv = [__file__, str(port)]
639 server = web.application(opensecurity_urls, globals())
643 def serve(port = 8090, background = False):
645 """Start serving the REST Api
646 port ... port number to listen on
647 background ... cease into background (spawn thread) and return immediately"""
649 # start threaded or direct version
650 if background == True:
651 t = RESTServerThread(port)
658 """Stop serving the REST Api"""
664 global log_file_bouncer
665 if log_file_bouncer is not None:
666 log_file_bouncer.cancel()
671 if __name__ == "__main__":