Ejemplo n.º 1
0
 def __init__(self):
     """
     Initialize sessionManager util.
     """
     self._session_stub = SessionProxyResponderStub(
         get_rpc_channel("sessiond"))
     self._directorydstub = GatewayDirectoryServiceStub(
         get_rpc_channel("directoryd"))
Ejemplo n.º 2
0
def main():
    service = MagmaService('policydb', mconfigs_pb2.PolicyDB())

    apn_rules_dict = ApnRuleAssignmentsDict()
    assignments_dict = RuleAssignmentsDict()
    basenames_dict = BaseNameDict()
    rating_groups_dict = RatingGroupsDict()
    sessiond_chan = ServiceRegistry.get_rpc_channel('sessiond',
                                                    ServiceRegistry.LOCAL)
    session_mgr_stub = LocalSessionManagerStub(sessiond_chan)
    sessiond_stub = SessionProxyResponderStub(sessiond_chan)
    reauth_handler = ReAuthHandler(assignments_dict, sessiond_stub)

    # Add all servicers to the server
    session_servicer = SessionRpcServicer(service.mconfig,
                                          rating_groups_dict,
                                          basenames_dict,
                                          apn_rules_dict)
    session_servicer.add_to_server(service.rpc_server)

    orc8r_chan = ServiceRegistry.get_rpc_channel('policydb',
                                                 ServiceRegistry.CLOUD)
    policy_stub = PolicyAssignmentControllerStub(orc8r_chan)
    policy_servicer = PolicyRpcServicer(reauth_handler, basenames_dict,
                                        policy_stub)
    policy_servicer.add_to_server(service.rpc_server)

    # Start a background thread to stream updates from the cloud
    if service.config['enable_streaming']:
        stream = StreamerClient(
            {
                'policydb': PolicyDBStreamerCallback(),
                'apn_rule_mappings': ApnRuleMappingsStreamerCallback(
                    session_mgr_stub,
                    basenames_dict,
                    apn_rules_dict,
                ),
                'rule_mappings': RuleMappingsStreamerCallback(
                    reauth_handler,
                    basenames_dict,
                    assignments_dict,
                    apn_rules_dict,
                ),
                'rating_groups': RatingGroupsStreamerCallback(
                    rating_groups_dict),

            },
            service.loop,
        )
        stream.start()
    else:
        logging.info('enable_streaming set to False. Streamer disabled!')

    # Run the service loop
    service.run()

    # Cleanup the service
    service.close()
