Exemplo n.º 1
0
def _dump_key(private_key):
    return private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption())
Exemplo n.º 2
0
def generateKey():       #Generate serialized public and private key
    private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=backend)
    public_key = private_key.public_key()
    pemprivate = private_key.private_bytes(encoding=serialization.Encoding.PEM,format=serialization.PrivateFormat.PKCS8,encryption_algorithm=serialization.NoEncryption())
    pempublic = public_key.public_bytes(encoding=serialization.Encoding.PEM,format=serialization.PublicFormat.SubjectPublicKeyInfo)
    return pemprivate,pempublic
Exemplo n.º 3
0
 def private_pem(self):
     return self.private_key.private_bytes(
         encoding=serialization.Encoding.PEM,
         format=serialization.PrivateFormat.PKCS8,
         encryption_algorithm=serialization.NoEncryption())
Exemplo n.º 4
0
class TestX25519Exchange(object):
    @pytest.mark.parametrize(
        "vector",
        load_vectors_from_file(
            os.path.join("asymmetric", "X25519", "rfc7748.txt"),
            load_nist_vectors,
        ),
    )
    def test_rfc7748(self, vector, backend):
        private = binascii.unhexlify(vector["input_scalar"])
        public = binascii.unhexlify(vector["input_u"])
        shared_key = binascii.unhexlify(vector["output_u"])
        private_key = X25519PrivateKey.from_private_bytes(private)
        public_key = X25519PublicKey.from_public_bytes(public)
        computed_shared_key = private_key.exchange(public_key)
        assert computed_shared_key == shared_key

    def test_rfc7748_1000_iteration(self, backend):
        old_private = private = public = binascii.unhexlify(
            b"090000000000000000000000000000000000000000000000000000000000"
            b"0000")
        shared_key = binascii.unhexlify(
            b"684cf59ba83309552800ef566f2f4d3c1c3887c49360e3875f2eb94d9953"
            b"2c51")
        private_key = X25519PrivateKey.from_private_bytes(private)
        public_key = X25519PublicKey.from_public_bytes(public)
        for _ in range(1000):
            computed_shared_key = private_key.exchange(public_key)
            private_key = X25519PrivateKey.from_private_bytes(
                computed_shared_key)
            public_key = X25519PublicKey.from_public_bytes(old_private)
            old_private = computed_shared_key

        assert computed_shared_key == shared_key

    def test_null_shared_key_raises_error(self, backend):
        """
        The vector used here is taken from wycheproof's x25519 test vectors
        """
        public = binascii.unhexlify(
            "5f9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f1157")
        private = binascii.unhexlify(
            "78f1e8edf14481b389448dac8f59c70b038e7cf92ef2c7eff57a72466e115296")
        private_key = X25519PrivateKey.from_private_bytes(private)
        public_key = X25519PublicKey.from_public_bytes(public)
        with pytest.raises(ValueError):
            private_key.exchange(public_key)

    def test_public_bytes_bad_args(self, backend):
        key = X25519PrivateKey.generate().public_key()
        with pytest.raises(ValueError):
            key.public_bytes(None, serialization.PublicFormat.Raw)
        with pytest.raises(TypeError):
            key.public_bytes(serialization.Encoding.Raw)

    # These vectors are also from RFC 7748
    # https://tools.ietf.org/html/rfc7748#section-6.1
    @pytest.mark.parametrize(
        ("private_bytes", "public_bytes"),
        [
            (
                binascii.unhexlify(
                    b"77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba"
                    b"51db92c2a"),
                binascii.unhexlify(
                    b"8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98"
                    b"eaa9b4e6a"),
            ),
            (
                binascii.unhexlify(
                    b"5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b2"
                    b"7ff88e0eb"),
                binascii.unhexlify(
                    b"de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e1"
                    b"46f882b4f"),
            ),
        ],
    )
    def test_pub_priv_bytes_raw(self, private_bytes, public_bytes, backend):
        private_key = X25519PrivateKey.from_private_bytes(private_bytes)
        assert (private_key.private_bytes(
            serialization.Encoding.Raw,
            serialization.PrivateFormat.Raw,
            serialization.NoEncryption(),
        ) == private_bytes)
        assert (private_key.public_key().public_bytes(
            serialization.Encoding.Raw,
            serialization.PublicFormat.Raw) == public_bytes)
        public_key = X25519PublicKey.from_public_bytes(public_bytes)
        assert (public_key.public_bytes(
            serialization.Encoding.Raw,
            serialization.PublicFormat.Raw) == public_bytes)

    def test_generate(self, backend):
        key = X25519PrivateKey.generate()
        assert key
        assert key.public_key()

    def test_invalid_type_exchange(self, backend):
        key = X25519PrivateKey.generate()
        with pytest.raises(TypeError):
            key.exchange(object())

    def test_invalid_length_from_public_bytes(self, backend):
        with pytest.raises(ValueError):
            X25519PublicKey.from_public_bytes(b"a" * 31)

        with pytest.raises(ValueError):
            X25519PublicKey.from_public_bytes(b"a" * 33)

    def test_invalid_length_from_private_bytes(self, backend):
        with pytest.raises(ValueError):
            X25519PrivateKey.from_private_bytes(b"a" * 31)

        with pytest.raises(ValueError):
            X25519PrivateKey.from_private_bytes(b"a" * 33)

    def test_invalid_private_bytes(self, backend):
        key = X25519PrivateKey.generate()
        with pytest.raises(ValueError):
            key.private_bytes(
                serialization.Encoding.Raw,
                serialization.PrivateFormat.Raw,
                None,
            )

        with pytest.raises(ValueError):
            key.private_bytes(
                serialization.Encoding.Raw,
                serialization.PrivateFormat.PKCS8,
                None,
            )

        with pytest.raises(ValueError):
            key.private_bytes(
                serialization.Encoding.PEM,
                serialization.PrivateFormat.Raw,
                serialization.NoEncryption(),
            )

    def test_invalid_public_bytes(self, backend):
        key = X25519PrivateKey.generate().public_key()
        with pytest.raises(ValueError):
            key.public_bytes(
                serialization.Encoding.Raw,
                serialization.PublicFormat.SubjectPublicKeyInfo,
            )

        with pytest.raises(ValueError):
            key.public_bytes(serialization.Encoding.PEM,
                             serialization.PublicFormat.PKCS1)

        with pytest.raises(ValueError):
            key.public_bytes(serialization.Encoding.PEM,
                             serialization.PublicFormat.Raw)

    @pytest.mark.parametrize(
        ("encoding", "fmt", "encryption", "passwd", "load_func"),
        [
            (
                serialization.Encoding.PEM,
                serialization.PrivateFormat.PKCS8,
                serialization.BestAvailableEncryption(b"password"),
                b"password",
                serialization.load_pem_private_key,
            ),
            (
                serialization.Encoding.DER,
                serialization.PrivateFormat.PKCS8,
                serialization.BestAvailableEncryption(b"password"),
                b"password",
                serialization.load_der_private_key,
            ),
            (
                serialization.Encoding.PEM,
                serialization.PrivateFormat.PKCS8,
                serialization.NoEncryption(),
                None,
                serialization.load_pem_private_key,
            ),
            (
                serialization.Encoding.DER,
                serialization.PrivateFormat.PKCS8,
                serialization.NoEncryption(),
                None,
                serialization.load_der_private_key,
            ),
        ],
    )
    def test_round_trip_private_serialization(self, encoding, fmt, encryption,
                                              passwd, load_func, backend):
        key = X25519PrivateKey.generate()
        serialized = key.private_bytes(encoding, fmt, encryption)
        loaded_key = load_func(serialized, passwd, backend)
        assert isinstance(loaded_key, X25519PrivateKey)

    def test_buffer_protocol(self, backend):
        private_bytes = bytearray(os.urandom(32))
        key = X25519PrivateKey.from_private_bytes(private_bytes)
        assert (key.private_bytes(
            serialization.Encoding.Raw,
            serialization.PrivateFormat.Raw,
            serialization.NoEncryption(),
        ) == private_bytes)
