Beispiel #1
0
def send_connection_request(request, con_req, con_req_dict):
    """
    Sends the connection request to SCION Coordination Service.
    :param HttpRequest request: Django HTTP request passed on through urls.py.
    :param con_req: Database object of the connection request.
    :param con_req_dict: Connection request dictionary to be sent.
    :returns: Tuple containing the response and a Django HTTP error response.
    :rtype: (requests.Response, django.http.HttpResponse)
    """
    # get the account_id and secret necessary to query SCION-coord
    coord = get_object_or_404(OrganisationAdmin, user_id=request.user.id)
    logger.info("Sending Connection Request: %s", con_req_dict)
    con_req_id = con_req_dict['RequestId']
    # upload the request to scion-coord
    request_url = urljoin(COORD_SERVICE_URI, posixpath.join(
                          UPLOAD_CONN_REQUEST_SVC, coord.account_id,
                          coord.secret))
    resp, error = post_req_to_scion_coord(request_url, con_req_dict,
                                          "connection request %s" % con_req_id)
    if error:
        return None, error
    logging.info("Connection request %s successfully sent.", con_req_id)
    # set the status of the connection request to SENT
    con_req.status = REQ_SENT
    con_req.save()
    return resp, None
Beispiel #2
0
def send_join_reply(request, status, isd_as, request_id):
    """
    Accepts or declines the join request. In case of accept, it assigns a new
    AS ID to the requesting party and creates the certificate. This function
    is only executed by a core AS.
    """
    current_page = request.META.get('HTTP_REFERER')
    coord = get_object_or_404(OrganisationAdmin, user_id=request.user.id)
    own_isdas = TopoID(isd_as)
    own_as_obj = AD.objects.get(as_id=own_isdas[1], isd=own_isdas[0])
    if not own_as_obj.is_core_ad:
        logging.error("%s has to be a core AS to send join reply" % own_as_obj)
        return redirect(current_page)
    join_rep_dict = {
        'RequestId': int(request_id),
        'Status': status,
        'RespondIA': str(own_isdas),
        'RequesterId': request.POST['requester']
    }
    if status == REQ_APPROVED:
        prep_approved_join_reply(request, join_rep_dict, own_isdas, own_as_obj)
    else:
        logger.debug("Declining Join Request = %s", join_rep_dict)
    request_url = urljoin(COORD_SERVICE_URI, posixpath.join(
                          UPLOAD_JOIN_REPLY_SVC, coord.account_id,
                          coord.secret))
    _, error = post_req_to_scion_coord(request_url, join_rep_dict,
                                       "join reply %s" % request_id)
    if error:
        return error
    return redirect(current_page)
Beispiel #3
0
def poll_join_reply(request):
    """
    Polls the join replies from SCION Coordination Service.
    :param HttpRequest request: Django Http Request passed on via the urls.py
    :returns: HTTP Response returned to the user.
    :rtype: HttpResponse
    """
    current_page = request.META.get('HTTP_REFERER')
    try:
        coord = OrganisationAdmin.objects.get(user_id=request.user.id)
    except OrganisationAdmin.DoesNotExist:
        logger.error("Retrieving account_id and secret failed.")
        return redirect(current_page)
    open_join_requests = JoinRequest.objects.filter(status=REQ_SENT)
    for req in open_join_requests:
        jr_id = req.id
        logger.info('Pending request = %s', jr_id)
        request_url = urljoin(COORD_SERVICE_URI, posixpath.join(
                              POLL_JOIN_REPLY_SVC, coord.account_id,
                              coord.secret))
        logger.info('url = %s' % request_url)
        r, error = post_req_to_scion_coord(request_url, {'request_id': jr_id},
                                           "poll join reply %s" % jr_id)
        if error:
            return error
        handle_join_reply(request, r, jr_id)
    return redirect(current_page)
