1# Copyright 2020 Google LLC
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#      http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""Utilites for mutual TLS."""
16
17import six
18
19from google.auth import exceptions
20from google.auth.transport import _mtls_helper
21
22
23def has_default_client_cert_source():
24    """Check if default client SSL credentials exists on the device.
25
26    Returns:
27        bool: indicating if the default client cert source exists.
28    """
29    metadata_path = _mtls_helper._check_dca_metadata_path(
30        _mtls_helper.CONTEXT_AWARE_METADATA_PATH
31    )
32    return metadata_path is not None
33
34
35def default_client_cert_source():
36    """Get a callback which returns the default client SSL credentials.
37
38    Returns:
39        Callable[[], [bytes, bytes]]: A callback which returns the default
40            client certificate bytes and private key bytes, both in PEM format.
41
42    Raises:
43        google.auth.exceptions.DefaultClientCertSourceError: If the default
44            client SSL credentials don't exist or are malformed.
45    """
46    if not has_default_client_cert_source():
47        raise exceptions.MutualTLSChannelError(
48            "Default client cert source doesn't exist"
49        )
50
51    def callback():
52        try:
53            _, cert_bytes, key_bytes = _mtls_helper.get_client_cert_and_key()
54        except (OSError, RuntimeError, ValueError) as caught_exc:
55            new_exc = exceptions.MutualTLSChannelError(caught_exc)
56            six.raise_from(new_exc, caught_exc)
57
58        return cert_bytes, key_bytes
59
60    return callback
61
62
63def default_client_encrypted_cert_source(cert_path, key_path):
64    """Get a callback which returns the default encrpyted client SSL credentials.
65
66    Args:
67        cert_path (str): The cert file path. The default client certificate will
68            be written to this file when the returned callback is called.
69        key_path (str): The key file path. The default encrypted client key will
70            be written to this file when the returned callback is called.
71
72    Returns:
73        Callable[[], [str, str, bytes]]: A callback which generates the default
74            client certificate, encrpyted private key and passphrase. It writes
75            the certificate and private key into the cert_path and key_path, and
76            returns the cert_path, key_path and passphrase bytes.
77
78    Raises:
79        google.auth.exceptions.DefaultClientCertSourceError: If any problem
80            occurs when loading or saving the client certificate and key.
81    """
82    if not has_default_client_cert_source():
83        raise exceptions.MutualTLSChannelError(
84            "Default client encrypted cert source doesn't exist"
85        )
86
87    def callback():
88        try:
89            (
90                _,
91                cert_bytes,
92                key_bytes,
93                passphrase_bytes,
94            ) = _mtls_helper.get_client_ssl_credentials(generate_encrypted_key=True)
95            with open(cert_path, "wb") as cert_file:
96                cert_file.write(cert_bytes)
97            with open(key_path, "wb") as key_file:
98                key_file.write(key_bytes)
99        except (exceptions.ClientCertError, OSError) as caught_exc:
100            new_exc = exceptions.MutualTLSChannelError(caught_exc)
101            six.raise_from(new_exc, caught_exc)
102
103        return cert_path, key_path, passphrase_bytes
104
105    return callback
106