Ejemplo n.º 3
0
class SessionManagerUtil(object):
    """
    Helper class to communicate with session manager for the tests.
    """
    def __init__(self):
        """
        Initialize sessionManager util.
        """
        self._session_stub = SessionProxyResponderStub(
            get_rpc_channel("sessiond"))
        self._abort_session_stub = AbortSessionResponderStub(
            get_rpc_channel("abort_session_service"))
        self._directorydstub = GatewayDirectoryServiceStub(
            get_rpc_channel("directoryd"))

    def get_flow_match(self, flow_list, flow_match_list):
        """
        Populates flow match list
        """
        for flow in flow_list:
            flow_direction = flow["direction"]
            ip_protocol = flow["ip_proto"]
            if ip_protocol == FlowMatch.IPPROTO_TCP:
                udp_src_port = 0
                udp_dst_port = 0
                tcp_src_port = (int(flow["tcp_src_port"])
                                if "tcp_src_port" in flow else 0)
                tcp_dst_port = (int(flow["tcp_dst_port"])
                                if "tcp_dst_port" in flow else 0)
            elif ip_protocol == FlowMatch.IPPROTO_UDP:
                tcp_src_port = 0
                tcp_dst_port = 0
                udp_src_port = (int(flow["udp_src_port"])
                                if "udp_src_port" in flow else 0)
                udp_dst_port = (int(flow["udp_dst_port"])
                                if "udp_dst_port" in flow else 0)
            else:
                udp_src_port = 0
                udp_dst_port = 0
                tcp_src_port = 0
                tcp_dst_port = 0

            src_addr = None
            if flow.get("ipv4_src", None):
                src_addr = IPAddress(
                    version=IPAddress.IPV4,
                    address=flow.get("ipv4_src").encode('utf-8'))
            elif flow.get("ipv6_src", None):
                src_addr = IPAddress(
                    version=IPAddress.IPV6,
                    address=flow.get("ipv6_src").encode('utf-8'))

            dst_addr = None
            if flow.get("ipv4_dst", None):
                dst_addr = IPAddress(
                    version=IPAddress.IPV4,
                    address=flow.get("ipv4_dst").encode('utf-8'))
            elif flow.get("ipv6_dst", None):
                dst_addr = IPAddress(
                    version=IPAddress.IPV6,
                    address=flow.get("ipv6_dst").encode('utf-8'))

            flow_match_list.append(
                FlowDescription(
                    match=FlowMatch(
                        ip_dst=dst_addr,
                        ip_src=src_addr,
                        tcp_src=tcp_src_port,
                        tcp_dst=tcp_dst_port,
                        udp_src=udp_src_port,
                        udp_dst=udp_dst_port,
                        ip_proto=ip_protocol,
                        direction=flow_direction,
                    ),
                    action=FlowDescription.PERMIT,
                ))

    def create_ReAuthRequest(self, imsi, policy_id, flow_list, qos):
        """
        Sends Policy RAR message to session manager
        """
        print("Sending Policy RAR message to session manager")
        flow_match_list = []
        res = None
        self.get_flow_match(flow_list, flow_match_list)

        policy_qos = FlowQos(
            qci=qos["qci"],
            max_req_bw_ul=qos["max_req_bw_ul"],
            max_req_bw_dl=qos["max_req_bw_dl"],
            gbr_ul=qos["gbr_ul"],
            gbr_dl=qos["gbr_dl"],
            arp=QosArp(
                priority_level=qos["arp_prio"],
                pre_capability=qos["pre_cap"],
                pre_vulnerability=qos["pre_vul"],
            ),
        )

        policy_rule = PolicyRule(
            id=policy_id,
            priority=qos["priority"],
            flow_list=flow_match_list,
            tracking_type=PolicyRule.NO_TRACKING,
            rating_group=1,
            monitoring_key=None,
            qos=policy_qos,
        )

        qos = QoSInformation(qci=qos["qci"])

        # Get sessionid
        req = GetDirectoryFieldRequest(id=imsi, field_key="session_id")
        try:
            res = self._directorydstub.GetDirectoryField(
                req, DEFAULT_GRPC_TIMEOUT)
        except grpc.RpcError as err:
            logging.error(
                "GetDirectoryFieldRequest error for id: %s! [%s] %s",
                imsi,
                err.code(),
                err.details(),
            )

        self._session_stub.PolicyReAuth(
            PolicyReAuthRequest(
                session_id=res.value,
                imsi=imsi,
                rules_to_remove=[],
                rules_to_install=[],
                dynamic_rules_to_install=[
                    DynamicRuleInstall(policy_rule=policy_rule)
                ],
                event_triggers=[],
                revalidation_time=None,
                usage_monitoring_credits=[],
                qos_info=qos,
            ))

    def create_AbortSessionRequest(self, imsi: str) -> AbortSessionResult:
        # Get SessionID
        req = GetDirectoryFieldRequest(id=imsi, field_key="session_id")
        try:
            res = self._directorydstub.GetDirectoryField(
                req, DEFAULT_GRPC_TIMEOUT)
        except grpc.RpcError as err:
            logging.error(
                "GetDirectoryFieldRequest error for id: %s! [%s] %s",
                imsi,
                err.code(),
                err.details(),
            )
        return self._abort_session_stub.AbortSession(
            AbortSessionRequest(
                session_id=res.value,
                user_name=imsi,
            ))
