def WriteConfiguration(server, dest, authPath): root = os.path.join(HOME, 'resources', 'configs') config = os.path.join(root, 'cfg.ovpn') cert = os.path.join(root, 'vpn.crt') port = ADDON.getSetting('PORT') file = open(config, mode='r') content = file.read() file.close() authPath = authPath.replace('\\', '/') cert = cert.replace('\\', '/') content = content.replace('#SERVER#', server) content = content.replace('#PORT#', port) if utils.platform() == 'android': authentication = '<auth-user-pass>\r\n' \ + ADDON.getSetting('USER') + '@vpnicity' + '\r\n' \ + ADDON.getSetting('PASS') + '\r\n' \ + '</auth-user-pass>' else: authentication = 'auth-user-pass "%s"' % authPath content = content.replace('#AUTHENTICATION#', authentication) file = open(dest, mode='w') file.write(content) file.close()
def WriteConfiguration(server, dest, authPath): root = os.path.join(HOME, 'resources', 'configs') config = os.path.join(root, 'cfg.ovpn') cert = os.path.join(root, 'vpn.crt') port = ADDON.getSetting('PORT') file = open(config, mode='r') content = file.read() file.close() authPath = authPath.replace('\\', '/') cert = cert.replace('\\', '/') content = content.replace('#SERVER#', server) content = content.replace('#PORT#', port) if utils.platform() == 'android': authentication = '<auth-user-pass>\r\n' \ + ADDON.getSetting('USER') + '\r\n' \ + ADDON.getSetting('PASS') + '\r\n' \ + '</auth-user-pass>' else: authentication = 'auth-user-pass "%s"' % authPath content = content.replace('#AUTHENTICATION#', authentication) file = open(dest, mode='w') file.write(content) file.close()
def OpenVPN(config): import path exe = path.getPath(ADDON.getSetting('OS')) if not exe: return None try: timeout = int(ADDON.getSetting('TIMEOUT')) except: timeout = 99999 if utils.platform() == "android": cmdline = "StartAndroidActivity(%s,%s,%s,%s)" % \ ( "com.vpnicity.openvpn.control", "com.vpnicity.openvpn.control.CONNECT", "com.vpnicity.openvpn.control.PROFILE_PATH", "file://" + config ) timeout = 0 else: cmdline = utils.getSudo() cmdline += '"' + exe + '"' cmdline += ' ' cmdline += '"' + config + '"' cmdline = cmdline.replace('\\', '/') print '++++++++++++++++++++++++++ cmdline is...', cmdline return Run(cmdline, timeout)
def KillVPN(): xbmcgui.Window(10000).clearProperty('VPNICITY_LABEL') xbmcgui.Window(10000).clearProperty('VPNICITY_ABRV') xbmcgui.Window(10000).clearProperty('VPNICITY_SERVER') if os.name == 'nt': try: si = subprocess.STARTUPINFO si.dwFlags |= subprocess._subprocess.STARTF_USESHOWWINDOW si.wShowWindow = subprocess._subprocess.SW_HIDE ps = subprocess.Popen('TASKKILL /F /IM openvpn.exe', shell=True, stdout=subprocess.PIPE, startupinfo=None) ps.wait() except: pass return # Android if utils.platform() == "android": xbmc.executebuiltin("StartAndroidActivity(%s,%s)" % ("com.vpnicity.openvpn.control", "com.vpnicity.openvpn.control.DISCONNECT")) return #LINUX try: cmd = utils.getSudo() + 'killall -9 openvpn' ps = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) ps.wait() except: pass
def KillVPN(): xbmcgui.Window(10000).clearProperty('VPNICITY_LABEL') xbmcgui.Window(10000).clearProperty('VPNICITY_ABRV') xbmcgui.Window(10000).clearProperty('VPNICITY_SERVER') if os.name == 'nt': try: si = subprocess.STARTUPINFO si.dwFlags |= subprocess._subprocess.STARTF_USESHOWWINDOW si.wShowWindow = subprocess._subprocess.SW_HIDE ps = subprocess.Popen('TASKKILL /F /IM openvpn.exe', shell=True, stdout=subprocess.PIPE, startupinfo=None) ps.wait() except: pass return # Android if utils.platform() == "android" : xbmc.executebuiltin( "StartAndroidActivity(%s,%s)" % ( "com.vpnicity.openvpn.control", "com.vpnicity.openvpn.control.DISCONNECT") ) return #LINUX try: cmd = utils.getSudo() + 'killall -9 openvpn' ps = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) ps.wait() except: pass
def check_leaks(shell, query, count=1, supp_file=None): if utils.platform() == "darwin": return check_leaks_darwin(shell, query, count=count) else: return check_leaks_linux(shell, query, count=count, supp_file=supp_file)
def test_no_avx_instructions(self): if platform() == "darwin": tool = "otool -tV" else: tool = "objdump -d" proc = subprocess.call( "%s %s | grep vxorps" % (tool, self.binary), shell=True) # Require no AVX instructions self.assertEqual(proc, 1)
def test_no_local_link(self): if platform() == "darwin": tool = "otool -L" else: tool = "ldd" proc = subprocess.call( "%s %s | grep /usr/local/" % (tool, self.binary), shell=True) # Require no local dynamic dependent links. self.assertEqual(proc, 1)
def VPN(label, abrv, server): authPath = os.path.join(PROFILE, 'temp') cfgPath = os.path.join(PROFILE, 'cfg.ovpn') KillVPN(silent=True) WriteAuthentication(authPath) WriteConfiguration(server, cfgPath, authPath) busy = utils.showBusy() response = OpenVPN(cfgPath) if busy: busy.close() success = True if response: label = label.rsplit(' (', 1)[0] if IsEnabled(response): if utils.platform() == "android": xbmc.sleep(10000) utils.dialogOK('%s %s now enabled' % (label, TITLE)) xbmcgui.Window(10000).setProperty('VPNICITY_LABEL', label) xbmcgui.Window(10000).setProperty('VPNICITY_ABRV', abrv) xbmcgui.Window(10000).setProperty('VPNICITY_SERVER', server) ipcheck.Network() else: KillVPN(silent=True) if utils.platform() == "android": xbmc.sleep(5000) utils.dialogOK('%s %s failed to start' % (label, TITLE), 'Please check your settings', 'and try again') ipcheck.Network() success = False #DeleteFile(authPath) #DeleteFile(cfgPath) #DeleteFile(RESPONSE) return success
def get_stats(p, interval=1): """Run psutil and downselect the information.""" utilization = p.cpu_percent(interval=interval) return { "utilization": utilization, "counters": p.io_counters() if utils.platform() != "darwin" else None, "fds": p.num_fds(), "cpu_times": p.cpu_times(), "memory": p.memory_info_ex(), }
def allowed_platform(qp): if qp in ["all", "any"]: return True if len(qp) == 0: return True curr_platform = utils.platform() if (curr_platform == "linux" or curr_platform == "darwin") and qp.find("posix") >= 0: return True return qp.find(curr_platform) >= 0
def Run(cmdline, timeout=0): if utils.platform() == "android": xbmc.executebuiltin(cmdline) return 'Initialization Sequence Completed' #print "COMMAND - %s" % cmdline ret = 'Error: Process failed to start' if timeout > 0: path = RESPONSE shell = True si = None if os.name == 'nt': shell = False si = subprocess.STARTUPINFO si.dwFlags |= subprocess._subprocess.STARTF_USESHOWWINDOW si.wShowWindow = subprocess._subprocess.SW_HIDE f = open(path, mode='w') ps = subprocess.Popen(cmdline, shell=shell, stdout=f, startupinfo=si) xbmc.sleep(5000) while timeout > 0: xbmc.sleep(1000) timeout -= 1 f1 = open(path, mode='r') ret = f1.read() f1.close() if IsEnabled(ret) or IsDisabled(ret): timeout = 0 f.close() else: ps = subprocess.Popen(cmdline, shell=False, stdout=subprocess.PIPE) ret = ps.stdout.read() ps.stdout.close() #try: # print "RESULT - %s" % str(ret) #except: # pass return ret
def Run(cmdline, timeout=0): if utils.platform() == "android": xbmc.executebuiltin( cmdline ) return 'Initialization Sequence Completed' #print "COMMAND - %s" % cmdline ret = 'Error: Process failed to start' if timeout > 0: path = RESPONSE shell = True si = None if os.name == 'nt': shell = False si = subprocess.STARTUPINFO si.dwFlags |= subprocess._subprocess.STARTF_USESHOWWINDOW si.wShowWindow = subprocess._subprocess.SW_HIDE f = open(path, mode='w') ps = subprocess.Popen(cmdline, shell=shell, stdout=f, startupinfo=si) xbmc.sleep(5000) while timeout > 0: xbmc.sleep(1000) timeout -= 1 f1 = open(path, mode='r') ret = f1.read() f1.close() if IsEnabled(ret) or IsDisabled(ret): timeout = 0 f.close() else: ps = subprocess.Popen(cmdline, shell=False, stdout=subprocess.PIPE) ret = ps.stdout.read() ps.stdout.close() #try: # print "RESULT - %s" % str(ret) #except: # pass return ret
def VPN(label, abrv, server): if not validToRun(): utils.log('Login Error via Context Menu') return False authPath = os.path.join(PROFILE, 'temp') cfgPath = os.path.join(PROFILE, 'cfg.ovpn') KillVPN(silent=True) WriteAuthentication(authPath) WriteConfiguration(server, cfgPath, authPath) busy = utils.showBusy() response = OpenVPN(cfgPath) if busy: busy.close() success = True if response: label = label.rsplit(' (', 1)[0] if IsEnabled(response): # if utils.platform() == "android": # xbmc.sleep(10000) message = '%s %s now enabled' % (label, TITLE) utils.notify(message) xbmcgui.Window(10000).setProperty('VPNICITY_LABEL', label) xbmcgui.Window(10000).setProperty('VPNICITY_ABRV', abrv) xbmcgui.Window(10000).setProperty('VPNICITY_SERVER', server) ipcheck.Network() else: KillVPN(silent=True) if utils.platform() == "android": xbmc.sleep(5000) message = '%s %s failed to start. Please check your settings.' % (label, TITLE) utils.notify(message) ipcheck.Network() success = False #DeleteFile(authPath) #DeleteFile(cfgPath) #DeleteFile(RESPONSE) return success
def test_no_nonsystem_link(self): if utils.platform() == "linux": proc = subprocess.call( "ldd %s | awk '{ print $1\" \"$3 }' | grep -Ev '^/lib64|^/lib| /lib|linux-vdso.so.1'" % (BUILD_DIR + "/osquery/osqueryd"), shell=True, ) else: proc = subprocess.call( "otool -L %s | awk '{ if (NR > 1) print $1}' | grep -Ev '^/usr/lib|^/System/Library'" % (BUILD_DIR + "/osquery/osqueryd"), shell=True, ) # Require all libraries to be system libraries. self.assertEqual(proc, 1)
def OpenVPN(config): import path exe = path.getPath(ADDON.getSetting('OS')) if not exe: return None try: timeout = int(ADDON.getSetting('TIMEOUT')) except: timeout = 99999 if utils.platform() == "android": cmdline = "StartAndroidActivity(%s,%s,%s,%s)" % \ ( "com.vpnicity.openvpn.control", "com.vpnicity.openvpn.control.CONNECT", "com.vpnicity.openvpn.control.PROFILE_PATH", "file://" + config ) else : cmdline = utils.getSudo() cmdline += '"' + exe + '"' cmdline += ' ' cmdline += '"' + config + '"' cmdline = cmdline.replace('\\', '/') return Run(cmdline, timeout)
def WriteAuthentication(path): # CheckUsername() user = USERNAME + '@vpnicity' pwd = PASSWORD if user == '' and pwd == '': return f = open(path, mode='w') if utils.platform() == 'osx': f.write(user) f.write('\n') f.write(pwd) f.write('\n') f.close() else: f.write(user) f.write('\r\n') f.write(pwd) f.write('\r\n') f.close()
def WriteAuthentication(path): CheckUsername() user = ADDON.getSetting('USER') pwd = ADDON.getSetting('PASS') if user == '' and pwd == '': return f = open(path, mode='w') if utils.platform() == 'osx': f.write(user) f.write('\n') f.write(pwd) f.write('\n') f.close() else: f.write(user) f.write('\r\n') f.write(pwd) f.write('\r\n') f.close()
def WriteAuthentication(path): CheckUsername() user = ADDON.getSetting('USER') + '@vpnicity' pwd = ADDON.getSetting('PASS') if user == '' and pwd == '': return f = open(path, mode='w') if utils.platform() == 'osx': f.write(user) f.write('\n') f.write(pwd) f.write('\n') f.close() else: f.write(user) f.write('\r\n') f.write(pwd) f.write('\r\n') f.close()
SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) sys.path.append(SCRIPT_DIR + "/../tests") from utils import platform # the log format for the logging module LOG_FORMAT = "%(levelname)s [Line %(lineno)d]: %(message)s" # Read all implementation templates TEMPLATES = {} # Temporary reserved column names RESERVED = ["n", "index"] # Set the platform in osquery-language PLATFORM = platform() # Supported SQL types for spec class DataType(object): def __init__(self, affinity, cpp_type="std::string"): '''A column datatype is a pair of a SQL affinity to C++ type.''' self.affinity = affinity self.type = cpp_type def __repr__(self): return self.affinity # Define column-type MACROs for the table specs TEXT = DataType("TEXT_TYPE")
def test_platform_specific_queries(self): posix = ["darwin", "linux"] if utils.platform() in posix: self._execute_set(PLATFORM_EXAMPLES["posix"]) self._execute_set(PLATFORM_EXAMPLES[utils.platform()])
def test_linked_system_libraries(self): if utils.platform() == "linux": output_bytes = subprocess.check_output( "ldd %s | awk '{ print $1 }'" % (BUILD_DIR + "/osquery/osqueryd"), shell=True, ) self.assertTrue(output_bytes) output = output_bytes.decode("utf-8") libraries = list(filter(None, output.split(sep="\n"))) self.assertGreaterEqual(len(libraries), 0) if platform.processor() == "x86_64": linux_expected_libraries.append("ld-linux-x86-64.so") else: linux_expected_libraries.append("ld-linux-aarch64.so") for expected_library in linux_expected_libraries: found_index = -1 for i, library in enumerate(libraries): if expected_library in library: found_index = i self.assertGreaterEqual( found_index, 0, msg="Missing expected library %s" % expected_library, ) libraries.pop(found_index) if len(libraries) > 0: self.fail( "Found these additional unwanted libraries linked:\n%s" % ("\n".join(libraries))) elif utils.platform() == "win32": output_bytes = subprocess.check_output( "dumpbin /DEPENDENTS %s" % (BUILD_DIR + "/osquery/osqueryd.exe"), ) self.assertTrue(output_bytes) output = output_bytes.decode("utf-8") libraries = [ line for line in list(filter(None, output.split(sep="\r\n"))) if ".dll" in line.lower() ] self.assertGreaterEqual(len(libraries), 0) for expected_library in windows_expected_libraries: found_index = -1 for i, library in enumerate(libraries): if expected_library.lower() in library.lower().strip(): found_index = i self.assertGreaterEqual( found_index, 0, msg="Missing expected library %s" % expected_library, ) libraries.pop(found_index) if len(libraries) > 0: self.fail( "Found these additional unwanted libraries linked:\n%s" % ("\n".join(libraries)))
help="Max seconds a query may run --count times.") group.add_argument("--count", metavar="N", default=1, type=int, help="Run the query N times serially.") group.add_argument( "--rounds", metavar="N", default=1, type=int, help="Run the profile for N rounds and use the average.") group.add_argument( "--shell", metavar="PATH", default="./build/%s/osquery/osqueryi" % (utils.platform()), help="Path to osqueryi shell (./build/<sys>/osquery/osqueryi).") group.add_argument( "--force", action="store_true", default=False, help="Force run the target of shell", ) group = parser.add_argument_group("Performance Options:") group.add_argument("--output", metavar="FILE", default=None, help="Write JSON performance output to file.") group.add_argument("--check", metavar="OLD_OUTPUT",
def test_platform_specific_queries(self): self._execute_set(PLATFORM_EXAMPLES[utils.platform()])
def allowed_platform(qp): if qp in ["all", "any"]: return True if len(qp) == 0: return True return qp.find(platform()) >= 0
group = parser.add_argument_group("Query Options:") group.add_argument("--restrict", metavar="LIST", default="", help="Limit to a list of comma-separated tables.") group.add_argument("--tables", metavar="PATH", default="./specs", help="Path to the osquery table specs.") group.add_argument("--config", metavar="FILE", default=None, help="Use scheduled queries from a config.") group.add_argument("--query", metavar="STRING", default=None, help="Profile a single query.") group = parser.add_argument_group("Run Options:") group.add_argument("--timeout", metavar="N", default=0, type=int, help="Max seconds a query may run --count times.") group.add_argument("--count", metavar="N", default=1, type=int, help="Run the query N times serially.") group.add_argument( "--rounds", metavar="N", default=1, type=int, help="Run the profile for N rounds and use the average." ) group.add_argument( "--shell", metavar="PATH", default="./build/%s/osquery/osqueryi" % (utils.platform()), help="Path to osqueryi shell (./build/<sys>/osquery/osqueryi).", ) group = parser.add_argument_group("Performance Options:") group.add_argument("--output", metavar="FILE", default=None, help="Write JSON performance output to file.") group.add_argument("--check", metavar="OLD_OUTPUT", nargs=1, help="Check regressions using an existing output.") group.add_argument("--compare", metavar="FILE", nargs=2, help="Compare existing performance outputs (old, new).") group = parser.add_argument_group("Memory Options:") group.add_argument( "--suppressions", metavar="SUPP", default="./tools/tests/osquery.supp", help="Add a suppressions files to memory leak checking (linux only).", )
group = parser.add_argument_group("Run Options:") group.add_argument( "--timeout", metavar="N", default=0, type=int, help="Max seconds a query may run --count times." ) group.add_argument( "--count", metavar="N", default=1, type=int, help="Run the query N times serially." ) group.add_argument( "--rounds", metavar="N", default=1, type=int, help="Run the profile for N rounds and use the average." ) group.add_argument( "--shell", metavar="PATH", default="./build/%s/osquery/osqueryi" % ( utils.platform()), help="Path to osqueryi shell (./build/<sys>/osquery/osqueryi)." ) group.add_argument( "--force", action="store_true", default=False, help="Force run the target of shell", ) group = parser.add_argument_group("Performance Options:") group.add_argument( "--output", metavar="FILE", default=None, help="Write JSON performance output to file." ) group.add_argument( "--check", metavar="OLD_OUTPUT", nargs=1, help="Check regressions using an existing output."
class ReleaseTests(unittest.TestCase): @unittest.skipUnless( utils.platform() == "linux" or utils.platform() == "darwin", "Test for Darwin and Linux only", ) def test_no_nonsystem_link(self): if utils.platform() == "linux": proc = subprocess.call( "ldd %s | awk '{ print $1\" \"$3 }' | grep -Ev '^/lib64|^/lib| /lib|linux-vdso.so.1'" % (BUILD_DIR + "/osquery/osqueryd"), shell=True, ) else: proc = subprocess.call( "otool -L %s | awk '{ if (NR > 1) print $1}' | grep -Ev '^/usr/lib|^/System/Library'" % (BUILD_DIR + "/osquery/osqueryd"), shell=True, ) # Require all libraries to be system libraries. self.assertEqual(proc, 1) @unittest.skipUnless( utils.platform() == "linux" or utils.platform() == "win32", "Test for Windows and Linux only", ) def test_linked_system_libraries(self): if utils.platform() == "linux": output_bytes = subprocess.check_output( "ldd %s | awk '{ print $1 }'" % (BUILD_DIR + "/osquery/osqueryd"), shell=True, ) self.assertTrue(output_bytes) output = output_bytes.decode("utf-8") libraries = list(filter(None, output.split(sep="\n"))) self.assertGreaterEqual(len(libraries), 0) if platform.processor() == "x86_64": linux_expected_libraries.append("ld-linux-x86-64.so") else: linux_expected_libraries.append("ld-linux-aarch64.so") for expected_library in linux_expected_libraries: found_index = -1 for i, library in enumerate(libraries): if expected_library in library: found_index = i self.assertGreaterEqual( found_index, 0, msg="Missing expected library %s" % expected_library, ) libraries.pop(found_index) if len(libraries) > 0: self.fail( "Found these additional unwanted libraries linked:\n%s" % ("\n".join(libraries))) elif utils.platform() == "win32": output_bytes = subprocess.check_output( "dumpbin /DEPENDENTS %s" % (BUILD_DIR + "/osquery/osqueryd.exe"), ) self.assertTrue(output_bytes) output = output_bytes.decode("utf-8") libraries = [ line for line in list(filter(None, output.split(sep="\r\n"))) if ".dll" in line.lower() ] self.assertGreaterEqual(len(libraries), 0) for expected_library in windows_expected_libraries: found_index = -1 for i, library in enumerate(libraries): if expected_library.lower() in library.lower().strip(): found_index = i self.assertGreaterEqual( found_index, 0, msg="Missing expected library %s" % expected_library, ) libraries.pop(found_index) if len(libraries) > 0: self.fail( "Found these additional unwanted libraries linked:\n%s" % ("\n".join(libraries)))