Ejemplo n.º 1
0
 def test_init(self):
     """
     Test that the PublicKey object is initialized correctly.
     """
     obj = keys.Key._fromRSAComponents(n=long(5), e=long(3))._keyObject
     key = keys.Key(obj)
     self.assertEqual(key._keyObject, obj)
Ejemplo n.º 2
0
 def test_init(self):
     """
     Test that the PublicKey object is initialized correctly.
     """
     obj = keys.Key._fromRSAComponents(n=long(5), e=long(3))._keyObject
     key = keys.Key(obj)
     self.assertEqual(key._keyObject, obj)
Ejemplo n.º 3
0
 def test_init(self):
     """
     Test that the PublicKey object is initialized correctly.
     """
     obj = Crypto.PublicKey.RSA.construct((long(1), long(2)))
     key = keys.Key(obj)
     self.assertEqual(key.keyObject, obj)
Ejemplo n.º 4
0
 def opt_random(self, option):
     try:
         self["random"] = long(option)
     except ValueError:
         raise usage.UsageError("Argument to --random must be a positive integer")
     else:
         if self["random"] < 0:
             raise usage.UsageError("Argument to --random must be a positive integer")
         elif self["random"] == 0:
             self["random"] = long(time.time() * 100)
Ejemplo n.º 5
0
 def opt_random(self, option):
     try:
         self['random'] = long(option)
     except ValueError:
         raise usage.UsageError(
             "Argument to --random must be a positive integer")
     else:
         if self['random'] < 0:
             raise usage.UsageError(
                 "Argument to --random must be a positive integer")
         elif self['random'] == 0:
             self['random'] = long(time.time() * 100)
Ejemplo n.º 6
0
 def test_notEqual(self):
     """
     Test that Key objects are not-compared correctly.
     """
     rsa1 = keys.Key(self.rsaObj)
     rsa2 = keys.Key(self.rsaObj)
     rsa3 = keys.Key(Crypto.PublicKey.RSA.construct((long(1), long(2))))
     dsa = keys.Key(self.dsaObj)
     self.assertFalse(rsa1 != rsa2)
     self.assertTrue(rsa1 != rsa3)
     self.assertTrue(rsa1 != dsa)
     self.assertTrue(rsa1 != object)
     self.assertTrue(rsa1 != None)
Ejemplo n.º 7
0
    def keyObject(self):
        """
        A C{Crypto.PublicKey} object similar to this key.

        As PyCrypto is no longer used for the underlying operations, this
        property should be avoided.
        """
        # Lazy import to have PyCrypto as a soft dependency.
        from Crypto.PublicKey import DSA, RSA

        keyObject = None
        keyType = self.type()
        keyData = self.data()
        isPublic = self.isPublic()

        if keyType == 'RSA':
            if isPublic:
                keyObject = RSA.construct((
                    keyData['n'],
                    long(keyData['e']),
                ))
            else:
                keyObject = RSA.construct((
                    keyData['n'],
                    long(keyData['e']),
                    keyData['d'],
                    keyData['p'],
                    keyData['q'],
                    keyData['u'],
                ))
        elif keyType == 'DSA':
            if isPublic:
                keyObject = DSA.construct((
                    keyData['y'],
                    keyData['g'],
                    keyData['p'],
                    keyData['q'],
                ))
            else:
                keyObject = DSA.construct((
                    keyData['y'],
                    keyData['g'],
                    keyData['p'],
                    keyData['q'],
                    keyData['x'],
                ))
        else:
            raise BadKeyError('Unsupported key type.')

        return keyObject
Ejemplo n.º 8
0
 def test_notEqual(self):
     """
     Test that Key objects are not-compared correctly.
     """
     rsa1 = keys.Key(self.rsaObj)
     rsa2 = keys.Key(self.rsaObj)
     rsa3 = keys.Key(
         keys.Key._fromRSAComponents(n=long(5), e=long(3))._keyObject)
     dsa = keys.Key(self.dsaObj)
     self.assertFalse(rsa1 != rsa2)
     self.assertTrue(rsa1 != rsa3)
     self.assertTrue(rsa1 != dsa)
     self.assertTrue(rsa1 != object)
     self.assertTrue(rsa1 != None)
