Beispiel #1
0
    def from_values(cls, subject, subject_sig_key, subject_enc_key, issuer,
                    iss_priv_key, version):
        """
        Generate a Certificate instance.

        :param str subject:
            the certificate subject. It can either be an AS, an email address or
            a domain address.
        :param bytes subject_sig_key: the public key of the subject.
        :param bytes subject_enc_key: the public part of the encryption key.
        :param str issuer: the certificate issuer. It can only be an AS.
        :param bytes iss_priv_key:
            the issuer's private key. It is used to sign the certificate.
        :param int version: the certificate version.
        :returns: the newly created Certificate instance.
        :rtype: :class:`Certificate`
        """
        cert = Certificate()
        cert.subject = subject
        cert.subject_sig_key = subject_sig_key
        cert.subject_enc_key = subject_enc_key
        cert.issuer = issuer
        cert.version = version
        cert.issuing_time = int(time.time())
        cert.expiration_time = cert.issuing_time + Certificate.VALIDITY_PERIOD
        cert.sign_algorithm = Certificate.SIGN_ALGORITHM
        cert.encryption_algorithm = Certificate.ENCRYPT_ALGORITHM
        data_to_sign = cert.__str__(with_signature=False)
        data_to_sign = data_to_sign.encode('utf-8')
        cert.signature = sign(data_to_sign, iss_priv_key)
        return cert
Beispiel #2
0
def get_drkey_reply(sv, src_ia, dst_ia, priv_key, signing_key, cert_ver,
                    dst_cert, trc_ver):
    """
    Generate a DRKeyReply. The Reply is signed with the signing key.
    The contained drkey is encrypted using the public key of the
    destination certificate.

    :param DRKeySecretValue sv: the local secret value used to derive the DRKey.
    :param ISD_AS src_ia: the local ISD-AS address.
    :param ISD_AS dst_ia: the ISD-AS for which the DRKey is computed.
    :param PrivateKey priv_key: local private key.
    :param SigningKey signing_key: local signing key.
    :param int cert_ver: version of the certificate, priv_key and signing_key are associated with.
    :param Certificate dst_cert: the certificated of the destination ISD-AS.
    :param int trc_ver: version of trc associated with cert_ver.
    :returns: the resulting DRKeyReply
    :rtype: DRKeyReply
    """
    drkey = derive_drkey_raw(sv, dst_ia)
    cipher = bytes(
        encrypt(drkey, priv_key, PublicKey(dst_cert.subject_enc_key_raw)))
    timestamp = drkey_time()
    signature = sign(
        get_signing_input_rep(src_ia, timestamp, sv.exp_time, cipher),
        signing_key)
    return DRKeyReply.from_values(src_ia, timestamp, sv.exp_time, cipher,
                                  signature, cert_ver, dst_cert.version,
                                  trc_ver)
Beispiel #3
0
 def _sign_trc(self, topo_id, as_conf):
     if not as_conf.get('core', False):
         return
     trc = self.trcs[topo_id[0]]
     trc_str = trc.to_json(with_signatures=False).encode('utf-8')
     trc.signatures[str(topo_id)] = sign(trc_str,
                                         self.sig_priv_keys[topo_id])
Beispiel #4
0
    def sign(self, isd_as, sig_priv_key):
        """
        Sign TRC and add computed signature to the TRC.

        :param ISD_AS isd_as: the ISD-AS of signer.
        :param SigningKey sig_priv_key: the signing key of signer.
        """
        data = self._sig_input()
        self.signatures[str(isd_as)] = sign(data, sig_priv_key)
