Beispiel #1
0
def add_rule(args):
    rule_id = args.rule_id
    policy_dict = PolicyRuleDict()
    arg_list = {
        'ip_proto':
        args.ip_proto,
        'ip_dst':
        IPAddress(version=IPAddress.IPV4,
                  address=args.ipv4_dst.encode('utf-8')),
        'ip_src':
        IPAddress(version=IPAddress.IPV4,
                  address=args.ipv4_src.encode('utf-8')),
        'tcp_dst':
        args.tcp_dst,
        'tcp_src':
        args.tcp_src,
        'udp_dst':
        args.udp_dst,
        'udp_src':
        args.udp_src,
        'direction':
        args.direction
    }
    match = FlowMatch(**arg_list)
    flow = FlowDescription(match=match, action=args.action)
    rule = policy_dict.get(rule_id)
    if not rule or args.overwrite:
        action = 'add'
        rule = PolicyRule(id=rule_id, flow_list=[flow])
    else:
        action = 'edit'
        rule.flow_list.extend([flow])
    policy_dict[rule_id] = rule
    print("Rule '%s' successfully %sed!" % (rule_id, action))
Beispiel #2
0
 def __init__(self, *args, **kwargs):
     super(PolicyMixin, self).__init__(*args, **kwargs)
     self._datapath = None
     self._policy_dict = PolicyRuleDict()
     self._rule_mapper = kwargs['rule_id_mapper']
     self._session_rule_version_mapper = kwargs[
         'session_rule_version_mapper']
Beispiel #3
0
 def __init__(self, *args, **kwargs):
     super(PolicyMixin, self).__init__(*args, **kwargs)
     self._datapath = None
     self._policy_dict = PolicyRuleDict()
     self._rule_mapper = kwargs['rule_id_mapper']
     self._session_rule_version_mapper = kwargs[
         'session_rule_version_mapper']
     self._relay_enabled = kwargs['mconfig'].relay_enabled
     if not self._relay_enabled:
         self.logger.info('Relay mode is not enabled, init finished')
         self.init_finished = True
Beispiel #4
0
 def __init__(self, *args, **kwargs):
     super(RestartMixin, self).__init__(*args, **kwargs)
     self._policy_dict = PolicyRuleDict()
     self._rule_mapper = kwargs['rule_id_mapper']
     self._session_rule_version_mapper = kwargs[
         'session_rule_version_mapper']
     if 'proxy' in kwargs['app_futures']:
         self.proxy_controller_fut = kwargs['app_futures']['proxy']
     else:
         self.proxy_controller_fut = None
     self.proxy_controller = None
Beispiel #5
0
class PolicyDBStreamerCallback(StreamerClient.Callback):
    """
    Callback implementation for the PolicyDB StreamerClient instance.
    """

    def __init__(self):
        self._policy_dict = PolicyRuleDict()

    def get_request_args(self, stream_name: str) -> Any:
        return None

    def process_update(self, stream_name, updates, resync):
        logging.info(
            "Processing %d policy updates (resync=%s)",
            len(updates), resync,
        )
        if resync:
            policy_ids = set()
            for update in updates:
                policy = PolicyRule()
                policy.ParseFromString(update.value)
                self._store_policy_rule(policy)
                policy_ids.add(policy.id)
            logging.debug("Resync with policies: %s", ','.join(policy_ids))
            self._remove_old_policies(policy_ids)
            self._policy_dict.send_update_notification()
        else:
            pass

    def _store_policy_rule(self, policy):
        self._policy_dict[policy.id] = policy

    def _remove_old_policies(self, id_set):
        """
        Scan the set of ids passes in the streaming update to see which have
        been deleted and delete them in the policy dictionary
        """
        missing_rules = set(self._policy_dict.keys()) - id_set
        for rule in missing_rules:
            del self._policy_dict[rule]
Beispiel #6
0
    def __init__(self, *args, **kwargs):
        super(EnforcementController, self).__init__(*args, **kwargs)
        self.tbl_num = self._service_manager.get_table_num(self.APP_NAME)
        self.next_table = self._service_manager.get_next_table_num(
            self.APP_NAME)
        self._datapath = None
        self._rule_mapper = kwargs['rule_id_mapper']
        self.loop = kwargs['loop']
        self._policy_dict = PolicyRuleDict()
        self._qos_map = QosQueueMap(kwargs['config']['nat_iface'],
                                    kwargs['config']['enodeb_iface'],
                                    kwargs['config']['enable_queue_pgm'])
        self._msg_hub = MessageHub(self.logger)

        self._redirect_manager = RedirectionManager(
            kwargs['config']['bridge_ip_address'], self.logger, self.tbl_num,
            self.next_table)