Ejemplo n.º 9
0
    def keyObject(self):
        """
        A C{Crypto.PublicKey} object similar to this key.

        As PyCrypto is no longer used for the underlying operations, this
        property should be avoided.
        """
        # Lazy import to have PyCrypto as a soft dependency.
        from Crypto.PublicKey import DSA, RSA

        keyObject = None
        keyType = self.type()
        keyData = self.data()
        isPublic = self.isPublic()

        if keyType == 'RSA':
            if isPublic:
                keyObject = RSA.construct((
                    keyData['n'],
                    long(keyData['e']),
                    ))
            else:
                keyObject = RSA.construct((
                    keyData['n'],
                    long(keyData['e']),
                    keyData['d'],
                    keyData['p'],
                    keyData['q'],
                    keyData['u'],
                    ))
        elif keyType == 'DSA':
            if isPublic:
                keyObject = DSA.construct((
                    keyData['y'],
                    keyData['g'],
                    keyData['p'],
                    keyData['q'],
                    ))
            else:
                keyObject = DSA.construct((
                    keyData['y'],
                    keyData['g'],
                    keyData['p'],
                    keyData['q'],
                    keyData['x'],
                    ))
        else:
            raise BadKeyError('Unsupported key type.')

        return keyObject
Ejemplo n.º 10
0
 def test_notEqual(self):
     """
     Test that Key objects are not-compared correctly.
     """
     rsa1 = keys.Key(self.rsaObj)
     rsa2 = keys.Key(self.rsaObj)
     rsa3 = keys.Key(
         keys.Key._fromRSAComponents(n=long(5), e=long(3))._keyObject)
     dsa = keys.Key(self.dsaObj)
     self.assertFalse(rsa1 != rsa2)
     self.assertTrue(rsa1 != rsa3)
     self.assertTrue(rsa1 != dsa)
     self.assertTrue(rsa1 != object)
     self.assertTrue(rsa1 != None)
Ejemplo n.º 11
0
def parseModuliFile(filename):
    with open(filename) as f:
        lines = f.readlines()
    primes = {}
    for l in lines:
        l = l.strip()
        if not l or l[0] == '#':
            continue
        tim, typ, tst, tri, size, gen, mod = l.split()
        size = int(size) + 1
        gen = long(gen)
        mod = long(mod, 16)
        if size not in primes:
            primes[size] = []
        primes[size].append((gen, mod))
    return primes
Ejemplo n.º 12
0
def parseModuliFile(filename):
    with open(filename) as f:
        lines = f.readlines()
    primes = {}
    for l in lines:
        l = l.strip()
        if  not l or l[0]=='#':
            continue
        tim, typ, tst, tri, size, gen, mod = l.split()
        size = int(size) + 1
        gen = long(gen)
        mod = long(mod, 16)
        if size not in primes:
            primes[size] = []
        primes[size].append((gen, mod))
    return primes
Ejemplo n.º 13
0
def _fastgetMP(data, count=1):
    mp = []
    c = 0
    for i in range(count):
        length = struct.unpack('!L', data[c:c + 4])[0]
        mp.append(long(
            gmpy.mpz(data[c + 4:c + 4 + length][::-1] + b'\x00', 256)))
        c += length + 4
    return tuple(mp) + (data[c:],)
Ejemplo n.º 14
0
def _fastgetMP(data, count=1):
    mp = []
    c = 0
    for i in range(count):
        length = struct.unpack('!L', data[c:c + 4])[0]
        mp.append(
            long(gmpy.mpz(data[c + 4:c + 4 + length][::-1] + b'\x00', 256)))
        c += length + 4
    return tuple(mp) + (data[c:], )
Ejemplo n.º 15
0
 def test_string_int_or_string(self):
     Type = self.spec.pclass_for_definition(u"string.int-or-string")
     self.expectThat(
         lambda: Type(s=b"foo"),
         raises_exception(PTypeError),
     )
     self.expectThat(Type(s=u"foo").s, Equals(u"foo"))
     self.expectThat(Type(s=u"50").s, Equals(u"50"))
     self.expectThat(Type(s=50).s, Equals(50))
     self.expectThat(Type(s=long(50)).s, Equals(50))
Ejemplo n.º 16
0
 def test_int(self):
     """
     A positive integer less than 2 ** 32 should round-trip through
     banana without changing value and should come out represented
     as an C{int} (regardless of the type which was encoded).
     """
     for value in (10151, long(10151)):
         self.enc.sendEncoded(value)
         self.enc.dataReceived(self.io.getvalue())
         self.assertEqual(self.result, 10151)
         self.assertIsInstance(self.result, int)
Ejemplo n.º 17
0
 def test_int(self):
     """
     A positive integer less than 2 ** 32 should round-trip through
     banana without changing value and should come out represented
     as an C{int} (regardless of the type which was encoded).
     """
     for value in (10151, long(10151)):
         self.enc.sendEncoded(value)
         self.enc.dataReceived(self.io.getvalue())
         self.assertEqual(self.result, 10151)
         self.assertIsInstance(self.result, int)
