Example #1
0
 def test_pubkey_from_der(self):
     a = EC.gen_params(tested_curve[0])
     a.gen_key()
     b = EC.gen_params(tested_curve[0])
     b.gen_key()
     a_pub_der = a.pub().get_der()
     a_pub = EC.pub_key_from_der(a_pub_der)
     ak = a.compute_dh_key(b.pub())
     bk = b.compute_dh_key(a_pub)
     self.assertEqual(ak, bk)
Example #2
0
 def test_pubkey_from_der(self):
     a = EC.gen_params(EC.NID_sect233k1)
     a.gen_key()
     b = EC.gen_params(EC.NID_sect233k1)
     b.gen_key()
     a_pub_der = a.pub().get_der()
     a_pub = EC.pub_key_from_der(a_pub_der)
     ak = a.compute_dh_key(b.pub())
     bk = b.compute_dh_key(a_pub)
     self.assertEqual(ak, bk)
    def __init__(self,port,testcase):
        Thread.__init__(self)
        self.setDaemon(True)
        self.testcase = testcase
        self.port = port
        self.my_keypair = EC.gen_params(EC.NID_sect233k1)
        self.my_keypair.gen_key()

        self.other_keypair = EC.gen_params(EC.NID_sect233k1)
        self.other_keypair.gen_key()
Example #4
0
    def __init__(self, port, testcase):
        Thread.__init__(self)
        self.setDaemon(True)
        self.testcase = testcase
        self.port = port
        self.my_keypair = EC.gen_params(EC.NID_sect233k1)
        self.my_keypair.gen_key()

        self.other_keypair = EC.gen_params(EC.NID_sect233k1)
        self.other_keypair.gen_key()
Example #5
0
 def test_pubkey_from_der(self):
     a = EC.gen_params(tested_curve[0])
     a.gen_key()
     b = EC.gen_params(tested_curve[0])
     b.gen_key()
     a_pub_der = a.pub().get_der()
     a_pub = EC.pub_key_from_der(a_pub_der)
     ak = a.compute_dh_key(b.pub())
     bk = b.compute_dh_key(a_pub)
     self.assertEqual(ak, bk)
 def test_pubkey_from_der(self):
     a = EC.gen_params(EC.NID_X9_62_prime256v1)
     a.gen_key()
     b = EC.gen_params(EC.NID_X9_62_prime256v1)
     b.gen_key()
     a_pub_der = a.pub().get_der()
     a_pub = EC.pub_key_from_der(a_pub_der)
     ak = a.compute_dh_key(b.pub())
     bk = b.compute_dh_key(a_pub)
     assert ak == bk
Example #7
0
 def test_pubkey_from_der(self):
     a = EC.gen_params(EC.NID_sect233k1)
     a.gen_key()
     b = EC.gen_params(EC.NID_sect233k1)
     b.gen_key()
     a_pub_der = a.pub().get_der()
     a_pub = EC.pub_key_from_der(a_pub_der)
     ak = a.compute_dh_key(b.pub())
     bk = b.compute_dh_key(a_pub)
     assert ak == bk
Example #8
0
def test():
    print 'generating ec keys:'
    a=EC.gen_params(EC.NID_sect233k1)
    a.gen_key()
    b=EC.gen_params(EC.NID_sect233k1)
    b.gen_key()
    a_shared_key = a.compute_dh_key(b.pub())
    b_shared_key = b.compute_dh_key(a.pub())
    print 'shared key according to a = ', `a_shared_key`
    print 'shared key according to b = ', `b_shared_key`
    if a_shared_key == b_shared_key:
        print 'ok'
    else:
        print 'not ok'
 def test_compute_key(self):
     a = EC.load_key(self.privkey)
     b = EC.gen_params(EC.NID_X9_62_prime256v1)
     b.gen_key()
     ak = a.compute_dh_key(b.pub())
     bk = b.compute_dh_key(a.pub())
     assert ak == bk
Example #10
0
 def genkey(self, curveName, curveLen):
     curve = getattr(EC, 'NID_'+curveName)
     ec = EC.gen_params(curve)
     assert len(ec) == curveLen
     ec.gen_key()
     assert  ec.check_key(), 'check_key() failure for "%s"' % curveName
     return ec
Example #11
0
    def _register(self, data):
        client_param = data[:32]
        app_param = data[32:]

        # ECC key generation
        privu = EC.gen_params(CURVE)
        privu.gen_key()
        pub_key = str(privu.pub().get_der())[-65:]

        # Store
        key_handle = os.urandom(64)
        bio = BIO.MemoryBuffer()
        privu.save_key_bio(bio, None)
        self.data['keys'][key_handle.encode('hex')] = {
            'priv_key': bio.read_all(),
            'app_param': app_param.encode('hex')
        }
        self._persist()

        # Attestation signature
        cert_priv = EC.load_key_bio(BIO.MemoryBuffer(CERT_PRIV))
        cert = CERT
        digest = H(chr(0x00) + app_param + client_param + key_handle + pub_key)
        signature = cert_priv.sign_dsa_asn1(digest)

        raw_response = chr(0x05) + pub_key + chr(len(key_handle)) + \
            key_handle + cert + signature

        return raw_response
Example #12
0
File: cs.py Project: sr-gi/paysense
    def generate_keys(self):
        # Generate the elliptic curve and the keys
        ec = EC.gen_params(EC.NID_secp256k1)
        ec.gen_key()

        # Generate a Pkey object to store the EC keys
        mem = BIO.MemoryBuffer()
        ec.save_pub_key_bio(mem)
        ec.save_key_bio(mem, None)
        pk = EVP.load_key_bio(mem)

        # Generate the bitcoin address from the public key
        public_key_hex = get_pub_key_hex(ec.pub())
        bitcoin_address = public_key_to_btc_address(public_key_hex, 'test')

        # Save both keys
        if not path.exists(self.data_path + tmp):
            mkdir(self.data_path + tmp)
        ec.save_key(self.data_path + tmp + bitcoin_address + '_key.pem', None)
        ec.save_pub_key(self.data_path + tmp + bitcoin_address + '_public_key.pem')

        # Create the WIF file
        wif = private_key_to_wif(get_priv_key_hex(self.data_path + tmp + bitcoin_address + '_key.pem'), 'image', 'test')
        wif.save(self.data_path + tmp + bitcoin_address + "_WIF.png")

        return pk, bitcoin_address
    def setUpPostSession(self):
        """ override TestAsServer """
        TestCrawler.setUpPostSession(self)

        self.some_keypair = EC.gen_params(EC.NID_sect233k1)
        self.some_keypair.gen_key()
        self.some_permid = str(self.some_keypair.pub().get_der())

        self.friendshipStatistics_db = FriendshipStatisticsDBHandler.getInstance(
        )
        self.friendshipStatistics_db.insertFriendshipStatistics(
            bin2str(self.his_permid),
            bin2str(self.some_permid),
            int(time.time()),
            0,
            commit=True)
        self.friendshipStatistics_db.insertFriendshipStatistics(
            bin2str(self.my_permid),
            bin2str(self.some_permid),
            int(time.time()),
            0,
            commit=True)

        # make sure that the OLConnection IS in the crawler_db
        crawler_db = CrawlerDBHandler.getInstance()
        crawler_db.temporarilyAddCrawler(self.my_permid)
Example #14
0
def mk_ec_pair():
    priv_key = EC.gen_params(EC.NID_secp384r1)
    priv_key.gen_key()
    priv_key.save_key('ec.priv.pem',
                      callback=util.no_passphrase_callback)
    pub_key = priv_key.pub()
    pub_key.save_pub_key('ec.pub.pem')
