Пример #1
0
    def test_041_trigger_rule_untag_host(self):
        settings = uvmContext.eventManager().getSettings()
        orig_settings = copy.deepcopy(settings)
        new_rule = create_trigger_rule("TAG_HOST", "localAddr", "test-tag", 30, "test tag rule", "class", "=", "*SessionEvent*", "localAddr", "=", "*"+remote_control.client_ip+"*")
        settings['triggerRules']['list'] = [ new_rule ]
        uvmContext.eventManager().setSettings( settings )

        result = remote_control.is_online()
        time.sleep(4)

        entry = uvmContext.hostTable().getHostTableEntry( remote_control.client_ip )
        tag_test = entry.get('tagsString')
        uvmContext.eventManager().setSettings( orig_settings )

        new_rule = create_trigger_rule("UNTAG_HOST", "localAddr", "test*", 30, "test tag rule", "class", "=", "*SessionEvent*", "localAddr", "=", "*"+remote_control.client_ip+"*")
        settings['triggerRules']['list'] = [ new_rule ]
        uvmContext.eventManager().setSettings( settings )

        result = remote_control.is_online()
        time.sleep(4)

        entry = uvmContext.hostTable().getHostTableEntry( remote_control.client_ip )
        tag_test2 = entry.get('tagsString')

        uvmContext.eventManager().setSettings( orig_settings )
        assert( tag_test != None )
        assert( "test-tag" in tag_test )
        assert( tag_test2 == None or "test-tag" not in tag_test2)
Пример #2
0
    def test_041_trigger_rule_untag_host(self):
        settings = uvmContext.eventManager().getSettings()
        orig_settings = copy.deepcopy(settings)
        new_rule = create_trigger_rule("TAG_HOST", "localAddr", "test-tag", 30, "test tag rule", "class", "=", "*SessionEvent*", "localAddr", "=", "*"+remote_control.client_ip+"*")
        settings['triggerRules']['list'] = [ new_rule ]
        uvmContext.eventManager().setSettings( settings )

        result = remote_control.is_online()
        time.sleep(4)

        entry = uvmContext.hostTable().getHostTableEntry( remote_control.client_ip )
        tag_test = entry.get('tagsString')
        uvmContext.eventManager().setSettings( orig_settings )

        new_rule = create_trigger_rule("UNTAG_HOST", "localAddr", "test*", 30, "test tag rule", "class", "=", "*SessionEvent*", "localAddr", "=", "*"+remote_control.client_ip+"*")
        settings['triggerRules']['list'] = [ new_rule ]
        uvmContext.eventManager().setSettings( settings )

        result = remote_control.is_online()
        time.sleep(4)

        entry = uvmContext.hostTable().getHostTableEntry( remote_control.client_ip )
        tag_test2 = entry.get('tagsString')

        uvmContext.eventManager().setSettings( orig_settings )
        assert( tag_test != None )
        assert( "test-tag" in tag_test )
        assert( tag_test2 == None or "test-tag" not in tag_test2)
Пример #3
0
 def initial_setup(self):
     global appSettings, 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)
     appSettings = app.getSettings()
     # run a few sessions so that the classd daemon starts classifying
     for i in range(2): remote_control.is_online()
Пример #4
0
 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)
Пример #5
0
 def test_028_addFirewallToThirdRack(self):
     global thirdRackFirewall
     thirdRackFirewall = uvmContext.appManager().instantiate(
         "firewall", thirdRackId)
     assert (thirdRackFirewall != None)
     result = remote_control.is_online()
     assert (result == 0)
Пример #6
0
    def test_023_childShouldNotEffectParent(self):
        # add a child that blocks everything
        blockRackId = addRack(name="Block Rack", parentId=default_policy_id)
        blockRackFirewall = uvmContext.appManager().instantiate(
            "firewall", blockRackId)
        assert (blockRackFirewall != None)
        # add a block rule for the client IP
        rules = blockRackFirewall.getRules()
        rules["list"].append(
            createFirewallSingleConditionRule("SRC_ADDR",
                                              remote_control.client_ip))
        blockRackFirewall.setRules(rules)
        # client should still be online
        result = remote_control.is_online()
        assert (result == 0)
        uvmContext.appManager().destroy(
            blockRackFirewall.getAppSettings()["id"])
        assert (removeRack(blockRackId))

        # Get the IP address of test.untangle.com
        test_untangle_com_ip = socket.gethostbyname("test.untangle.com")

        events = global_functions.get_events('Policy Manager', 'All Events',
                                             None, 100)
        assert (events != None)
        found = global_functions.check_events(events.get('list'), 100,
                                              "s_server_addr",
                                              str(test_untangle_com_ip),
                                              "policy_id", 1, "c_client_addr",
                                              remote_control.client_ip)
        assert (found)