Exemplo n.º 5
0
 def test_private_bytes_rejects_invalid(self, encoding, fmt, backend):
     key = DSA_KEY_1024.private_key(backend)
     with pytest.raises(ValueError):
         key.private_bytes(encoding, fmt, serialization.NoEncryption())
Exemplo n.º 6
0
 def test_buffer_protocol(self, backend):
     private_bytes = bytearray(os.urandom(32))
     key = X25519PrivateKey.from_private_bytes(private_bytes)
     assert key.private_bytes(serialization.Encoding.Raw,
                              serialization.PrivateFormat.Raw,
                              serialization.NoEncryption()) == private_bytes
Exemplo n.º 7
0
    def _get_conn_params(self) -> Dict[str, Optional[str]]:
        """
        One method to fetch connection params as a dict
        used in get_uri() and get_connection()
        """
        conn = self.get_connection(self.snowflake_conn_id)  # type: ignore[attr-defined]
        account = conn.extra_dejson.get('extra__snowflake__account', '') or conn.extra_dejson.get(
            'account', ''
        )
        warehouse = conn.extra_dejson.get('extra__snowflake__warehouse', '') or conn.extra_dejson.get(
            'warehouse', ''
        )
        database = conn.extra_dejson.get('extra__snowflake__database', '') or conn.extra_dejson.get(
            'database', ''
        )
        region = conn.extra_dejson.get('extra__snowflake__region', '') or conn.extra_dejson.get('region', '')
        role = conn.extra_dejson.get('extra__snowflake__role', '') or conn.extra_dejson.get('role', '')
        schema = conn.schema or ''
        authenticator = conn.extra_dejson.get('authenticator', 'snowflake')
        session_parameters = conn.extra_dejson.get('session_parameters')
        insecure_mode = _try_to_boolean(
            conn.extra_dejson.get(
                'extra__snowflake__insecure_mode', conn.extra_dejson.get('insecure_mode', None)
            )
        )

        conn_config = {
            "user": conn.login,
            "password": conn.password or '',
            "schema": self.schema or schema,
            "database": self.database or database,
            "account": self.account or account,
            "warehouse": self.warehouse or warehouse,
            "region": self.region or region,
            "role": self.role or role,
            "authenticator": self.authenticator or authenticator,
            "session_parameters": self.session_parameters or session_parameters,
            # application is used to track origin of the requests
            "application": os.environ.get("AIRFLOW_SNOWFLAKE_PARTNER", "AIRFLOW"),
        }
        if insecure_mode:
            conn_config['insecure_mode'] = insecure_mode

        # If private_key_file is specified in the extra json, load the contents of the file as a private key.
        # If private_key_content is specified in the extra json, use it as a private key.
        # As a next step, specify this private key in the connection configuration.
        # The connection password then becomes the passphrase for the private key.
        # If your private key is not encrypted (not recommended), then leave the password empty.

        private_key_file = conn.extra_dejson.get(
            'extra__snowflake__private_key_file'
        ) or conn.extra_dejson.get('private_key_file')
        private_key_content = conn.extra_dejson.get(
            'extra__snowflake__private_key_content'
        ) or conn.extra_dejson.get('private_key_content')

        private_key_pem = None
        if private_key_content and private_key_file:
            raise AirflowException(
                "The private_key_file and private_key_content extra fields are mutually exclusive. "
                "Please remove one."
            )
        elif private_key_file:
            private_key_pem = Path(private_key_file).read_bytes()
        elif private_key_content:
            private_key_pem = private_key_content.encode()

        if private_key_pem:
            passphrase = None
            if conn.password:
                passphrase = conn.password.strip().encode()

            p_key = serialization.load_pem_private_key(
                private_key_pem, password=passphrase, backend=default_backend()
            )

            pkb = p_key.private_bytes(
                encoding=serialization.Encoding.DER,
                format=serialization.PrivateFormat.PKCS8,
                encryption_algorithm=serialization.NoEncryption(),
            )

            conn_config['private_key'] = pkb
            conn_config.pop('password', None)

        return conn_config
Exemplo n.º 8
0
def generate_public_and_private(scheme='ecdsa-sha2-nistp256'):
    """
  <Purpose>
    Generate a pair of ECDSA public and private keys with one of the supported,
    external cryptography libraries.  The public and private keys returned
    conform to 'securesystemslib.formats.PEMECDSA_SCHEMA' and
    'securesystemslib.formats.PEMECDSA_SCHEMA', respectively.

    The public ECDSA public key has the PEM format:
    TODO: should we encrypt the private keys returned here?  Should the
    create_signature() accept encrypted keys?

    '-----BEGIN PUBLIC KEY-----

    ...

    '-----END PUBLIC KEY-----'



    The private ECDSA private key has the PEM format:

    '-----BEGIN EC PRIVATE KEY-----

    ...

    -----END EC PRIVATE KEY-----'

    >>> public, private = generate_public_and_private()
    >>> securesystemslib.formats.PEMECDSA_SCHEMA.matches(public)
    True
    >>> securesystemslib.formats.PEMECDSA_SCHEMA.matches(private)
    True

  <Arguments>
    scheme:
      A string indicating which algorithm to use for the generation of the
      public and private ECDSA keys.  'ecdsa-sha2-nistp256' is the only
      currently supported ECDSA algorithm, which is supported by OpenSSH and
      specified in RFC 5656 (https://tools.ietf.org/html/rfc5656).

  <Exceptions>
    securesystemslib.exceptions.FormatError, if 'algorithm' is improperly
    formatted.

    securesystemslib.exceptions.UnsupportedAlgorithmError, if 'scheme' is an
    unsupported algorithm.

  <Side Effects>
    None.

  <Returns>
    A (public, private) tuple that conform to
    'securesystemslib.formats.PEMECDSA_SCHEMA' and
    'securesystemslib.formats.PEMECDSA_SCHEMA', respectively.
  """

    # Does 'scheme' have the correct format?
    # Verify that 'scheme' is of the correct type, and that it's one of the
    # supported ECDSA .  It must conform to
    # 'securesystemslib.formats.ECDSA_SCHEME_SCHEMA'.  Raise
    # 'securesystemslib.exceptions.FormatError' if the check fails.
    securesystemslib.formats.ECDSA_SCHEME_SCHEMA.check_match(scheme)

    public_key = None
    private_key = None

    # An if-clause is strictly not needed, since 'ecdsa_sha2-nistp256' is the
    # only currently supported ECDSA signature scheme.  Nevertheness, include the
    # conditional statement to accomodate any schemes that might be added.
    if scheme == 'ecdsa-sha2-nistp256':
        private_key = ec.generate_private_key(ec.SECP256R1, default_backend())
        public_key = private_key.public_key()

    # The ECDSA_SCHEME_SCHEMA.check_match() above should have detected any
    # invalid 'scheme'.  This is a defensive check.
    else:  #pragma: no cover
        raise securesystemslib.exceptions.UnsupportedAlgorithmError(
            'An unsupported'
            ' scheme specified: ' + repr(scheme) + '.\n  Supported'
            ' algorithms: ' + repr(_SUPPORTED_ECDSA_SCHEMES))

    private_pem = private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption())

    public_pem = public_key.public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo)

    return public_pem.decode('utf-8'), private_pem.decode('utf-8')