Example #15
0
def ec_generate_key(security):
    """
    Generate a new Elliptic Curve object with a new public / private key pair.

    Security can be u'low', u'medium', or u'high' depending on how secure you need your Elliptic
    Curve to be.  Currently these values translate into:
        - very-low: NID_sect163k1  ~42 byte signatures
        - low:      NID_sect233k1  ~60 byte signatures
        - medium:   NID_sect409k1 ~104 byte signatures
        - high:     NID_sect571r1 ~144 byte signatures

    Besides these predefined curves, all other curves provided by M2Crypto are also available.  For
    a full list of available curves, see ec_get_curves().

    @param security: Level of security {u'very-low', u'low', u'medium', or u'high'}.
    @type security: unicode

    @note that the NID must always be 160 bits or more, otherwise it will not be able to sign a sha1
        digest.
    """
    assert isinstance(security, unicode)
    assert security in _CURVES
    ec = EC.gen_params(_CURVES[security])
    ec.gen_key()
    return ec
Example #16
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
Example #17
0
def mk_ec_pair():
    priv_key = EC.gen_params(tested_curve[0])
    priv_key.gen_key()
    priv_key.save_key('ec.priv.pem',
                      callback=util.no_passphrase_callback)
    pub_key = priv_key.pub()
    pub_key.save_pub_key('ec.pub.pem')
Example #18
0
def mk_ec_pair():
    priv_key = EC.gen_params(tested_curve[0])
    priv_key.gen_key()
    priv_key.save_key('ec.priv.pem',
                      callback=util.no_passphrase_callback)
    pub_key = priv_key.pub()
    pub_key.save_pub_key('ec.pub.pem')
Example #19
0
    def encrypt(self,message,encryptor):
        if self._pubkey == None or self._pubkey_curve == None: # To send message via PublicKey, We must know it's curve.
            return False
        # Get a temp. key
        tempkey = EC.gen_params(self._pubkey_curve)
        tempkey.gen_key()
        sharedsecret = tempkey.compute_dh_key(self._pubkey)
        
        log.debug("Length of key is: %d",(len(sharedsecret) * 8))

        # Encrypt
        ciphertext = encryptor(sharedsecret,message)
        # Get tempkey's public key.
        membuff = BIO.MemoryBuffer()
        tempkey.save_pub_key_bio(membuff)
        publickey = membuff.read_all()  #open(filename).read()
        # Return with serializer.
        ret = serializer.dumps(
            {
                'type':'EC_Encrypted',
                'public_key':publickey,
                'ciphertext':ciphertext,
            }
        )
        return ret
Example #20
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)
Example #21
0
File: cs.py Project: sr-gi/paysense
    def generate_keys(self):
        # Generate the elliptic curve and the keys
        ec = EC.gen_params(EC.NID_secp256k1)
        ec.gen_key()

        # Generate a Pkey object to store the EC keys
        mem = BIO.MemoryBuffer()
        ec.save_pub_key_bio(mem)
        ec.save_key_bio(mem, None)
        pk = EVP.load_key_bio(mem)

        # Generate the bitcoin address from the public key
        public_key_hex = get_pub_key_hex(ec.pub())
        bitcoin_address = public_key_to_btc_address(public_key_hex, 'test')

        # Save both keys
        if not path.exists(self.data_path + tmp):
            mkdir(self.data_path + tmp)
        ec.save_key(self.data_path + tmp + bitcoin_address + '_key.pem', None)
        ec.save_pub_key(self.data_path + tmp + bitcoin_address +
                        '_public_key.pem')

        # Create the WIF file
        wif = private_key_to_wif(
            get_priv_key_hex(self.data_path + tmp + bitcoin_address +
                             '_key.pem'), 'image', 'test')
        wif.save(self.data_path + tmp + bitcoin_address + "_WIF.png")

        return pk, bitcoin_address
Example #22
0
    def __init__(self, nid_or_path=None):
        """nid_or_path is either a nid to create a new key or a path to a pem encoded key"""

        self._key = None

        # we don't have anything to initialize anymore
        if type(nid_or_path) == type(None):
            return  # do nothing
        elif type(nid_or_path) == int:
            self._key = EC.gen_params(nid_or_path)
            self._key.gen_key()
        elif type(nid_or_path) == str:
            # the string is a DER public key ?
            # OID == 1.2.840.10045.2.1
            # encoder.encode(univ.ObjectIdentifier("1.2.840.10045.2.1"))
            if nid_or_path.startswith("\x30") and "\x06\x07\x2a\x86\x48\xce\x3d\x02\x01" in nid_or_path:
                self.PubKey_from_DER(nid_or_path)

            # the string is a PEM key ?
            elif "-----BEGIN EC PRIVATE KEY-----" in nid_or_path:
                self.from_PEM(nid_or_path)
            elif "-----BEGIN PUBLIC KEY-----" in nid_or_path:
                self.PubKey_from_PEM(nid_or_path)

            else:
                # the string is a path ?
                with open(nid_or_path) as f:
                    self.from_PEM(f.read())

        elif isinstance(nid_or_path, ECCkey):
            self.from_PEM(nid_or_path.to_PEM())
        else:
            raise ECCException("ECCkey should be instanciated py a NID number or a path to a valid EC key" "")
Example #23
0
def ec_generate_key(security):
    """
    Generate a new Elliptic Curve object with a new public / private key pair.

    Security can be u'low', u'medium', or u'high' depending on how secure you need your Elliptic
    Curve to be.  Currently these values translate into:
        - very-low: NID_sect163k1  ~42 byte signatures
        - low:      NID_sect233k1  ~60 byte signatures
        - medium:   NID_sect409k1 ~104 byte signatures
        - high:     NID_sect571r1 ~144 byte signatures

    Besides these predefined curves, all other curves provided by M2Crypto are also available.  For
    a full list of available curves, see ec_get_curves().

    @param security: Level of security {u'very-low', u'low', u'medium', or u'high'}.
    @type security: unicode

    @note that the NID must always be 160 bits or more, otherwise it will not be able to sign a sha1
        digest.
    """
    assert isinstance(security, unicode)
    assert security in _CURVES
    ec = EC.gen_params(_CURVES[security])
    ec.gen_key()
    return ec
Example #24
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())
     self.assertEqual(ak, bk)
Example #25
0
 def genkey(self, curveName, curveLen):
     curve = getattr(EC, 'NID_' + curveName)
     ec = EC.gen_params(curve)
     assert len(ec) == curveLen
     ec.gen_key()
     assert ec.check_key(), 'check_key() failure for "%s"' % curveName
     return ec
Example #26
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)
Example #27
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)
Example #28
0
 def _test_sign_dsa(self):
     ec = EC.gen_params(EC.NID_sect233k1)
     # 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)
Example #29
0
    def generateECKeyPair(self):
        # Generate M2Crypto.EC.EC object
        ec = EC.gen_params(EC.NID_X9_62_prime256v1)
        ec.gen_key()

        rawPrivateKey, rawPublicKey = self._constructRawKeysFromEc(ec)

        return ECPublicKey(rawPublicKey, ec), ECPrivateKey(rawPrivateKey, rawPublicKey, ec)
Example #30
0
 def genkey(self, curveName, curveLen):
     curve = getattr(EC, 'NID_' + curveName)
     ec = EC.gen_params(curve)
     self.assertEqual(len(ec), curveLen)
     ec.gen_key()
     self.assertTrue(ec.check_key(),
                     'check_key() failure for "%s"' % curveName)
     return ec
