Esempio n. 1
0
 def test_compute_key(self):
     a = EC.load_key(self.privkey)
     b = EC.gen_params(tested_curve[0])
     b.gen_key()
     ak = a.compute_dh_key(b.pub())
     bk = b.compute_dh_key(a.pub())
     self.assertEqual(ak, bk)
Esempio n. 2
0
    def __init__(self):
        """
        Initialize the s1aplibrary and its callbacks.
        """
        lib_path = os.environ["S1AP_TESTER_ROOT"]
        lib = os.path.join(lib_path, "bin", S1ApUtil.lib_name)
        os.chdir(lib_path)
        self._test_lib = ctypes.cdll.LoadLibrary(lib)
        self._callback_type = ctypes.CFUNCTYPE(None, ctypes.c_short,
                                               ctypes.c_void_p, ctypes.c_short)
        # Maintain a reference to the function object so GC doesn't release it.
        self._callback_fn = self._callback_type(S1ApUtil.s1ap_callback)
        self._test_lib.initTestFrameWork(self._callback_fn)
        self._test_api = self._test_lib.tfwApi
        self._test_api.restype = ctypes.c_int16
        self._test_api.argtypes = [ctypes.c_uint16, ctypes.c_void_p]

        # Mutex for state change operations
        self._lock = threading.RLock()

        # Maintain a map of UE IDs to IPs
        self._ue_ip_map = {}

        # added for brokerd utelco
        self.br_rsa_pub_key = RSA.load_pub_key(
            expanduser('~/key_files/br_rsa_pub.pem'))
        self.ue_ecdsa_pri_key = EC.load_key(
            expanduser('~/key_files/ue_ec_pri.pem'))
        self.ut_rsa_pub_key = RSA.load_pub_key(
            expanduser('~/key_files/ut_rsa_pub.pem'))
Esempio n. 3
0
 def test_compute_key(self):
     a = EC.load_key(self.privkey)
     b = EC.gen_params(EC.NID_sect233k1)
     b.gen_key()
     ak = a.compute_dh_key(b.pub())
     bk = b.compute_dh_key(a.pub())
     assert ak == bk
Esempio n. 4
0
def create_torrent_signature(metainfo,keypairfilename):
    keypair = EC.load_key(keypairfilename)
    bmetainfo = bencode(metainfo)
    digester = sha(bmetainfo[:])
    digest = digester.digest()
    sigstr = keypair.sign_dsa_asn1(digest)
    metainfo['signature'] = sigstr
    metainfo['signer'] = str(keypair.pub().get_der())
Esempio n. 5
0
 def _test_sign_dsa(self):
     ec = EC.gen_params(EC.NID_X9_62_prime256v1)
     # ec.gen_key()
     self.assertRaises(EC.ECError, ec.sign_dsa, self.data)
     ec = EC.load_key(self.privkey)
     r, s = ec.sign_dsa(self.data)
     assert ec.verify_dsa(self.data, r, s)
     assert not ec.verify_dsa(self.data, s, r)
Esempio n. 6
0
def create_torrent_signature(response, keypairfilename):
    keypair = EC.load_key(keypairfilename)
    bresponse = bencode(response)
    digester = sha(bresponse[:])
    digest = digester.digest()
    sigstr = keypair.sign_dsa_asn1(digest)
    response['signature'] = sigstr
    response['signer'] = str(keypair.pub().get_der())
Esempio n. 7
0
 def _test_sign_dsa(self):
     ec = EC.gen_params(tested_curve[0])
     # ec.gen_key()
     with self.assertRaises(EC.ECError):
         ec.sign_dsa(self.data)
     ec = EC.load_key(self.privkey)
     r, s = ec.sign_dsa(self.data)
     assert ec.verify_dsa(self.data, r, s)
     assert not ec.verify_dsa(self.data, s, r)