Ejemplo n.º 18
0
 def setUp(self):
     self.rsaObj = Crypto.PublicKey.RSA.construct(
         (long(1), long(2), long(3), long(4), long(5)))
     self.dsaObj = Crypto.PublicKey.DSA.construct(
         (long(1), long(2), long(3), long(4), long(5)))
     self.rsaSignature = (
         b'\x00\x00\x00\x07ssh-rsa\x00'
         b'\x00\x00`N\xac\xb4@qK\xa0(\xc3\xf2h \xd3\xdd\xee6Np\x9d_'
         b'\xb0>\xe3\x0c(L\x9d{\txUd|!\xf6m\x9c\xd3\x93\x842\x7fU'
         b'\x05\xf4\xf7\xfaD\xda\xce\x81\x8ea\x7f=Y\xed*\xb7\xba\x81'
         b'\xf2\xad\xda\xeb(\x97\x03S\x08\x81\xc7\xb1\xb7\xe6\xe3'
         b'\xcd*\xd4\xbd\xc0wt\xf7y\xcd\xf0\xb7\x7f\xfb\x1e>\xf9r'
         b'\x8c\xba')
     self.dsaSignature = (
         b'\x00\x00\x00\x07ssh-dss\x00\x00\x00(?\xc7\xeb\x86;\xd5TFA\xb4'
         b'\xdf\x0c\xc4E@4,d\xbc\t\xd9\xae\xdd[\xed-\x82nQ\x8cf\x9b\xe8\xe1'
         b'jrg\x84p<')
     self.oldSecureRandom = randbytes.secureRandom
     randbytes.secureRandom = lambda x: b'\xff' * x
     self.keyFile = self.mktemp()
     open(self.keyFile, 'wb').write(keydata.privateRSA_lsh)
 def test_constantsAgainstSpec(self):
     """
     The constants used by the SFTP protocol implementation match those
     found by searching through the spec.
     """
     constants = {}
     for excerpt in self.filexferSpecExcerpts:
         for line in excerpt.splitlines():
             m = re.match('^\s*#define SSH_([A-Z_]+)\s+([0-9x]*)\s*$', line)
             if m:
                 constants[m.group(1)] = long(m.group(2), 0)
     self.assertTrue(
         len(constants) > 0, "No constants found (the test must be buggy).")
     for k, v in constants.items():
         self.assertEqual(v, getattr(filetransfer, k))
Ejemplo n.º 20
0
def getGitMagic():
    try:
        with open("/sys/devices/platform/ff000000.zsiposver/zsiposver",
                  'r') as f:
            for l in f.readlines():
                n, v = l.split(':')
                gitversions[n] = long(v, 16)
    except:
        gitversions['FPGA-GIT'] = 0
        gitversions['KERNEL-GIT'] = 0
    res = 0
    for n, v in gitversions.items():
        if not n in ['FPGA-GIT', 'KERNEL-GIT']:
            res = res ^ v
    return res
Ejemplo n.º 21
0
def touch_file(path, offset_seconds=None):
    """Touch a file, creating it if it doesn't exist.

    @param path: the path to the file to be touched.
    @param offset_seconds: a signed integer number of seconds to offset the
        atime and mtime of the file from the current time.

    """
    open(path, "ab").close()
    if offset_seconds is not None:
        offset_time = long(time.time()) + offset_seconds
        touch_time = (offset_time, offset_time)
    else:
        touch_time = None
    os.utime(path, touch_time)
Ejemplo n.º 22
0
 def test_constantsAgainstSpec(self):
     """
     The constants used by the SFTP protocol implementation match those
     found by searching through the spec.
     """
     constants = {}
     for excerpt in self.filexferSpecExcerpts:
         for line in excerpt.splitlines():
             m = re.match('^\s*#define SSH_([A-Z_]+)\s+([0-9x]*)\s*$', line)
             if m:
                 constants[m.group(1)] = long(m.group(2), 0)
     self.assertTrue(
         len(constants) > 0, "No constants found (the test must be buggy).")
     for k, v in constants.items():
         self.assertEqual(v, getattr(filetransfer, k))