Example #31
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)
Example #32
0
    def generateECKeyPair(self):
        # Generate M2Crypto.EC.EC object
        ec = EC.gen_params(EC.NID_X9_62_prime256v1)
        ec.gen_key()

        rawPrivateKey, rawPublicKey = self._constructRawKeysFromEc(ec)

        return ECPublicKey(rawPublicKey,
                           ec), ECPrivateKey(rawPrivateKey, rawPublicKey, ec)
    def setUpPreSession(self):
        """ override TestAsServer """
        print >> sys.stderr,"test: Pre Tribler Init"
        TestAsServer.setUpPreSession(self)
        print >> sys.stderr,"test: Pre Tribler Init: config_path",self.config_path
        # Enable dialback support
        self.config.set_dialback(True)
        self.config.set_buddycast(True) # make sure overlay connections are being made
        self.config.set_start_recommender(True)

        # Write superpeers.txt
        self.install_path = tempfile.mkdtemp()
        spdir = os.path.join(self.install_path, LIBRARYNAME, 'Core')
        os.makedirs(spdir)

        statsdir = os.path.join(self.install_path, LIBRARYNAME, 'Core', 'Statistics')
        os.makedirs(statsdir)
        
        superpeerfilename = os.path.join(spdir, 'superpeer.txt')
        print >> sys.stderr,"test: writing",self.NLISTENERS,"superpeers to",superpeerfilename
        f = open(superpeerfilename, "w")

        self.mylistenport = []
        self.myss = []
        self.mykeypairs = []
        self.mypermids = []
        for i in range(self.NLISTENERS):
            # Start our server side, to with Tribler will try to connect
            self.mylistenport.append(4810+i)
            self.myss.append(socket.socket(socket.AF_INET, socket.SOCK_STREAM))
            self.myss[i].setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.myss[i].bind(('', self.mylistenport[i]))
            self.myss[i].listen(1)

            self.mykeypairs.append(EC.gen_params(EC.NID_sect233k1))
            self.mykeypairs[i].gen_key()
            self.mypermids.append(str(self.mykeypairs[i].pub().get_der()))

            content = '127.0.0.1, '+str(self.mylistenport[i])+', '+show_permid(self.mypermids[i])+', FakeSuperPeer\n'
            f.write(content)
        f.close()
        
        self.config.set_install_dir(self.install_path)
        
        srcfiles = []
        srcfiles.append(os.path.join(LIBRARYNAME,"schema_sdb_v"+str(CURRENT_MAIN_DB_VERSION)+".sql"))
        srcfiles.append(os.path.join(LIBRARYNAME,"Core","Statistics","tribler_seedingstats_sdb.sql"))
        srcfiles.append(os.path.join(LIBRARYNAME,"Core","Statistics","tribler_friendship_stats_sdb.sql"))
        srcfiles.append(os.path.join(LIBRARYNAME,"Core","Statistics","tribler_videoplayback_stats.sql"))
        for srcfile in srcfiles:
            sfn = os.path.join('..','..',srcfile)
            dfn = os.path.join(self.install_path,srcfile)
            print >>sys.stderr,"test: copying",sfn,dfn
            shutil.copyfile(sfn,dfn)

        """
Example #34
0
    def setUp(self):
        self.my_keypair = EC.gen_params(EC.NID_sect233k1)
        self.my_keypair.gen_key()

        self.server_port = 4810
        self.server = MyServer(self.server_port,self)
        self.server.start()
        time.sleep(1) # allow server to start

        self.overlay = SecureOverlay()
Example #35
0
    def setUp(self):
        self.my_keypair = EC.gen_params(EC.NID_sect233k1)
        self.my_keypair.gen_key()

        self.server_port = 4810
        self.server = MyServer(self.server_port, self)
        self.server.start()
        time.sleep(1)  # allow server to start

        self.overlay = SecureOverlay()
Example #36
0
 def test_pub_key_from_params(self):
     curve = EC.NID_prime256v1
     ec = EC.gen_params(curve)
     ec.gen_key()
     ec_pub = ec.pub()
     k = ec_pub.get_key()
     ec2 = EC.pub_key_from_params(curve, k)
     assert ec2.check_key()
     r, s = ec.sign_dsa(self.data)
     assert ec2.verify_dsa(self.data, r, s)
Example #37
0
    def setUp(self):
        self.app = create_app('testing')
        self.flush_mongodb()

        self.ec1 = EC.gen_params(self.ec_name)
        self.ec1.gen_key()
        bio1 = BIO.MemoryBuffer()
        self.ec1.save_pub_key_bio(bio1)

        self.mai = MetaAppInstance(mai_id=self.test_mai_id,
                                   pubkey_ec=bio1.getvalue())
        self.mai.save()

        self.ec2 = EC.gen_params(self.ec_name)
        self.ec2.gen_key()

        self.verifyer = crypto.ECVerifier(self.mai)

        self.sha = sha512()
        self.temp = tempfile.TemporaryFile()
def generateMasterkey():
    """Generate an M2Crypto Elliptic Curve key.
    """
    membuffer = BIO.MemoryBuffer()
    keypair = EC.gen_params(EC.NID_sect233k1)
    keypair.gen_key()
    keypair.save_pub_key_bio(membuffer)
    rawpubkey = membuffer.read()
    membuffer.reset()
    fpubkey = rawpubkey[27:]
    fpubkey = fpubkey[:string.find(fpubkey, '-')]
    return fpubkey  # BASE64 ENCODED
Example #39
0
 def __init__(self):
     self._ec = EC.gen_params(EC.NID_X9_62_c2tnb431r1)
     self._ec.gen_key()
     parser = ArgumentParser(description=('Generate ECDSA keys and '
                                          'export them'))
     parser.add_argument('--pub', nargs=1, default='testkey.pub',
                         help=('Destination public key file. Defaults to '
                               "'testkey.pub'."))
     parser.add_argument('--priv', nargs=1, default='testkey.key',
                         help=('Destination private key file. Defaults to '
                               "'testkey.key'."))
     self.args = parser.parse_args()
 def genkey(self, curve):
     try:
         curve_name = m2.obj_nid2sn(curve[0])
     except TypeError:
         # we have to throw different exception for compatibility
         raise AttributeError('Unknown cipher %s', curve[0])
     ec = EC.gen_params(curve[0])
     self.assertEqual(len(ec), curve[1])
     ec.gen_key()
     self.assertTrue(ec.check_key(),
                     'check_key() failure for "%s"' % curve_name)
     return ec
def generateMasterkey():
    """Generate an M2Crypto Elliptic Curve key.
    """
    membuffer = BIO.MemoryBuffer()
    keypair = EC.gen_params(EC.NID_sect233k1)
    keypair.gen_key()
    keypair.save_pub_key_bio(membuffer)
    rawpubkey = membuffer.read()
    membuffer.reset()
    fpubkey = rawpubkey[27:]
    fpubkey = fpubkey[:string.find(fpubkey, '-')]
    return fpubkey  # BASE64 ENCODED
Example #42
0
def EC_GenerateKey(size):
	"""
	Generate Elliptic Curve object with public/private keypair 

	Default security level for curve is 415
	@param size: Level of security
	@type size: Integer
	"""
	assert isinstance(size, int)
	ec = EC.gen_params(size)
	ec.gen_key()
	return ec
Example #43
0
 def genkey(self, curve):
     try:
         curve_name = m2.obj_nid2sn(curve[0])
     except TypeError:
         # we have to throw different exception for compatibility
         raise AttributeError('Unknown cipher %s', curve[0])
     ec = EC.gen_params(curve[0])
     self.assertEqual(len(ec), curve[1])
     ec.gen_key()
     self.assertTrue(ec.check_key(),
                     'check_key() failure for "%s"' %
                     curve_name)
     return ec
    def register(
        self,
        data,
        facet="https://www.example.com",
    ):
        """
        data = {
            "version": "U2F_V2",
            "challenge": string, //b64 encoded challenge
            "appId": string, //app_id
        }
        """
        if isinstance(data, basestring):
            data = json.loads(data)

        if data['version'] != "U2F_V2":
            raise ValueError("Unsupported U2F version: %s" % data['version'])

        # Client data
        client_data = {
            'typ': "navigator.id.finishEnrollment",
            'challenge': data['challenge'],
            'origin': facet
        }
        client_data = json.dumps(client_data)
        client_param = H(client_data)

        # ECC key generation
        privu = EC.gen_params(CURVE)
        privu.gen_key()
        pub_key = str(privu.pub().get_der())[-65:]

        # Store
        key_handle = rand_bytes(64)
        app_param = H(data['appId'])
        self.keys[key_handle] = (privu, app_param)

        # Attestation signature
        cert_priv = EC.load_key_bio(BIO.MemoryBuffer(CERT_PRIV))
        cert = CERT
        digest = H(chr(0x00) + app_param + client_param + key_handle + pub_key)
        signature = cert_priv.sign_dsa_asn1(digest)

        raw_response = chr(0x05) + pub_key + chr(len(key_handle)) + \
            key_handle + cert + signature

        return json.dumps({
            "registrationData": websafe_encode(raw_response),
            "clientData": websafe_encode(client_data),
        })
Example #45
0
    def setUpMyListenSocket(self):
        self.dest_keypair = EC.gen_params(EC.NID_sect233k1)
        self.dest_keypair.gen_key()
        self.destpermid = str(self.dest_keypair.pub().get_der())
        self.destport = 4810
        
        # Start our server side, to with Tribler will try to connect
        self.destss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.destss.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.destss.bind(('', self.destport))
        self.destss.listen(1)

        print >>sys.stderr,"test: my   permid",show_permid_short(self.mypermid)
        print >>sys.stderr,"test: his  permid",show_permid_short(self.hispermid)
        print >>sys.stderr,"test: dest permid",show_permid_short(self.destpermid)
    def setUpPostSession(self):
        """ override TestAsServer """
        TestCrawler.setUpPostSession(self)

        self.some_keypair = EC.gen_params(EC.NID_sect233k1)
        self.some_keypair.gen_key()
        self.some_permid = str(self.some_keypair.pub().get_der())

        self.friendshipStatistics_db = FriendshipStatisticsDBHandler.getInstance()
        self.friendshipStatistics_db.insertFriendshipStatistics( bin2str(self.his_permid), bin2str(self.some_permid), int(time.time()), 0, commit=True)        
        self.friendshipStatistics_db.insertFriendshipStatistics( bin2str(self.my_permid), bin2str(self.some_permid), int(time.time()), 0, commit=True)

        # make sure that the OLConnection IS in the crawler_db
        crawler_db = CrawlerDBHandler.getInstance()
        crawler_db.temporarilyAddCrawler(self.my_permid)
    def setUpMyListenSocket(self):
        self.dest_keypair = EC.gen_params(EC.NID_sect233k1)
        self.dest_keypair.gen_key()
        self.destpermid = str(self.dest_keypair.pub().get_der())
        self.destport = 4810
        
        # Start our server side, to with Tribler will try to connect
        self.destss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.destss.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.destss.bind(('', self.destport))
        self.destss.listen(1)

        print >>sys.stderr,"test: my   permid",show_permid_short(self.mypermid)
        print >>sys.stderr,"test: his  permid",show_permid_short(self.hispermid)
        print >>sys.stderr,"test: dest permid",show_permid_short(self.destpermid)
Example #48
0
    def __init__(self, curve=None, keystring=None, filename=None):
        if curve:
            self.ec = EC.gen_params(curve)
            self.ec.gen_key()

        elif keystring:
            self.ec = self.key_from_pem(
                "-----BEGIN EC PRIVATE KEY-----\n%s-----END EC PRIVATE KEY-----\n"
                % keystring.encode("BASE64"))

        elif filename:
            # this workaround is needed to run Tribler on Windows 64 bit
            membuf = BIO.MemoryBuffer(open(filename, 'rb').read())
            self.ec = EC.load_key_bio(membuf)
            membuf.close()
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')
Example #50
0
    def register(self, request, facet="https://www.example.com"):
        """
        RegisterRequest = {
            "version": "U2F_V2",
            "challenge": string, //b64 encoded challenge
            "appId": string, //app_id
        }
        """

        if not isinstance(request, RegisterRequest):
            request = RegisterRequest(request)

        if request.version != "U2F_V2":
            raise ValueError("Unsupported U2F version: %s" % request.version)

        # Client data
        client_data = ClientData(typ='navigator.id.finishEnrollment',
                                 challenge=request['challenge'],
                                 origin=facet)
        client_data = client_data.json
        client_param = H(client_data)

        # ECC key generation
        privu = EC.gen_params(CURVE)
        privu.gen_key()
        pub_key = str(privu.pub().get_der())[-65:]

        # Store
        key_handle = rand_bytes(64)
        app_param = request.appParam
        self.keys[key_handle] = (privu, app_param)

        # Attestation signature
        cert_priv = EC.load_key_bio(BIO.MemoryBuffer(CERT_PRIV))
        cert = CERT
        digest = H(chr(0x00) + app_param + client_param + key_handle + pub_key)
        signature = cert_priv.sign_dsa_asn1(digest)

        raw_response = chr(0x05) + pub_key + chr(len(key_handle)) + \
            key_handle + cert + signature

        return RegisterResponse(
            registrationData=websafe_encode(raw_response),
            clientData=websafe_encode(client_data),
        )
Example #51
0
    def setUpPreSession(self):
        """ override TestAsServer """
        print >> sys.stderr, "test: Pre Tribler Init"
        TestAsServer.setUpPreSession(self)
        print >> sys.stderr, "test: Pre Tribler Init: config_path", self.config_path
        # Enable dialback support
        self.config.set_dialback(True)
        self.config.set_buddycast(
            True)  # make sure overlay connections are being made
        self.config.set_start_recommender(True)

        # Write superpeers.txt
        self.install_path = tempfile.mkdtemp()
        spdir = os.path.join(self.install_path, 'Tribler', 'Core')
        os.makedirs(spdir)
        superpeerfilename = os.path.join(spdir, 'superpeer.txt')
        print >> sys.stderr, "test: writing", self.NLISTENERS, "superpeers to", superpeerfilename
        f = open(superpeerfilename, "w")

        self.mylistenport = []
        self.myss = []
        self.mykeypairs = []
        self.mypermids = []
        for i in range(self.NLISTENERS):
            # Start our server side, to with Tribler will try to connect
            self.mylistenport.append(4810 + i)
            self.myss.append(socket.socket(socket.AF_INET, socket.SOCK_STREAM))
            self.myss[i].setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.myss[i].bind(('', self.mylistenport[i]))
            self.myss[i].listen(1)

            self.mykeypairs.append(EC.gen_params(EC.NID_sect233k1))
            self.mykeypairs[i].gen_key()
            self.mypermids.append(str(self.mykeypairs[i].pub().get_der()))

            content = '127.0.0.1, ' + str(
                self.mylistenport[i]) + ', ' + show_permid(
                    self.mypermids[i]) + ', FakeSuperPeer\n'
            f.write(content)
        f.close()

        self.config.set_install_dir(self.install_path)
        """