Пример #7
0
 def test_029_stopFirewallToThirdRack(self):
     global thirdRackFirewall
     thirdRackFirewall.stop()
     assert (thirdRackFirewall != None)
     result = remote_control.is_online()
     assert (result == 0)
     thirdRackFirewall.start()
Пример #8
0
 def test_029_stopFirewallToThirdRack(self):
     global thirdRackFirewall
     thirdRackFirewall.stop()
     assert (thirdRackFirewall != None)
     result = remote_control.is_online()
     assert (result == 0)
     thirdRackFirewall.start()
Пример #9
0
    def test_025_ping_test_wan_offline(self):
        if runtests.quick_tests_only:
            raise unittest.SkipTest('Skipping a time consuming test')
        if (len(indexOfWans) < 2):
            raise unittest.SkipTest(
                "Need at least two WANS for test_025_addPingFailTestForWans")
        nuke_rules()
        orig_offline_count = offline_wan_count()
        for wanIndexTup in indexOfWans:
            wanIndex = wanIndexTup[0]
            build_wan_test(wanIndex, "ping", pingHost="192.168.244.1")

        wait_for_wan_offline()

        offline_count = offline_wan_count()
        assert (offline_count > orig_offline_count)

        result = remote_control.is_online()
        assert (result == 0)

        events = global_functions.get_events('WAN Failover', 'Outage Events',
                                             None, 1)
        assert (events != None)
        found = global_functions.check_events(events.get('list'), 2, "action",
                                              "DISCONNECTED")
        assert (found)
Пример #10
0
    def test_035_arp_test_wan_offline(self):
        if runtests.quick_tests_only:
            raise unittest.SkipTest('Skipping a time consuming test')
        if (len(indexOfWans) < 2):
            raise unittest.SkipTest(
                "Need at least two WANS for test_035_addArpFailTestForWans")
        nuke_rules()
        orig_offline_count = offline_wan_count()
        netsettings = uvmContext.networkManager().getNetworkSettings()
        # Add a fake gateway for each of the interfaces
        for wanIndexTup in indexOfWans:
            wanIndex = wanIndexTup[0]
            # set gateway to fake gateway
            set_interface_field(wanIndex, netsettings, 'v4StaticGateway',
                                '192.168.244.' + str(wanIndex))
            set_interface_field(wanIndex, netsettings, 'v4AutoGatewayOverride',
                                '192.168.244.' + str(wanIndex))
            build_wan_test(wanIndex, "arp")

        uvmContext.networkManager().setNetworkSettings(netsettings)

        wait_for_wan_offline()

        offline_count = offline_wan_count()

        uvmContext.networkManager().setNetworkSettings(orig_netsettings)

        assert (offline_count > orig_offline_count)
        result = remote_control.is_online()
        assert (result == 0)
Пример #11
0
    def test_023_childShouldNotEffectParent(self):
        # add a child that blocks everything
        blockRackId = addRack(name="Block Rack", parentId=default_policy_id)
        blockRackFirewall = uvmContext.appManager().instantiate("firewall", blockRackId)
        assert (blockRackFirewall != None)
        # add a block rule for the client IP
        rules = blockRackFirewall.getRules()
        rules["list"].append(createFirewallSingleConditionRule("SRC_ADDR",remote_control.client_ip));
        blockRackFirewall.setRules(rules);
        # client should still be online
        result = remote_control.is_online()
        assert (result == 0)
        uvmContext.appManager().destroy( blockRackFirewall.getAppSettings()["id"] )
        assert (removeRack(blockRackId))

        # Get the IP address of test.untangle.com
        test_untangle_com_ip = socket.gethostbyname("test.untangle.com")
        
        events = global_functions.get_events('Policy Manager','All Events',None,100)
        assert(events != None)
        found = global_functions.check_events( events.get('list'), 100, 
                                            "s_server_addr", str(test_untangle_com_ip),
                                            "policy_id", 1,
                                            "c_client_addr", remote_control.client_ip)
        assert( found )