Exemplo n.º 9
0
Arquivo: vm.py Projeto: ctfctl/ctfctl
def create_backup(from_vm_name, to_vm_name="backup"):
    """Creates a backup droplet if needed and syncs the data from the
    vm {from_vm_name} to the backup every 10 minutes"""

    if not get(from_vm_name):
        print(f"could not find to-be-backuped vm {from_vm_name}!")
        return

    if not get(to_vm_name):
        print(
            f"could not find backup server for vm {to_vm_name}. Will create one."
        )
        create(to_vm_name)

    ip_addr = get(from_vm_name)[0].ip_address

    # generate keys for backup server
    key = rsa.generate_private_key(backend=crypto_default_backend(),
                                   public_exponent=65537,
                                   key_size=2048)

    private_key = key.private_bytes(
        crypto_serialization.Encoding.PEM,
        crypto_serialization.PrivateFormat.PKCS8,
        crypto_serialization.NoEncryption()).decode('utf8')
    public_key = key.public_key().public_bytes(
        crypto_serialization.Encoding.OpenSSH,
        crypto_serialization.PublicFormat.OpenSSH).decode('utf8')

    ssh(from_vm_name, f"echo '{public_key}' >> /root/.ssh/authorized_keys")

    backup_script_path = f"/root/backup_{from_vm_name}.sh"

    systemd_configs = get_systemd_timer_service(f"Backup-{from_vm_name}",
                                                f"{backup_script_path}")

    timer = systemd_configs["timer"]
    service = systemd_configs["service"]

    commands = [
        f"echo '{private_key}' > /root/.ssh/id_{from_vm_name}_rsa",
        f"chmod 0600 /root/.ssh/id_{from_vm_name}_rsa",
        "pacman --noconfirm --needed -Syu borg socat",

        # init the borg repo
        "mkdir -p /root/backups",
        "borg init -e none /root/backups",

        # listening to connections
        f"echo '#!/bin/sh' > {backup_script_path}",
        f"echo 'socat TCP-LISTEN:12345,fork \"EXEC:borg serve --append-only --restrict-to-path /root/backups/ --umask 077\"&' >> {backup_script_path}",
        # performing push from remote
        f"echo 'ssh -i /root/.ssh/id_{from_vm_name}_rsa -oStrictHostKeyChecking=no -R 12345:localhost:12345 {ip_addr} BORG_RSH=\"/root/socat-wrap.sh\" BORG_UNKNOWN_UNENCRYPTED_REPO_ACCESS_IS_OK=yes borg create --stats ssh://foo/root/backups::{from_vm_name}-$(date +%Y-%m-%d-%R) /root/' >> {backup_script_path}",
        f"chmod +x {backup_script_path}",
        f"echo '{timer}' > /etc/systemd/system/backup_{from_vm_name}.timer",
        f"echo '{service}' > /etc/systemd/system/backup_{from_vm_name}.service",
        "systemctl daemon-reload",
        f"systemctl start backup_{from_vm_name}.timer",
        f"systemctl enable --now backup_{from_vm_name}.timer"
    ]
    ssh(to_vm_name, commands)

    print(f'[*] created backup job for vm {from_vm_name}')
Exemplo n.º 10
0
def load_cert_files(common_name, key_file, public_key_file, csr_file,
                    certificate_file, crl_file):
    """Loads the certificate, keys and revoked list files from storage

    :param common_name: Common Name for CA
    :type common_name: str, required when there is no CA
    :param key_file: key file full path
    :type key_file: str, required
    :param public_key_file: public key file full path
    :type public_key_file: str, required
    :param csr_file: certificate signing request file full path
    :type csr_file: str, required
    :param certificate_file: certificate file full path
    :type certificate_file: str, required
    :param crl_file: certificate revocation list file full path
    :type key_file: str, required

    :return: ``OwncaCertData``
    :raises: ``OwnCAInconsistentData``
    """

    # certificate signing request (if ICA)
    try:
        with open(csr_file, "rb") as csr_f:
            csr_data = csr_f.read()

        csr = x509.load_pem_x509_csr(csr_data, default_backend())
        csr_bytes = csr.public_bytes(encoding=serialization.Encoding.PEM)

    except FileNotFoundError:
        csr = None
        csr_bytes = None

    # certificate

    try:
        with open(certificate_file, "rb") as cert_f:
            cert_data = cert_f.read()

        certificate = x509.load_pem_x509_certificate(cert_data,
                                                     default_backend())
        current_cn_name = (certificate.subject.rfc4514_string().split("CN=")
                           [-1].split(",")[0])
        certificate_bytes = certificate.public_bytes(
            encoding=serialization.Encoding.PEM)

    except FileNotFoundError:
        certificate = None
        certificate_bytes = None

    if common_name is not None and common_name != current_cn_name:
        raise OwnCAInconsistentData(
            "Initialized CN name does not match with current existent " +
            f"common_name: {current_cn_name}")

    # key
    try:
        with open(key_file, "rb") as key_f:
            key_data = key_f.read()

        key = serialization.load_pem_private_key(key_data,
                                                 password=None,
                                                 backend=default_backend())

        key_bytes = key.private_bytes(
            serialization.Encoding.PEM,
            serialization.PrivateFormat.PKCS8,
            serialization.NoEncryption(),
        )

    except FileNotFoundError:
        key = None
        key_bytes = None

    with open(public_key_file, "rb") as pub_key_f:
        pub_key_data = pub_key_f.read()

    public_key = serialization.load_ssh_public_key(pub_key_data,
                                                   backend=default_backend())

    public_key_bytes = public_key.public_bytes(
        serialization.Encoding.OpenSSH, serialization.PublicFormat.OpenSSH)

    # certificate revocation list (crl)
    # if there is not crl file it is created (backward compatible)
    try:
        with open(crl_file, "rb") as crl_f:
            crl_data = crl_f.read()

        crl = x509.load_pem_x509_crl(crl_data, default_backend())
        crl_bytes = crl.public_bytes(encoding=serialization.Encoding.PEM)

    except FileNotFoundError:
        if certificate is None:
            crl = None
            crl_bytes = None

        else:
            crl = ca_crl(ca_cert=certificate,
                         ca_key=key,
                         common_name=common_name)
            crl_bytes = crl.public_bytes(encoding=serialization.Encoding.PEM)

    return OwncaCertData({
        "cert": certificate,
        "cert_bytes": certificate_bytes,
        "csr": csr,
        "csr_bytes": csr_bytes,
        "key": key,
        "key_bytes": key_bytes,
        "public_key": public_key,
        "public_key_bytes": public_key_bytes,
        "crl": crl,
        "crl_bytes": crl_bytes
    })