Beispiel #5
0
 def sign(self, key, msg):
     assert isinstance(msg, bytes), type(msg)
     if len(msg) == 0:
         raise ProtoSignError("Message is empty (sign)")
     if len(self.p.signature) > 0:
         raise ProtoSignError("Signature already present")
     if self.p.type == ProtoSignType.ED25519:
         self.p.signature = sign(self._sig_input(msg), key)
     else:
         raise ProtoSignError("Unsupported proto signature type (sign): %s" % self.p.type)
 def _create_ad_marking(self):
     """
     Create an AD Marking with the given ingress and egress interfaces.
     """
     hof = HopOpaqueField.from_values(1, 111, 222)
     rev_token = HashChain(Random.new().read(32)).next_element()
     pcbm = PCBMarking.from_values(1, 10, hof)
     peer_markings = []
     signing_key = read_file(get_sig_key_file_path(1, 10))
     signing_key = base64.b64decode(signing_key)
     data_to_sign = (b'11' + pcbm.hof.pack())
     signature = sign(data_to_sign, signing_key)
     return ADMarking.from_values(pcbm, peer_markings, rev_token, signature)
Beispiel #7
0
def get_drkey_request(dst_ia, prefetch, signing_key, cert_ver, trc_ver):
    """
    Generate a DRKeyRequest. The Request is signed with the signing key of the
    specified certificate.

    :param ISD_AS dst_ia: destination of the DRKey request.
    :param Bool prefetch: indicator if prefetch (True) or not (False).
    :param SigningKey signing_key: the signing key
    :param int cert_ver: version of the certificate associated with singing key
    :param int trc_ver: version of the trc associated with the certificate.
    :returns: the signed DRKeyRequest.
    :rtype: DRKeyRequest
    """
    timestamp = drkey_time()
    signature = sign(drkey_signing_input_req(dst_ia, prefetch, timestamp),
                     signing_key)
    return DRKeyRequest.from_values(prefetch, dst_ia, timestamp, signature,
                                    cert_ver, trc_ver)
Beispiel #8
0
def solve_challenge(challenge):
    """
    The parameter challenge comes in binary already
    """
    global IA
    # 1) get the location of the certificates and keys
    SC = os.environ["SC"] if "SC" in os.environ else os.path.join(
        str(pathlib.Path.home()), "go", "src", "github.com", "scionproto",
        "scion")
    SC = os.path.join(SC, "gen")
    m = re.match("^([0-9]+)-([0-9]+)$", IA)
    if not m:
        print("ERROR: could not understand the IA from: ", IA)
        sys.exit(1)
    I = m.group(1)
    A = m.group(2)
    filepath = os.path.join(SC, "ISD" + I, "AS" + A, "bs" + I + "-" + A + "-1")
    privkey = os.path.join(filepath, "keys")
    if not os.path.exists(privkey):
        print("ERROR: no such path: ", privkey)
        sys.exit(1)
    privkeys = [
        k for k in sorted(os.listdir(privkey), reverse=True)
        if k.endswith(".seed")
    ]
    if len(privkeys) < 1:
        print("ERROR: could not find a private key under ", privkey)
        sys.exit(1)
    privkey = os.path.join(privkey, privkeys[0])
    try:
        with open(privkey) as f:
            privkey = f.read()
    except Exception as ex:
        print("ERROR: could not read file %s: %s" % (privkey, ex))
        sys.exit(1)
    privkey = base64.standard_b64decode(privkey)

    # 2) instantiate the private key and certificate and sign the challenge
    signed = sign(challenge, privkey)
    return signed
Beispiel #9
0
 def sign(self, key, set_=True):  # pragma: no cover
     assert not self.p.asms[-1].sig
     sig = sign(self.sig_pack(3), key)
     if set_:
         self.p.asms[-1].sig = sig
     return sig
Beispiel #10
0
 def sign(self, isd_as, sig_priv_key):
     data = self._sig_input()
     self.signatures[isd_as] = sign(data, sig_priv_key)
Beispiel #11
0
 def sign(self, key, set_=True):  # pragma: no cover
     sig = sign(self.sig_pack3(), key)
     if set_:
         self.p.asms[-1].sig = sig
     return sig
Beispiel #12
0
 def sign(self, isd_as, sig_priv_key):
     data = self._sig_input()
     self.signatures[isd_as] = base64.b64encode(sign(data, sig_priv_key)). \
         decode('utf-8')