Пример #12
0
    def test_060_customized_email_alert(self):
        """Create custom email template and verify alert email is received correctly"""
        #get settings, backup original settings
        email_settings = uvmContext.eventManager().getSettings()
        orig_email_settings = copy.deepcopy(email_settings)
        admin_settings = uvmContext.adminManager().getSettings()
        orig_admin_settings = copy.deepcopy(admin_settings)

        #change admin email to verify sent email
        new_admin_email = global_functions.random_email()
        admin_settings["users"]["list"][0]["emailAddress"] = new_admin_email
        uvmContext.adminManager().setSettings(admin_settings)

        #set custom email template subject and body
        new_email_subject = "NEW EMAIL SUBJECT TEST"
        new_email_body = "NEW EMAIL BODY TEST"
        email_settings["emailSubject"] = new_email_subject
        email_settings["emailBody"] = new_email_body

        #set new alert rule for easy trigger of email
        new_rule = create_alert_rule("test alert rule", "class", "=", "*SessionEvent*", "localAddr", "=", "*"+remote_control.client_ip+"*", sendEmail=True)
        email_settings['alertRules']['list'].append(new_rule)
        
        #set new settings
        uvmContext.eventManager().setSettings(email_settings)
        
        #send a session
        remote_control.is_online()
        time.sleep(4)

        #check email sent is correct
        emailFound = False
        timeout = 5
        alertEmail = ""
        while not emailFound and timeout > 0:
            timeout -= 1
            time.sleep(1)
            alertEmail = remote_control.run_command("wget -q --timeout=5 -O - http://test.untangle.com/cgi-bin/getEmail.py?toaddress=" + new_admin_email + " 2>&1 | grep TEST" ,stdout=True)
            if (alertEmail != ""):
                emailFound = True
        
        #set settings back
        uvmContext.eventManager().setSettings(orig_email_settings)
        uvmContext.adminManager().setSettings(orig_admin_settings)
        
        assert(emailFound)
Пример #13
0
 def test_027_addRuleForThirdRack(self):
     global thirdRackId
     appendRule(
         createPolicySingleConditionRule("SRC_ADDR",
                                         remote_control.client_ip,
                                         thirdRackId))
     # client should be offline
     result = remote_control.is_online(tries=1)
     assert (result != 0)
Пример #14
0
    def test_020_ping_test_wan_online(self):
        nuke_rules()
        for wanIndexTup in indexOfWans:
            wanIndex = wanIndexTup[0]
            build_wan_test(wanIndex)

        time.sleep(30)

        assert (all_wans_online())
        result = remote_control.is_online()
        assert (result == 0)
Пример #15
0
    def test_040_dns_test_wan_online(self):
        if runtests.quick_tests_only:
            raise unittest.SkipTest('Skipping a time consuming test')
        nuke_rules()
        for wanIndexTup in indexOfWans:
            wanIndex = wanIndexTup[0]
            build_wan_test(wanIndex, "dns")

        time.sleep(30)

        assert (all_wans_online())
        result = remote_control.is_online()
        assert (result == 0)
Пример #16
0
    def test_900_logEventLog(self):
        rules_clear()
        rule_append(create_rule_single_condition("DST_PORT","80",blocked=False,flagged=False))
        result = remote_control.is_online()
        assert (result == 0)

        events = global_functions.get_events('Firewall','All Events',None,1)
        assert(events != None)
        found = global_functions.check_events( events.get('list'), 5,
                                            'c_client_addr', remote_control.client_ip,
                                            's_server_port', 80,
                                            'firewall_blocked', False,
                                            'firewall_flagged', False)
Пример #17
0
    def test_030_arp_test_wan_online(self):
        if runtests.quick_tests_only:
            raise unittest.SkipTest('Skipping a time consuming test')
        nuke_rules()
        for wanIndexTup in indexOfWans:
            wanIndex = wanIndexTup[0]
            print("Testing interface : " + str(wanIndex))
            build_wan_test(wanIndex, "arp")

        time.sleep(30)

        assert (all_wans_online())
        result = remote_control.is_online()
        assert (result == 0)
Пример #18
0
 def test_030_addWebFilterToSecondRack(self):
     global secondRackWebfilter
     secondRackWebfilter = uvmContext.appManager().instantiate("web-filter", secondRackId)
     assert (secondRackWebfilter != None)
     result = remote_control.is_online()
     assert (result == 0)
     # add a block rule
     newRule = { "blocked": True, "description": "desc", "flagged": True, "javaClass": "com.untangle.uvm.app.GenericRule", "string": "test.untangle.com/test/testPage1.html" }
     rules = secondRackWebfilter.getBlockedUrls()
     rules["list"].append(newRule)
     secondRackWebfilter.setBlockedUrls(rules)
     # verify traffic is now blocked (third rack inherits web filter from second rack)
     result = remote_control.run_command("wget -4 -t 2 --timeout=5 -q -O - http://test.untangle.com/test/testPage1.html 2>&1 | grep -q blockpage")
     assert (result == 0)
Пример #19
0
    def test_050_http_test_wan_online(self):
        if runtests.quick_tests_only:
            raise unittest.SkipTest('Skipping a time consuming test')
        nuke_rules()
        for wanIndexTup in indexOfWans:
            wanIndex = wanIndexTup[0]
            build_wan_test(wanIndex, "http", httpURL="http://test.untangle.com/")

        time.sleep(30)

        wansOnline = all_wans_online()

        assert (wansOnline)                        
        result = remote_control.is_online()
        assert (result == 0)        