Ejemplo n.º 23
0
class _DHGroup1SHA1(object):
    """
    Diffie-Hellman key exchange with SHA-1 as HASH, and Oakley Group 2
    (1024-bit MODP Group). Defined in RFC 4253, 8.1.
    """

    preference = 3
    hashProcessor = sha1
    # Diffie-Hellman primes from Oakley Group 2 (RFC 2409, 6.2).
    prime = long(
        '17976931348623159077083915679378745319786029604875601170644'
        '44236841971802161585193689478337958649255415021805654859805036464405'
        '48199239100050792877003355816639229553136239076508735759914822574862'
        '57500742530207744771258955095793777842444242661733472762929938766870'
        '9205606050270810842907692932019128194467627007')
    generator = 2
Ejemplo n.º 24
0
    def test_touch_file_with_offset_seconds(self):
        """
        The L{touch_file} function can be called with a offset in seconds that
        will be reflected in the access and modification times of the file.
        """
        path = self.makeFile()
        current_time = long(time.time())
        expected_time = current_time - 1

        with patch.object(time, "time",
                          return_value=current_time) as time_mock:
            with patch.object(os, "utime") as utime_mock:
                touch_file(path, offset_seconds=-1)

        time_mock.assert_called_once_with()
        utime_mock.assert_called_once_with(path,
                                           (expected_time, expected_time))

        self.assertFileContent(path, b"")
Ejemplo n.º 25
0
class _DHGroup14SHA1:
    """
    Diffie-Hellman key exchange with SHA-1 as HASH and Oakley Group 14
    (2048-bit MODP Group). Defined in RFC 4253, 8.2.
    """

    preference = 8
    hashProcessor = sha1
    # Diffie-Hellman primes from Oakley Group 14 (RFC 3526, 3).
    prime = long('32317006071311007300338913926423828248817941241140239112842'
        '00975140074170663435422261968941736356934711790173790970419175460587'
        '32091950288537589861856221532121754125149017745202702357960782362488'
        '84246189477587641105928646099411723245426622522193230540919037680524'
        '23551912567971587011700105805587765103886184728025797605490356973256'
        '15261670813393617995413364765591603683178967290731783845896806396719'
        '00977202194168647225871031411336429319536193471636533209717077448227'
        '98858856536920864529663607725026895550592836275112117409697299806841'
        '05543595848665832916421362182310789909994486524682624169720359118525'
        '07045361090559')
    generator = 2
Ejemplo n.º 26
0
 def _lookupChannelErrorTest(self, code):
     """
     Deliver a request for a channel open which will result in an exception
     being raised during channel lookup.  Assert that an error response is
     delivered as a result.
     """
     self.transport.avatar._ARGS_ERROR_CODE = code
     self.conn.ssh_CHANNEL_OPEN(
         common.NS(b'conch-error-args') + b'\x00\x00\x00\x01' * 4)
     errors = self.flushLoggedErrors(error.ConchError)
     self.assertEqual(
         len(errors), 1, "Expected one error, got: %r" % (errors,))
     self.assertEqual(errors[0].value.args, (long(123), "error args in wrong order"))
     self.assertEqual(
         self.transport.packets,
         [(connection.MSG_CHANNEL_OPEN_FAILURE,
           # The response includes some bytes which identifying the
           # associated request, as well as the error code (7b in hex) and
           # the error message.
           b'\x00\x00\x00\x01\x00\x00\x00\x7b' + common.NS(
                     b'error args in wrong order') + common.NS(b''))])
Ejemplo n.º 27
0
 def _lookupChannelErrorTest(self, code):
     """
     Deliver a request for a channel open which will result in an exception
     being raised during channel lookup.  Assert that an error response is
     delivered as a result.
     """
     self.transport.avatar._ARGS_ERROR_CODE = code
     self.conn.ssh_CHANNEL_OPEN(
         common.NS(b'conch-error-args') + b'\x00\x00\x00\x01' * 4)
     errors = self.flushLoggedErrors(error.ConchError)
     self.assertEqual(
         len(errors), 1, "Expected one error, got: %r" % (errors,))
     self.assertEqual(errors[0].value.args, (long(123), "error args in wrong order"))
     self.assertEqual(
         self.transport.packets,
         [(connection.MSG_CHANNEL_OPEN_FAILURE,
           # The response includes some bytes which identifying the
           # associated request, as well as the error code (7b in hex) and
           # the error message.
           b'\x00\x00\x00\x01\x00\x00\x00\x7b' + common.NS(
                     b'error args in wrong order') + common.NS(b''))])
Ejemplo n.º 28
0
 def test_lookupChannelErrorLongCode(self):
     """
     Like L{test_lookupChannelError}, but for the case where the failure code
     is represented as a L{long} instead of a L{int}.
     """
     self._lookupChannelErrorTest(long(123))