Exemplo n.º 11
0
def create_ecdsa_public_and_private_from_pem(pem, password=None):
    """
  <Purpose>
    Create public and private ECDSA keys from a private 'pem'.  The public and
    private keys are strings in PEM format:

    public: '-----BEGIN PUBLIC KEY----- ... -----END PUBLIC KEY-----',
    private: '-----BEGIN EC PRIVATE KEY----- ... -----END EC PRIVATE KEY-----'}}

    >>> junk, private = generate_public_and_private()
    >>> public, private = create_ecdsa_public_and_private_from_pem(private)
    >>> securesystemslib.formats.PEMECDSA_SCHEMA.matches(public)
    True
    >>> securesystemslib.formats.PEMECDSA_SCHEMA.matches(private)
    True
    >>> passphrase = 'secret'
    >>> encrypted_pem = create_ecdsa_encrypted_pem(private, passphrase)
    >>> public, private = create_ecdsa_public_and_private_from_pem(encrypted_pem, passphrase)
    >>> securesystemslib.formats.PEMECDSA_SCHEMA.matches(public)
    True
    >>> securesystemslib.formats.PEMECDSA_SCHEMA.matches(private)
    True

  <Arguments>
    pem:
      A string in PEM format.  The private key is extracted and returned in
      an ecdsakey object.

    password: (optional)
      The password, or passphrase, to decrypt the private part of the ECDSA key
      if it is encrypted.  'password' is not used directly as the encryption
      key, a stronger encryption key is derived from it.

  <Exceptions>
    securesystemslib.exceptions.FormatError, if the arguments are improperly
    formatted.

    securesystemslib.exceptions.UnsupportedAlgorithmError, if the ECDSA key
    pair could not be extracted, possibly due to an unsupported algorithm.

  <Side Effects>
    None.

  <Returns>
    A dictionary containing the ECDSA keys and other identifying information.
    Conforms to 'securesystemslib.formats.ECDSAKEY_SCHEMA'.
  """

    # Does 'pem' have the correct format?
    # This check will ensure 'pem' conforms to
    # 'securesystemslib.formats.ECDSARSA_SCHEMA'.
    securesystemslib.formats.PEMECDSA_SCHEMA.check_match(pem)

    if password is not None:
        securesystemslib.formats.PASSWORD_SCHEMA.check_match(password)
        password = password.encode('utf-8')

    else:
        logger.debug('The password/passphrase is unset.  The PEM is expected'
                     ' to be unencrypted.')

    public = None
    private = None

    # Generate the public and private ECDSA keys.  The pyca/cryptography library
    # performs the actual import operation.
    try:
        private = load_pem_private_key(pem.encode('utf-8'),
                                       password=password,
                                       backend=default_backend())

    except (ValueError, cryptography.exceptions.UnsupportedAlgorithm) as e:
        raise securesystemslib.exceptions.CryptoError(
            'Could not import private'
            ' PEM.\n' + str(e))

    public = private.public_key()

    # Serialize public and private keys to PEM format.
    private = private.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption())

    public = public.public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo)

    return public.decode('utf-8'), private.decode('utf-8')
Exemplo n.º 12
0
def rsa_export_privkey(private_key):
    """ export private key  """
    return private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption())
Exemplo n.º 13
0
    def _toString_OPENSSH(self, extra):
        """
        Return a public or private OpenSSH string.  See
        _fromString_PUBLIC_OPENSSH and _fromString_PRIVATE_OPENSSH for the
        string formats.  If extra is present, it represents a comment for a
        public key, or a passphrase for a private key.

        @param extra: Comment for a public key or passphrase for a
            private key
        @type extra: L{bytes}

        @rtype: L{bytes}
        """
        data = self.data()
        if self.isPublic():
            if self.type() == 'EC':
                if not extra:
                    extra = b''
                return (self._keyObject.public_bytes(
                    serialization.Encoding.OpenSSH,
                    serialization.PublicFormat.OpenSSH) + b' ' +
                        extra).strip()

            b64Data = encodebytes(self.blob()).replace(b'\n', b'')
            if not extra:
                extra = b''
            return (self.sshType() + b' ' + b64Data + b' ' + extra).strip()
        else:

            if self.type() == 'EC':
                # EC keys has complex ASN.1 structure hence we do this this way.
                if not extra:
                    # unencrypted private key
                    encryptor = serialization.NoEncryption()
                else:
                    encryptor = serialization.BestAvailableEncryption(extra)

                return self._keyObject.private_bytes(
                    serialization.Encoding.PEM,
                    serialization.PrivateFormat.TraditionalOpenSSL, encryptor)

            lines = [
                b''.join((b'-----BEGIN ', self.type().encode('ascii'),
                          b' PRIVATE KEY-----'))
            ]
            if self.type() == 'RSA':
                p, q = data['p'], data['q']
                objData = (0, data['n'], data['e'], data['d'], q, p,
                           data['d'] % (q - 1), data['d'] % (p - 1), data['u'])
            else:
                objData = (0, data['p'], data['q'], data['g'], data['y'],
                           data['x'])
            asn1Sequence = univ.Sequence()
            for index, value in izip(itertools.count(), objData):
                asn1Sequence.setComponentByPosition(index, univ.Integer(value))
            asn1Data = berEncoder.encode(asn1Sequence)
            if extra:
                iv = randbytes.secureRandom(8)
                hexiv = ''.join(['%02X' % (ord(x), ) for x in iterbytes(iv)])
                hexiv = hexiv.encode('ascii')
                lines.append(b'Proc-Type: 4,ENCRYPTED')
                lines.append(b'DEK-Info: DES-EDE3-CBC,' + hexiv + b'\n')
                ba = md5(extra + iv).digest()
                bb = md5(ba + extra + iv).digest()
                encKey = (ba + bb)[:24]
                padLen = 8 - (len(asn1Data) % 8)
                asn1Data += (chr(padLen) * padLen).encode('ascii')

                encryptor = Cipher(algorithms.TripleDES(encKey),
                                   modes.CBC(iv),
                                   backend=default_backend()).encryptor()

                asn1Data = encryptor.update(asn1Data) + encryptor.finalize()

            b64Data = encodebytes(asn1Data).replace(b'\n', b'')
            lines += [b64Data[i:i + 64] for i in range(0, len(b64Data), 64)]
            lines.append(b''.join((b'-----END ', self.type().encode('ascii'),
                                   b' PRIVATE KEY-----')))
            return b'\n'.join(lines)
Exemplo n.º 14
0
def create_csr(**csr_config):
    """
    Given a list of domains create the appropriate csr
    for those domains

    :param csr_config:
    """
    private_key = generate_private_key(csr_config.get("key_type"))

    builder = x509.CertificateSigningRequestBuilder()
    name_list = [
        x509.NameAttribute(x509.OID_COMMON_NAME, csr_config["common_name"])
    ]
    if current_app.config.get("LEMUR_OWNER_EMAIL_IN_SUBJECT", True):
        name_list.append(
            x509.NameAttribute(x509.OID_EMAIL_ADDRESS, csr_config["owner"]))
    if "organization" in csr_config and csr_config["organization"].strip():
        name_list.append(
            x509.NameAttribute(x509.OID_ORGANIZATION_NAME,
                               csr_config["organization"]))
    if ("organizational_unit" in csr_config
            and csr_config["organizational_unit"].strip()):
        name_list.append(
            x509.NameAttribute(x509.OID_ORGANIZATIONAL_UNIT_NAME,
                               csr_config["organizational_unit"]))
    if "country" in csr_config and csr_config["country"].strip():
        name_list.append(
            x509.NameAttribute(x509.OID_COUNTRY_NAME, csr_config["country"]))
    if "state" in csr_config and csr_config["state"].strip():
        name_list.append(
            x509.NameAttribute(x509.OID_STATE_OR_PROVINCE_NAME,
                               csr_config["state"]))
    if "location" in csr_config and csr_config["location"].strip():
        name_list.append(
            x509.NameAttribute(x509.OID_LOCALITY_NAME, csr_config["location"]))
    builder = builder.subject_name(x509.Name(name_list))

    extensions = csr_config.get("extensions", {})
    critical_extensions = ["basic_constraints", "sub_alt_names", "key_usage"]
    noncritical_extensions = ["extended_key_usage"]
    for k, v in extensions.items():
        if v:
            if k in critical_extensions:
                current_app.logger.debug(
                    "Adding Critical Extension: {0} {1}".format(k, v))
                if k == "sub_alt_names":
                    if v["names"]:
                        builder = builder.add_extension(v["names"],
                                                        critical=True)
                else:
                    builder = builder.add_extension(v, critical=True)

            if k in noncritical_extensions:
                current_app.logger.debug("Adding Extension: {0} {1}".format(
                    k, v))
                builder = builder.add_extension(v, critical=False)

    ski = extensions.get("subject_key_identifier", {})
    if ski.get("include_ski", False):
        builder = builder.add_extension(
            x509.SubjectKeyIdentifier.from_public_key(
                private_key.public_key()),
            critical=False,
        )

    request = builder.sign(private_key, hashes.SHA256(), default_backend())

    # serialize our private key and CSR
    private_key = private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.
        TraditionalOpenSSL,  # would like to use PKCS8 but AWS ELBs don't like it
        encryption_algorithm=serialization.NoEncryption(),
    ).decode("utf-8")

    csr = request.public_bytes(
        encoding=serialization.Encoding.PEM).decode("utf-8")

    return csr, private_key