Esempio n. 8
0
 def __init__(self, s6a_proxy_stub: s6a_proxy_pb2_grpc.S6aProxyStub):
     logging.info("starting brokerd servicer")
     self._s6a_proxy_stub = s6a_proxy_stub
     key_dir = os.getenv('KEY_DIR', '/var/opt/magma/key_files')
     self.br_rsa_pri_key =  RSA.load_key(os.path.join(key_dir, 'br_rsa_pri.pem'))
     self.br_ecdsa_pri_key =  EC.load_key(os.path.join(key_dir, 'br_ec_pri.pem'))
     self.ue_rsa_pub_key = RSA.load_pub_key(os.path.join(key_dir, 'ue_rsa_pub.pem'))
     self.ue_ecdsa_pub_key = EC.load_pub_key(os.path.join(key_dir, 'ue_ec_pub.pem'))
     self.ut_rsa_pub_key = RSA.load_pub_key(os.path.join(key_dir, 'ut_rsa_pub.pem'))
     self.ut_ecdsa_pub_key = EC.load_pub_key(os.path.join(key_dir, 'ut_ec_pub.pem'))
     self.br_id = 0
     logging.info("done loading broker keys")
Esempio n. 9
0
def private_key_type(key_file):
    """ Determines type of the private key: RSA, DSA, EC.

    :param key_file: file path
    :type key_file: str
    :return: one of "RSA", "DSA" or "EC"
    :except CannotFindKeyTypeError
    """
    try:
        RSA.load_key(key_file)
        return "RSA"
    except:
        pass
    try:
        DSA.load_key(key_file)
        return "DSA"
    except:
        pass
    try:
        EC.load_key(key_file)
        return "EC"
    except:
        raise CannotFindKeyTypeError
def main(curve, hashalg):
    global ec, dgst  # this exists ONLY for speed testing

    Rand.load_file('randpool.dat', -1)

    if curve in curves2:
        curve = 'X9_62_' + curve
    ec_curve = eval('EC.NID_%s' % curve)

    pvtkeyfilename = '%spvtkey.pem' % (curve)
    pubkeyfilename = '%spubkey.pem' % (curve)

    if makenewkey:
        print '  making and saving a new key'
        ec = EC.gen_params(ec_curve)
        ec.gen_key()
        ec.save_key(pvtkeyfilename, None)
        ec.save_pub_key(pubkeyfilename)
    else:
        print '  loading an existing key'
        ec = EC.load_key(pvtkeyfilename)
    print '  ecdsa key length:', len(ec)
    print '  curve: %s' % curve

    if not ec.check_key():
        raise 'key is not initialised'

    if showpubkey:
        ec_pub = ec.pub()
        pub_der = ec_pub.get_der()
        pub_pem = base64.encodestring(pub_der)
        print '  PEM public key is: \n', pub_pem

    # since we are testing signing and verification, let's not
    # be fussy about the digest.  Just make one.
    md = EVP.MessageDigest(hashalg)
    md.update('can you spell subliminal channel?')
    dgst = md.digest()
    print '  hash algorithm: %s' % hashalg
    if showdigest:
        print '  %s digest: \n%s' % (base64.encodestring(dgst))

    test(ec, dgst)
    #    test_asn1(ec, dgst)
    test_speed(ec, dgst)
    Rand.save_file('randpool.dat')
Esempio n. 11
0
File: cs.py Progetto: sr-gi/paysense
    def report_data(self, message, certificate=False):

        # Load CS private key
        ec = EC.load_key(self.data_path + S_KEY)

        signature = ec.sign_dsa_asn1(message)
        signature = b64encode(signature)

        headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
        data = {
            'message': message,
            'signature': signature,
            'bitcoin_address': self.btc_address
        }

        if certificate is True:
            f = open(self.data_path + CERT, 'r')
            cs_pem_data = b64encode(f.read())
            f.close()
            data['cs_pem_data'] = cs_pem_data

        r = post(DCS, data=dumps(data), headers=headers)

        return r.status_code, r.reason, r.content