Ejemplo n.º 29
0
    def _fromString_PRIVATE_OPENSSH(Class, data, passphrase):
        """
        Return a private key object corresponding to this OpenSSH private key
        string.  If the key is encrypted, passphrase MUST be provided.
        Providing a passphrase for an unencrypted key is an error.

        The format of an OpenSSH private key string is::
            -----BEGIN <key type> PRIVATE KEY-----
            [Proc-Type: 4,ENCRYPTED
            DEK-Info: DES-EDE3-CBC,<initialization value>]
            <base64-encoded ASN.1 structure>
            ------END <key type> PRIVATE KEY------

        The ASN.1 structure of a RSA key is::
            (0, n, e, d, p, q)

        The ASN.1 structure of a DSA key is::
            (0, p, q, g, y, x)

        @type data: C{bytes}
        @type passphrase: C{bytes}
        @return: a C{Crypto.PublicKey.pubkey.pubkey} object
        @raises BadKeyError: if
            * a passphrase is provided for an unencrypted key
            * the ASN.1 encoding is incorrect
        @raises EncryptedKeyError: if
            * a passphrase is not provided for an encrypted key
        """
        lines = data.strip().split(b'\n')
        kind = lines[0][11:14]
        if lines[1].startswith(b'Proc-Type: 4,ENCRYPTED'):  # encrypted key
            if not passphrase:
                raise EncryptedKeyError('Passphrase must be provided '
                                        'for an encrypted key')

            # Determine cipher and initialization vector
            try:
                _, cipher_iv_info = lines[2].split(b' ', 1)
                cipher, ivdata = cipher_iv_info.rstrip().split(b',', 1)
            except ValueError:
                raise BadKeyError('invalid DEK-info %r' % (lines[2], ))

            if cipher == b'AES-128-CBC':
                CipherClass = AES
                keySize = 16
                if len(ivdata) != 32:
                    raise BadKeyError('AES encrypted key with a bad IV')
            elif cipher == b'DES-EDE3-CBC':
                CipherClass = DES3
                keySize = 24
                if len(ivdata) != 16:
                    raise BadKeyError('DES encrypted key with a bad IV')
            else:
                raise BadKeyError('unknown encryption type %r' % (cipher, ))

            # extract keyData for decoding
            iv = bytes(
                bytearray([
                    int(ivdata[i:i + 2], 16) for i in range(0, len(ivdata), 2)
                ]))
            ba = md5(passphrase + iv[:8]).digest()
            bb = md5(ba + passphrase + iv[:8]).digest()
            decKey = (ba + bb)[:keySize]
            b64Data = base64.decodestring(b''.join(lines[3:-1]))
            keyData = CipherClass.new(decKey, CipherClass.MODE_CBC,
                                      iv).decrypt(b64Data)
            removeLen = ord(keyData[-1:])
            keyData = keyData[:-removeLen]
        else:
            b64Data = b''.join(lines[1:-1])
            keyData = base64.decodestring(b64Data)

        try:
            decodedKey = berDecoder.decode(keyData)[0]
        except PyAsn1Error as e:
            raise BadKeyError('Failed to decode key (Bad Passphrase?): %s' %
                              (e, ))

        if kind == b'RSA':
            if len(decodedKey) == 2:  # alternate RSA key
                decodedKey = decodedKey[0]
            if len(decodedKey) < 6:
                raise BadKeyError('RSA key failed to decode properly')

            n, e, d, p, q = [long(value) for value in decodedKey[1:6]]
            if p > q:  # make p smaller than q
                p, q = q, p
            return Class(RSA.construct((n, e, d, p, q)))
        elif kind == b'DSA':
            p, q, g, y, x = [long(value) for value in decodedKey[1:6]]
            if len(decodedKey) < 6:
                raise BadKeyError('DSA key failed to decode properly')
            return Class(DSA.construct((y, g, p, q, x)))
        else:
            raise BadKeyError("unknown key type %s" % (kind, ))
Ejemplo n.º 30
0
 def test_float_accepts_long(self):
     # This test can be removed after dropping Python 2 support
     self.assertEqual(Float().coerce(long(3)), 3.0)
