Пример #1
0
def vaildate_key(key: str):
    try:
        serialization.load_ssh_private_key(str.encode(key), password=None)
        return True
    except ValueError:
        pass

    try:
        serialization.load_pem_private_key(str.encode(key), password=None)
        return True
    except ValueError:
        pass

    return False
Пример #2
0
def load_ssh_auth_manager(private_key_path=_DEFAULT,
                          authorized_key_path=_DEFAULT):
    user_dir = os.path.expanduser('~')
    authorized_keys = []

    # Load the authorized keys first.
    if authorized_key_path is _DEFAULT:
        authorized_key_path = os.path.join(user_dir, '.ssh', 'authorized_keys')
    if not authorized_key_path:
        authorized_key_path = ''
    if os.path.exists(authorized_key_path):
        with open(authorized_key_path, 'rb') as stm:
            # Read each line as an authorized key.
            for line in stm:
                try:
                    key = load_ssh_public_key(line)
                    authorized_keys.append(key)
                except Exception as exc:
                    logger.warning("Skipping key due to error: %s", exc)

    # Load the private key to use here.
    if private_key_path is _DEFAULT:
        private_key_path = os.path.join(user_dir, '.ssh', 'id_ecdsa')
        if not os.path.exists(private_key_path):
            private_key_path = os.path.join(user_dir, '.ssh', 'id_rsa')
    if not private_key_path:
        private_key_path = ''
    if os.path.exists(private_key_path):
        with open(private_key_path, 'rb') as stm:
            private_key = load_ssh_private_key(stm.read(), password=None)

    return SSHAuthManager(private_key, authorized_keys)
    def sign_message(self, message: str) -> bytes:
        """Create a signature with use of secret key for message

        :param message: message of which the signature is created
        :return: signature for the message
        :rtype: bytes
        """

        if self.__KEYS['private_key'] is None:
            raise ValueError

        private_key: bytes = bytes.fromhex(self.__KEYS['private_key'])

        key = serialization.load_ssh_private_key(private_key,
                                                 password=None,
                                                 backend=default_backend())

        hashed_message = hashlib.sha256(message.encode('utf-8')).hexdigest()

        signature = key.sign(
            bytes(hashed_message.encode('ascii')),
            padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                        salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256())

        return base64.b64encode(signature)
    def decode_message(self, message: str) -> bytes:
        """Decode message with asymmetric keys

        :param message: message to be decrypted
        :return: decrypted message
        :rtype: bytes
        """

        if self.__KEYS['private_key'] is None:
            raise ValueError('Key is not set')

        ciphertext = base64.b64decode(message)

        private_key: bytes = bytes.fromhex(self.__KEYS['private_key'])

        key = serialization.load_ssh_private_key(private_key,
                                                 backend=default_backend(),
                                                 password=None)

        plaintext = key.decrypt(
            ciphertext,
            padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                         algorithm=hashes.SHA256(),
                         label=None))

        return base64.b64decode(plaintext)
Пример #5
0
def PostMiddleware(request, session, spec):
    tyk.log("This is my post middleware", "info")

    customerID = request.get_header('CustomerID')
    #tyk.log("customerID: " + customerID, "info")

    payload = {
        "customerID": "1234",
        "userID": "*****@*****.**",
        "country": "NL",
        "scope": "device:read"
    }

    my_secret = 'my_super_secret'
    private_key = open('/opt/tyk-gateway/id_rsa', 'r').read()
    key = serialization.load_ssh_private_key(private_key.encode(),
                                             password=b'')

    #token = jwt.encode(
    #    payload=payload,
    #    key=my_secret
    #)

    token = jwt.encode(payload=payload, key=key, algorithm='RS256')

    tyk.log("jwt: " + token, "info")
    request.add_header("Authorization", token)

    return request, session
Пример #6
0
 def from_openssh_key(cls,
                      buffer: AnyStr,
                      password: Optional[AnyStr] = None) -> PrivateKey:
     rsa_key = serialization.load_ssh_private_key(  # type: ignore
         cls._bytes(buffer),
         cls._bytes(password) if password else b'', default_backend())
     return PrivateKey(rsa_key)
Пример #7
0
def cast_private_key(value: str,
                     key_format: EncryptionKeyFormat,
                     passphrase: Optional[str] = None) -> Optional[PrivateKey]:
    """
    Parse a string into a valid cryptographic private key.
    the string can represent a file path in which the key exists, or the actual key contents.
    """
    if value is None:
        return None

    if isinstance(value, PrivateKey.__args__):
        return value

    if passphrase is None:
        password = None
    else:
        password = passphrase.encode('utf-8')

    key_path = os.path.expanduser(value)
    if os.path.isfile(key_path):
        raw_key = open(key_path, "rb").read()
    else:
        raw_key = maybe_decode_multiline_key(value)

    if key_format == EncryptionKeyFormat.pem:
        return serialization.load_pem_private_key(raw_key,
                                                  password=password,
                                                  backend=default_backend())

    if key_format == EncryptionKeyFormat.ssh:
        return serialization.load_ssh_private_key(raw_key,
                                                  password=password,
                                                  backend=default_backend())

    if key_format == EncryptionKeyFormat.der:
        return serialization.load_der_private_key(raw_key,
                                                  password=password,
                                                  backend=default_backend())