Ejemplo n.º 4
0
def send_policy_rar(client, args):
    sessiond_chan = ServiceRegistry.get_rpc_channel("sessiond", ServiceRegistry.LOCAL)
    sessiond_client = SessionProxyResponderStub(sessiond_chan)
    flow_list_str = args.flow_rules.split(";")
    flow_match_list = []
    for i, flow_str in enumerate(flow_list_str):
        print("%d: %s" % (i, flow_str))
        flow_fields = flow_str.split(",")
        if flow_fields[0] == "UL":
            flow_direction = FlowMatch.UPLINK
        elif flow_fields[0] == "DL":
            flow_direction = FlowMatch.DOWNLINK
        else:
            print("%s is not valid" % flow_fields[0])
            raise ValueError(
                "UL or DL are the only valid"
                " values for first parameter of flow match"
            )
        ip_protocol = int(flow_fields[1])
        if flow_fields[1] == FlowMatch.IPPROTO_TCP:
            udp_src_port = 0
            udp_dst_port = 0
            if flow_fields[3]:
                tcp_src_port = int(flow_fields[3])
            else:
                tcp_src_port = 0
            if flow_fields[5]:
                tcp_dst_port = int(flow_fields[5])
            else:
                tcp_dst_port = 0
        elif flow_fields[1] == FlowMatch.IPPROTO_UDP:
            tcp_src_port = 0
            tcp_dst_port = 0
            if flow_fields[3]:
                udp_src_port = int(flow_fields[3])
            else:
                udp_src_port = 0
            if flow_fields[5]:
                udp_dst_port = int(flow_fields[5])
            else:
                udp_dst_port = 0
        else:
            udp_src_port = 0
            udp_dst_port = 0
            tcp_src_port = 0
            tcp_dst_port = 0

        flow_match_list.append(
            FlowDescription(
                match=FlowMatch(
                    direction=flow_direction,
                    ip_proto=ip_protocol,
                    ipv4_src=flow_fields[2],
                    ipv4_dst=flow_fields[4],
                    tcp_src=tcp_src_port,
                    tcp_dst=tcp_dst_port,
                    udp_src=udp_src_port,
                    udp_dst=udp_dst_port,
                ),
                action=FlowDescription.PERMIT,
            )
        )

    qos_parameter_list = args.qos.split(",")
    if len(qos_parameter_list) == 7:
        # utilize user passed arguments
        policy_qos = FlowQos(
            qci=int(args.qci),
            max_req_bw_ul=int(qos_parameter_list[0]),
            max_req_bw_dl=int(qos_parameter_list[1]),
            gbr_ul=int(qos_parameter_list[2]),
            gbr_dl=int(qos_parameter_list[3]),
            arp=QosArp(
                priority_level=int(qos_parameter_list[4]),
                pre_capability=int(qos_parameter_list[5]),
                pre_vulnerability=int(qos_parameter_list[6]),
            ),
        )
    else:
        # parameter missing, use default values
        policy_qos = FlowQos(
            qci=int(args.qci),
            max_req_bw_ul=100000,
            max_req_bw_dl=100000,
            arp=QosArp(priority_level=1, pre_capability=1, pre_vulnerability=0),
        )

    policy_rule = PolicyRule(
        id=args.policy_id,
        priority=int(args.priority),
        flow_list=flow_match_list,
        tracking_type=PolicyRule.NO_TRACKING,
        rating_group=1,
        monitoring_key=None,
        qos=policy_qos,
    )

    qos = QoSInformation(qci=int(args.qci))

    reauth_result = sessiond_client.PolicyReAuth(
        PolicyReAuthRequest(
            session_id=args.session_id,
            imsi=args.imsi,
            rules_to_remove=[],
            rules_to_install=[],
            dynamic_rules_to_install=[DynamicRuleInstall(policy_rule=policy_rule)],
            event_triggers=[],
            revalidation_time=None,
            usage_monitoring_credits=[],
            qos_info=qos,
        )
    )
    print(reauth_result)