Exemplo n.º 15
0
    def generate_ocsp_key(self,
                          profile='ocsp',
                          expires=3,
                          algorithm=None,
                          password=None,
                          key_size=None,
                          key_type=None,
                          ecc_curve=None):
        """Generate OCSP keys for this CA.

        Parameters
        ----------

        profile : str, optional
            The profile to use for generating the certificate. The default is ``"ocsp"``.
        expires : int or datetime, optional
            Number of days or datetime when this certificate expires. The default is ``3`` (OCSP certificates
            are usually renewed frequently).
        algorithm : str, optional
            Passed to :py:func:`~django_ca.utils.parse_hash_algorithm` and defaults to
            :ref:`CA_DIGEST_ALGORITHM <settings-ca-digest-algorithm>`.
        password : bytes, optional
            The password to the CA as bytes, if its private key is encrypted.
        key_size : int, optional
            The key size of the private key, defaults to :ref:`CA_DEFAULT_KEY_SIZE
            <settings-ca-default-key-size>`.
        key_type : {"RSA", "DSA", "ECC"}, optional
            The private key type to use, the default is ``"RSA"``.
        ecc_curve : str, optional
            Passed to :py:func:`~django_ca.utils.parse_key_curve`, defaults to the :ref:`CA_DEFAULT_ECC_CURVE
            <settings-ca-default-ecc-curve>`.

        """
        key_size, key_type, ecc_curve = validate_key_parameters(
            key_size, key_type, ecc_curve)
        if isinstance(expires, six.integer_types):
            expires = timedelta(days=expires)
        algorithm = parse_hash_algorithm(algorithm)

        # generate the private key
        private_key = generate_private_key(key_size, key_type, ecc_curve)
        private_pem = private_key.private_bytes(
            encoding=Encoding.PEM,
            format=PrivateFormat.PKCS8,
            encryption_algorithm=serialization.NoEncryption())
        private_path = ca_storage.generate_filename(
            'ocsp/%s.key' % self.serial.replace(':', ''))

        csr = x509.CertificateSigningRequestBuilder().subject_name(
            self.x509.subject).sign(private_key, hashes.SHA256(),
                                    default_backend())

        kwargs = get_cert_profile_kwargs(profile)
        # TODO: This value is just a guess - see what public CAs do!?
        kwargs['subject'] = self.subject
        cert = Certificate.objects.init(ca=self,
                                        csr=csr,
                                        expires=expires,
                                        ocsp_url=False,
                                        password=password,
                                        **kwargs)

        cert_path = ca_storage.generate_filename('ocsp/%s.pem' %
                                                 self.serial.replace(':', ''))
        cert_pem = cert.dump_certificate(encoding=Encoding.PEM)

        for path, contents in [(private_path, private_pem),
                               (cert_path, cert_pem)]:
            if ca_storage.exists(path):
                with ca_storage.open(path, 'wb') as stream:
                    stream.write(contents)
            else:
                ca_storage.save(path, ContentFile(contents))
        return private_path, cert_path, cert
Exemplo n.º 16
0
    def init(self, config, servermode):
        try:
            extended_nonce = os.urandom(4) * 4
            algorithm = algorithms.ChaCha20("0" * 32, extended_nonce)
            cipher = Cipher(algorithm, mode=None, backend=default_backend())
            decryptor = cipher.decryptor()
        except UnsupportedAlgorithm:
            common.internal_print(
                "OpenSSL library is outdated. Please update.", -1)
            return False
        except:
            common.internal_print(
                "Something went wrong with the cryptography engine. Most probably OpenSSL related.",
                -1)
            return False

        if servermode:
            if not (os.path.exists(self.server_public_key_file)
                    or os.path.exists(self.server_private_key_file)):
                common.internal_print(
                    "Both public and private key is missing. This must be the first run. Generating keys...",
                    1)

                private_key = ec.generate_private_key(self.curve,
                                                      default_backend())
                privkey_ser = private_key.private_bytes(
                    serialization.Encoding.PEM,
                    serialization.PrivateFormat.TraditionalOpenSSL,
                    serialization.NoEncryption())
                pubkey_ser = private_key.public_key().public_bytes(
                    serialization.Encoding.PEM,
                    serialization.PublicFormat.SubjectPublicKeyInfo)

                p = open(self.server_public_key_file, "w+")
                p.write(pubkey_ser)
                p.close()

                oldmask = os.umask(0366)
                p = open(self.server_private_key_file, "w+")
                p.write(privkey_ser)
                p.close()
                os.umask(oldmask)

            if not (os.path.exists(self.server_public_key_file)
                    and os.path.exists(self.server_private_key_file)):
                common.internal_print(
                    "Private or public key does not exist. Please make sure you have both or delete the existing one.",
                    -1)
                return False

            # load keys from files
            f = open(self.server_private_key_file, "r")
            serialized_private = f.read()
            f.close()

            f = open(self.server_public_key_file, "r")
            serialized_public = f.read()
            f.close()

            # load private and public keys from files
            try:
                self.server_public_key = serialization.load_pem_public_key(
                    serialized_public, backend=default_backend())
            except:
                common.internal_print(
                    "Error parsing '{0}' as a public key.".format(
                        self.server_public_key_file), -1)
                return False
            try:
                self.server_private_key = serialization.load_pem_private_key(
                    serialized_private,
                    password=None,
                    backend=default_backend())
            except:
                common.internal_print(
                    "Error parsing '{0}' as a private key.".format(
                        self.server_private_key_file), -1)
                return False

            return True
        else:
            return True

        return False