Пример #8
0
def private_key_from_encoding(data, password=None):
    try:
        key = load_pem_private_key(data,
                                   password=password,
                                   backend=default_backend())
        return key
    except ValueError:
        pass
    try:
        key = load_ssh_private_key(data,
                                   password=password,
                                   backend=default_backend())
        return key
    except ValueError:
        pass
    try:
        key = load_der_private_key(data,
                                   password=password,
                                   backend=default_backend())
        return key
    except ValueError:
        pass

    raise ValueError("Unsupported key format")
Пример #9
0
    def importkey(self,
                  phandle,
                  pauth,
                  objauth,
                  privkey,
                  objattrs=None,
                  seal=None,
                  alg=None,
                  passin=None):

        if privkey and len(privkey) > 0:
            exists = os.path.isfile(privkey)
            if not exists:
                raise RuntimeError("File '%s' path is invalid or is missing" %
                                   privkey)
        else:
            sys.exit("Invalid file path")

        _, priv = mkstemp(prefix='', suffix='.priv', dir=self._tmp)
        _, pub = mkstemp(prefix='', suffix='.pub', dir=self._tmp)

        # If the key is an OpenSSH key, convert it to PEM format
        pem_priv_name = None
        with open(privkey, "rb") as f:
            privey_data = f.read()
        if privey_data.startswith(b'-----BEGIN OPENSSH PRIVATE KEY-----'):
            if passin:
                # Parse passin to extract the password
                if passin.startswith('env:'):
                    password_bytes = os.getenvb(passin[4:].encode())
                elif passin.startswith('file:'):
                    with open(passin[5:], 'rb') as f:
                        password_bytes = f.read()
                elif passin.startswith('pass:'******'ecc'
                elif isinstance(ssh_key, RSAPrivateKey):
                    alg = 'rsa'
                else:
                    raise NotImplementedError(
                        "Unsupported SSH key type {}".format(type(ssh_key)))

            pem_key = ssh_key.private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.TraditionalOpenSSL,
                encryption_algorithm=enc_alg)

            pem_priv_fd, pem_priv_name = mkstemp(prefix='',
                                                 suffix='.privpem',
                                                 dir=self._tmp)
            os.write(pem_priv_fd, pem_key)
            os.close(pem_priv_fd)
            privkey = pem_priv_name
        elif alg is None:
            # Guess the key algorithm from the PEM header
            if privey_data.startswith(b'-----BEGIN EC PARAMETERS-----'):
                alg = 'ecc'
            elif privey_data.startswith(b'-----BEGIN EC PRIVATE KEY-----'):
                alg = 'ecc'
            elif privey_data.startswith(b'-----BEGIN RSA PRIVATE KEY-----'):
                alg = 'rsa'
            else:
                raise RuntimeError(
                    "Unable to detect key type, use --algorithm to specify it")

        parent_path = str(phandle)
        cmd = [
            'tpm2_import', '-V', '-C', parent_path, '-i', privkey, '-u', pub,
            '-r', priv
        ]

        if pauth and len(pauth) > 0:
            cmd.extend(['-P', pauth])

        if objauth and len(objauth) > 0:
            cmd.extend(['-p', objauth])

        if objattrs != None:
            cmd.extend(['-a', objattrs])

        if seal != None:
            cmd.extend(['-i', '-'])

        if alg != None:
            cmd.extend(['-G', alg])

        if passin is not None:
            cmd.extend(['--passin', passin])

        p = Popen(cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE, env=os.environ)
        stdout, stderr = p.communicate(input=seal)
        rc = p.wait()
        if pem_priv_name is not None:
            os.remove(pem_priv_name)
        if (rc != 0):
            os.remove(pub)
            os.remove(priv)
            print("command: %s" % str(" ".join(cmd)))
            raise RuntimeError("Could not execute tpm2_import: %s" % stderr)

        return priv, pub, stdout