Beispiel #4
0
def request_join_isd(request):
    """
    Sends the join request to SCION Coordination Service.
    :param HttpRequest request: Django HTTP request passed on through urls.py.
    :returns: Django HTTP Response object.
    :rtype: HttpResponse.
    """
    current_page = request.META.get('HTTP_REFERER')
    # check the validity of parameters
    if not request.POST["inputISDToJoin"].isdigit():
        messages.error(request, 'ISD to join has to be a number!')
        return redirect(current_page)
    isd_to_join = int(request.POST["inputISDToJoin"])
    join_as_a_core = request.POST["inputJoinAsACore"]
    # get the account_id and secret necessary to query SCION-coord.
    coord = get_object_or_404(OrganisationAdmin, user_id=request.user.id)
    # generate the sign and encryption keys
    public_key_sign, private_key_sign = generate_sign_keypair()
    public_key_encr, private_key_encr = generate_enc_keypair()
    join_req = JoinRequest.objects.create(
        created_by=request.user,
        isd_to_join=isd_to_join,
        join_as_a_core=join_as_a_core.lower() == "true",
        sig_pub_key=to_b64(public_key_sign),
        sig_priv_key=to_b64(private_key_sign),
        enc_pub_key=to_b64(public_key_encr),
        enc_priv_key=to_b64(private_key_encr))
    join_req_dict = {
        "RequestId": join_req.id,
        "IsdToJoin": isd_to_join,
        "JoinAsACoreAS": join_req.join_as_a_core,
        "SigPubKey": to_b64(public_key_sign),
        "EncPubKey": to_b64(public_key_encr)
    }
    request_url = urljoin(
        COORD_SERVICE_URI,
        posixpath.join(UPLOAD_JOIN_REQUEST_SVC, coord.account_id,
                       coord.secret))
    _, error = post_req_to_scion_coord(request_url, join_req_dict,
                                       "join request %s" % join_req.id)
    if error:
        return error
    logger.info("Request = %s, Join Request Dict = %s", request_url,
                join_req_dict)
    join_req.status = REQ_SENT
    join_req.save()
    messages.success(
        request, 'Join Request Submitted Successfully.'
        ' Request ID = %s' % join_req.id)
    return redirect(current_page)
Beispiel #5
0
def request_join_isd(request):
    """
    Sends the join request to SCION Coordination Service.
    :param HttpRequest request: Django HTTP request passed on through urls.py.
    :returns: Django HTTP Response object.
    :rtype: HttpResponse.
    """
    current_page = request.META.get('HTTP_REFERER')
    # check the validity of parameters
    if not request.POST["inputISDToJoin"].isdigit():
        messages.error(request, 'ISD to join has to be a number!')
        return redirect(current_page)
    isd_to_join = int(request.POST["inputISDToJoin"])
    join_as_a_core = request.POST["inputJoinAsACore"]
    # get the account_id and secret necessary to query SCION-coord.
    coord = get_object_or_404(OrganisationAdmin, user_id=request.user.id)
    # generate the sign and encryption keys
    public_key_sign, private_key_sign = generate_sign_keypair()
    public_key_encr, private_key_encr = generate_enc_keypair()
    join_req = JoinRequest.objects.create(
        created_by=request.user,
        isd_to_join=isd_to_join,
        join_as_a_core=join_as_a_core.lower() == "true",
        sig_pub_key=to_b64(public_key_sign),
        sig_priv_key=to_b64(private_key_sign),
        enc_pub_key=to_b64(public_key_encr),
        enc_priv_key=to_b64(private_key_encr)
    )
    join_req_dict = {
        "RequestId": join_req.id,
        "IsdToJoin": isd_to_join,
        "JoinAsACoreAS": join_req.join_as_a_core,
        "SigPubKey": to_b64(public_key_sign),
        "EncPubKey": to_b64(public_key_encr)
    }
    request_url = urljoin(COORD_SERVICE_URI, posixpath.join(
                          UPLOAD_JOIN_REQUEST_SVC, coord.account_id,
                          coord.secret))
    _, error = post_req_to_scion_coord(request_url, join_req_dict,
                                       "join request %s" % join_req.id)
    if error:
        return error
    logger.info("Request = %s, Join Request Dict = %s", request_url,
                join_req_dict)
    join_req.status = REQ_SENT
    join_req.save()
    messages.success(request, 'Join Request Submitted Successfully.'
                     ' Request ID = %s' % join_req.id)
    return redirect(current_page)
