# check for netcat options assert remote_control.run_command(r"netcat -h 2>&1 | grep -q '\-d\s'") == 0 assert remote_control.run_command(r"netcat -h 2>&1 | grep -q '\-z\s'") == 0 assert remote_control.run_command(r"netcat -h 2>&1 | grep -q '\-w\s'") == 0 assert remote_control.run_command(r"netcat -h 2>&1 | grep -q '\-l\s'") == 0 assert remote_control.run_command(r"netcat -h 2>&1 | grep -q '\-4\s'") == 0 assert remote_control.run_command(r"netcat -h 2>&1 | grep -q '\-p\s'") == 0 def test_14_client_is_online(self): """verify client is online""" assert remote_control.is_online() == 0 def test_15_client_is_online_udp(self): """verify client can pass UDP""" timeout = 5 result_cnn = 1 result_google = 1 while timeout > 0 and (result_cnn != 0 or result_google != 0): timeout -= 1 result_cnn = remote_control.run_command("host cnn.com 8.8.8.8") result_google = remote_control.run_command("host google.com 8.8.8.8") assert result_cnn == 0 assert result_google == 0 def test_16_client_not_running_openvpn(self): """verify client is online""" assert remote_control.run_command("pidof openvpn") != 0 test_registry.register_module("environment", EnvironmentTests)
nuke_rules() for wanIndexTup in indexOfWans: wanIndex = wanIndexTup[0] if upWanIndex != wanIndex: # make this interface test disconnected build_wan_test(wanIndex, "ping", pingHost="192.168.244.1") else: validWanIP = wanIndexTup[2] build_wan_test(upWanIndex, "ping", pingHost="8.8.8.8") print("validIP is %s" % validWanIP) wait_for_wan_offline() online_count = online_wan_count() offline_count = offline_wan_count() assert (online_count == 1) assert (offline_count > 0) for x in range(0, 8): result = global_functions.get_public_ip_address() print("IP address %s and validWanIP %s" % (result, validWanIP)) assert (result == validWanIP) # Check to see if the faceplate counters have incremented. post_count = global_functions.get_app_metric_value(app, "changed") assert (pre_count < post_count) test_registry.register_module("wan-failover", WanFailoverTests)
from tests.spam_blocker_base_tests import SpamBlockerBaseTests # # Just extends the spam base tests to include SSL Inspector with default settings # class SpamBlockerTests(SpamBlockerBaseTests): @staticmethod def module_name(): return "spam-blocker" @staticmethod def shortName(): return "spam-blocker" @staticmethod def displayName(): return "Spam Blocker" # verify daemon is running def test_009_IsRunningAndSSL(self): appSSL = appSP = uvmContext.appManager().app(self.appNameSSLInspector()) appSSL.start() result = subprocess.call("ps aux | grep spamd | grep -v grep >/dev/null 2>&1", shell=True) assert (result == 0) result = subprocess.call("ps aux | grep spamcatd | grep -v grep >/dev/null 2>&1", shell=True) assert ( result == 0 ) test_registry.register_module("spam-blocker-w-ssl", SpamBlockerTests)
uvmContext.appManager().destroy( thirdRackFirewall.getAppSettings()["id"] ) # remove third rack def test_982_removeSecondRack(self): global thirdRackId nukeRules() assert (removeRack(thirdRackId)) result = remote_control.is_online() assert (result == 0) # remove second rack def test_983_removeSecondRack(self): global secondRackId nukeRules() assert (removeRack(secondRackId)) result = remote_control.is_online() assert (result == 0) @staticmethod def final_tear_down(self): global app, defaultRackCaptivePortal if app != None: uvmContext.appManager().destroy( app.getAppSettings()["id"] ) app = None if defaultRackCaptivePortal != None: uvmContext.appManager().destroy( defaultRackCaptivePortal.getAppSettings()["id"] ) defaultRackCaptivePortal = None test_registry.register_module("policy-manager", PolicyManagerTests)
default_policy_id = 1 app = None class SmtpTests(unittest.TestCase): @staticmethod def module_name(): return "smtp" @staticmethod def initial_setup(self): global app if (uvmContext.appManager().isInstantiated(self.module_name())): app = uvmContext.appManager().app(self.module_name()) else: app = uvmContext.appManager().instantiate(self.module_name(), default_policy_id) def setUp(self): pass # verify client is online def test_010_runTests(self): l = app.getTests() for name in l['list']: print(app.runTests(name)) test_registry.register_module("smtp-casing", SmtpTests)
for i in range(len(tunnelAppData['tunnels']['list'])): tunnelAppData['tunnels']['list'][i]['enabled'] = False print(tunnelAppData['tunnels']['list'][i]['enabled']) tunnelApp.setSettings(tunnelAppData) #stop tunnel here time.sleep(3) tunnelApp.stop() # If VPN tunnel has failed to connect, fail the test, assert(connected) @staticmethod def final_tear_down(self): global app, appWeb, appDC, tunnelApp if app != None: uvmContext.appManager().destroy( app.getAppSettings()["id"] ) app = None if appWeb != None: uvmContext.appManager().destroy( appWeb.getAppSettings()["id"] ) appWeb = None if appDC != None: uvmContext.appManager().destroy( appDC.getAppSettings()["id"] ) appDC = None if tunnelApp != None: uvmContext.appManager().destroy( tunnelApp.getAppSettings()["id"] ) tunnelApp = None # print(tunnelApp.getAppSettings()["id"]) test_registry.register_module("openvpn", OpenVpnTests)
# remove tags entry['tags']['list'] = [] entry = uvmContext.hostTable().setHostTableEntry(remote_control.client_ip, entry) # check penalty box events = global_functions.get_events('Hosts','Hosts Events', None, 50) assert(events != None) event = global_functions.find_event( events.get('list'), 50, "address", remote_control.client_ip, "key", "tags" ) print(event) assert((event != None)) @staticmethod def final_tear_down(self): global app, app_web_filter, orig_network_settings # Restore original settings to return to initial settings if orig_network_settings != None: uvmContext.networkManager().setNetworkSettings( orig_network_settings ) if app != None: uvmContext.appManager().destroy( app.getAppSettings()["id"] ) app = None if app_web_filter != None: uvmContext.appManager().destroy( app_web_filter.getAppSettings()["id"] ) app_web_filter = None test_registry.register_module("bandwidth-control", BandwidthControlTests)
# remove tags entry['tags']['list'] = [] entry = uvmContext.hostTable().setHostTableEntry( remote_control.client_ip, entry) # check penalty box events = global_functions.get_events('Hosts', 'Hosts Events', None, 50) assert (events != None) event = global_functions.find_event(events.get('list'), 50, "address", remote_control.client_ip, "key", "tags") print(event) assert ((event != None)) @classmethod def final_extra_tear_down(cls): global orig_network_settings # Restore original settings to return to initial settings if orig_network_settings != None: uvmContext.networkManager().setNetworkSettings( orig_network_settings) if cls._app_web_filter != None: uvmContext.appManager().destroy( cls._app_web_filter.getAppSettings()["id"]) cls._app_web_filter = None test_registry.register_module("bandwidth-control", BandwidthControlTests)
connected = False while (not connected and timeout > 0): newWanIP = remote_control.run_command("wget --timeout=4 -q -O - \"$@\" test.untangle.com/cgi-bin/myipaddress.py",stdout=True) if (currentWanIP != newWanIP): listOfConnections = app.getTunnelStatusList() connectStatus = listOfConnections['list'][0]['stateInfo'] connected = True listOfConnections = app.getTunnelStatusList() connectStatus = listOfConnections['list'][0]['stateInfo'] else: time.sleep(1) timeout-=1 # remove the added tunnel appData['rules']['list'][:] = [] appData['tunnels']['list'][:] = [] app.setSettings(appData) # If VPN tunnel has failed to connect, fail the test, assert(connected) assert(connectStatus == "CONNECTED") @staticmethod def final_tear_down(self): global app if app != None: uvmContext.appManager().destroy( app.getAppSettings()["id"] ) app = None test_registry.register_module("tunnel-vpn", TunnelVpnTests)
if runtests.quick_tests_only: raise unittest.SkipTest('Skipping a time consuming test') wan_ip = uvmContext.networkManager().getFirstWanAddress() iperf_avail = global_functions.verify_iperf_configuration(wan_ip) device_in_office = global_functions.is_in_office_network(wan_ip) # Also test that it can probably reach us (we're on a 10.x network) if not device_in_office: raise unittest.SkipTest("Not on office network, skipping") if (not iperf_avail): raise unittest.SkipTest("IperfServer test client unreachable, skipping alternate port forwarding test") startTime = datetime.datetime.now() # start nmap on client remote_control.run_command("nmap " + wan_ip + " >/dev/null 2>&1",host=global_functions.iperf_server) app.forceUpdateStats() events = global_functions.get_events('Intrusion Prevention','All Events',None,5) found = global_functions.check_events( events.get('list'), 5, 'msg', "NMAP", 'blocked', False, min_date=startTime) @staticmethod def final_tear_down(self): global app if app != None: uvmContext.appManager().destroy( app.getAppSettings()["id"] ) app = None test_registry.register_module("intrusion-prevention", IntrusionPreventionTests)
def test_022_changeBranding_bannerMessage_removed(self): global app, appWeb, appData appData['companyName'] = newCompanyName; appData['companyUrl'] = newURL; appData['contactName'] = newContactName; appData['contactEmail'] = newContactEmail; appData['bannerMessage'] = "" app.setSettings(appData) internalAdmin = None result = remote_control.run_command("wget -q -O - \"$@\" " + global_functions.get_http_url() ,stdout=True) myRegex = re.compile('.*A regulation banner requirement containing a mix of text including <b>html<\/b> and<br\/>multiple<br\/>lines.*', re.DOTALL|re.MULTILINE) if re.match(myRegex,result): assert(False) else: assert(True) @staticmethod def final_tear_down(self): global app, appWeb if app != None: # Restore original settings to return to initial settings setDefaultBrandingManagerSettings() global_functions.uvmContextLongTimeout.appManager().destroy( app.getAppSettings()["id"] ) app = None if appWeb != None: global_functions.uvmContextLongTimeout.appManager().destroy( appWeb.getAppSettings()["id"] ) appWeb = None test_registry.register_module("branding-manager", BrandingManagerTests)
def test_060_testDnsUdpPatternBlock(self): nukepatterns() addPatterns(definition="^.?.?.?.?[\x01\x02].?.?.?.?.?.?[\x01-?][a-z0-9][\x01-?a-z]*[\x02-\x06][a-z][a-z][fglmoprstuvz]?[aeop]?(um)?[\x01-\x10\x1c]", protocol="DNS", blocked=True, category="Web", description="Domain Name System") result = remote_control.run_command("host -R 1 www.google.com 8.8.8.8") assert (result != 0) time.sleep(3); events = global_functions.get_events('Application Control Lite','All Events',None,1) assert(events != None) found = global_functions.check_events( events.get('list'), 5, 'c_client_addr', remote_control.client_ip, 'application_control_lite_protocol', 'DNS', 'application_control_lite_blocked', True ) assert( found ) @staticmethod def final_tear_down(self): global app if app != None: uvmContext.appManager().destroy( app.getAppSettings()["id"] ) app = None test_registry.register_module("application-control-lite", ApplicationControlLiteTests)
default_policy_id = 1 app = None class SmtpTests(unittest.TestCase): @staticmethod def module_name(): return "smtp" @staticmethod def initial_setup(self): global app if (uvmContext.appManager().isInstantiated(self.module_name())): app = uvmContext.appManager().app(self.module_name()) else: app = uvmContext.appManager().instantiate(self.module_name(), default_policy_id) def setUp(self): pass # verify client is online def test_010_runTests(self): l = app.getTests(); for name in l['list']: print(app.runTests(name)) test_registry.register_module("smtp-casing", SmtpTests)
# verify daemon is running def test_009_IsRunning(self): result = subprocess.call( "ps aux | grep spamd | grep -v grep >/dev/null 2>&1", shell=True) assert (result == 0) result = subprocess.call( "ps aux | grep spamcatd | grep -v grep >/dev/null 2>&1", shell=True) assert (result == 0) # verify MAIL_SHELL is scoring. Relies on test_20_smtpTest def test_021_check_for_mailshell(self): if (not self.canRelay): raise unittest.SkipTest('Unable to relay through ' + global_functions.TEST_SERVER_HOST) events = global_functions.get_events(self.displayName(), 'Quarantined Events', None, 8) if events != None: assert (events.get('list') != None) found = False for event in events['list']: if 'MAILSHELL_SCORE_' in event['spam_blocker_tests_string']: found = True break assert (found) else: raise unittest.SkipTest('No events to check for MAIL_SHELL') test_registry.register_module("spam-blocker", SpamBlockerTests)
# Test report only user can login and report serlvet displays # add report user with test_email_address settings = app.getSettings() settings["reportsUsers"]["list"] = settings["reportsUsers"]["list"][:1] settings["reportsUsers"]["list"].append(create_reports_user(profile_email='test', access=True)) # password = passwd app.setSettings(settings) adminURL = global_functions.get_http_url() print("URL %s" % adminURL) resultLoginPage = subprocess.call("wget -q -O - " + adminURL + "reports 2>&1 | grep -q Login", shell=True) assert (resultLoginPage == 0) resultLoginPage = subprocess.call("wget -q -O - " + adminURL + '"auth/login?url=/reports&realm=Reports&username=test&password=passwd" 2>&1 | grep -q Report', shell=True) assert (resultLoginPage == 0) @staticmethod def final_tear_down(self): global app, web_app # remove all the apps in case test 103 does not remove them. for name in apps_list: if (uvmContext.appManager().isInstantiated(name)): remove_app = uvmContext.appManager().app(name) uvmContext.appManager().destroy(remove_app.getAppSettings()["id"]) if app != None: app.setSettings(orig_settings) if orig_mailsettings != None: uvmContext.mailSender().setSettings(orig_mailsettings) app = None web_app = None test_registry.register_module("reports", ReportsTests)
"value": "DNS" }], "dict sessions ct id application_id_inferred long_string \"DNS\""], [[{ "type": "APPLICATION_ID_INFERRED", "op": "!=", "value": "DNS" }], "dict sessions ct id application_id_inferred long_string != \"DNS\""], [[{ "type": "APPLICATION_ID_INFERRED", "op": "==", "value": "DNS,SSL" }], "dict sessions ct id application_id_inferred long_string \"{DNS,SSL}\""], [[{ "type": "APPLICATION_ID_INFERRED", "op": "!=", "value": "DNS,SSL" }], "dict sessions ct id application_id_inferred long_string != \"{DNS,SSL}\"" ], ] for i, obj in enumerate(conditions_tests): method = create_conditions_test(obj[0], obj[1]) first_condition = obj[0][0] method.__name__ = "test_" + str(500 + i) + "_" + str( first_condition.get('type')).lower() setattr(NftablesTests, method.__name__, method) test_registry.register_module("nftables_util", NftablesTests)
import runtests.test_registry as test_registry import tests.global_functions as global_functions import tests.ipaddr as ipaddr from uvm import Uvm from tests.spam_blocker_base_tests import SpamBlockerBaseTests # # Just extends the spam base tests # class SpamBlockerLiteTests(SpamBlockerBaseTests): @staticmethod def module_name(): return "spam-blocker-lite" @staticmethod def shortName(): return "spam-blocker-lite" @staticmethod def displayName(): return "Spam Blocker Lite" # verify daemon is running def test_009_IsRunning(self): result = subprocess.call("ps aux | grep spamd | grep -v grep >/dev/null 2>&1", shell=True) assert (result == 0) test_registry.register_module("spam-blocker-lite", SpamBlockerLiteTests)
if (not mail_app): raise unittest.SkipTest('Unable download mailsendder app') ip_address_testuntangle = socket.gethostbyname(smtpServerHost) appSSL.start() tlsSMTPResult = sendPhishMail(mailfrom="test060", host=smtpServerHost, useTLS=True) # print("TLS : " + str(tlsSMTPResult)) appSSL.stop() assert (tlsSMTPResult == 0) events = global_functions.get_events('Phish Blocker', 'All Phish Events', None, 1) assert (events != None) found = global_functions.check_events( events.get('list'), 5, 'c_server_addr', ip_address_testuntangle, 's_server_port', 25, 'addr', '*****@*****.**', 'c_client_addr', remote_control.client_ip, 'phish_blocker_action', 'D') @classmethod def final_extra_tear_down(cls): global appSSL if appSSL != None: uvmContext.appManager().destroy(appSSL.getAppSettings()["id"]) appSSL = None test_registry.register_module("phish-blocker", PhishBlockerTests)
@staticmethod def module_name(): return "virus-blocker-lite" @staticmethod def shortName(): return "virus_blocker_lite" @staticmethod def displayName(): return "Virus Blocker Lite" # verify daemon is running def test_009_clamdIsRunning(self): # wait for freshclam to finish updating sigs subprocess.call("freshclam >/dev/null 2>&1", shell=True) result = subprocess.call("pidof clamd >/dev/null 2>&1", shell=True) assert (result == 0) # give it up to 20 minutes to download signatures for the first time print("Waiting for server to start...") for i in range(1200): time.sleep(1) result = subprocess.call("netcat -n -z 127.0.0.1 3310 >/dev/null 2>&1", shell=True) if result == 0: break print("Number of sleep cycles waiting: %d" % i) test_registry.register_module("virus-blocker-lite", VirusBlockerLiteTests)
raise unittest.SkipTest("IPsec test only configed for IPs %s" % (listOfPairs)) timeout = 10 ipsecHostLANResult = 1 while (ipsecHostLANResult != 0 and timeout > 0): timeout -= 1 time.sleep(1) # ping the remote LAN to see if the IPsec tunnel is connected. ipsecHostLANResult = remote_control.run_command( "wget -q -O /dev/null --no-check-certificate -4 -t 2 --timeout=5 https://%s/" % ipsecHostLANIP) post_events_enabled = global_functions.get_app_metric_value( self._app, "enabled") nukeIPSecTunnels(self._app) assert (ipsecHostLANResult == 0) # Check to see if the faceplate counters have incremented. assert (pre_events_enabled < post_events_enabled) @classmethod def final_extra_tear_down(cls): global appAD # Restore original settings to return to initial settings # print("orig_netsettings <%s>" % orig_netsettings) uvmContext.networkManager().setNetworkSettings(orig_netsettings) if appAD != None: uvmContext.appManager().destroy(appAD.getAppSettings()["id"]) appAD = None test_registry.register_module("ipsec-vpn", IPsecTests)
[[{"type": "REMOTE_HOSTNAME","op":"!=","value": "hostname,hostname2"}], "dict sessions ct id remote_hostname long_string != '{hostname,hostname2}'"], [[{"type": "CLIENT_USERNAME","op":"==","value": "username"}], "dict sessions ct id client_username long_string 'username'"], [[{"type": "CLIENT_USERNAME","op":"!=","value": "username"}], "dict sessions ct id client_username long_string != 'username'"], [[{"type": "CLIENT_USERNAME","op":"==","value": "username,username2"}], "dict sessions ct id client_username long_string '{username,username2}'"], [[{"type": "CLIENT_USERNAME","op":"!=","value": "username,username2"}], "dict sessions ct id client_username long_string != '{username,username2}'"], [[{"type": "SERVER_USERNAME","op":"==","value": "username"}], "dict sessions ct id server_username long_string 'username'"], [[{"type": "SERVER_USERNAME","op":"!=","value": "username"}], "dict sessions ct id server_username long_string != 'username'"], [[{"type": "SERVER_USERNAME","op":"==","value": "username,username2"}], "dict sessions ct id server_username long_string '{username,username2}'"], [[{"type": "SERVER_USERNAME","op":"!=","value": "username,username2"}], "dict sessions ct id server_username long_string != '{username,username2}'"], [[{"type": "LOCAL_USERNAME","op":"==","value": "username"}], "dict sessions ct id local_username long_string 'username'"], [[{"type": "LOCAL_USERNAME","op":"!=","value": "username"}], "dict sessions ct id local_username long_string != 'username'"], [[{"type": "LOCAL_USERNAME","op":"==","value": "username,username2"}], "dict sessions ct id local_username long_string '{username,username2}'"], [[{"type": "LOCAL_USERNAME","op":"!=","value": "username,username2"}], "dict sessions ct id local_username long_string != '{username,username2}'"], [[{"type": "REMOTE_USERNAME","op":"==","value": "username"}], "dict sessions ct id remote_username long_string 'username'"], [[{"type": "REMOTE_USERNAME","op":"!=","value": "username"}], "dict sessions ct id remote_username long_string != 'username'"], [[{"type": "REMOTE_USERNAME","op":"==","value": "username,username2"}], "dict sessions ct id remote_username long_string '{username,username2}'"], [[{"type": "REMOTE_USERNAME","op":"!=","value": "username,username2"}], "dict sessions ct id remote_username long_string != '{username,username2}'"], ] for i, obj in enumerate(conditions_tests): method = create_conditions_test(obj[0],obj[1]) first_condition = obj[0][0] method.__name__="test_"+str(500+i)+"_"+str(first_condition.get('type')).lower() setattr(NftablesTests, method.__name__, method) test_registry.register_module("nftables_util", NftablesTests)
},{ "host": "search.yahoo.com", "uri": "/search?p=two+terms", "term": "two terms" }] host = "www.bing.com" uri = "/search?q=oneterm&qs=n&form=QBRE" for t in termTests: eventTime = datetime.datetime.now() result = remote_control.run_command("curl -s -4 -o /dev/null -A 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1' --connect-timeout 10 --insecure 'https://%s%s'" % ( t["host"], t["uri"] ) ) assert( result == 0 ) events = global_functions.get_events('Web Filter','All Query Events',None,1) assert(events != None) found = global_functions.check_events( events.get('list'), 5, "host", t["host"], "term", t["term"]) assert( found ) @staticmethod def final_tear_down(self): global app, appWeb if app != None: uvmContext.appManager().destroy( app.getAppSettings()["id"] ) app = None if appWeb != None: uvmContext.appManager().destroy( appWeb.getAppSettings()["id"]) appWeb = None test_registry.register_module("ssl-inspector", SslInspectorTests)
import tests.ipaddr as ipaddr from uvm import Uvm from tests.spam_blocker_base_tests import SpamBlockerBaseTests # # Just extends the spam base tests # class SpamBlockerLiteTests(SpamBlockerBaseTests): @staticmethod def module_name(): return "spam-blocker-lite" @staticmethod def shortName(): return "spam-blocker-lite" @staticmethod def displayName(): return "Spam Blocker Lite" # verify daemon is running def test_009_IsRunning(self): result = subprocess.call( "ps aux | grep spamd | grep -v grep >/dev/null 2>&1", shell=True) assert (result == 0) test_registry.register_module("spam-blocker-lite", SpamBlockerLiteTests)
True) assert (found) def test_500_classdDaemonReconnect(self): if runtests.quick_tests_only: raise unittest.SkipTest('Skipping a time consuming test') for i in range(10): print("Test %i" % i) result = subprocess.call( "systemctl restart untangle-classd >/dev/null 2>&1", shell=True) assert (result == 0) result = remote_control.is_online() assert (result == 0) # delay so we don't trigger systemd throttling of 5 restarts in 10 seconds time.sleep(3) # give it some time to recover for future tests for i in range(5): result = remote_control.is_online() time.sleep(1) @staticmethod def final_tear_down(self): global app if app != None: uvmContext.appManager().destroy(app.getAppSettings()["id"]) app = None test_registry.register_module("application-control", ApplicationControlTests)
print("md5LargeVirus <%s> vs md5TestNum <%s>" % (md5LargeVirus, md5TestNum)) assert (md5LargeVirus != md5TestNum) # test the cloud scanner with http using our special large clean file def test_270_httpMemoryLargeClean(self): remote_control.run_command("rm -f /tmp/temp_270_httpMemoryClean_file") result = remote_control.run_command( "wget -q -O /tmp/temp_270_httpMemoryClean_file http://test.untangle.com/5MB.zip" ) assert (result == 0) md5TestNum = remote_control.run_command( "\"md5sum /tmp/temp_270_httpMemoryClean_file | awk '{print $1}'\"", stdout=True) print("md5LargeClean <%s> vs md5TestNum <%s>" % (md5LargeClean, md5TestNum)) assert (md5LargeClean == md5TestNum) # turn off forceMemoryMode when we are finished def test_280_disableForceMemoryScanMode(self): virusSettings = self.app.getSettings() assert (virusSettings['forceMemoryMode'] == True) virusSettings['forceMemoryMode'] = False self.app.setSettings(virusSettings) virusSettings = self.app.getSettings() assert (virusSettings['forceMemoryMode'] == False) test_registry.register_module("virus-blocker", VirusBlockTests)
with open("/tmp/cloudBackup.backup", "wb") as f: f.write(dlResponse.content) #extract cloud backup subprocess.call("mkdir /tmp/cloudBackup", shell=True) subprocess.call("tar -xf /tmp/cloudBackup.backup -C /tmp/cloudBackup", shell=True) subprocess.call("tar -xf "+glob.glob("/tmp/cloudBackup/files*.tar.gz")[0] + " -C /tmp/cloudBackup", shell=True) #use glob since extracted file has timestamp cloudBackupPath = "/tmp/cloudBackup/usr" #compare directories def is_same(dir1, dir2): compared = filecmp.dircmp(dir1, dir2) if (compared.left_only or compared.right_only or compared.diff_files or compared.funny_files): return False for subdir in compared.common_dirs: if not is_same(os.path.join(dir1, subdir), os.path.join(dir2, subdir)): return False return True assert(is_same(localBackupPath, cloudBackupPath)) @staticmethod def final_tear_down(self): global app if app != None: uvmContext.appManager().destroy( app.getAppSettings()["id"] ) app = None test_registry.register_module("configuration-backup", ConfigurationBackupTests)
appData['rules']['list'].append(create_tunnel_rule(vpn_tunnel_id=-1)) appData['tunnels']['list'].append(create_tunnel_profile()) self._app.setSettings(appData) # wait for vpn tunnel to form timeout = 60 connected = False while (not connected and timeout > 0): newWanIP = remote_control.run_command("wget --timeout=4 -q -O - \"$@\" test.untangle.com/cgi-bin/myipaddress.py",stdout=True) if (currentWanIP != newWanIP): listOfConnections = self._app.getTunnelStatusList() connectStatus = listOfConnections['list'][0]['stateInfo'] connected = True listOfConnections = self._app.getTunnelStatusList() connectStatus = listOfConnections['list'][0]['stateInfo'] else: time.sleep(1) timeout-=1 # remove the added tunnel appData['rules']['list'][:] = [] appData['tunnels']['list'][:] = [] self._app.setSettings(appData) # If VPN tunnel has failed to connect, fail the test, assert(connected) assert(connectStatus == "CONNECTED") test_registry.register_module("tunnel-vpn", TunnelVpnTests)
time.sleep(1) wanStatus = app_wan_failover.getWanStatus() for statusInterface in wanStatus['list']: if statusInterface['interfaceId'] == offlineWanIndex: online = statusInterface['online'] subprocess.check_output("ip route flush cache", shell=True) for x in range(0, 5): result = global_functions.get_public_ip_address() print("WAN Down NAT 1:1 IP %s External IP %s and retrieved IP %s" % (wanIP, wanExternalIP, result)) assert (result == wanExternalIP) uvmContext.networkManager().setNetworkSettings(orig_netsettings) nuke_wan_failover_rules() # Check to see if the faceplate counters have incremented. post_count = global_functions.get_app_metric_value(app_wan_failover,"changed") assert(pre_count < post_count) @classmethod def final_extra_tear_down(cls): global app_wan_failover # Restore original settings to return to initial settings if app_wan_failover != None: uvmContext.appManager().destroy( app_wan_failover.getAppSettings()["id"] ) app_wan_failover = None if orig_netsettings != None: uvmContext.networkManager().setNetworkSettings(orig_netsettings) test_registry.register_module("wan-balancer", WanBalancerTests)
for i in range(len(appADData)): userName = appADData[i]['uid'] if (global_functions.AD_USER in userName): result = 0 # print('userName %s' % userName) assert (result == 0) def test_060_setRadiusSettings(self): """ Test and save settings for test Radius server """ if (RADIUS_RESULT != 0): raise unittest.SkipTest("No RADIUS server available") self._app.setSettings(create_radius_settings()) attempts = 0 while attempts < 3: test_result_string = self._app.getRadiusManager( ).getRadiusStatusForSettings(create_radius_settings(), "normal", "passwd") if ("success" in test_result_string): break else: attempts += 1 print('test_result_string %s attempts %s' % (test_result_string, attempts)) # debug line assert ("success" in test_result_string) test_registry.register_module("directory-connector", DirectoryConnectorTests)
pairMatchNotFound = False if (pairMatchNotFound): raise unittest.SkipTest("IPsec test only configed for IPs %s" % (listOfPairs)) timeout = 10 ipsecHostLANResult = 1 while (ipsecHostLANResult != 0 and timeout > 0): timeout -= 1 time.sleep(1) # ping the remote LAN to see if the IPsec tunnel is connected. ipsecHostLANResult = remote_control.run_command("wget -q -O /dev/null --no-check-certificate -4 -t 2 --timeout=5 https://%s/" % ipsecHostLANIP) post_events_enabled = global_functions.get_app_metric_value(app,"enabled") nukeIPSecTunnels() assert (ipsecHostLANResult == 0) # Check to see if the faceplate counters have incremented. assert(pre_events_enabled < post_events_enabled) @staticmethod def final_tear_down(self): global app, appAD # Restore original settings to return to initial settings # print("orig_netsettings <%s>" % orig_netsettings) uvmContext.networkManager().setNetworkSettings(orig_netsettings) if app != None: uvmContext.appManager().destroy( app.getAppSettings()["id"] ) app = None if appAD != None: uvmContext.appManager().destroy( appAD.getAppSettings()["id"] ) appAD = None test_registry.register_module("ipsec-vpn", IPsecTests)
language_settings = uvmContext.languageManager().getLanguageSettings() language_settings_orig = copy.deepcopy(language_settings) language_settings['language'] = 'es' uvmContext.languageManager().setLanguageSettings(language_settings) result = subprocess.call('"wget -q -O - -t 2 --timeout 10 --content-on-error http://localhost/admin/download" 2>&1 | grep -q "no permitido"', shell=True) # revert language uvmContext.languageManager().setLanguageSettings(language_settings_orig) assert(result) def test_150_synchronize_Language(self): """Check synchronizeLanguage returns OK""" synchronized = uvmContext.languageManager().synchronizeLanguage() def test_160_change_community_language(self): """Check if changing community language converts the GUI""" #set language to Russian language_settings_community = uvmContext.languageManager().getLanguageSettings() language_settings_community_orig = copy.deepcopy(language_settings_community) language_settings_community['language'] = "ru" uvmContext.languageManager().setLanguageSettings(language_settings_community) result = subprocess.call('"wget -q -0 - -t 2 --timeout 10 --content-on-error http://localhost/admin/download" 2>&1 | grep -q "ne polozheno"', shell=True) #Revert language uvmContext.languageManager().setLanguageSettings(language_settings_community_orig) assert(result) test_registry.register_module("uvm", UvmTests)
def test_022_changeBranding_bannerMessage_removed(self): global app, appWeb, appData appData['companyName'] = newCompanyName; appData['companyUrl'] = newURL; appData['contactName'] = newContactName; appData['contactEmail'] = newContactEmail; appData['bannerMessage'] = "" app.setSettings(appData) internalAdmin = None result = remote_control.run_command("wget -q -O - \"$@\" " + global_functions.get_http_url() ,stdout=True) myRegex = re.compile('.*A regulation banner requirement containing a mix of text including <b>html<\/b> and<br\/>multiple<br\/>lines.*', re.DOTALL|re.MULTILINE) if re.match(myRegex,result): assert(False) else: assert(True) @classmethod def final_extra_tear_down(cls): global appWeb if cls._app != None: # Restore original settings to return to initial settings setDefaultBrandingManagerSettings(cls._app) global_functions.uvmContextLongTimeout.appManager().destroy( app.getAppSettings()["id"] ) if appWeb != None: global_functions.uvmContextLongTimeout.appManager().destroy( appWeb.getAppSettings()["id"] ) appWeb = None test_registry.register_module("branding-manager", BrandingManagerTests)
assert system_status.get('meminfo').get('mem_total') != None assert system_status.get('meminfo').get('mem_available') != None assert system_status.get('uptime') != None assert system_status.get('diskstats') != None assert system_status.get('rootfs') != None assert system_status.get('tmpfs') != None def test_002_get_status_sessions(self): """Get the sessions""" sessions = get_status("sessions") assert isinstance(sessions, list) if len(sessions) > 0: assert sessions[0].get("client_address") != None assert sessions[0].get("server_address") != None assert sessions[0].get("family") != None assert sessions[0].get("ip_protocol") != None def test_003_get_status_hardware(self): """Get the hardware status""" hardware_status = get_status("hardware") assert hardware_status.get("cpuinfo") != None assert hardware_status.get("cpuinfo").get("processors") != None assert len(hardware_status.get("cpuinfo").get("processors")) > 0 def final_tear_down(self): """final_tear_down unittest method""" pass test_registry.register_module("status", StatusTests)
"application_control_category", "Web Services", "application_control_blocked", True, "application_control_flagged", True) assert( found ) def test_500_classdDaemonReconnect(self): if runtests.quick_tests_only: raise unittest.SkipTest('Skipping a time consuming test') for i in range(10): print("Test %i" % i) result = subprocess.call("systemctl restart untangle-classd >/dev/null 2>&1", shell=True) assert (result == 0) result = remote_control.is_online() assert (result == 0) # delay so we don't trigger systemd throttling of 5 restarts in 10 seconds time.sleep(3) # give it some time to recover for future tests for i in range(5): result = remote_control.is_online() time.sleep(1) @staticmethod def final_tear_down(self): global app if app != None: uvmContext.appManager().destroy( app.getAppSettings()["id"] ) app = None test_registry.register_module("application-control", ApplicationControlTests)
# verify a accuweather cookie can be blocked, but set both "enabled" and "blocked" params def test_102_webCookieBlockedEnabled(self): addCookieBlockedEnabled("untangle.com") # remove any previous instance of testcookie.txt remote_control.run_command("/bin/rm -f /tmp/testcookie.txt") # see if cookie is downloaded. result = remote_control.run_command("rm -f /tmp/testcookie.txt ; wget -4 -q -O /dev/null --save-cookies /tmp/testcookie.txt http://test.untangle.com/mycookie.php ; grep -q untangle.com /tmp/testcookie.txt") assert (result == 1) # verify update mechanism def test_110_updateAdBlockRules(self): app.updateList() result = app.getListLastUpdate() today_str = datetime.datetime.utcnow().strftime("%d %b %Y") yesterday_str = (datetime.datetime.utcnow() - datetime.timedelta(days=1)).strftime("%d %b %Y") print("Last Update: \"%s\"" % (result)) print("Today: \"%s\"" % (today_str)) print("Yesterday: \"%s\"" % (yesterday_str)) assert((today_str in result) or (yesterday_str in result)) @staticmethod def final_tear_down(self): global app if app != None: uvmContext.appManager().destroy( app.getAppSettings()["id"] ) app = None test_registry.register_module("ad-blocker", AdBlockerTests)
events = global_functions.get_events(self.displayName(),'All Web Events',None,1) assert(events != None) found = global_functions.check_events( events.get('list'), 5, "c_client_addr",remote_control.client_ip, self.eventAppName() + '_blocked', False, self.eventAppName() + '_flagged', False ) assert( found ) def test_080_multiple_rule_conditions_matching(self): """Verify that conditions are AND logic""" self.rules_clear() self.multiple_rule_add("DST_ADDR",global_functions.test_server_ip,"DST_PORT","443") result = remote_control.run_command("wget -q -4 -t 2 -O - http://test.untangle.com 2>&1 | grep -q Hi") assert (result == 0) result = remote_control.run_command("wget --no-check-certificate -q -4 -t 2 -O - https://test.untangle.com 2>&1 | grep -q blocked") self.rules_clear() assert (result == 0) events = global_functions.get_events(self.displayName(),'All Web Events',None,1) assert(events != None) found = global_functions.check_events( events.get('list'), 1, "host","test.untangle.com", self.eventAppName() + '_blocked', True, self.eventAppName() + '_flagged', True ) assert( found ) @classmethod def final_extra_tear_down(cls): pass test_registry.register_module("threat-prevention", ThreatpreventionTests)
fallocate_path = "" full_filename = "/tmp/full.txt"; # check if fallocate exists and if in /bin or /usr/bin fallocate_output_obj = subprocess.run(["which", "fallocate"], capture_output=True) if fallocate_output_obj.returncode != 0 or fallocate_output_obj.stdout is None : raise unittest.SkipTest("fallocate not available") else: fallocate_path = fallocate_output_obj.stdout.decode("utf-8") fallocate_path = fallocate_path.replace("\n","") filename_output_obj = subprocess.run([fallocate_path,"-l",str(in_threshold),full_filename]) if filename_output_obj.returncode != 0: raise unittest.SkipTest(full_filename + " not available") df_fields = subprocess.check_output("df | grep /$ | tr -s ' '", shell=True).decode('utf-8').split(' ') time.sleep(60) metrics_and_stats = uvmContext.metricManager().getMetricsAndStats() uvm_free_disk_percent = (float(metrics_and_stats["systemStats"]["freeDiskSpace"]) / float(metrics_and_stats["systemStats"]["totalDiskSpace"]) * 100) subprocess.run(["rm", "-f", full_filename]) assert(uvm_free_disk_percent < 5) filename_output_obj= subprocess.run([fallocate_path, "-l", str(out_threshold), full_filename]) if filename_output_obj.returncode != 0: raise unittest.SkipTest(full_filename + " not available 2nd") df_fields = subprocess.check_output("df | grep /$ | tr -s ' '", shell=True).decode('utf-8').split(' ') time.sleep(60) metrics_and_stats = uvmContext.metricManager().getMetricsAndStats() uvm_free_disk_percent = (float(metrics_and_stats["systemStats"]["freeDiskSpace"]) / float(metrics_and_stats["systemStats"]["totalDiskSpace"]) * 100) subprocess.run(["rm", "-f", full_filename]) assert(uvm_free_disk_percent > 5) test_registry.register_module("uvm", UvmTests)
assert (uvmContext.licenseManager().isLicenseValid(self.module_name())) def test_020_testBasicWebCache(self): if runtests.quick_tests_only: raise unittest.SkipTest('Skipping a time consuming test') pre_events_hit = global_functions.get_app_metric_value(app, "hit") app.clearSquidCache() for x in range(0, 10): result = remote_control.run_command( "wget -q -O /dev/null -4 -t 2 --timeout=5 http://test.untangle.com/" ) time.sleep(1) assert (result == 0) time.sleep(65) # summary-events only written every 60 seconds events = global_functions.get_events('Web Cache', 'Web Cache Events', None, 1) assert (events != None) # verify at least one hit assert (events['list'][0]) assert (events['list'][0]['hits']) # Check to see if the faceplate counters have incremented. post_events_hit = global_functions.get_app_metric_value(app, "hit") assert (pre_events_hit < post_events_hit) test_registry.register_module("web-cache", WebCacheTests)
def vendorName(): return "Untangle" @staticmethod def initial_setup(self): global app if (uvmContext.appManager().isInstantiated(self.module_name())): raise Exception('app %s already instantiated' % self.module_name()) app = uvmContext.appManager().instantiate(self.module_name(), default_policy_id) def setUp(self): pass # verify client is online def test_010_clientIsOnline(self): result = remote_control.is_online() assert (result == 0) def test_011_license_valid(self): assert(uvmContext.licenseManager().isLicenseValid(self.module_name())) @staticmethod def final_tear_down(self): global app if app != None: uvmContext.appManager().destroy( app.getAppSettings()["id"] ) app = None test_registry.register_module("live-support", LiveSupportTests)
adminURL = global_functions.get_http_url() print("URL %s" % adminURL) resultLoginPage = subprocess.call("wget -q -O - " + adminURL + "reports 2>&1 | grep -q Login", shell=True) assert (resultLoginPage == 0) resultLoginPage = subprocess.call( "wget -q -O - " + adminURL + '"auth/login?url=/reports&realm=Reports&username=test&password=passwd" 2>&1 | grep -q Report', shell=True) assert (resultLoginPage == 0) @classmethod def final_extra_tear_down(cls): global web_app # remove all the apps in case test 103 does not remove them. for name in apps_list: if (uvmContext.appManager().isInstantiated(name)): remove_app = uvmContext.appManager().app(name) uvmContext.appManager().destroy( remove_app.getAppSettings()["id"]) if orig_mailsettings != None: uvmContext.mailSender().setSettings(orig_mailsettings) web_app = None test_registry.register_module("reports", ReportsTests)
rules_clear() rule_append( create_rule_single_condition("CLIENT_COUNTRY", "XL", blocked=False, flagged=True)) result = remote_control.run_command( "wget -q -O /dev/null -t 1 --timeout=3 http://test.untangle.com/") assert (result == 0) events = global_functions.get_events('Firewall', 'Flagged Events', None, 1) assert (events != None) found = global_functions.check_events(events.get('list'), 5, 'c_client_addr', remote_control.client_ip, 'client_country', "XL", 'firewall_blocked', False, 'firewall_flagged', True) assert (found) @staticmethod def final_tear_down(self): global app if app != None: uvmContext.appManager().destroy(app.getAppSettings()["id"]) app = None test_registry.register_module("firewall", FirewallTests)
if runtests.quick_tests_only: raise unittest.SkipTest('Skipping a time consuming test') pre_events_hit = global_functions.get_app_metric_value(app,"hit") app.clearSquidCache() for x in range(0, 10): result = remote_control.run_command("wget -q -O /dev/null -4 -t 2 --timeout=5 http://test.untangle.com/") time.sleep(1) assert (result == 0) time.sleep(65) # summary-events only written every 60 seconds events = global_functions.get_events('Web Cache','Web Cache Events',None,1) assert(events != None) # verify at least one hit assert(events['list'][0]) assert(events['list'][0]['hits']) # Check to see if the faceplate counters have incremented. post_events_hit = global_functions.get_app_metric_value(app,"hit") assert(pre_events_hit < post_events_hit) @staticmethod def final_tear_down(self): global app if app != None: uvmContext.appManager().destroy( app.getAppSettings()["id"] ) app = None test_registry.register_module("web-cache", WebCacheTests)
assert result4.get('fakepart1') is None def test_031_trim_settings_nonexistant(self): """Trim a non-existant settings from the root settings object""" fname = sys._getframe().f_code.co_name result1 = trim_settings([fname]) assert result1 != None assert result1.get('result') == 'OK' def test_032_trim_settings_nondict(self): """Trim a path that doesnt make sense""" fname = sys._getframe().f_code.co_name result1 = set_settings(['fakepart1', 'fakepart2'], fname, seperator="//") result2 = get_settings(seperator="//") result3 = trim_settings(['fakepart1', 'fakepart2', 'fakepart3']) assert result1 != None assert result1.get('result') == 'OK' assert result2 != None assert result2.get('fakepart1').get('fakepart2') == fname assert result3 != None assert result3.get('error') != None def final_tear_down(self): """final_tear_down unittest method""" set_settings(None, self.initial_settings) test_registry.register_module("settings", SettingsTests)
intf['dhcpRangeEnd'] = testingDhcpEnd break # Set the settings to new config uvmContext.networkManager().setNetworkSettings(newNetSettings) # Test that the custom WG network exists in the latest WG networks list, and that the local networks are not wgSettings = self._app.getSettings() assert (testingAddressNet not in wgSettings['networks']['list'][0]['address']) assert (testingCustomWGAddr in wgSettings['networks']['list'][0]['address']) # Set app back to normal self._app.setSettings(origWGSettings) # Set network settings back to normal uvmContext.networkManager().setNetworkSettings(origNetSettings) # Get the WG settings again to verify wgSettings = self._app.getSettings() # Assert that old settings were set back properly assert (testingAddressNet not in wgSettings['networks']['list'][0]['address']) assert (testingCustomWGAddr not in wgSettings['networks']['list'][0]['address']) test_registry.register_module("wireguard-vpn", WireGuardVpnTests)
def test_033_check_https_cert(self): """check HTTPS session cert details in the dictionary""" assert playback_start(PlaybackTests.play_file_name, PlaybackTests.play_file_hash, 0) == 0 assert playback_wait() == 0 rawdata = read_dict_sessions(PlaybackTests.https_ctid) playback_cleanup() assert "field: certificate_subject_cn string: www.japan.go.jp" in rawdata def test_040_check_dns_hint(self): """check for DNS hint in the dictionary""" assert playback_start(PlaybackTests.hint_file_name, PlaybackTests.hint_file_hash, 0) == 0 assert playback_wait() == 0 rawdata = read_dict_sessions(PlaybackTests.hint_ctid) playback_cleanup() assert "field: server_dns_hint string: www.yahoo.com" in rawdata def test_050_check_dns_reverse(self): """check for reverse DNS in the dictionary""" assert playback_start(PlaybackTests.revd_file_name, PlaybackTests.revd_file_hash, 0) == 0 assert playback_wait() == 0 rawdata = read_dict_sessions(PlaybackTests.revd_ctid) playback_cleanup() assert "field: server_reverse_dns string: google-public-dns-a.google.com" in rawdata def final_tear_down(self): """final_tear_down""" playback_cleanup() packetd_traffic_resume() test_registry.register_module("playback", PlaybackTests)
headers=dlHeaders, params=dlQueryString) with open("/tmp/cloudBackup.backup", "wb") as f: f.write(dlResponse.content) #extract cloud backup subprocess.call("mkdir /tmp/cloudBackup", shell=True) subprocess.call("tar -xf /tmp/cloudBackup.backup -C /tmp/cloudBackup", shell=True) subprocess.call( "tar -xf " + glob.glob("/tmp/cloudBackup/files*.tar.gz")[0] + " -C /tmp/cloudBackup", shell=True) #use glob since extracted file has timestamp cloudBackupPath = "/tmp/cloudBackup/usr" #compare directories def is_same(dir1, dir2): compared = filecmp.dircmp(dir1, dir2) if (compared.left_only or compared.right_only or compared.diff_files or compared.funny_files): return False for subdir in compared.common_dirs: if not is_same(os.path.join(dir1, subdir), os.path.join(dir2, subdir)): return False return True assert (is_same(localBackupPath, cloudBackupPath)) test_registry.register_module("configuration-backup", ConfigurationBackupTests)
print(tunnelAppData['tunnels']['list'][i]['enabled']) tunnelApp.setSettings(tunnelAppData) #stop tunnel here time.sleep(3) tunnelApp.stop() # If VPN tunnel has failed to connect, fail the test, assert (connected) @staticmethod def final_tear_down(self): global app, appWeb, appDC, tunnelApp if app != None: uvmContext.appManager().destroy(app.getAppSettings()["id"]) app = None if appWeb != None: uvmContext.appManager().destroy(appWeb.getAppSettings()["id"]) appWeb = None if appDC != None: uvmContext.appManager().destroy(appDC.getAppSettings()["id"]) appDC = None if tunnelApp != None: uvmContext.appManager().destroy(tunnelApp.getAppSettings()["id"]) tunnelApp = None # print(tunnelApp.getAppSettings()["id"]) test_registry.register_module("openvpn", OpenVpnTests)
result = remote_control.run_command( "rm -f /tmp/testcookie.txt ; wget -4 -q -O /dev/null --save-cookies /tmp/testcookie.txt http://test.untangle.com/mycookie.php ; grep -q untangle.com /tmp/testcookie.txt" ) assert (result == 1) # verify a accuweather cookie can be blocked, but set both "enabled" and "blocked" params def test_102_webCookieBlockedEnabled(self): addCookieBlockedEnabled("untangle.com") # remove any previous instance of testcookie.txt remote_control.run_command("/bin/rm -f /tmp/testcookie.txt") # see if cookie is downloaded. result = remote_control.run_command( "rm -f /tmp/testcookie.txt ; wget -4 -q -O /dev/null --save-cookies /tmp/testcookie.txt http://test.untangle.com/mycookie.php ; grep -q untangle.com /tmp/testcookie.txt" ) assert (result == 1) # verify update mechanism def test_110_updateAdBlockRules(self): app.updateList() result = app.getListLastUpdate() today_str = datetime.datetime.utcnow().strftime("%d %b %Y") yesterday_str = (datetime.datetime.utcnow() - datetime.timedelta(days=1)).strftime("%d %b %Y") print("Last Update: \"%s\"" % (result)) print("Today: \"%s\"" % (today_str)) print("Yesterday: \"%s\"" % (yesterday_str)) assert ((today_str in result) or (yesterday_str in result)) test_registry.register_module("ad-blocker", AdBlockerTests)
def test_060_setRadiusSettings(self): """ Test and save settings for test Radius server """ if (RADIUS_RESULT != 0): raise unittest.SkipTest("No RADIUS server available") app.setSettings(create_radius_settings()) attempts = 0 while attempts < 3: test_result_string = app.getRadiusManager().getRadiusStatusForSettings(create_radius_settings(), "normal", "passwd") if ("success" in test_result_string): break else: attempts += 1 print('test_result_string %s attempts %s' % (test_result_string, attempts) ) # debug line assert ("success" in test_result_string) @staticmethod def final_tear_down(self): """ Tear down """ global app if app != None: uvmContext.appManager().destroy( app.getAppSettings()["id"] ) app = None test_registry.register_module("directory-connector", DirectoryConnectorTests)