Пример #10
0
def add_ssh_key(private_key, passphrase,
                key_name):  # type: (str, str, str) -> Optional[Callable]
    ssh_socket_path = os.environ.get('SSH_AUTH_SOCK')
    header, _, _ = private_key.partition('\n')
    if 'BEGIN OPENSSH PRIVATE KEY' in header:
        private_key = serialization.load_ssh_private_key(
            private_key.encode(),
            password=passphrase.encode() if passphrase else None)
    else:
        private_key = serialization.load_pem_private_key(
            private_key.encode(),
            password=passphrase.encode() if passphrase else None)
    if isinstance(private_key, rsa.RSAPrivateKey):
        private_numbers = private_key.private_numbers()
        public_numbers = private_key.public_key().public_numbers()

        store_payload = SSH2_AGENTC_ADD_IDENTITY.to_bytes(1, byteorder='big')
        store_payload += ssh_agent_encode_str('ssh-rsa')
        store_payload += ssh_agent_encode_long(public_numbers.n)
        store_payload += ssh_agent_encode_long(public_numbers.e)
        store_payload += ssh_agent_encode_long(private_numbers.d)
        store_payload += ssh_agent_encode_long(private_numbers.iqmp)
        store_payload += ssh_agent_encode_long(private_numbers.p)
        store_payload += ssh_agent_encode_long(private_numbers.q)
        store_payload += ssh_agent_encode_str(key_name)
        # windows ssh implementation does not support constrained identity
        # store_payload += SSH_AGENT_CONSTRAIN_LIFETIME.to_bytes(1, byteorder='big')
        # store_payload += int(10).to_bytes(4, byteorder='big')

        remove_payload = ssh_agent_encode_str('ssh-rsa')
        remove_payload += ssh_agent_encode_long(public_numbers.e)
        remove_payload += ssh_agent_encode_long(public_numbers.n)
        remove_payload = SSH2_AGENTC_REMOVE_IDENTITY.to_bytes(
            1, byteorder='big') + ssh_agent_encode_bytes(remove_payload)
    elif isinstance(private_key, ec.EllipticCurvePrivateKey):
        private_numbers = private_key.private_numbers()
        curve_name = 'nistp256'
        store_payload = SSH2_AGENTC_ADD_IDENTITY.to_bytes(1, byteorder='big')
        store_payload += ssh_agent_encode_str(f'ecdsa-sha2-{curve_name}')
        store_payload += ssh_agent_encode_str(curve_name)
        public_key_bytes = private_key.public_key().public_bytes(
            encoding=serialization.Encoding.X962,
            format=serialization.PublicFormat.UncompressedPoint)
        store_payload += ssh_agent_encode_bytes(public_key_bytes)
        store_payload += ssh_agent_encode_long(private_numbers.private_value)
        store_payload += ssh_agent_encode_str(key_name)

        remove_payload = ssh_agent_encode_str(f'ecdsa-sha2-{curve_name}')
        remove_payload += ssh_agent_encode_str(curve_name)
        remove_payload += ssh_agent_encode_bytes(public_key_bytes)
        remove_payload = SSH2_AGENTC_REMOVE_IDENTITY.to_bytes(
            1, byteorder='big') + ssh_agent_encode_bytes(remove_payload)

    elif isinstance(private_key, ed25519.Ed25519PrivateKey):
        public_key_bytes = private_key.public_key().public_bytes(
            encoding=serialization.Encoding.Raw,
            format=serialization.PublicFormat.Raw)
        private_key_bytes = private_key.private_bytes(
            encoding=serialization.Encoding.Raw,
            format=serialization.PrivateFormat.Raw,
            encryption_algorithm=serialization.NoEncryption())

        store_payload = SSH2_AGENTC_ADD_IDENTITY.to_bytes(1, byteorder='big')
        store_payload += ssh_agent_encode_str('ssh-ed25519')
        store_payload += ssh_agent_encode_bytes(public_key_bytes)
        store_payload += ssh_agent_encode_bytes(private_key_bytes +
                                                public_key_bytes)
        store_payload += ssh_agent_encode_str(key_name)

        remove_payload = ssh_agent_encode_str('ssh-ed25519')
        remove_payload += ssh_agent_encode_bytes(public_key_bytes)
        remove_payload = SSH2_AGENTC_REMOVE_IDENTITY.to_bytes(
            1, byteorder='big') + ssh_agent_encode_bytes(remove_payload)
    else:
        if private_key:
            key_type = type(private_key)
            raise Exception(
                f'Add ssh-key. Key type \"{key_type.__name__}\" is not supported yet.'
            )
        else:
            raise Exception('Cannot load SSH private key.')

    if store_payload:
        with ConnectSshAgent(ssh_socket_path) as fd:
            recv_payload = fd.send(store_payload)
            if recv_payload and recv_payload[0] == SSH_AGENT_FAILURE:
                raise Exception(
                    f'Add ssh-key. Failed to add ssh key \"{key_name}\" to ssh-agent'
                )
        if remove_payload:

            def remove_key():
                delete_ssh_key(remove_payload)

            return remove_key
Пример #11
0
 def __setstate__(self, state):
     self.__dict__.update(state)
     self._private_key = serialization.load_ssh_private_key(
         self._private_key, password=None)