Пример #20
0
    def test_090_heavyWeightWanDown(self):
        # Set the one WAN as 100 weight and the other as zero and down the 100 weight wan
        # if there are more than one WAN
        if (len(index_of_wans) < 2):
            raise unittest.SkipTest(
                "Need at least two WANS for combination of wan-balancer and wan failover tests"
            )
        # initialize all the weights to 50
        nuke_wan_balancer_rules()
        # create valid failover tests
        for wanIndexTup in index_of_wans:
            build_wan_test_rule(wanIndexTup[0])
        result = remote_control.is_online()
        assert (result == 0)
        for wanIndexTup in index_of_wans:
            wanIndex = wanIndexTup[0]
            # set the selected wan to 100 and others to zero
            set_wan_weight("all", 0)
            set_wan_weight(wanIndex, 100)
            # Set the weighted interface with invalid rule
            build_wan_test_rule(wanIndex, "ping", "192.168.244.1")
            # get the WAN IP address which was weighted to 100
            weightedIP = wanIndexTup[1]
            # Wait for targeted the WAN to be off line before testing that the WAN is off line.
            timeout = 50000
            online = True
            offlineWanIndex = wanIndex
            while online and timeout > 0:
                timeout -= 1
                wanStatus = app_wan_failover.getWanStatus()
                for statusInterface in wanStatus['list']:
                    if statusInterface['interfaceId'] == offlineWanIndex:
                        online = statusInterface['online']
            time.sleep(
                10)  # Let WAN balancer see that the heavy interface is down
            # Test that other interfaces are used 10 times
            for x in range(0, 9):
                result = global_functions.get_public_ip_address()
                print("Weighted IP %s and retrieved IP %s" %
                      (weightedIP, result))
                assert (result != weightedIP)
            # reset weight to zero and interface to valid rule
            set_wan_weight(wanIndex, 0)
            build_wan_test_rule(wanIndex)

        # return settings to default
        nuke_wan_balancer_rules()
        nuke_wan_failover_rules()
Пример #21
0
    def test_050_alert_rule(self):
        settings = uvmContext.eventManager().getSettings()
        orig_settings = copy.deepcopy(settings)
        new_rule = create_alert_rule("test alert rule", "class", "=", "*SessionEvent*", "localAddr", "=", "*"+remote_control.client_ip+"*")
        settings['alertRules']['list'].append( new_rule )
        uvmContext.eventManager().setSettings( settings )

        result = remote_control.is_online()
        time.sleep(4)

        events = global_functions.get_events('Events','Alert Events',None,10)
        found = global_functions.check_events( events.get('list'), 5,
                                            'description', 'test alert rule' )
        uvmContext.eventManager().setSettings( orig_settings )
        assert(events != None)
        assert ( found )
Пример #22
0
    def test_050_alert_rule(self):
        settings = uvmContext.eventManager().getSettings()
        orig_settings = copy.deepcopy(settings)
        new_rule = create_alert_rule("test alert rule", "class", "=", "*SessionEvent*", "localAddr", "=", "*"+remote_control.client_ip+"*")
        settings['alertRules']['list'].append( new_rule )
        uvmContext.eventManager().setSettings( settings )

        result = remote_control.is_online()
        time.sleep(4)

        events = global_functions.get_events('Events','Alert Events',None,10)
        found = global_functions.check_events( events.get('list'), 5,
                                            'description', 'test alert rule' )
        uvmContext.eventManager().setSettings( orig_settings )
        assert(events != None)
        assert ( found )
Пример #23
0
    def test_070_penalty_rule(self):
        global app
        nuke_rules(self._app)
        tag_time = 2000000

        # remove tags
        entry = uvmContext.hostTable().getHostTableEntry(
            remote_control.client_ip)
        entry['tags']['list'] = []
        entry = uvmContext.hostTable().setHostTableEntry(
            remote_control.client_ip, entry)

        # Create penalty rule
        append_rule(
            self._app,
            create_penalty_rule("SRC_ADDR", remote_control.client_ip,
                                "TAG_HOST", "penalty-box", tag_time))

        # go to test.untangle.com
        result = remote_control.is_online()

        # Look for tag
        entry = uvmContext.hostTable().getHostTableEntry(
            remote_control.client_ip)
        print(entry['tags']['list'])
        found = False
        for tag in entry['tags']['list']:
            if tag['name'] == 'penalty-box':
                found = True

        assert (found)

        # 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))