Example #52
0
    def setUpPreSession(self):
        """ Should set self.config_path and self.config """
        self.config_path = tempfile.mkdtemp()
        self.install_path = '..'

        self.config = SessionStartupConfig()
        self.config.set_state_dir(self.config_path)
        self.config.set_listen_port(random.randint(10000, 60000))
        self.config.set_buddycast(False)
        self.config.set_start_recommender(False)
        self.config.set_torrent_checking(False)
        self.config.set_superpeer(False)
        self.config.set_dialback(False)
        self.config.set_social_networking(False)
        self.config.set_remote_query(False)
        self.config.set_internal_tracker(False)
        self.config.set_bartercast(False)
        self.config.set_install_dir(os.path.join('..', '..'))

        self.my_keypair = EC.gen_params(EC.NID_sect233k1)
        self.my_keypair.gen_key()
Example #53
0
    def setUpPreSession(self):
        """ Should set self.config_path and self.config """
        self.config_path = tempfile.mkdtemp()

        self.config = SessionStartupConfig()
        self.config.set_state_dir(self.config_path)
        self.config.set_listen_port(random.randint(10000, 60000))
        self.config.set_buddycast(False)
        self.config.set_start_recommender(False)
        self.config.set_torrent_checking(False)
        self.config.set_superpeer(False)
        self.config.set_dialback(False)
        self.config.set_social_networking(False)
        self.config.set_remote_query(False)
        self.config.set_internal_tracker(False)
        self.config.set_bartercast(False)
        self.config.set_multicast_local_peer_discovery(False)
        self.config.set_dispersy(False)
        # Assume all test scripts are run from Tribler/Test
        self.config.set_install_dir(os.path.abspath(os.path.join('..', '..')))

        self.my_keypair = EC.gen_params(EC.NID_sect233k1)
        self.my_keypair.gen_key()