Beispiel #13
0
 def sign(self, iss_priv_key):
     data = self._sig_input()
     self.signature_raw = sign(data, iss_priv_key)
     self.signature = base64.b64encode(self.signature_raw).decode('utf-8')
Beispiel #14
0
 def sign(self, privkey):
     inst = copy.copy(self)
     inst.signature = b""
     self.signature = sign(inst.pack(), privkey)
Beispiel #15
0
    def test(self):
        """
        Create a certificate chain and verify it with a TRC file. Sign a message
        with the private key of the last certificate in the chain and verify it.
        """
        cert10 = CertificateChain(get_cert_chain_file_path(1, 10, 1, 10, 0))
        trc = TRC(get_trc_file_path(1, 10, 1, 0))
        print('TRC verification', trc.verify())
        print('Cert Chain verification:', cert10.verify('ISD:1-AD:10', trc, 0))

        sig_priv10 = read_file(get_sig_key_file_path(1, 10))
        sig_priv10 = base64.b64decode(sig_priv10)
        msg = b'abcd'
        sig = sign(msg, sig_priv10)
        print('Sig test:', verify_sig_chain_trc(msg, sig, 'ISD:1-AD:10', cert10,
                                                trc, 0))

        sig_priv13 = read_file(get_sig_key_file_path(1, 13))
        sig_priv13 = base64.b64decode(sig_priv13)
        msg = b'abd'
        sig = sign(msg, sig_priv13)
        CertificateChain.from_values([])
        print('Sig test 2:', verify_sig_chain_trc(msg, sig, 'ISD:1-AD:13',
                                                  cert10, trc, 0), '\n')

        topology = Topology.from_file(
            "topology/ISD1/topologies/ISD:1-AD:10.json")
        src_addr = SCIONAddr.from_values(topology.isd_id, topology.ad_id,
                                         IPv4Address("127.0.0.1"))
        dst_addr = topology.certificate_servers[0].addr
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.bind((str(src_addr.host_addr), SCION_UDP_PORT))

        print("Sending TRC request (ISD:1-V:0) to local CS.")
        msg = TRCRequest.from_values(
            PT.TRC_REQ_LOCAL, src_addr,
            topology.parent_border_routers[0].interface.if_id,
            topology.isd_id, topology.ad_id, 1, 0).pack()
        sock.sendto(msg, (str(dst_addr), SCION_UDP_PORT))

        temp_file = './temp.txt'
        timeout = 5

        ready = select.select([sock], [], [], timeout)
        if not ready[0]:
            print("Error: no TRC reply was received!")
            sock.close()
            return

        data, _ = sock.recvfrom(SCION_BUFLEN)
        print("Received TRC reply from local CS.")
        trc_reply = TRCReply(data)
        write_file(temp_file, trc_reply.trc.decode('utf-8'))
        trc = TRC(temp_file)
        assert trc.verify()

        print("Sending cert chain request (ISD:1-AD:16-V:0) to local CS.")
        msg = CertChainRequest.from_values(
            PT.CERT_CHAIN_REQ_LOCAL, src_addr,
            topology.parent_border_routers[0].interface.if_id,
            topology.isd_id, topology.ad_id, 1, 16, 0).pack()
        sock.sendto(msg, (str(dst_addr), SCION_UDP_PORT))

        ready = select.select([sock], [], [], timeout)
        if not ready[0]:
            print("Error: no cert chain reply was received!")
            sock.close()
            return

        data, _ = sock.recvfrom(SCION_BUFLEN)
        print("Received cert chain reply from local CS.")
        cert_chain_reply = CertChainReply(data)
        write_file(temp_file, cert_chain_reply.cert_chain.decode('utf-8'))
        cert_chain = CertificateChain(temp_file)
        assert cert_chain.verify('ISD:1-AD:16', trc, 0)

        os.remove(temp_file)
        sock.close()