Пример #24
0
    def test_055_http_test_wan_offline(self):
        if runtests.quick_tests_only:
            raise unittest.SkipTest('Skipping a time consuming test')
        if (len(indexOfWans) < 2):
            raise unittest.SkipTest("Need at least two WANS for test_055_addHTTPFailTestForWans")
        nuke_rules()
        orig_offline_count = offline_wan_count()
        for wanIndexTup in indexOfWans:
            wanIndex = wanIndexTup[0]
            build_wan_test(wanIndex, "http", httpURL="http://192.168.244.1/")

        wait_for_wan_offline()
        offline_count = offline_wan_count()

        assert (offline_count > orig_offline_count)                        
        result = remote_control.is_online()
        assert (result == 0)        
Пример #25
0
    def test_070_penalty_rule(self):
        global app
        nuke_rules()
        tag_time = 2000000

        # remove tags
        entry = uvmContext.hostTable().getHostTableEntry(remote_control.client_ip)
        entry['tags']['list'] = []
        entry = uvmContext.hostTable().setHostTableEntry(remote_control.client_ip, entry)
        
        # Create penalty rule
        append_rule(create_penalty_rule("SRC_ADDR",remote_control.client_ip,"TAG_HOST","penalty-box",tag_time))
        
        # go to test.untangle.com 
        result = remote_control.is_online()

        # Look for tag
        entry = uvmContext.hostTable().getHostTableEntry(remote_control.client_ip)
        print(entry['tags']['list'])
        found = False
        for tag in entry['tags']['list']:
            if tag['name'] == 'penalty-box':
                found = True

        assert(found)
                
        # 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))
Пример #26
0
 def test_030_addWebFilterToSecondRack(self):
     global secondRackWebfilter
     secondRackWebfilter = uvmContext.appManager().instantiate(
         "web-filter", secondRackId)
     assert (secondRackWebfilter != None)
     result = remote_control.is_online()
     assert (result == 0)
     # add a block rule
     newRule = {
         "blocked": True,
         "description": "desc",
         "flagged": True,
         "javaClass": "com.untangle.uvm.app.GenericRule",
         "string": "test.untangle.com/test/testPage1.html"
     }
     rules = secondRackWebfilter.getBlockedUrls()
     rules["list"].append(newRule)
     secondRackWebfilter.setBlockedUrls(rules)
     # verify traffic is now blocked (third rack inherits web filter from second rack)
     result = remote_control.run_command(
         "wget -4 -t 2 --timeout=5 -q -O - http://test.untangle.com/test/testPage1.html 2>&1 | grep -q blockpage"
     )
     assert (result == 0)
Пример #27
0
 def test_027_addRuleForThirdRack(self):
     global thirdRackId
     appendRule(createPolicySingleConditionRule("SRC_ADDR",remote_control.client_ip, thirdRackId))
     # client should be offline
     result = remote_control.is_online(tries=1)
     assert (result != 0)
Пример #28
0
 def test_028_addFirewallToThirdRack(self):
     global thirdRackFirewall
     thirdRackFirewall = uvmContext.appManager().instantiate("firewall", thirdRackId)
     assert (thirdRackFirewall != None)
     result = remote_control.is_online()
     assert (result == 0)
Пример #29
0
 def test_983_removeSecondRack(self):
     global secondRackId
     nukeRules()
     assert (removeRack(secondRackId))
     result = remote_control.is_online()
     assert (result == 0)
Пример #30
0
 def test_14_client_is_online(self):
     """verify client is online"""
     assert remote_control.is_online() == 0
Пример #31
0
 def test_015_addRack(self):
     global secondRackId
     secondRackId = addRack()
     result = remote_control.is_online()
     assert (result == 0)
Пример #32
0
 def test_016_removeRack(self):
     global secondRackId
     assert (removeRack(secondRackId))
     result = remote_control.is_online()
     assert (result == 0)
Пример #33
0
 def test_010_clientIsOnline(self):
     """
     Verify client is online
     """
     result = remote_control.is_online()
     assert (result == 0)
Пример #34
0
 def initial_extra_setup(cls):
     for i in range(2):
         remote_control.is_online()
Пример #35
0
 def test_983_removeSecondRack(self):
     global secondRackId
     nukeRules()
     assert (removeRack(secondRackId))
     result = remote_control.is_online()
     assert (result == 0)
Пример #36
0
 def test_14_client_is_online(self):
     """verify client is online"""
     assert remote_control.is_online() == 0