Esempio n. 12
0
#!/usr/bin/env python
"""ECDSA demonstration.

Copyright (c) 1999-2003 Ng Pheng Siong. All rights reserved.
Portions copyright (c) 2005-2006 Vrije Universiteit Amsterdam. All rights reserved.
"""

from M2Crypto import EC, EVP, Rand
import base64

md = EVP.MessageDigest('sha1')
md.update('can you spell subliminal channel?')
dgst = md.digest()

ec = EC.load_key('ecdsatest.pem')
#ec=EC.gen_params(EC.NID_sect233k1)
#ec.gen_key()
ec_pub = ec.pub()
pub_der = ec_pub.get_der()
pub_pem = base64.encodestring(pub_der)
print 'PEM public key is', pub_pem
ec.save_key('ecdsatest.pem', None)


def test():
    print 'testing signing...',
    r, s = ec.sign_dsa(dgst)
    if not ec.verify_dsa(dgst, r, s):
        print 'not ok'
    else:
        print 'ok'
Esempio n. 13
0
 def test_loadkey(self):
     ec = EC.load_key(self.privkey)
     assert len(ec) == 256
Esempio n. 14
0
 def test_loadkey(self):
     ec = EC.load_key(self.privkey)
     self.assertEqual(len(ec), tested_curve[1])
Esempio n. 15
0
 def test_loadkey_junk(self):
     with self.assertRaises(ValueError):
         EC.load_key(self.errkey)
Esempio n. 16
0
def read_keypair(keypairfilename):
    return EC.load_key(keypairfilename)
Esempio n. 17
0
 def setUpPostSession(self):
     """ Should set self.his_keypair """
     keypair_filename = os.path.join(self.config_path, 'ec.pem')
     self.his_keypair = EC.load_key(keypair_filename)
Esempio n. 18
0
 def test_sign_dsa_asn1(self):
     ec = EC.load_key(self.privkey)
     blob = ec.sign_dsa_asn1(self.data)
     assert ec.verify_dsa_asn1(self.data, blob)
     self.assertRaises(EC.ECError, ec.verify_dsa_asn1, blob, self.data)
Esempio n. 19
0
 def __init__(self, key_len=128, from_file=None):
     if from_file:
         self.ec = EC.load_key(from_file)
     else:
         self.ec = EC.gen_params(self.curve[key_len])
         self.ec.gen_key()