Ejemplo n.º 31
0
    def _fromString_PRIVATE_OPENSSH(cls, data, passphrase):
        """
        Return a private key object corresponding to this OpenSSH private key
        string.  If the key is encrypted, passphrase MUST be provided.
        Providing a passphrase for an unencrypted key is an error.

        The format of an OpenSSH private key string is::
            -----BEGIN <key type> PRIVATE KEY-----
            [Proc-Type: 4,ENCRYPTED
            DEK-Info: DES-EDE3-CBC,<initialization value>]
            <base64-encoded ASN.1 structure>
            ------END <key type> PRIVATE KEY------

        The ASN.1 structure of a RSA key is::
            (0, n, e, d, p, q)

        The ASN.1 structure of a DSA key is::
            (0, p, q, g, y, x)

        @type data: L{bytes}
        @param data: The key data.

        @type passphrase: L{bytes} or C{None}
        @param passphrase: The passphrase the key is encrypted with, or C{None}
        if it is not encrypted.

        @return: A new key.
        @rtype: L{twisted.conch.ssh.keys.Key}
        @raises BadKeyError: if
            * a passphrase is provided for an unencrypted key
            * the ASN.1 encoding is incorrect
        @raises EncryptedKeyError: if
            * a passphrase is not provided for an encrypted key
        """
        lines = data.strip().split(b'\n')
        kind = lines[0][11:14]
        if lines[1].startswith(b'Proc-Type: 4,ENCRYPTED'):
            if not passphrase:
                raise EncryptedKeyError('Passphrase must be provided '
                                        'for an encrypted key')

            # Determine cipher and initialization vector
            try:
                _, cipherIVInfo = lines[2].split(b' ', 1)
                cipher, ivdata = cipherIVInfo.rstrip().split(b',', 1)
            except ValueError:
                raise BadKeyError('invalid DEK-info %r' % (lines[2],))

            if cipher == b'AES-128-CBC':
                algorithmClass = algorithms.AES
                keySize = 16
                if len(ivdata) != 32:
                    raise BadKeyError('AES encrypted key with a bad IV')
            elif cipher == b'DES-EDE3-CBC':
                algorithmClass = algorithms.TripleDES
                keySize = 24
                if len(ivdata) != 16:
                    raise BadKeyError('DES encrypted key with a bad IV')
            else:
                raise BadKeyError('unknown encryption type %r' % (cipher,))

            # Extract keyData for decoding
            iv = bytes(bytearray([int(ivdata[i:i + 2], 16)
                                  for i in range(0, len(ivdata), 2)]))
            ba = md5(passphrase + iv[:8]).digest()
            bb = md5(ba + passphrase + iv[:8]).digest()
            decKey = (ba + bb)[:keySize]
            b64Data = base64.decodestring(b''.join(lines[3:-1]))

            decryptor = Cipher(
                algorithmClass(decKey),
                modes.CBC(iv),
                backend=default_backend()
            ).decryptor()
            keyData = decryptor.update(b64Data) + decryptor.finalize()

            removeLen = ord(keyData[-1:])
            keyData = keyData[:-removeLen]
        else:
            b64Data = b''.join(lines[1:-1])
            keyData = base64.decodestring(b64Data)

        try:
            decodedKey = berDecoder.decode(keyData)[0]
        except PyAsn1Error as e:
            raise BadKeyError(
                'Failed to decode key (Bad Passphrase?): %s' % (e,))

        if kind == b'RSA':
            if len(decodedKey) == 2:  # Alternate RSA key
                decodedKey = decodedKey[0]
            if len(decodedKey) < 6:
                raise BadKeyError('RSA key failed to decode properly')

            n, e, d, p, q, dmp1, dmq1, iqmp = [
                long(value) for value in decodedKey[1:9]
            ]
            if p > q:  # Make p smaller than q
                p, q = q, p
            return cls(
                rsa.RSAPrivateNumbers(
                    p=p,
                    q=q,
                    d=d,
                    dmp1=dmp1,
                    dmq1=dmq1,
                    iqmp=iqmp,
                    public_numbers=rsa.RSAPublicNumbers(e=e, n=n),
                ).private_key(default_backend())
            )
        elif kind == b'DSA':
            p, q, g, y, x = [long(value) for value in decodedKey[1: 6]]
            if len(decodedKey) < 6:
                raise BadKeyError('DSA key failed to decode properly')
            return cls(
                dsa.DSAPrivateNumbers(
                    x=x,
                    public_numbers=dsa.DSAPublicNumbers(
                        y=y,
                        parameter_numbers=dsa.DSAParameterNumbers(
                            p=p,
                            q=q,
                            g=g
                        )
                    )
                ).private_key(backend=default_backend())
            )
        else:
            raise BadKeyError("unknown key type %s" % (kind,))