Example #54
0
    def __init__(self, nid_or_path=None):
        """nid_or_path is either a nid to create a new key or a path to a pem encoded key"""

        self._key = None

        # we don't have anything to initialize anymore
        if type(nid_or_path) == type(None):
            return  # do nothing
        elif type(nid_or_path) == int:
            self._key = EC.gen_params(nid_or_path)
            self._key.gen_key()
        elif type(nid_or_path) == str:
            # the string is a DER public key ?
            # OID == 1.2.840.10045.2.1
            # encoder.encode(univ.ObjectIdentifier("1.2.840.10045.2.1"))
            if nid_or_path.startswith("\x30") and \
                    "\x06\x07\x2a\x86\x48\xce\x3d\x02\x01" in nid_or_path:
                self.PubKey_from_DER(nid_or_path)

            # the string is a PEM key ?
            elif "-----BEGIN EC PRIVATE KEY-----" in nid_or_path:
                self.from_PEM(nid_or_path)
            elif "-----BEGIN PUBLIC KEY-----" in nid_or_path:
                self.PubKey_from_PEM(nid_or_path)

            else:
                # the string is a path ?
                with open(nid_or_path) as f:
                    self.from_PEM(f.read())

        elif isinstance(nid_or_path, ECCkey):
            self.from_PEM(nid_or_path.to_PEM())
        else:
            raise ECCException(
                "ECCkey should be instanciated py a NID number or a path to a valid EC key"
                "")