Exemplo n.º 17
0
def execute_snowflake_query(snowflake_database, query,
                            snowflake_session_parameters, autocommit, verbose):
    # Password authentication is the default
    snowflake_password = None
    if os.getenv("SNOWFLAKE_PASSWORD") is not None and os.getenv(
            "SNOWFLAKE_PASSWORD"):
        snowflake_password = os.getenv("SNOWFLAKE_PASSWORD")
    elif os.getenv("SNOWSQL_PWD") is not None and os.getenv(
            "SNOWSQL_PWD"):  # Check legacy/deprecated env variable
        snowflake_password = os.getenv("SNOWSQL_PWD")
        warnings.warn(
            "The SNOWSQL_PWD environment variable is deprecated and will be removed in a later version of schemachange. Please use SNOWFLAKE_PASSWORD instead.",
            DeprecationWarning)

    if snowflake_password is not None:
        if verbose:
            print("Proceeding with password authentication")

        con = snowflake.connector.connect(
            user=os.environ["SNOWFLAKE_USER"],
            account=os.environ["SNOWFLAKE_ACCOUNT"],
            role=os.environ["SNOWFLAKE_ROLE"],
            warehouse=os.environ["SNOWFLAKE_WAREHOUSE"],
            database=snowflake_database,
            authenticator=os.environ["SNOWFLAKE_AUTHENTICATOR"],
            password=snowflake_password,
            application=_snowflake_application_name,
            session_parameters=snowflake_session_parameters)
    # If no password, try private key authentication
    elif os.getenv("SNOWFLAKE_PRIVATE_KEY_PATH", ''):
        if verbose:
            print("Proceeding with private key authentication")

        private_key_password = os.getenv("SNOWFLAKE_PRIVATE_KEY_PASSPHRASE",
                                         '')
        if private_key_password:
            private_key_password = private_key_password.encode()
        else:
            private_key_password = None
            if verbose:
                print(
                    "No private key passphrase provided. Assuming the key is not encrypted."
                )
        with open(os.environ["SNOWFLAKE_PRIVATE_KEY_PATH"], "rb") as key:
            p_key = serialization.load_pem_private_key(
                key.read(),
                password=private_key_password,
                backend=default_backend())

        pkb = p_key.private_bytes(
            encoding=serialization.Encoding.DER,
            format=serialization.PrivateFormat.PKCS8,
            encryption_algorithm=serialization.NoEncryption())

        con = snowflake.connector.connect(
            user=os.environ["SNOWFLAKE_USER"],
            account=os.environ["SNOWFLAKE_ACCOUNT"],
            role=os.environ["SNOWFLAKE_ROLE"],
            warehouse=os.environ["SNOWFLAKE_WAREHOUSE"],
            database=snowflake_database,
            authenticator=os.environ["SNOWFLAKE_AUTHENTICATOR"],
            application=_snowflake_application_name,
            private_key=pkb,
            session_parameters=snowflake_session_parameters)
    else:
        raise ValueError(
            "Unable to find connection credentials for private key or password authentication"
        )

    if not autocommit:
        con.autocommit(False)

    if verbose:
        print(SecretManager.global_redact("SQL query: %s" % query))

    try:
        res = con.execute_string(query)
        if not autocommit:
            con.commit()
        return res
    except Exception as e:
        if not autocommit:
            con.rollback()
        raise e
    finally:
        con.close()
Exemplo n.º 18
0
 def export_private_der(self) -> bytes:
     return self._privkey.private_bytes(
         encoding=serialization.Encoding.DER,
         format=serialization.PrivateFormat.PKCS8,
         encryption_algorithm=serialization.NoEncryption(),
     )
Exemplo n.º 19
0
from flask import Flask, request
import jwt

app = Flask(__name__)
# Check if PRIVATE_KEY and PUBIC_KEY is set, if not generate them.
# NOTE: For web deployment, please set the these enviorment variable to be the same between
# the instance
if os.environ.get('PRIVATE_KEY') is None or os.environ.get(
        'PUBLIC_KEY') is None:
    key = rsa.generate_private_key(backend=crypto_default_backend(),
                                   public_exponent=65537,
                                   key_size=2048)
    os.environ['PRIVATE_KEY'] = key.private_bytes(
        crypto_serialization.Encoding.PEM,
        crypto_serialization.PrivateFormat.PKCS8,
        crypto_serialization.NoEncryption()).decode()
    os.environ['PUBLIC_KEY'] = key.public_key().public_bytes(
        crypto_serialization.Encoding.OpenSSH,
        crypto_serialization.PublicFormat.OpenSSH).decode()


def protected_route(function: Callable):
    """
    Protected route function decorator which authenticates requests
    :param function: Function to decorate, typically routes
    :type function: :class:`typing.Callable`
    :return: Function output if jwt authecation is successful, otherwise return error message
    :rtype: class:`typing.Callable`
    """
    def wrapper():
        try:
Exemplo n.º 20
0
 def export_private_pem(self) -> str:
     return self._privkey.private_bytes(
         encoding=serialization.Encoding.PEM,
         format=serialization.PrivateFormat.PKCS8,
         encryption_algorithm=serialization.NoEncryption(),
     ).decode()
def generate_signer_certificate():
    """Generates a x.509 certificate signed by ECDSA key
    This signer certificate is used to generate the device manifest file and helps 
    ensure the validity/ownership of the manifest contents. This signer certificate's
    Distinguished Name (DN) includes the AWS IoT registration code (FDQN)as the 
    common name and can be helpful for fleet provisioning.

    Signer certificate and key is saved in ./output_files/

    Certificate is set to expire in 1 year.
    """
    print("Generating ECDSA 256-bit prime field key...")
    signer_key = ec.generate_private_key(curve=ec.SECP256R1(),
                                         backend=default_backend())

    signer_key_pem = signer_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption(),
    )
    with open(
            os.path.join(os.path.dirname(__file__), "output_files",
                         "signer_key.pem"), "wb") as signer_key_file:
        signer_key_file.write(signer_key_pem)

    print("Generating self-signed x.509 certificate...")
    try:
        aws_iot_reg_code = iot.get_registration_code()
    except ClientError:
        print(ClientError.response['Error']['Code'])
        print(
            "Error with the AWS CLI when running the command 'aws iot get-registration-code'."
        )
        exit(0)

    signer_public_key = signer_key.public_key()
    time_now = datetime.utcnow()
    days_to_expire = 365
    x509_cert = (
        x509.CertificateBuilder().issuer_name(
            x509.Name([
                x509.NameAttribute(NameOID.COMMON_NAME,
                                   aws_iot_reg_code['registrationCode']),
            ])).subject_name(
                x509.Name([
                    x509.NameAttribute(NameOID.COMMON_NAME,
                                       aws_iot_reg_code['registrationCode']),
                ])).serial_number(
                    x509.random_serial_number()).public_key(signer_public_key).
        not_valid_before(time_now).not_valid_after(time_now + timedelta(
            days=days_to_expire)).add_extension(
                x509.SubjectKeyIdentifier.from_public_key(signer_public_key),
                False).add_extension(
                    x509.AuthorityKeyIdentifier.from_issuer_public_key(
                        signer_public_key), False).add_extension(
                            x509.BasicConstraints(ca=True, path_length=None),
                            True).sign(signer_key, hashes.SHA256(),
                                       default_backend()))

    signer_cert_pem = x509_cert.public_bytes(
        encoding=serialization.Encoding.PEM)

    with open(
            os.path.join(os.path.dirname(__file__), "output_files",
                         "signer_cert.crt"), "wb") as signer_cert_file:
        signer_cert_file.write(signer_cert_pem)
    print(
        f"Successfully created x.509 certificate with expiration in {days_to_expire} days..."
    )