Пример #37
0
    def test_040_remote_syslog(self):
        if (not can_syslog):
            raise unittest.SkipTest('Unable to syslog through ' + syslog_server_host)

        firewall_app = None
        if (uvmContext.appManager().isInstantiated("firewall")):
            print("App %s already installed" % "firewall")
            firewall_app = uvmContext.appManager().app("firewall")
        else:
            firewall_app = uvmContext.appManager().instantiate("firewall", default_policy_id)

        # Install firewall rule to generate syslog events
        rules = firewall_app.getRules()
        rules["list"].append(create_firewall_rule("SRC_ADDR",remote_control.client_ip));
        firewall_app.setRules(rules);
        rules = firewall_app.getRules()
        # Get rule ID
        for rule in rules['list']:
            if rule['enabled'] and rule['block']:
                targetRuleId = rule['ruleId']
                break
        # Setup syslog to send events to syslog host in /config/events/syslog
        syslogSettings = uvmContext.eventManager().getSettings()
        syslogSettings["syslogEnabled"] = True
        syslogSettings["syslogPort"] = 514
        syslogSettings["syslogProtocol"] = "UDP"
        syslogSettings["syslogHost"] = syslog_server_host
        uvmContext.eventManager().setSettings( syslogSettings )

        # create some traffic (blocked by firewall and thus create a syslog event)
        exactly_now = datetime.now()
        exactly_now_minus1 = datetime.now() - timedelta(minutes=1)
        exactly_now_plus1 = datetime.now() + timedelta(minutes=1)
        timestamp = exactly_now.strftime('%Y-%m-%d %H:%M')
        timestamp_minus1 = exactly_now_minus1.strftime('%Y-%m-%d %H:%M')
        timestamp_now_plus1 = exactly_now_plus1.strftime('%Y-%m-%d %H:%M')
        result = remote_control.is_online(tries=1)
        # flush out events
        app.flushEvents()

        # remove the firewall rule aet syslog back to original settings
        app.setSettings(orig_settings)
        rules["list"]=[];
        firewall_app.setRules(rules);

        # remove firewall
        if firewall_app != None:
            uvmContext.appManager().destroy( firewall_app.getAppSettings()["id"] )
        firewall_app = None
        
        # parse the output and look for a rule that matches the expected values
        tries = 5
        found_count = 0
        timestamp_variations  = [str('\"timeStamp\":\"%s' % timestamp_minus1),str('\"timeStamp\":\"%s' % timestamp_now_plus1)]
        strings_to_find = ['\"blocked\":true',str('\"ruleId\":%i' % targetRuleId),str('\"timeStamp\":\"%s' % timestamp)]
        num_string_find = len(strings_to_find)
        while (tries > 0 and found_count < num_string_find):
            # get syslog results on server
            rsyslogResult = remote_control.run_command("sudo tail -n 200 /var/log/syslog | grep 'FirewallEvent'", host=syslog_server_host, stdout=True)
            tries -= 1
            for line in rsyslogResult.splitlines():
                print("\nchecking line: %s " % line)
                found_count = 0
                for string in strings_to_find:
                    if not string in line:
                        print("missing: %s" % string)
                        if ('timeStamp' in string):
                            # Allow +/- one minute in timestamp
                            if (timestamp_variations [0] in line) or (timestamp_variations [1] in line):
                                print("found: time with varation %s or %s" % (timestamp_variations [0],timestamp_variations [1]))
                                found_count += 1
                            else:
                                break
                        else:
                            # continue
                            break
                    else:
                        found_count += 1
                        print("found: %s" % string)
                # break if all the strings have been found.
                if found_count == num_string_find:
                    break
            time.sleep(2)

        # Disable syslog
        syslogSettings = uvmContext.eventManager().getSettings()
        syslogSettings["syslogEnabled"] = False
        uvmContext.eventManager().setSettings( syslogSettings )
            
        assert(found_count == num_string_find)