Esempio n. 20
0
def pace(security_infos_efca: List[bytes], sm_object: SMObject, secret: bytes, pub_key_ref: str):
    """
    List of Security Infos from EF.CardAccesss
    SMObject,
    Secret (MRZ info or CAN)
    pub_key_ref choices ("MRZ" or "CAN")
    """
    openssl_nid_to_name = {
        409: "prime192v1",
        923: "brainpoolP192r1",
        713: "secp224r1",
        925: "brainpoolP224r1",
        415: "prime256v1",
        927: "brainpoolP256r1",
        929: "brainpoolP320r1",
        715: "secp384r1",
        931: "brainpoolP384r1",
        933: "brainpoolP512r1",
        716: "secp521r1",
    }

    domain_parameters: Dict[int, Union[Tuple[str], Tuple[int, str]]] = {
        0: ("1024-bit MODP Group with 160-bit Prime Order Subgroup",),
        1: ("2048-bit MODP Group with 224-bit Prime Order Subgroup",),
        2: ("2048-bit MODP Group with 256-bit Prime Order Subgroup",),
        3: ("Reserved for Future Use",),
        4: ("Reserved for Future Use",),
        5: ("Reserved for Future Use",),
        6: ("Reserved for Future Use",),
        7: ("Reserved for Future Use",),
        8: (
            409,
            "NIST P-192 (secp192r1)",
        ),  #  https://stackoverflow.com/a/41953717/6077951
        9: (
            923,
            "BrainpoolP192r1",
        ),
        10: (
            713,
            "NIST P-224 (secp224r1) (can't be used with im)",
        ),
        11: (
            925,
            "BrainpoolP224r1",
        ),
        12: (
            415,
            "NIST P-256 (secp256r1)",
        ),  #  https://stackoverflow.com/a/41953717/6077951
        13: (
            927,
            "BrainpoolP256r1",
        ),
        14: (
            929,
            "BrainpoolP320r1",
        ),
        15: (
            715,
            "NIST P-384 (secp384r1)",
        ),
        16: (
            931,
            "BrainpoolP384r1",
        ),
        17: (
            933,
            "BrainpoolP512r1",
        ),
        18: (
            716,
            "NIST P-521 (secp521r1)",
        ),
        19: ("Reserved for Future Use",),
        20: ("Reserved for Future Use",),
        21: ("Reserved for Future Use",),
        22: ("Reserved for Future Use",),
        23: ("Reserved for Future Use",),
        24: ("Reserved for Future Use",),
        25: ("Reserved for Future Use",),
        26: ("Reserved for Future Use",),
        27: ("Reserved for Future Use",),
        28: ("Reserved for Future Use",),
        29: ("Reserved for Future Use",),
        30: ("Reserved for Future Use",),
        31: ("Reserved for Future Use",),
    }

    id_pace = "0.4.0.127.0.7.2.2.4"
    pace_protocol_dict = {
        encode_oid_string(id_pace + ".1.1"): "id-PACE-DH-GM-3DES-CBC-CBC",
        encode_oid_string(id_pace + ".1.2"): "id-PACE-DH-GM-AES-CBC-CMAC-128",
        encode_oid_string(id_pace + ".1.3"): "id-PACE-DH-GM-AES-CBC-CMAC-192",
        encode_oid_string(id_pace + ".1.4"): "id-PACE-DH-GM-AES-CBC-CMAC-256",
        encode_oid_string(id_pace + ".2.1"): "id-PACE-ECDH-GM-3DES-CBC-CBC",
        encode_oid_string(id_pace + ".2.2"): "id-PACE-ECDH-GM-AES-CBC-CMAC-128",
        encode_oid_string(id_pace + ".2.3"): "id-PACE-ECDH-GM-AES-CBC-CMAC-192",
        encode_oid_string(id_pace + ".2.4"): "id-PACE-ECDH-GM-AES-CBC-CMAC-256",
        encode_oid_string(id_pace + ".3.1"): "id-PACE-DH-IM-3DES-CBC-CBC",
        encode_oid_string(id_pace + ".3.2"): "id-PACE-DH-IM-AES-CBC-CMAC-128",
        encode_oid_string(id_pace + ".3.3"): "id-PACE-DH-IM-AES-CBC-CMAC-192",
        encode_oid_string(id_pace + ".3.4"): "id-PACE-DH-IM-AES-CBC-CMAC-256",
        encode_oid_string(id_pace + ".4.1"): "id-PACE-ECDH-IM-3DES-CBC-CBC",
        encode_oid_string(id_pace + ".4.2"): "id-PACE-ECDH-IM-AES-CBC-CMAC-128",
        encode_oid_string(id_pace + ".4.3"): "id-PACE-ECDH-IM-AES-CBC-CMAC-192",
        encode_oid_string(id_pace + ".4.4"): "id-PACE-ECDH-IM-AES-CBC-CMAC-256",
        encode_oid_string(id_pace + ".6.2"): "id-PACE-ECDH-CAM-AES-CBC-CMAC-128",
        encode_oid_string(id_pace + ".6.3"): "id-PACE-ECDH-CAM-AES-CBC-CMAC-192",
        encode_oid_string(id_pace + ".6.4"): "id-PACE-ECDH-CAM-AES-CBC-CMAC-256",
    }

    supported_pace: List[Tuple[bytes, int]] = find_paceinfos(security_infos_efca)

    if supported_pace == []:
        raise PACEError("[-] No supported PACEInfo found.")

    used_pace = supported_pace[0]
    used_pace_str = pace_protocol_dict[used_pace[0]].split("-")

    if pub_key_ref == "MRZ":
        key_seed = hashlib.sha1(secret).digest()
    if used_pace_str[4] == "3DES":
        k_dec = compute_key(key_seed, "pace", "3DES")
    else:  # AES
        k_dec = compute_key(key_seed, "pace", "AES-" + used_pace_str[7])

    payload = b"\x80" + used_pace[0][1:]
    if pub_key_ref == "MRZ":
        payload += b"\x83" + b"\x01" + b"\x01"
    elif pub_key_ref == "CAN":
        payload += b"\x83" + b"\x01" + b"\x02"
    else:
        raise PACEError("[-] Only MRZ and CAN are supported.")

    # if more than one set of DomainParameters is available:
    # payload = b"\x84" + reference of ...

    # MSE: AT
    ########data = send(sm_object, APDU(b"\x00", b"\x22", b"\xC1", b"\xA4", Lc=nb(len(payload)), cdata=payload))

    # Query encrypted nonce
    ########data = send(sm_object,APDU(b"\x10", b"\x86", b"\x00", b"\x00", Lc=b"\x02", cdata=b"\x7C\x00", Le=b"\x00"))
    data = bytes.fromhex("7C12801095A3A016522EE98D01E76CB6B98B42C3")
    # THE EXAMPLES ARE TAKEN FROM ICAO Doc 9303-11 App G-1

    i = asn1_node_root(data)  # Dynamic authentication data (0x7C)
    i = asn1_node_first_child(data, i)  # Encrypted Nonce (0x80)
    encrypted_nonce = asn1_get_value(data, i)

    if used_pace_str[4] == "3DES":
        decrypted_nonce = DES3.new(k_dec, DES3.MODE_CBC, iv=bytes([0] * 8)).decrypt(encrypted_nonce)
    else:
        decrypted_nonce = AES.new(k_dec, AES.MODE_CBC, iv=bytes([0] * 16)).decrypt(encrypted_nonce)

    assert decrypted_nonce == bytes.fromhex("3F00C4D39D153F2B2A214A078D899B22")

    if used_pace_str[3] == "GM":
        if used_pace_str[2] == "ECDH":
            used_domain_par = domain_parameters[used_pace[1]]
            if not isinstance(used_domain_par[0], int):
                raise PACEError("[-] These Domain parameters are not supported.")

            # ec_key_pair = EC.gen_params(used_domain_par[0])
            # ec_key_pair.gen_key()
            ec_key_pair = EC.load_key("tests/brainpoolP256r1.pem")
            ec_pub_key = ec_key_pair.pub().get_key()

            payload = b"\x81" + asn1_len(ec_pub_key) + ec_pub_key
            payload = b"\x7C" + asn1_len(payload) + payload

            # data = send(sm_object,APDU(b"\x10", b"\x86", b"\x00", b"\x00", Lc=nb(len(payload)), cdata=payload, Le=b"\x00"))
            data = bytes.fromhex(
                "7C43824104824FBA91C9CBE26BEF53A0EBE7342A3BF178CEA9F45DE0B70AA601651FBA3F5730D8C879AAA9C9F73991E61B58F4D52EB87A0A0C709A49DC63719363CCD13C54"
            )

            i = asn1_node_root(data)  # Dynamic Authentication Data (0x7C)
            i = asn1_node_first_child(data, i)  # Mapping Data (0x82)

            card_pace_pub_key = EC.pub_key_from_params(
                used_domain_par[0], asn1_get_value(data, i)
            )  # https://gitlab.com/m2crypto/m2crypto/-/blob/master/tests/test_ecdsa.py

            print((card_pace_pub_key.pub().get_key().hex()))
            # A different ecdsa library might be needed.
            shared_secret = ec_key_pair.compute_dh_key(card_pace_pub_key.pub())

            ec_pem_buf = BIO.MemoryBuffer()
            card_pace_pub_key.save_pub_key_bio(ec_pem_buf)
            ec_pem = ec_pem_buf.read()

            cmd = (
                "openssl ecparam -name "
                + openssl_nid_to_name[used_domain_par[0]]
                + " -param_enc explicit -text -noout"
            )
            ec_parameters, err = execute(cmd, ec_pem)

            generator = bytes.fromhex(
                ec_parameters.split(b"Generator (uncompressed):", 1)[1]
                .split(b"Order:", 1)[0]
                .replace(b"    ", b"")
                .replace(b":", b"")
                .replace(b"\n", b"")
                .decode("utf-8")
            )
            if generator[0] != 0x04:
                raise PACEError("[-] Problem in openssl.")

            generator = generator[1:]
            generator_x = generator[: len(generator) // 2]
            generator_y = generator[len(generator) // 2 :]
Esempio n. 21
0
def main():
    try:
        # opts = a list of (option, value) pairs
        # args = the list of program arguments left after the option list was stripped
        opts, args = getopt.getopt(sys.argv[1:], "hvo:p:", ["help", "version", "output-dir=", "port=", "doemode=", "proxyservice=", "proxies=", "test-mode=", "state-dir=", "no-download"])
    except getopt.GetoptError as err:
        print str(err)
        usage()
        sys.exit(2)

    # init the default values
    output_dir = os.getcwd()
    port = random.randint(10000, 65535)
    id = None
    doe_mode = DOE_MODE_OFF
    proxy_service = PROXYSERVICE_OFF
    proxies = 5
    test_mode = "off"  # off, doe, proxy
    no_download = False
    statedir = "/tmp/tmp-tribler"

    # get values from arguments
    for option, value in opts:
        if option in ("-h", "--help"):
            usage()
            sys.exit(0)
        elif option in ("-o", "--output-dir"):
            output_dir = value
        elif option in ("--state-dir"):
            statedir = value
        elif option in ("-p", "--port"):
            port = int(value)
        elif option in ("--doemode"):
            if value == "off":
                doe_mode = DOE_MODE_OFF
            elif value == "private":
                doe_mode = DOE_MODE_PRIVATE
            elif value == "speed":
                doe_mode = DOE_MODE_SPEED
            else:
                doe_mode = DOE_MODE_OFF
        elif option in ("--proxyservice"):
            if value == "off":
                proxy_service = PROXYSERVICE_OFF
            elif value == "on":
                proxy_service = PROXYSERVICE_ON
            else:
                proxy_service = PROXYSERVICE_OFF
        elif option in ("--proxies"):
            proxies = int(value)
        elif option in ("--test-mode"):
            test_mode = value
        elif option in ("-v", "--version"):
            print_version()
            sys.exit(0)
        elif option in ("--no-download"):
            no_download = True
        else:
            assert False, "unhandled option"

    # arg should have only one element left: the torrent file name
    # ProxyDevel
    # if no_download is false (the client has to download torrent data), check number of arguments
    if (no_download == False) and len(args) == 0:
        usage()
        sys.exit(2)
    if len(args) > 1:
        print "Too many arguments"
        usage()
        sys.exit(2)

    # ProxyDevel
    # is no_download is false (the client has to download torrent data), get torrent file name
    if (no_download == False):
        torrent_file = args[0]

    print "Press Ctrl-C to stop the download"

    # session setup
    session_startup_config = SessionStartupConfig()
    # statedir = tempfile.mkdtemp()
    # ProxyDevel - set custom state dir
    session_startup_config.set_state_dir(statedir)
    session_startup_config.set_proxyservice_dir(os.path.join(statedir, "proxyservice"))
    session_startup_config.set_listen_port(port)
    session_startup_config.set_megacache(True)
    session_startup_config.set_overlay(True)
    session_startup_config.set_dialback(True)
    session_startup_config.set_internal_tracker(False)
    session_startup_config.set_dispersy(True)
    # ProxyDevel - turn DHT off
    # session_startup_config.set_mainline_dht(False)
    # ProxyDevel - turn buddycast off
    # session_startup_config.set_buddycast(False)
    # ProxyDevel - set new core API values
    session_startup_config.set_proxyservice_status(proxy_service)

    s = Session(session_startup_config)

    # DEBUG
    print "*** My Permid = ", show_permid_short(s.get_permid())

    # ProxyDevel - Receive overlay messages from anyone
    s.set_overlay_request_policy(AllowAllRequestPolicy())

    if test_mode == "doe":
        # add the helper 1 as a friend
        # get helper1 permid
        helper1_keypair_filename = os.path.join("../../P2P-Testing-Infrastructure/ClientWorkingFolders/Proxy01/statedir", "ec.pem")
        helper1_keypair = EC.load_key(helper1_keypair_filename)
        helper1_permid = str(helper1_keypair.pub().get_der())
        # set helper1 ip address
#        helper1_ip="10.10.3.1"
        helper1_ip = "141.85.224.202"
        # set helper1 port
        helper1_port = 25123
        # add helper1 as a peer
        peerdb = s.open_dbhandler(NTFY_PEERS)
        peer = {}
        peer['permid'] = helper1_permid
        peer['ip'] = helper1_ip
        peer['port'] = helper1_port
        peer['last_seen'] = 0
        peerdb.addPeer(peer['permid'], peer, update_dns=True, commit=True)

        # add the helper 2 as a friend
        # get helper2 permid
        helper2_keypair_filename = os.path.join("../../P2P-Testing-Infrastructure/ClientWorkingFolders/Proxy02/statedir", "ec.pem")
        helper2_keypair = EC.load_key(helper2_keypair_filename)
        helper2_permid = str(helper2_keypair.pub().get_der())
        # set helper2 ip address
#        helper2_ip="10.10.4.1"
        helper2_ip = "141.85.224.203"
        # set helper2 port
        helper2_port = 25123
        # add helper2 as a peer
        peerdb = s.open_dbhandler(NTFY_PEERS)
        peer = {}
        peer['permid'] = helper2_permid
        peer['ip'] = helper2_ip
        peer['port'] = helper2_port
        peer['last_seen'] = 0
        peerdb.addPeer(peer['permid'], peer, update_dns=True, commit=True)

        # add the helper 3 as a friend
        # get helper3 permid
        helper3_keypair_filename = os.path.join("../../P2P-Testing-Infrastructure/ClientWorkingFolders/Proxy03/statedir", "ec.pem")
        helper3_keypair = EC.load_key(helper3_keypair_filename)
        helper3_permid = str(helper3_keypair.pub().get_der())
        # set helper3 ip address
        helper3_ip = "141.85.224.204"
        # set helper3 port
        helper3_port = 25123
        # add helper3 as a peer
        peerdb = s.open_dbhandler(NTFY_PEERS)
        peer = {}
        peer['permid'] = helper3_permid
        peer['ip'] = helper3_ip
        peer['port'] = helper3_port
        peer['last_seen'] = 0
        peerdb.addPeer(peer['permid'], peer, update_dns=True, commit=True)

        # add the helper 4 as a friend
        # get helper4 permid
        helper4_keypair_filename = os.path.join("../../P2P-Testing-Infrastructure/ClientWorkingFolders/Proxy04/statedir", "ec.pem")
        helper4_keypair = EC.load_key(helper4_keypair_filename)
        helper4_permid = str(helper4_keypair.pub().get_der())
        # set helper4 ip address
        helper4_ip = "141.85.224.205"
        # set helper4 port
        helper4_port = 25123
        # add helper4 as a peer
        peerdb = s.open_dbhandler(NTFY_PEERS)
        peer = {}
        peer['permid'] = helper4_permid
        peer['ip'] = helper4_ip
        peer['port'] = helper4_port
        peer['last_seen'] = 0
        peerdb.addPeer(peer['permid'], peer, update_dns=True, commit=True)

    # ProxyDevel - if no_download is false (the client has to download torrent data), then start downloading
    if (no_download == False):
        if test_mode == "doe":
            # setup and start download
            download_startup_config = DownloadStartupConfig()
            download_startup_config.set_dest_dir(output_dir)
            # ProxyDevel - turn PEX off
            # download_startup_config.set_ut_pex_max_addrs_from_peer(0)
            download_startup_config.set_doe_mode(doe_mode)
            download_startup_config.set_proxyservice_role(PROXYSERVICE_ROLE_DOE)
            download_startup_config.set_no_proxies(proxies)

            torrent_def = TorrentDef.load(torrent_file)

            d = s.start_download(torrent_def, download_startup_config)
            d.set_state_callback(state_callback, getpeerlist=[])
        else:
            # setup and start download
            download_startup_config = DownloadStartupConfig()
            download_startup_config.set_dest_dir(output_dir)

            torrent_def = TorrentDef.load(torrent_file)

            d = s.start_download(torrent_def, download_startup_config)
            d.set_state_callback(state_callback, getpeerlist=[])

        # if the client is a coordinator
        if test_mode == "doe":
            # allow time for the download to start, before starting the help request
            time.sleep(3)
            # ask peer for help
            for download in s.get_downloads():
                peerlist = []
                peerlist.append(helper1_permid)
                peerlist.append(helper2_permid)
                peerlist.append(helper3_permid)
                peerlist.append(helper4_permid)
                # download.sd.dow.proxydownloader.doe.send_relay_request(peerlist)

    #
    # loop while waiting for CTRL-C (or any other signal/interrupt)
    #
    # - cannot use sys.stdin.read() - it means busy waiting when running
    #   the process in background
    # - cannot use condition variable - that don't listen to KeyboardInterrupt
    #
    # time.sleep(sys.maxint) has "issues" on 64bit architectures; divide it
    # by some value (2048) to solve problem
    #

    try:
        while True:
            time.sleep(sys.maxsize / 2048)
    except:
        print_exc()

    s.shutdown()
    time.sleep(3)
Esempio n. 22
0
 def test_verify_dsa(self):
     ec = EC.load_key(self.privkey)
     r, s = ec.sign_dsa(self.data)
     ec2 = EC.load_pub_key(self.pubkey)
     assert ec2.verify_dsa(self.data, r, s)
     assert not ec2.verify_dsa(self.data, s, r)
    s = Session(session_startup_config)

    # DEBUG
    print "*** My Permid = ", show_permid_short(s.get_permid())

    # ProxyDevel - Receive overlay messages from anyone
    s.set_overlay_request_policy(AllowAllRequestPolicy())

    if test_mode == "doe":
        # add the helper 1 as a friend
        # get helper1 permid
        helper1_keypair_filename = os.path.join(
            "../../P2P-Testing-Infrastructure/ClientWorkingFolders/Proxy01/statedir",
            "ec.pem")
        helper1_keypair = EC.load_key(helper1_keypair_filename)
        helper1_permid = str(helper1_keypair.pub().get_der())
        # set helper1 ip address
        #        helper1_ip="10.10.3.1"
        helper1_ip = "141.85.224.202"
        # set helper1 port
        helper1_port = 25123
        # add helper1 as a peer
        peerdb = s.open_dbhandler(NTFY_PEERS)
        peer = {}
        peer['permid'] = helper1_permid
        peer['ip'] = helper1_ip
        peer['port'] = helper1_port
        peer['last_seen'] = 0
        peerdb.addPeer(peer['permid'], peer, update_dns=True, commit=True)