Example #55
0
class TestU2FController(TestController):

    ATTESTATION_PRIVATE_KEY_PEM = \
        '-----BEGIN EC PRIVATE KEY-----\n' \
        'MHQCAQEEIBMsy03r5KbBIxkWY91FDJ7BvtTQhgPgndi282K4YrIOoAcGBSuBBAAK\n' \
        'oUQDQgAE6WAdbosEirjc9p2R17WVNzz9hbITpR90OMf/sK+1ncXMiNt06oXF/0zw\n' \
        'YnFZlka4GPRBhBtTWdgff+Ys/3JPKg==\n' \
        '-----END EC PRIVATE KEY-----'

    ATTESTATION_CERT_HEX = '30820202308201a8a003020102020900bedc78032c47968b300a06082a8648ce3d0' \
                           '40302305f310b30090603550406130244453113301106035504080c0a536f6d652d' \
                           '53746174653121301f060355040a0c18496e7465726e65742057696467697473205' \
                           '07479204c74643118301606035504030c0f4c696e4f545020553246205465737430' \
                           '1e170d3135303331383039353230315a170d3432303830333039353230315a305f3' \
                           '10b30090603550406130244453113301106035504080c0a536f6d652d5374617465' \
                           '3121301f060355040a0c18496e7465726e6574205769646769747320507479204c7' \
                           '4643118301606035504030c0f4c696e4f5450205532462054657374305630100607' \
                           '2a8648ce3d020106052b8104000a03420004e9601d6e8b048ab8dcf69d91d7b5953' \
                           '73cfd85b213a51f7438c7ffb0afb59dc5cc88db74ea85c5ff4cf06271599646b818' \
                           'f441841b5359d81f7fe62cff724f2aa350304e301d0603551d0e04160414c17d9d5' \
                           '2e8f4696d4f485353fa78e903dab72aae301f0603551d23041830168014c17d9d52' \
                           'e8f4696d4f485353fa78e903dab72aae300c0603551d13040530030101ff300a060' \
                           '82a8648ce3d0403020348003045022007e475efd0c9575e915ab89b5c8b1b436b2c' \
                           'c9a5cc4df37889e9511b1f7808f6022100c1faaa0fa5f36363962058a2e9f679338' \
                           'eca18b12725f807ffe68d1c05d3d35b'

    # Example key handle taken from the FIDO U2F specification
    KEY_HANDLE_HEX1 = '2a552dfdb7477ed65fd84133f86196010b2215b57da75d315b7b9e8fe2e3925a6019551ba' \
                      'b61d16591659cbaf00b4950f7abfe6660e2e006f76868b772d70c25'
    # Random made up key handle
    KEY_HANDLE_HEX2 = '2ae0b2f28fae6053fd697972ba7c81009137f4f46a764bc29751a28987d053ccfffb0687d' \
                      'ef306f47fd45906e838401a6437270a45a37da9c25d8db8b559a888'

    # Generate ECC key, NIST P-256 elliptic curve
    ECC_KEY1 = EC.gen_params(EC.NID_X9_62_prime256v1)
    ECC_KEY1.gen_key()

    ECC_KEY2 = EC.gen_params(EC.NID_X9_62_prime256v1)
    ECC_KEY2.gen_key()

    key_set = {1: (KEY_HANDLE_HEX1, ECC_KEY1), 2: (KEY_HANDLE_HEX2, ECC_KEY2)}

    key_handle_set = {
        KEY_HANDLE_HEX1: ECC_KEY1,
        KEY_HANDLE_HEX2: ECC_KEY2,
    }

    FAKE_REGISTRATION_DATA_HEX = '0504113fafb0da1a6a90bb3a017552c1561af88bfd02c36eec334551959' \
                                 'ffe562a6f050b496545810b64b738e7673a314efd67216cc1b7c7e46f1b' \
                                 '34dcd6212a36fe402a552dfdb7477ed65fd84133f86196010b2215b57da' \
                                 '75d315b7b9e8fe2e3925a6019551bab61d16591659cbaf00b4950f7abfe' \
                                 '6660e2e006f76868b772d70c2530820202308201a8a003020102020900b' \
                                 'edc78032c47968b300a06082a8648ce3d040302305f310b300906035504' \
                                 '06130244453113301106035504080c0a536f6d652d53746174653121301' \
                                 'f060355040a0c18496e7465726e6574205769646769747320507479204c' \
                                 '74643118301606035504030c0f4c696e4f5450205532462054657374301' \
                                 'e170d3135303331383039353230315a170d343230383033303935323031' \
                                 '5a305f310b30090603550406130244453113301106035504080c0a536f6' \
                                 'd652d53746174653121301f060355040a0c18496e7465726e6574205769' \
                                 '646769747320507479204c74643118301606035504030c0f4c696e4f545' \
                                 '02055324620546573743056301006072a8648ce3d020106052b8104000a' \
                                 '03420004e9601d6e8b048ab8dcf69d91d7b595373cfd85b213a51f7438c' \
                                 '7ffb0afb59dc5cc88db74ea85c5ff4cf06271599646b818f441841b5359' \
                                 'd81f7fe62cff724f2aa350304e301d0603551d0e04160414c17d9d52e8f' \
                                 '4696d4f485353fa78e903dab72aae301f0603551d23041830168014c17d' \
                                 '9d52e8f4696d4f485353fa78e903dab72aae300c0603551d13040530030' \
                                 '101ff300a06082a8648ce3d0403020348003045022007e475efd0c9575e' \
                                 '915ab89b5c8b1b436b2cc9a5cc4df37889e9511b1f7808f6022100c1faa' \
                                 'a0fa5f36363962058a2e9f679338eca18b12725f807ffe68d1c05d3d35b' \
                                 '30440220387f2d2927e4a2bb9053b4ac09b22cc4c1bac2987e868be6f22' \
                                 '6a8f139171838022013e19c68829d52b2e5db0e80e2efb46738cc418ea9' \
                                 'ef3b94664f3817e18ddc4d'

    serials = set()

    def setUp(self):
        self.serial = ''
        self.counter = 0
        self.origin = 'https://u2f-fakeurl.com'
        TestController.setUp(self)
        self.__createResolvers__()
        self.__createRealms__()

    def tearDown(self):
        for serial in self.serials:
            self.removeTokenBySerial(serial)
        self.__deleteAllRealms__()
        self.__deleteAllResolvers__()
        TestController.tearDown(self)

    def _registration1(self, pin=None):
        """
        Performs the first registration step
        """
        parameters = {
            'type': 'u2f',
            'phase': 'registration1',
            'user': '******',
            'session': self.session
        }
        if pin is not None:
            parameters['pin'] = pin

        response = self.app.get(url(controller='admin', action='init'),
                                params=parameters)
        return response

    def _registration2(self, register_response_message, pin=None):
        """
        Performs the second registration step
        """
        parameters = {
            'type': 'u2f',
            'phase': 'registration2',
            'user': '******',
            'otpkey': register_response_message,
            'serial': self.serial,
            'session': self.session
        }
        if pin is not None:
            parameters['pin'] = pin

        response = self.app.get(url(controller='admin', action='init'),
                                params=parameters)
        return response

    def _authentication1(self, pin=None):
        """
        Performs the initial authentication step
        """
        parameters = {'user': '******', 'pass': ''}
        if pin is not None:
            parameters['pass'] = pin

        response = self.app.get(url(controller='validate', action='check'),
                                params=parameters)
        return response

    def _authentication2(self, transactionid, authentication_response_message):
        """
        Performs the second authentication step
        """
        parameters = {'user': '******', 'transactionid': transactionid}

        parameters['pass'] = authentication_response_message

        response = self.app.get(url(controller='validate', action='check'),
                                params=parameters)

        return response

    def _createClientDataObject(self, typ, challenge):
        """
        Creates a client data object of the type 'registration' or 'authentication'
        """
        typ_string = ''
        if typ == 'registration':
            typ_string = 'navigator.id.finishEnrollment'
        elif typ == 'authentication':
            typ_string = 'navigator.id.getAssertion'
        else:
            raise ValueError('Unknown typ')

        client_data_object = {
            'typ': typ_string,
            'challenge': challenge,
            'origin': self.origin
        }
        client_data_object_JSON = json.dumps(client_data_object)
        return client_data_object_JSON

    def _createRegistrationResponseMessage(self,
                                           client_data,
                                           key_set=None,
                                           correct=True):
        """
        Create a registration response message according to the FIDO U2F specification
        """
        if not key_set:
            raise ValueError("Unknown key number requested!")
        (key_handle_hex, ecc_key) = key_set

        #
        # Create the registration_data object
        #
        registration_data = chr(0x05)  # First byte must be 0x05

        # The public key length is set to a fixed length of 65 characters in the U2F specification
        public_key = str(ecc_key.pub().get_der())[-65:]
        registration_data += public_key

        key_handle = binascii.unhexlify(key_handle_hex)
        registration_data += chr(len(key_handle))
        registration_data += key_handle

        attestation_cert_der = binascii.unhexlify(self.ATTESTATION_CERT_HEX)
        registration_data += attestation_cert_der

        # Create the ECDSA signature
        digest = sha256()
        digest.update(
            chr(0x00) + sha256(self.origin).digest() +
            sha256(client_data).digest() + key_handle + public_key)

        cert_private_key = EC.load_key_bio(
            BIO.MemoryBuffer(self.ATTESTATION_PRIVATE_KEY_PEM))
        signature = cert_private_key.sign_dsa_asn1(digest.digest())

        if correct is False:
            # Change the signature to create an invalid registration response
            signature = signature[:-1]

        registration_data += signature

        #
        # Create the registration_response
        #
        registration_response = {
            'registrationData': base64.urlsafe_b64encode(registration_data),
            'clientData': base64.urlsafe_b64encode(client_data)
        }

        return json.dumps(registration_response)

    def _createAuthenticationResponseMessage(self,
                                             client_data,
                                             key_handle,
                                             ecc_key=None,
                                             correct=True):
        """
        Create an authentication response message according to the FIDO U2F specification
        """
        # get the correct token for creating the response message
        if not ecc_key:
            raise ValueError("Unknown key handle received.")

        #
        # Create the signatureData object
        #
        authentication_data = chr(0x01)  # User presence byte

        # counter
        self.counter += 1
        authentication_data += struct.pack('>I', self.counter)

        # signature
        digest = sha256()
        digest.update(
            sha256(self.origin).digest() + chr(0x01) +
            struct.pack('>I', self.counter) + sha256(client_data).digest())
        signature = ecc_key.sign_dsa_asn1(digest.digest())

        if correct is False:
            # Change the signature to create an invalid authentication response
            signature = signature[:-1]

        authentication_data += signature

        #
        # Create the signResponse object
        #
        key_handle_index = 1
        # Remove trailing '=' characters
        while key_handle[-key_handle_index] == '=':
            key_handle_index = key_handle_index + 1
        if key_handle_index > 1:
            key_handle = key_handle[:-(key_handle_index - 1)]
        sign_response = {
            'keyHandle': key_handle,
            'signatureData': base64.urlsafe_b64encode(authentication_data),
            'clientData': base64.urlsafe_b64encode(client_data)
        }

        return json.dumps(sign_response)

    def _registration(self, pin=None, correct=True, key_num=1):
        """
        Enroll a U2F token with given token pin
        """
        # Initial token registration step
        response_registration1_JSON = self._registration1(pin)
        self.assertTrue('"value": true' in response_registration1_JSON,
                        "Response: %r" % response_registration1_JSON)
        self.assertTrue('"challenge":' in response_registration1_JSON,
                        "Response: %r" % response_registration1_JSON)
        self.assertTrue('"serial":' in response_registration1_JSON,
                        "Response: %r" % response_registration1_JSON)

        response_registration1 = json.loads(response_registration1_JSON.body)
        challenge_registration = response_registration1.get(
            'detail', {}).get('challenge')
        self.serial = response_registration1.get('detail', {}).get('serial')
        self.serials.add(self.serial)

        # Construct the registration response message
        client_data_registration = self._createClientDataObject(
            'registration',
            challenge_registration,
        )

        key_set = self.key_set.get(key_num, None)

        registration_response_message = \
            self._createRegistrationResponseMessage(client_data_registration,
                                                    correct=correct,
                                                    key_set=key_set
                                                    )

        # Complete the token registration
        response_registration2_JSON = self._registration2(
            registration_response_message, pin)
        if correct is True:
            # Registration should be successful
            self.assertTrue('"value": true' in response_registration2_JSON,
                            "Response: %r" % response_registration2_JSON)
        else:
            # Registration should have failed
            self.assertTrue('"status": false' in response_registration2_JSON,
                            "Response: %r" % response_registration2_JSON)

        return

    def _authentication_challenge(self, pin=None):
        """
        Test authentication of a previously registered token with given token pin
        """
        # Initial authentication phase
        response_authentication1_JSON = self._authentication1(pin)
        self.assertTrue('"value": false' in response_authentication1_JSON,
                        "Response: %r" % response_authentication1_JSON)
        self.assertTrue('"transactionid":' in response_authentication1_JSON,
                        "Response: %r" % response_authentication1_JSON)
        self.assertTrue('"message":' in response_authentication1_JSON,
                        "Response: %r" % response_authentication1_JSON)
        self.assertTrue('\\"challenge\\":' in response_authentication1_JSON,
                        "Response: %r" % response_authentication1_JSON)
        self.assertTrue('\\"version\\":' in response_authentication1_JSON,
                        "Response: %r" % response_authentication1_JSON)
        self.assertTrue('\\"keyHandle\\":' in response_authentication1_JSON,
                        "Response: %r" % response_authentication1_JSON)

        response_authentication1 = json.loads(
            response_authentication1_JSON.body)
        message_authentication_JSON = response_authentication1.get(
            'detail', {}).get('message')

        reply = []
        if message_authentication_JSON == "Multiple challenges submitted.":
            challenges = response_authentication1.get('detail')

            del challenges['message']
            del challenges['transactionid']

            for challenge in challenges:
                reply.append(
                    response_authentication1.get('detail').get(challenge))
        else:
            reply.append(response_authentication1.get('detail'))
        return reply

    def _authentication_response(self, challenge, correct=True):
        message_authentication = json.loads(challenge.get('message', ''))
        challenge_authentication = message_authentication.get('challenge', {})

        # Does the received keyHandle match the sent one?
        key_handle_authentication = message_authentication.get('keyHandle', '')
        transactionid_authentication = challenge.get('transactionid')
        # Correct the padding
        key_handle_authentication = \
            key_handle_authentication + ('=' * (4 - (len(key_handle_authentication) % 4)))
        key_handle_authentication = key_handle_authentication.encode('ascii')
        self.assertTrue(binascii.hexlify(base64.urlsafe_b64decode(key_handle_authentication)) in \
                        [self.KEY_HANDLE_HEX1, self.KEY_HANDLE_HEX2],
                        "Message: %r" % message_authentication
                        )

        # Construct the registration response message
        client_data_authentication = self._createClientDataObject(
            'authentication',
            challenge_authentication,
        )

        key_handle_hex = binascii.hexlify(
            base64.urlsafe_b64decode(key_handle_authentication))
        ecc_key = self.key_handle_set.get(key_handle_hex, None)

        authentication_response_message = \
            self._createAuthenticationResponseMessage(client_data_authentication,
                                                      key_handle_authentication,
                                                      ecc_key=ecc_key,
                                                      correct=correct
                                                      )
        # Complete the token authentication
        response_authentication2_JSON = self._authentication2(
            transactionid_authentication,
            authentication_response_message,
        )
        if correct is True:
            # Authentication should be successful
            self.assertTrue('"value": true' in response_authentication2_JSON,
                            "Response: %r" % response_authentication2_JSON)
        else:
            # Authentication should have failed
            self.assertTrue('"value": false' in response_authentication2_JSON,
                            "Response: %r" % response_authentication2_JSON)

    def _has_EC_support(self):
        has_ec_support = True
        # U2F needs OpenSSL 1.0.0 or higher
        # The EC OpenSSL API calls made by M2Crypto don't work with OpenSSl 0.9.8!
        version_text = m2.OPENSSL_VERSION_TEXT
        match = re.match(r"OpenSSL (?P<version>\d\.\d\.\d)", version_text)
        if match is None:
            # Fail on unknown OpenSSL version string format
            self.fail(
                "Could not detect OpenSSL version - unknown version string format: '%s'"
                % version_text)
        else:
            if match.group('version')[0] == '0':
                has_ec_support = False

        # The following command needs support for ECDSA in openssl!
        # Since Red Hat systems (including Fedora) use an openssl version without
        # support for the NIST P-256 elliptic curve (as of March 2015),
        # this command will fail with a NULL pointer exception on these systems
        try:
            EC.load_key_bio(BIO.MemoryBuffer(self.ATTESTATION_PRIVATE_KEY_PEM))
        except ValueError:
            has_ec_support = False

        return has_ec_support

    def test_u2f_registration_and_authentication_without_pin(self):
        """
        Enroll a U2F token without a token pin and authenticate
        """
        if not self._has_EC_support():
            self.skipTest(
                "Probably no OpenSSL support for the needed NIST P-256 curve!")
        self._registration()
        # Authenticate twice
        challenges = self._authentication_challenge()
        self._authentication_response(challenges[0])
        challenges = self._authentication_challenge()
        self._authentication_response(challenges[0])
        return

    def test_u2f_multiple_registration_and_authentication_without_pin(self):
        """
        Enroll a U2F token without a token pin and authenticate
        """
        if not self._has_EC_support():
            self.skipTest(
                "Probably no OpenSSL support for the needed NIST P-256 curve!")
        self._registration(key_num=1)
        self._registration(key_num=2)

        # Try authenticating twice with each token
        challenges = self._authentication_challenge()
        self._authentication_response(challenges[1])
        challenges = self._authentication_challenge()
        self._authentication_response(challenges[1])
        challenges = self._authentication_challenge()
        self._authentication_response(challenges[0])
        challenges = self._authentication_challenge()
        self._authentication_response(challenges[0])
        return

    def test_u2f_registration_and_wrong_authentication_without_pin(self):
        """
        Enroll a U2F token without a token pin and perform an invalid authentication
        """
        if not self._has_EC_support():
            self.skipTest(
                "Probably no OpenSSL support for the needed NIST P-256 curve!")
        self._registration()
        # Authenticate twice
        challenges = self._authentication_challenge()
        self._authentication_response(challenges[0], correct=False)
        return

    def test_u2f_multiple_registration_and_wrong_authentication_without_pin(
            self):
        """
        Enroll a U2F token without a token pin and authenticate
        """
        if not self._has_EC_support():
            self.skipTest(
                "Probably no OpenSSL support for the needed NIST P-256 curve!")
        self._registration(key_num=1)
        self._registration(key_num=2)

        # Try authenticating twice with each token
        challenges = self._authentication_challenge()
        self._authentication_response(challenges[0], correct=False)
        challenges = self._authentication_challenge()
        self._authentication_response(challenges[1], correct=False)
        return

    def test_u2f_wrong_registration_without_pin(self):
        """
        Try an invalid registration of a U2F token without pin
        """
        if not self._has_EC_support():
            self.skipTest(
                "Probably no OpenSSL support for the needed NIST P-256 curve!")
        self._registration(correct=False)
        return

    def test_u2f_registration_and_authentication_with_pin(self):
        """
        Enroll a U2F token with a token pin and authenticate
        """
        if not self._has_EC_support():
            self.skipTest(
                "Probably no OpenSSL support for the needed NIST P-256 curve!")
        pin = 'test{pass}word_with{curly-braces{'
        self._registration(pin)
        # Authenticate twice
        challenges = self._authentication_challenge(pin)
        self._authentication_response(challenges[0])
        challenges = self._authentication_challenge(pin)
        self._authentication_response(challenges[0])
        return

    def test_u2f_multiple_registration_and_authentication_with_pin(self):
        """
        Enroll a U2F token without a token pin and authenticate
        """
        if not self._has_EC_support():
            self.skipTest(
                "Probably no OpenSSL support for the needed NIST P-256 curve!")
        pin = 'test{pass}word_with{curly-braces{'
        self._registration(pin=pin, key_num=1)
        self._registration(pin=pin, key_num=2)

        # Try authenticating twice with each token
        challenges = self._authentication_challenge(pin)
        self._authentication_response(challenges[1])
        challenges = self._authentication_challenge(pin)
        self._authentication_response(challenges[1])
        challenges = self._authentication_challenge(pin)
        self._authentication_response(challenges[0])
        challenges = self._authentication_challenge(pin)
        self._authentication_response(challenges[0])
        return

    def test_u2f_registration_and_wrong_authentication_with_pin(self):
        """
        Enroll a U2F token with a token pin and authenticate
        """
        if not self._has_EC_support():
            self.skipTest(
                "Probably no OpenSSL support for the needed NIST P-256 curve!")
        pin = 'test{pass}word_with{curly-braces{'
        self._registration(pin)
        challenges = self._authentication_challenge(pin)
        self._authentication_response(challenges[0], correct=False)
        return

    def test_u2f_multiple_registration_and_wrong_authentication_with_pin(self):
        """
        Enroll a U2F token without a token pin and authenticate
        """
        if not self._has_EC_support():
            self.skipTest(
                "Probably no OpenSSL support for the needed NIST P-256 curve!")
        pin = 'test{pass}word_with{curly-braces{'
        self._registration(pin=pin, key_num=1)
        self._registration(pin=pin, key_num=2)

        # Try authenticating twice with each token
        challenges = self._authentication_challenge(pin)
        self._authentication_response(challenges[0], correct=False)
        challenges = self._authentication_challenge(pin)
        self._authentication_response(challenges[1], correct=False)
        return

    def test_u2f_wrong_registration_with_pin(self):
        """
        Try an invalid registration of a U2F token with pin
        """
        if not self._has_EC_support():
            self.skipTest(
                "Probably no OpenSSL support for the needed NIST P-256 curve!")
        pin = 'test{pass}word_with{curly-braces{'
        self._registration(pin=pin, correct=False)
        return

    def test_u2f_unsupported_openssl_version(self):
        """
        Try a registration with an unsupported OpenSSL version and check the error messages
        """
        version_text = m2.OPENSSL_VERSION_TEXT
        match = re.match(r"OpenSSL (?P<version>\d\.\d\.\d)", version_text)
        if match is None:
            # Fail on unknown OpenSSL version string format
            self.fail(
                "Could not detect OpenSSL version - unknown version string format: '%s'"
                % version_text)
        else:
            if match.group('version')[0] != '0':
                # Supported OpenSSL version - skip test
                self.skipTest(
                    "This test can only be run with an unsupported OpenSSL "
                    "version!")

        # Initial token registration step
        response_registration1_JSON = self._registration1()
        self.assertTrue('"value": true' in response_registration1_JSON,
                        "Response: %r" % response_registration1_JSON)
        self.assertTrue('"challenge":' in response_registration1_JSON,
                        "Response: %r" % response_registration1_JSON)
        self.assertTrue('"serial":' in response_registration1_JSON,
                        "Response: %r" % response_registration1_JSON)

        response_registration1 = json.loads(response_registration1_JSON.body)
        challenge_registration = response_registration1.get(
            'detail', {}).get('challenge')
        self.serial = response_registration1.get('detail', {}).get('serial')
        self.serials.add(self.serial)

        client_data_registration = self._createClientDataObject(
            'registration',
            challenge_registration,
        )
        # Since we have no supported OpenSSL version to calculate the registration response
        # we use a hard-coded correctly-formed fake registration response
        registration_response = binascii.unhexlify(
            self.FAKE_REGISTRATION_DATA_HEX)
        registration_response_message = {
            'registrationData':
            base64.urlsafe_b64encode(registration_response),
            'clientData': base64.urlsafe_b64encode(client_data_registration)
        }

        # Complete the token registration
        response_registration2_JSON = \
            self._registration2(json.dumps(registration_response_message))

        # Registration must fail
        self.assertTrue('"status": false' in response_registration2_JSON,
                        "Response: %r" % response_registration2_JSON)

        # Check for correct error messages
        self.assertTrue(
            '"message": "This version of OpenSSL is not supported!'
            in response_registration2_JSON,
            "Response: %r" % response_registration2_JSON)

    def test_u2f_unsupported_openssl_missing_curve(self):
        """
        Try registration with an OpenSSL missing the NIST P-256 curve and check the error messages
        """
        skip_test = True

        # Only allow OpenSSL >=1.0.0 with missing EC support
        version_text = m2.OPENSSL_VERSION_TEXT
        match = re.match(r"OpenSSL (?P<version>\d\.\d\.\d)", version_text)
        if match is None:
            # Fail on unknown OpenSSL version string format
            self.fail(
                "Could not detect OpenSSL version - unknown version string format: '%s'"
                % version_text)
        else:
            if match.group('version')[0] != '0':
                # Only run test on missing NIST P-256 curve support
                try:
                    EC.load_key_bio(
                        BIO.MemoryBuffer(self.ATTESTATION_PRIVATE_KEY_PEM))
                except ValueError:
                    skip_test = False

        if skip_test:
            self.skipTest("This test can only be run with OpenSSL missing the "
                          "NIST P-256 curve!")

        # Initial token registration step
        response_registration1_JSON = self._registration1()
        self.assertTrue('"value": true' in response_registration1_JSON,
                        "Response: %r" % response_registration1_JSON)
        self.assertTrue('"challenge":' in response_registration1_JSON,
                        "Response: %r" % response_registration1_JSON)
        self.assertTrue('"serial":' in response_registration1_JSON,
                        "Response: %r" % response_registration1_JSON)

        response_registration1 = json.loads(response_registration1_JSON.body)
        challenge_registration = response_registration1.get(
            'detail', {}).get('challenge')
        self.serial = response_registration1.get('detail', {}).get('serial')
        self.serials.add(self.serial)

        client_data_registration = self._createClientDataObject(
            'registration',
            challenge_registration,
        )
        # Since we have no supported OpenSSL version to calculate the registration response
        # we use a hard-coded correctly-formed fake registration response
        registration_response = binascii.unhexlify(
            self.FAKE_REGISTRATION_DATA_HEX)
        registration_response_message = {
            'registrationData':
            base64.urlsafe_b64encode(registration_response),
            'clientData': base64.urlsafe_b64encode(client_data_registration)
        }

        # Complete the token registration
        response_registration2_JSON = \
            self._registration2(json.dumps(registration_response_message))

        # Registration must fail
        self.assertTrue('"status": false' in response_registration2_JSON,
                        "Response: %r" % response_registration2_JSON)

        # Check for correct error messages
        self.assertTrue(
            'missing ECDSA support for the NIST P-256 curve in OpenSSL'
            in response_registration2_JSON,
            "Response: %r" % response_registration2_JSON)
Example #56
0
def generate_keypair():
    ec_keypair = EC.gen_params(KEYPAIR_ECC_CURVE)
    ec_keypair.gen_key()
    return ec_keypair
Example #57
0
 def test_genparam(self):
     ec = EC.gen_params(EC.NID_X9_62_prime256v1)
     assert len(ec) == 256