Пример #38
0
    def test_040_remote_syslog(self):
        if (not can_syslog):
            raise unittest.SkipTest('Unable to syslog through ' +
                                    syslog_server_host)

        firewall_app = None
        if (uvmContext.appManager().isInstantiated("firewall")):
            print("App %s already installed" % "firewall")
            firewall_app = uvmContext.appManager().app("firewall")
        else:
            firewall_app = uvmContext.appManager().instantiate(
                "firewall", default_policy_id)

        # Install firewall rule to generate syslog events
        rules = firewall_app.getRules()
        rules["list"].append(
            create_firewall_rule("SRC_ADDR", remote_control.client_ip))
        firewall_app.setRules(rules)
        rules = firewall_app.getRules()
        # Get rule ID
        for rule in rules['list']:
            if rule['enabled'] and rule['block']:
                targetRuleId = rule['ruleId']
                break
        # Setup syslog to send events to syslog host in /config/events/syslog
        syslogSettings = uvmContext.eventManager().getSettings()
        syslogSettings["syslogEnabled"] = True
        syslogSettings["syslogPort"] = 514
        syslogSettings["syslogProtocol"] = "UDP"
        syslogSettings["syslogHost"] = syslog_server_host
        uvmContext.eventManager().setSettings(syslogSettings)

        # create some traffic (blocked by firewall and thus create a syslog event)
        exactly_now = datetime.now()
        exactly_now_minus1 = datetime.now() - timedelta(minutes=1)
        exactly_now_plus1 = datetime.now() + timedelta(minutes=1)
        timestamp = exactly_now.strftime('%Y-%m-%d %H:%M')
        timestamp_minus1 = exactly_now_minus1.strftime('%Y-%m-%d %H:%M')
        timestamp_now_plus1 = exactly_now_plus1.strftime('%Y-%m-%d %H:%M')
        result = remote_control.is_online(tries=1)
        # flush out events
        self._app.flushEvents()

        # remove the firewall rule aet syslog back to original settings
        self._app.setSettings(orig_settings)
        rules["list"] = []
        firewall_app.setRules(rules)

        # remove firewall
        if firewall_app != None:
            uvmContext.appManager().destroy(
                firewall_app.getAppSettings()["id"])
        firewall_app = None

        # parse the output and look for a rule that matches the expected values
        tries = 5
        found_count = 0
        timestamp_variations = [
            str('\"timeStamp\":\"%s' % timestamp_minus1),
            str('\"timeStamp\":\"%s' % timestamp_now_plus1)
        ]
        strings_to_find = [
            '\"blocked\":true',
            str('\"ruleId\":%i' % targetRuleId),
            str('\"timeStamp\":\"%s' % timestamp)
        ]
        num_string_find = len(strings_to_find)
        while (tries > 0 and found_count < num_string_find):
            # get syslog results on server
            rsyslogResult = remote_control.run_command(
                "sudo tail -n 200 /var/log/syslog | grep 'FirewallEvent'",
                host=syslog_server_host,
                stdout=True)
            tries -= 1
            for line in rsyslogResult.splitlines():
                print("\nchecking line: %s " % line)
                found_count = 0
                for string in strings_to_find:
                    if not string in line:
                        print("missing: %s" % string)
                        if ('timeStamp' in string):
                            # Allow +/- one minute in timestamp
                            if (timestamp_variations[0]
                                    in line) or (timestamp_variations[1]
                                                 in line):
                                print("found: time with varation %s or %s" %
                                      (timestamp_variations[0],
                                       timestamp_variations[1]))
                                found_count += 1
                            else:
                                break
                        else:
                            # continue
                            break
                    else:
                        found_count += 1
                        print("found: %s" % string)
                # break if all the strings have been found.
                if found_count == num_string_find:
                    break
            time.sleep(2)

        # Disable syslog
        syslogSettings = uvmContext.eventManager().getSettings()
        syslogSettings["syslogEnabled"] = False
        uvmContext.eventManager().setSettings(syslogSettings)

        assert (found_count == num_string_find)
Пример #39
0
 def test_026_addThirdRack(self):
     global thirdRackId
     thirdRackId = addRack(name="Third Rack", parentId=secondRackId)
     result = remote_control.is_online()
     assert (result == 0)
Пример #40
0
 def test_025_removeRuleForSecondRack(self):
     nukeRules()
     result = remote_control.is_online()
     assert (result == 0)
Пример #41
0
 def test_026_addThirdRack(self):
     global thirdRackId
     thirdRackId = addRack(name="Third Rack", parentId=secondRackId)
     result = remote_control.is_online()
     assert (result == 0)
Пример #42
0
 def test_021_addSecondRack(self):
     global secondRackId
     secondRackId = addRack(name="Second Rack")
     result = remote_control.is_online()
     assert (result == 0)
Пример #43
0
 def test_025_removeRuleForSecondRack(self):
     nukeRules()
     result = remote_control.is_online()
     assert (result == 0)