Beispiel #6
0
def send_connection_reply(request, con_req_id, status, respond_as, data):
    """
    Sends connection reply to SCION Coordination Service.
    :param HttpRequest request: Django HTTP Request.
    :param str con_req_id: The ID of the connection request to be replied to.
    :param str status: The status of the the request. (e.g APPROVED)
    :param str respond_as: The AS responding to the connection request.
    :param dict data: Dictionary object containing the reply parameters.
    """
    coord = get_object_or_404(OrganisationAdmin,
                              user_id=request.user.id)
    con_rep_dict = {
        "RequestId": int(con_req_id),
        "Status": status,
        "RequestIA": data['RequestIA'],
        "RespondIA": str(respond_as)
    }
    if status == REQ_APPROVED:
        router_info = data['router_info']
        overlay_type = data['accepted_overlay_type']
        con_rep_dict["IP"] = router_info.split(':')[0]
        if "UDP" in overlay_type:
            con_rep_dict["Port"] = int(router_info.split(':')[1])
        con_rep_dict["OverlayType"] = overlay_type
        con_rep_dict["MTU"] = int(data['accepted_mtu'])
        con_rep_dict["Bandwidth"] = int(data['accepted_bandwidth'])
        cert_chain = CertificateChain.from_raw(respond_as.certificate)
        con_rep_dict["Certificate"] = cert_chain.to_json()
    request_url = urljoin(COORD_SERVICE_URI, posixpath.join(
                          UPLOAD_CONN_REPLY_SVC, coord.account_id,
                          coord.secret))
    _, error = post_req_to_scion_coord(request_url, con_rep_dict,
                                       "connection reply %s" % con_req_id)
    if error:
        return error
    logging.info("Connection reply %s successfully sent.",
                 con_rep_dict['RequestId'])
Beispiel #7
0
    def get_context_data(self, **kwargs):
        """
        Populate 'context' dictionary with the required objects
        """
        context = super().get_context_data(**kwargs)
        ad = context['object']

        # Status tab
        context['services'] = ad.service_set.select_related()
        context['service_addrs'] = ad.serviceaddress_set.select_related()
        context['border_routers'] = ad.borderrouter_set.select_related()
        context['router_addrs'] = ad.borderrouteraddress_set.select_related()
        context['interface_addrs'] = ad.borderrouterinterface_set.select_related()

        context['management_interface_ip'] = get_own_local_ip()
        flat_string = json.dumps(ad.original_topology, sort_keys=True)
        context['reloaded_topology'] = json.loads(flat_string)
        # hash for non cryptographic purpose (state comparison for user warning)
        context['reloaded_topology_hash'] = \
            hashlib.md5(flat_string.encode('utf-8')).hexdigest()
        context['as_id'] = ad.as_id
        context['isd_id'] = ad.isd_id
        context['as_id_str'] = ad.as_id_str

        # Sort by name numerically
        for list_name in ['services', 'border_routers']:
            context[list_name] = sorted(
                context[list_name],
                key=lambda el: el.name if el.name is not None else -1
            )
        # Sort by address numerically
        for list_name in ['service_addrs', 'router_addrs', 'interface_addrs']:
            context[list_name] = sorted(
                context[list_name],
                key=lambda el: el.addr if el.addr is not None else -1
            )
        # Permissions
        context['user_has_perm'] = self.request.user.has_perm('change_ad', ad)
        # Connection requests tab
        context['join_requests'] = {}
        context['received_requests'] = {}
        context['received_conn_replies'] = {}
        try:
            coord = OrganisationAdmin.objects.get(user_id=self.request.user.id)
        except OrganisationAdmin.DoesNotExist:
            logger.error("Retrieving account_id and secret failed!!.")
            return context
        request_url = urljoin(COORD_SERVICE_URI, posixpath.join(
                              POLL_EVENTS_SVC, coord.account_id, coord.secret))
        logger.info("Polling Events for %s", context['isdas'])
        r, error = post_req_to_scion_coord(
            request_url, {'IsdAs': context['isdas']},
            "poll events for ISD-AS %s" % context['isdas'])
        if error:
            messages.error(self.request, 'Could not poll events from SCION '
                           'Coordination Service!')
            return context
        resp = r.json()
        context['join_requests'] = resp['JoinRequests']
        context['received_requests'] = resp['ConnRequests']
        context['received_conn_replies'] = resp['ConnReplies']
        return context