Ejemplo n.º 32
0
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
Data used by test_keys as well as others.
"""

from __future__ import absolute_import, division

from base64 import decodestring

from twisted.python.compat import long

RSAData = {
    'n': long('106248668575524741116943830949539894737212779118943280948138'
              '20729711061576321820845393835692814935201176341295575504152775'
              '16685881326038852354459895734875625093273594925884531272867425'
              '864910490065695876046999646807138717162833156501'),
    'e': long(35),
    'd': long('667848773903298372735075508825679338348194611604786337388297'
              '30301040958479737159599618395783408164121679859572188879144827'
              '13602371850869127033494910375212470664166001439410214474266799'
              '85974425203903884190893469297150446322896587555'),
    'q': long('3395694744258061291019136154000709371890447462086362702627'
              '9704149412726577280741108645721676968699696898960891593323'),
    'p': long('3128922844292337321766351031842562691837301298995834258844'
              '4720539204069737532863831050930719431498338835415515173887'),
    'u': long('2777403202132551568802514199893235993376771442611051821485'
              '0278129927603609294283482712900532542110958095343012272938')
}

DSAData = {
Ejemplo n.º 33
0
    def _fromString_PRIVATE_OPENSSH(cls, data, passphrase):
        """
        Return a private key object corresponding to this OpenSSH private key
        string.  If the key is encrypted, passphrase MUST be provided.
        Providing a passphrase for an unencrypted key is an error.

        The format of an OpenSSH private key string is::
            -----BEGIN <key type> PRIVATE KEY-----
            [Proc-Type: 4,ENCRYPTED
            DEK-Info: DES-EDE3-CBC,<initialization value>]
            <base64-encoded ASN.1 structure>
            ------END <key type> PRIVATE KEY------

        The ASN.1 structure of a RSA key is::
            (0, n, e, d, p, q)

        The ASN.1 structure of a DSA key is::
            (0, p, q, g, y, x)

        The ASN.1 structure of a ECDSA key is::
            (ECParameters, OID, NULL)

        @type data: L{bytes}
        @param data: The key data.

        @type passphrase: L{bytes} or L{None}
        @param passphrase: The passphrase the key is encrypted with, or L{None}
        if it is not encrypted.

        @return: A new key.
        @rtype: L{twisted.conch.ssh.keys.Key}
        @raises BadKeyError: if
            * a passphrase is provided for an unencrypted key
            * the ASN.1 encoding is incorrect
        @raises EncryptedKeyError: if
            * a passphrase is not provided for an encrypted key
        """
        lines = data.strip().splitlines()
        kind = lines[0][11:-17]
        if lines[1].startswith(b'Proc-Type: 4,ENCRYPTED'):
            if not passphrase:
                raise EncryptedKeyError('Passphrase must be provided '
                                        'for an encrypted key')

            # Determine cipher and initialization vector
            try:
                _, cipherIVInfo = lines[2].split(b' ', 1)
                cipher, ivdata = cipherIVInfo.rstrip().split(b',', 1)
            except ValueError:
                raise BadKeyError('invalid DEK-info %r' % (lines[2],))

            if cipher in (b'AES-128-CBC', b'AES-256-CBC'):
                algorithmClass = algorithms.AES
                keySize = int(int(cipher.split(b'-')[1])/8)
                if len(ivdata) != 32:
                    raise BadKeyError('AES encrypted key with a bad IV')
            elif cipher == b'DES-EDE3-CBC':
                algorithmClass = algorithms.TripleDES
                keySize = 24
                if len(ivdata) != 16:
                    raise BadKeyError('DES encrypted key with a bad IV')
            else:
                raise BadKeyError('unknown encryption type %r' % (cipher,))

            # Extract keyData for decoding
            iv = bytes(bytearray([int(ivdata[i:i + 2], 16)
                                  for i in range(0, len(ivdata), 2)]))
            ba = md5(passphrase + iv[:8]).digest()
            bb = md5(ba + passphrase + iv[:8]).digest()
            decKey = (ba + bb)[:keySize]
            b64Data = decodebytes(b''.join(lines[3:-1]))

            decryptor = Cipher(
                algorithmClass(decKey),
                modes.CBC(iv),
                backend=default_backend()
            ).decryptor()
            keyData = decryptor.update(b64Data) + decryptor.finalize()

            removeLen = ord(keyData[-1:])
            keyData = keyData[:-removeLen]
        else:
            b64Data = b''.join(lines[1:-1])
            keyData = decodebytes(b64Data)

        try:
            decodedKey = berDecoder.decode(keyData)[0]
        except PyAsn1Error as e:
            raise BadKeyError(
                'Failed to decode key (Bad Passphrase?): %s' % (e,))

        if kind == b'EC':
            return cls(
                load_pem_private_key(data, passphrase, default_backend()))

        if kind == b'RSA':
            if len(decodedKey) == 2:  # Alternate RSA key
                decodedKey = decodedKey[0]
            if len(decodedKey) < 6:
                raise BadKeyError('RSA key failed to decode properly')

            n, e, d, p, q, dmp1, dmq1, iqmp = [
                long(value) for value in decodedKey[1:9]
                ]
            if p > q:  # Make p smaller than q
                p, q = q, p
            return cls(
                rsa.RSAPrivateNumbers(
                    p=p,
                    q=q,
                    d=d,
                    dmp1=dmp1,
                    dmq1=dmq1,
                    iqmp=iqmp,
                    public_numbers=rsa.RSAPublicNumbers(e=e, n=n),
                ).private_key(default_backend())
            )
        elif kind == b'DSA':
            p, q, g, y, x = [long(value) for value in decodedKey[1: 6]]
            if len(decodedKey) < 6:
                raise BadKeyError('DSA key failed to decode properly')
            return cls(
                dsa.DSAPrivateNumbers(
                    x=x,
                    public_numbers=dsa.DSAPublicNumbers(
                        y=y,
                        parameter_numbers=dsa.DSAParameterNumbers(
                            p=p,
                            q=q,
                            g=g
                        )
                    )
                ).private_key(backend=default_backend())
            )
        else:
            raise BadKeyError("unknown key type %s" % (kind,))
Ejemplo n.º 34
0
# -*- test-case-name: twisted.conch.test.test_keys -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
Data used by test_keys as well as others.
"""