Beispiel #7
0
    def __init__(self):
        self.static_rules = PolicyRuleDict()

        # Local sessiond
        self.sessiond = session_manager_pb2_grpc.LocalSessionManagerStub(
            ServiceRegistry.get_rpc_channel("sessiond",
                                            ServiceRegistry.LOCAL), )

        self.proxy_responder = session_manager_pb2_grpc.SessionProxyResponderStub(
            ServiceRegistry.get_rpc_channel("sessiond",
                                            ServiceRegistry.LOCAL), )

        # Mock session controller server
        cloud_port = load_service_config("sessiond")["local_controller_port"]
        self.controller = MockSessionManager()
        self.server = grpc.server(ThreadPoolExecutor(max_workers=10))
        session_manager_pb2_grpc.add_CentralSessionControllerServicer_to_server(
            self.controller,
            self.server,
        )
        self.server.add_insecure_port('127.0.0.1:{}'.format(cloud_port))
        self.server.start()

        # Add new controller to bridge
        BridgeTools.add_controller_to_bridge(self.BRIDGE, self.CONTROLLER_PORT)

        # Start ryu test controller for adding flows
        testing_controller_reference = Future()
        test_setup = TestSetup(
            apps=[PipelinedController.Testing],
            references={
                PipelinedController.Testing: testing_controller_reference,
            },
            config={
                'bridge_name': self.BRIDGE,
                'bridge_ip_address': '192.168.128.1',
                'controller_port': self.CONTROLLER_PORT,
            },
            mconfig=None,
            loop=None,
            integ_test=True,
        )
        self.thread = start_ryu_app_thread(test_setup)
        self.testing_controller = testing_controller_reference.result()
Beispiel #8
0
 def __init__(self):
     self._policy_dict = PolicyRuleDict()
Beispiel #9
0
 def __init__(self, service_config):
     self._config = service_config
     self._rules = PolicyRuleDict()
Beispiel #10
0
def dump_data(_client: PolicyDBStub, args):
    """
    Dump data from Redis tables:
    - policydb:installed
    - policydb:apn_installed
    - policydb:basenames
    - policydb:rating_groups
    - policydb:rules
    and formats them to be more human readable.

    Args:
        _client: gRPC stub to interact with policydb
        args: Args CLI was called with
    Returns:
        None
    """
    apn_rules_dict = ApnRuleAssignmentsDict(clear_data=False)
    assignments_dict = RuleAssignmentsDict(clear_data=False)
    basenames_dict = BaseNameDict()
    rating_groups_dict = RatingGroupsDict()
    policy_dict = PolicyRuleDict()

    print('*' * 80)
    print("*" + "policydb:installed".center(78) + "*")
    print('*' * 80)
    for k, v in assignments_dict.items():
        formatted_val = textwrap.indent(text_format.MessageToString(v),
                                        " " * 4)
        print(f"{k}:\n{formatted_val}")
    print('\n')

    print('*' * 80)
    print("*" + "policydb:apn_installed".center(78) + "*")
    print('*' * 80)
    for k, v in apn_rules_dict.items():
        formatted_val = textwrap.indent(text_format.MessageToString(v),
                                        " " * 4)
        print(f"{k}:\n{formatted_val}")
    print('\n')

    print('*' * 80)
    print("*" + "policydb:basenames".center(78) + "*")
    print('*' * 80)
    for k, v in basenames_dict.items():
        formatted_val = textwrap.indent(text_format.MessageToString(v),
                                        " " * 4)
        print(f"{k}:\n{formatted_val}")
    print('\n')

    print('*' * 80)
    print("*" + "policydb:rating_groups".center(78) + "*")
    print('*' * 80)
    for k, v in rating_groups_dict.items():
        formatted_val = textwrap.indent(text_format.MessageToString(v),
                                        " " * 4)
        print(f"{k}:\n{formatted_val}")
    print('\n')

    print('*' * 80)
    print("*" + "policydb:rules".center(78) + "*")
    print('*' * 80)
    for k, v in policy_dict.items():
        formatted_val = textwrap.indent(text_format.MessageToString(v),
                                        " " * 4)
        print(f"{k}:\n{formatted_val}")
    print('\n')