Пример #44
0
    def test_103_email_report_verify_apps(self):
        """
        1) Install all apps
        2) Generate a report
        3) Verify that the emailed report contains a section for each app
        """
        global app,apps_list,apps_name_list
        if (not can_relay):
            raise unittest.SkipTest('Unable to relay through ' + global_functions.TEST_SERVER_HOST)
        if runtests.quick_tests_only:
            raise unittest.SkipTest('Skipping a time consuming test')

        # create settings to receive test_email_address 
        configure_mail_relay()

        # add administrator
        adminsettings = uvmContext.adminManager().getSettings()
        orig_adminsettings = copy.deepcopy(adminsettings)
        adminsettings['users']['list'].append(create_admin_user(useremail=test_email_address))
        uvmContext.adminManager().setSettings(adminsettings)

        # clear all report users
        settings = app.getSettings()
        settings["reportsUsers"]["list"] = settings["reportsUsers"]["list"][:1]
        app.setSettings(settings)
        
        # install all the apps that aren't already installed
        system_stats = uvmContext.metricManager().getStats()
        # print system_stats
        system_memory = system_stats['systemStats']['MemTotal']
        if (int(system_memory) < 2200000000):   # don't use high memory apps in devices with 2G or less.
            apps_list = apps_list_short
            apps_name_list = apps_name_list_short
        apps = []
        for name in apps_list:
            if (uvmContext.appManager().isInstantiated(name)):
                print("App %s already installed" % name)
            else:
                apps.append( uvmContext.appManager().instantiate(name, default_policy_id) )
            
        # create some traffic 
        result = remote_control.is_online(tries=1)

        # flush out events
        app.flushEvents()

        # send emails
        subprocess.call([global_functions.get_prefix()+"/usr/share/untangle/bin/reports-generate-fixed-reports.py"],stdout=subprocess.PIPE,stderr=subprocess.PIPE)

        # look for email
        email_found = fetch_email( "/tmp/test_103_email_report_admin_file", test_email_address )

        # look for all the appropriate sections in the report email
        results = []
        if email_found:
            for str in apps_name_list:
                results.append(remote_control.run_command("grep -q -i '%s' /tmp/test_103_email_report_admin_file 2>&1"%str))

        # restore
        uvmContext.adminManager().setSettings(orig_adminsettings)

        # remove apps that were installed above
        for a in apps: uvmContext.appManager().destroy( a.getAppSettings()["id"] )
        
        assert(email_found)
        for result in results:
            assert(result == 0)
Пример #45
0
 def test_010_clientIsOnline(self):
     result = remote_control.is_online()
     assert (result == 0)
Пример #46
0
    def test_103_email_report_verify_apps(self):
        """
        1) Install all apps
        2) Generate a report
        3) Verify that the emailed report contains a section for each app
        """
        global app, apps_list, apps_name_list
        if (not can_relay):
            raise unittest.SkipTest('Unable to relay through ' +
                                    global_functions.TEST_SERVER_HOST)
        if runtests.quick_tests_only:
            raise unittest.SkipTest('Skipping a time consuming test')

        # create settings to receive test_email_address
        configure_mail_relay()

        # add administrator
        adminsettings = uvmContext.adminManager().getSettings()
        orig_adminsettings = copy.deepcopy(adminsettings)
        adminsettings['users']['list'].append(
            create_admin_user(useremail=test_email_address))
        uvmContext.adminManager().setSettings(adminsettings)

        # clear all report users
        settings = self._app.getSettings()
        settings["reportsUsers"]["list"] = settings["reportsUsers"]["list"][:1]
        self._app.setSettings(settings)

        # install all the apps that aren't already installed
        system_stats = uvmContext.metricManager().getStats()
        # print system_stats
        system_memory = system_stats['systemStats']['MemTotal']
        if (int(system_memory) < 2200000000
            ):  # don't use high memory apps in devices with 2G or less.
            apps_list = apps_list_short
            apps_name_list = apps_name_list_short
        apps = []
        for name in apps_list:
            if (uvmContext.appManager().isInstantiated(name)):
                print("App %s already installed" % name)
            else:
                apps.append(uvmContext.appManager().instantiate(
                    name, default_policy_id))

        # create some traffic
        result = remote_control.is_online(tries=1)

        # flush out events
        self._app.flushEvents()

        # send emails
        subprocess.call([
            global_functions.get_prefix() +
            "/usr/share/untangle/bin/reports-generate-fixed-reports.py"
        ],
                        stdout=subprocess.PIPE,
                        stderr=subprocess.PIPE)

        # look for email
        email_found = fetch_email("/tmp/test_103_email_report_admin_file",
                                  test_email_address)

        # look for all the appropriate sections in the report email
        results = []
        if email_found:
            for str in apps_name_list:
                results.append(
                    remote_control.run_command(
                        "grep -q -i '%s' /tmp/test_103_email_report_admin_file 2>&1"
                        % str))

        # restore
        uvmContext.adminManager().setSettings(orig_adminsettings)

        # remove apps that were installed above
        for a in apps:
            uvmContext.appManager().destroy(a.getAppSettings()["id"])

        assert (email_found)
        for result in results:
            assert (result == 0)
Пример #47
0
 def test_000_client_is_online(self):
     """test the client is online"""
     result = remote_control.is_online()
     assert result == 0
Пример #48
0
 def test_010_clientIsOnline(self):
     result = remote_control.is_online()
     assert (result == 0)
Пример #49
0
 def test_010_clientIsOnline(self):
     """
     Verify client is online
     """
     result = remote_control.is_online()
     assert (result == 0)