Exemplo n.º 22
0
def create_cert(ip, seconds, der, key_size):
    security_module.initialize_root_certificate()

    client_cert_path = os.path.join(
        os.path.dirname(os.path.realpath(__file__)), "certs/%s.crt" % ip)
    client_key_path = os.path.join(os.path.dirname(client_cert_path),
                                   "%s.key" % ip)

    # Ask the user for a password for the private key
    while True:
        print(
            "Please enter a password for the certificate private key (leave blank for no password)",
            flush=True)
        pass1 = getpass()
        print("Please repeat the password", flush=True)
        pass2 = getpass()

        if pass1 == pass2:
            break
        else:
            print("Passwords do not match, please try again\n")

    # Create the private key
    private_key = rsa.generate_private_key(public_exponent=65537,
                                           key_size=key_size,
                                           backend=default_backend())

    # Generate the certificate, signed with our root private key
    subject = x509.Name([
        x509.NameAttribute(NameOID.COUNTRY_NAME, u"ES"),
        x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"SE"),
        x509.NameAttribute(NameOID.LOCALITY_NAME, u"Sevilla"),
        x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"ACME"),
        x509.NameAttribute(NameOID.COMMON_NAME, ip),
    ])

    issuer = x509.Name([
        x509.NameAttribute(NameOID.COUNTRY_NAME, u"ES"),
        x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"SE"),
        x509.NameAttribute(NameOID.LOCALITY_NAME, u"Sevilla"),
        x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"ACME"),
        x509.NameAttribute(NameOID.COMMON_NAME, u"NAT-PMP Daemon"),
    ])

    client_cert = x509.CertificateBuilder() \
        .subject_name(subject) \
        .issuer_name(issuer) \
        .public_key(private_key.public_key()) \
        .serial_number(x509.random_serial_number()) \
        .not_valid_before(datetime.utcnow()) \
        .not_valid_after(datetime.utcnow() + timedelta(seconds=seconds)) \
        .add_extension(
            x509.SubjectAlternativeName([x509.DNSName(ip)]),
            critical=False,
        ) \
        .sign(security_module.ROOT_KEY, hashes.SHA256(), default_backend())

    key_encr_algo = serialization.BestAvailableEncryption(bytes(
        pass1, "utf-8")) if len(pass1) > 0 else serialization.NoEncryption()
    encoding = serialization.Encoding.DER if der else serialization.Encoding.PEM

    # Save the private key with 600 permissions
    with open(client_key_path, "wb") as f:
        f.write(
            private_key.private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.TraditionalOpenSSL,
                encryption_algorithm=key_encr_algo))

    os.chmod(client_key_path, 0o600)

    # Save the certificate with 644 permissions
    with open(client_cert_path, "wb") as f:
        f.write(client_cert.public_bytes(encoding))

    os.chmod(client_cert_path, 0o644)

    print("Certificate and key for %s stored in %s" %
          (ip, os.path.dirname(client_cert_path)))
Exemplo n.º 23
0
def certify():
    """Create certificate authority for federation."""
    from openfl.cryptography.ca import generate_root_cert, generate_signing_csr, sign_certificate
    from cryptography.hazmat.primitives import serialization

    echo('Setting Up Certificate Authority...\n')

    echo('1.  Create Root CA')
    echo('1.1 Create Directories')

    (PKI_DIR / 'ca/root-ca/private').mkdir(parents=True,
                                           exist_ok=True,
                                           mode=0o700)
    (PKI_DIR / 'ca/root-ca/db').mkdir(parents=True, exist_ok=True)

    echo('1.2 Create Database')

    with open(PKI_DIR / 'ca/root-ca/db/root-ca.db', 'w') as f:
        pass  # write empty file
    with open(PKI_DIR / 'ca/root-ca/db/root-ca.db.attr', 'w') as f:
        pass  # write empty file

    with open(PKI_DIR / 'ca/root-ca/db/root-ca.crt.srl', 'w') as f:
        f.write('01')  # write file with '01'
    with open(PKI_DIR / 'ca/root-ca/db/root-ca.crl.srl', 'w') as f:
        f.write('01')  # write file with '01'

    echo('1.3 Create CA Request and Certificate')

    root_crt_path = 'ca/root-ca.crt'
    root_key_path = 'ca/root-ca/private/root-ca.key'

    root_private_key, root_cert = generate_root_cert()

    # Write root CA certificate to disk
    with open(PKI_DIR / root_crt_path, 'wb') as f:
        f.write(root_cert.public_bytes(encoding=serialization.Encoding.PEM, ))

    with open(PKI_DIR / root_key_path, "wb") as f:
        f.write(
            root_private_key.private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.TraditionalOpenSSL,
                encryption_algorithm=serialization.NoEncryption()))

    echo('2.  Create Signing Certificate')
    echo('2.1 Create Directories')

    (PKI_DIR / 'ca/signing-ca/private').mkdir(parents=True,
                                              exist_ok=True,
                                              mode=0o700)
    (PKI_DIR / 'ca/signing-ca/db').mkdir(parents=True, exist_ok=True)

    echo('2.2 Create Database')

    with open(PKI_DIR / 'ca/signing-ca/db/signing-ca.db', 'w') as f:
        pass  # write empty file
    with open(PKI_DIR / 'ca/signing-ca/db/signing-ca.db.attr', 'w') as f:
        pass  # write empty file

    with open(PKI_DIR / 'ca/signing-ca/db/signing-ca.crt.srl', 'w') as f:
        f.write('01')  # write file with '01'
    with open(PKI_DIR / 'ca/signing-ca/db/signing-ca.crl.srl', 'w') as f:
        f.write('01')  # write file with '01'

    echo('2.3 Create Signing Certificate CSR')

    signing_csr_path = 'ca/signing-ca.csr'
    signing_crt_path = 'ca/signing-ca.crt'
    signing_key_path = 'ca/signing-ca/private/signing-ca.key'

    signing_private_key, signing_csr = generate_signing_csr()

    # Write Signing CA CSR to disk
    with open(PKI_DIR / signing_csr_path, 'wb') as f:
        f.write(signing_csr.public_bytes(
            encoding=serialization.Encoding.PEM, ))

    with open(PKI_DIR / signing_key_path, "wb") as f:
        f.write(
            signing_private_key.private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.TraditionalOpenSSL,
                encryption_algorithm=serialization.NoEncryption()))

    echo('2.4 Sign Signing Certificate CSR')

    signing_cert = sign_certificate(signing_csr,
                                    root_private_key,
                                    root_cert.subject,
                                    ca=True)

    with open(PKI_DIR / signing_crt_path, 'wb') as f:
        f.write(
            signing_cert.public_bytes(encoding=serialization.Encoding.PEM, ))

    echo('3   Create Certificate Chain')

    # create certificate chain file by combining root-ca and signing-ca
    with open(PKI_DIR / 'cert_chain.crt', 'w') as d:
        with open(PKI_DIR / 'ca/root-ca.crt') as s:
            d.write(s.read())
        with open(PKI_DIR / 'ca/signing-ca.crt') as s:
            d.write(s.read())

    echo('\nDone.')
Exemplo n.º 24
0
 def get_key_content(self):
     return self._key.private_bytes(
         encoding=serialization.Encoding.PEM,
         format=serialization.PrivateFormat.TraditionalOpenSSL,
         encryption_algorithm=serialization.NoEncryption(),
     )
Exemplo n.º 25
0
def get_rsa_private_key_in_pem_bytes(key):
    return key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption())
Exemplo n.º 26
0
def encode_private_key_pem_format(private_key):
    pem = private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption())
    return pem