from __future__ import absolute_import, division

from twisted.python.compat import long, _b64decodebytes as decodebytes

RSAData = {
    'n': long('106248668575524741116943830949539894737212779118943280948138'
              '20729711061576321820845393835692814935201176341295575504152775'
              '16685881326038852354459895734875625093273594925884531272867425'
              '864910490065695876046999646807138717162833156501'),
    'e': long(35),
    'd': long('667848773903298372735075508825679338348194611604786337388297'
              '30301040958479737159599618395783408164121679859572188879144827'
              '13602371850869127033494910375212470664166001439410214474266799'
              '85974425203903884190893469297150446322896587555'),
    'q': long('3395694744258061291019136154000709371890447462086362702627'
              '9704149412726577280741108645721676968699696898960891593323'),
    'p': long('3128922844292337321766351031842562691837301298995834258844'
              '4720539204069737532863831050930719431498338835415515173887'),
    'u': long('2777403202132551568802514199893235993376771442611051821485'
              '0278129927603609294283482712900532542110958095343012272938')
}

DSAData = {
Ejemplo n.º 35
0
 def test_lookupChannelErrorLongCode(self):
     """
     Like L{test_lookupChannelError}, but for the case where the failure code
     is represented as a L{long} instead of a L{int}.
     """
     self._lookupChannelErrorTest(long(123))
Ejemplo n.º 36
0
# pylint: disable=I0011,C0103,W9401,W9402
"""
Data used by test_keys as well as others.
"""

from __future__ import absolute_import, division

from twisted.python.compat import long, _b64decodebytes as decodebytes

RSAData = {
    'n':
    long('269413617238113438198661010376758399219880277968382122687862697'
         '296942471209955603071120391975773283844560230371884389952067978'
         '789684135947515341209478065209455427327369102356204259106807047'
         '964139525310539133073743116175821417513079706301100600025815509'
         '786721808719302671068052414466483676821987505720384645561708425'
         '794379383191274856941628512616355437197560712892001107828247792'
         '561858327085521991407807015047750218508971611590850575870321007'
         '991909043252470730134547038841839367764074379439843108550888709'
         '430958143271417044750314742880542002948053835745429446485015316'
         '60749404403945254975473896534482849256068133525751'),
    'e':
    long(65537),
    'd':
    long('420335724286999695680502438485489819800002417295071059780489811'
         '840828351636754206234982682752076205397047218449504537476523960'
         '987613148307573487322720481066677105211155388802079519869249746'
         '774085882219244493290663802569201213676433159425782937159766786'
         '329742053214957933941260042101377175565683849732354700525628975'
         '239000548651346620826136200952740446562751690924335365940810658'
         '931238410612521441739702170503547025018016868116037053013935451'
         '477930426013703886193016416453215950072147440344656137718959053'