Exemplo n.º 27
0
    def from_new_directory(cls, directory=None, force=False):
        """Create a Security object from a new certificate/key pair.

        This is equivalent to the cli command ``skein init`` with the option to
        specify an alternate directory *if needed*. Should only need to be
        called once per user upon install. Call again with ``force=True`` to
        generate new TLS keys and certificates.

        Parameters
        ----------
        directory : str, optional
            The directory to write the configuration to. Defaults to the global
            skein configuration directory at ``~/.skein/``.
        force : bool, optional
            If True, will overwrite existing configuration. Otherwise will
            error if already configured. Default is False.
        """
        from cryptography import x509
        from cryptography.hazmat.backends import default_backend
        from cryptography.hazmat.primitives import hashes
        from cryptography.hazmat.primitives import serialization
        from cryptography.hazmat.primitives.asymmetric import rsa
        from cryptography.x509.oid import NameOID

        directory = directory or CONFIG_DIR

        # Create directory if it doesn't exist
        makedirs(directory, exist_ok=True)

        key = rsa.generate_private_key(public_exponent=65537,
                                       key_size=2048,
                                       backend=default_backend())
        key_bytes = key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.PKCS8,
            encryption_algorithm=serialization.NoEncryption())

        subject = issuer = x509.Name(
            [x509.NameAttribute(NameOID.COMMON_NAME, u'skein-internal')])
        now = datetime.datetime.utcnow()
        cert = (x509.CertificateBuilder().subject_name(subject).issuer_name(
            issuer).public_key(key.public_key()).serial_number(
                x509.random_serial_number()).not_valid_before(
                    now).not_valid_after(now +
                                         datetime.timedelta(days=365)).sign(
                                             key, hashes.SHA256(),
                                             default_backend()))

        cert_bytes = cert.public_bytes(serialization.Encoding.PEM)

        cert_path = os.path.join(directory, 'skein.crt')
        key_path = os.path.join(directory, 'skein.pem')

        for path, name in [(cert_path, 'skein.crt'), (key_path, 'skein.pem')]:
            if os.path.exists(path):
                if force:
                    os.unlink(path)
                else:
                    msg = ("%r file already exists, use `%s` to overwrite" %
                           (name, '--force' if context.is_cli else 'force'))
                    raise context.FileExistsError(msg)

        flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
        for path, data in [(cert_path, cert_bytes), (key_path, key_bytes)]:
            with os.fdopen(os.open(path, flags, 0o600), 'wb') as fil:
                fil.write(data)

        return cls(cert_path, key_path)
Exemplo n.º 28
0
def _generate_certificate(path, keyfile=None, password=None):
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives import serialization
    from cryptography.hazmat.primitives.asymmetric import rsa
    from cryptography import x509
    from cryptography.x509.oid import NameOID
    from cryptography.hazmat.primitives import hashes

    if keyfile:
        with open(path, "rb") as kf:
            key_bytes = kf.read()
            key = serialization.load_pem_private_key(key_bytes, password, default_backend())
    else:
        key = rsa.generate_private_key(
            public_exponent=65537,
            key_size=2048,
            backend=default_backend()
        )
        key_bytes = key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.PKCS8,
            encryption_algorithm=serialization.BestAvailableEncryption(password) if password else serialization.NoEncryption(),
        )

    # Various details about who we are. For a self-signed certificate the
    # Subject and issuer are always the same.
    subject = issuer = x509.Name([
        x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
        x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u'WA'),
        x509.NameAttribute(NameOID.LOCALITY_NAME, u'Redmond'),
        x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"My Company"),
        x509.NameAttribute(NameOID.COMMON_NAME, u"mysite.com")])

    cert = x509.CertificateBuilder().subject_name(subject) \
                                    .issuer_name(issuer) \
                                    .public_key(key.public_key()) \
                                    .serial_number(x509.random_serial_number()) \
                                    .not_valid_before(datetime.utcnow()) \
                                    .not_valid_after(datetime.utcnow() + timedelta(days=10)) \
                                    .sign(key, hashes.SHA256(), default_backend())

    # Write the cert out to disk
    with open(path, "wb") as f:
        f.write(key_bytes)
        f.write(cert.public_bytes(serialization.Encoding.PEM))
Exemplo n.º 29
0
from cryptography.hazmat.backends import default_backend

fd = open('ad1.txt', 'r+')
for i in range(110):
    private_key = ec.generate_private_key(ec.SECP256K1, default_backend())
    public_key = private_key.public_key()
    sy = public_key.public_bytes(
        serialization.Encoding.PEM,
        serialization.PublicFormat.SubjectPublicKeyInfo)
    sha = hashlib.sha256()
    sha.update(sy)
    public_key_hash = sha.digest()
    serialized_private = private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption())

    fd.writelines(str(serialized_private) + 'ENDDING')
    fd.writelines(str(sy) + '\n')
    # print(serialized_private)
    # print(sy)
    # print(len(public_key_hash))
fd.close()

fd = open('ad1.txt', 'r')
for index, line in enumerate(fd.readlines()):
    print(index)
    line = line.rstrip()
    pr, pu = line.split('ENDDING')
    temp = bytes(pr[2:-1], encoding='utf-8')
    temp = temp.replace(b'\r\n', b'\n')
Exemplo n.º 30
0
    def set_JWT_keys(cls, passphrase, algorithm=None, jwks=None, privkey=None):
        '''Set the passphrase or keys used to sign and verify JWTs

        - algortihm: The JWT algorithm, e.g. HS256. If not supplied,
          then it is taken from the _algorithm class attribute.
          If it is supplied, it sets that class attribute.
        - passphrase: The passphrase to use for symmetric algorithms,
          or the passphrase to use to decrypt a private key file (when
          loading it from a file). It must be supplied, even if the
          given privkey is unencrypted (in which case passphrase must
          be None).
        - privkey: The private PEM key to use for signing the JWT.
          Only for asymmetric algorithms. It can be a filename, an
          open file handle, or an already decrypted PEM key (as
          a string, should begin with "-----BEGIN"). It must be
          supplied asymmetric algorithms.
        - jwks: Boolean specifying whether or not to user JWKS.
          If None, it is taken from the _enable_JWKS class attribute.
          If it is supplied, it sets that class attribute.
        '''
        def load_privkey(fh):
            _passphrase = passphrase
            if _passphrase is not None \
                    and not isinstance(_passphrase, bytes):
                _passphrase = _passphrase.encode('utf-8')
            return load_pem_private_key(fh.read(),
                                        password=_passphrase,
                                        backend=crypto_default_backend())

        def load_key(arg, loader):
            if is_str(arg):
                if not arg.startswith('-----BEGIN'):
                    with open(arg, 'rb') as f:
                        return loader(f)
            # it has to be an open file handle
            return loader(f)

        def get_jwks(pubkey):
            n = pubkey.public_numbers().n
            n_b64 = base64.urlsafe_b64encode(
                int_to_bytes(n)).decode('utf-8').strip('=')
            e = pubkey.public_numbers().e
            e_b64 = base64.urlsafe_b64encode(
                int_to_bytes(e)).decode('utf-8').strip('=')
            assert not cls._algorithm.startswith('HS')
            kty = 'RSA'
            if cls._algorithm.startswith('ES'):
                kty = 'EC'
            return {
                'keys': [{
                    'alg': cls._algorithm,
                    'kty': kty,
                    'use': 'sig',
                    'n': n_b64,
                    'e': e_b64,
                    'kid': randstr(40, use_punct=False),
                }]
            }

        if algorithm is not None:
            cls._algorithm = algorithm
        if cls._algorithm.startswith('HS'):
            # symmetric algorithm
            setattr(cls, '_enc_key', passphrase)
            setattr(cls, '_dec_key', passphrase)
            return
        # asymmetric algorithm
        privkey_loaded = load_key(privkey, load_privkey)
        pubkey = privkey_loaded.public_key()
        pubkey_pem = pubkey.public_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PublicFormat.SubjectPublicKeyInfo)
        privkey_pem = privkey_loaded.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.TraditionalOpenSSL,
            encryption_algorithm=serialization.NoEncryption())
        setattr(cls, '_enc_key', privkey_pem)
        setattr(cls, '_dec_key', pubkey_pem)
        if jwks is not None:
            cls._enable_JWKS = jwks
        if cls._enable_JWKS:
            setattr(cls, '_jwks', get_jwks(pubkey))