mtls.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. """Utilites for mutual TLS."""
  15. from google.auth import exceptions
  16. from google.auth.transport import _mtls_helper
  17. def has_default_client_cert_source():
  18. """Check if default client SSL credentials exists on the device.
  19. Returns:
  20. bool: indicating if the default client cert source exists.
  21. """
  22. metadata_path = _mtls_helper._check_dca_metadata_path(
  23. _mtls_helper.CONTEXT_AWARE_METADATA_PATH
  24. )
  25. return metadata_path is not None
  26. def default_client_cert_source():
  27. """Get a callback which returns the default client SSL credentials.
  28. Returns:
  29. Callable[[], [bytes, bytes]]: A callback which returns the default
  30. client certificate bytes and private key bytes, both in PEM format.
  31. Raises:
  32. google.auth.exceptions.DefaultClientCertSourceError: If the default
  33. client SSL credentials don't exist or are malformed.
  34. """
  35. if not has_default_client_cert_source():
  36. raise exceptions.MutualTLSChannelError(
  37. "Default client cert source doesn't exist"
  38. )
  39. def callback():
  40. try:
  41. _, cert_bytes, key_bytes = _mtls_helper.get_client_cert_and_key()
  42. except (OSError, RuntimeError, ValueError) as caught_exc:
  43. new_exc = exceptions.MutualTLSChannelError(caught_exc)
  44. raise new_exc from caught_exc
  45. return cert_bytes, key_bytes
  46. return callback
  47. def default_client_encrypted_cert_source(cert_path, key_path):
  48. """Get a callback which returns the default encrpyted client SSL credentials.
  49. Args:
  50. cert_path (str): The cert file path. The default client certificate will
  51. be written to this file when the returned callback is called.
  52. key_path (str): The key file path. The default encrypted client key will
  53. be written to this file when the returned callback is called.
  54. Returns:
  55. Callable[[], [str, str, bytes]]: A callback which generates the default
  56. client certificate, encrpyted private key and passphrase. It writes
  57. the certificate and private key into the cert_path and key_path, and
  58. returns the cert_path, key_path and passphrase bytes.
  59. Raises:
  60. google.auth.exceptions.DefaultClientCertSourceError: If any problem
  61. occurs when loading or saving the client certificate and key.
  62. """
  63. if not has_default_client_cert_source():
  64. raise exceptions.MutualTLSChannelError(
  65. "Default client encrypted cert source doesn't exist"
  66. )
  67. def callback():
  68. try:
  69. (
  70. _,
  71. cert_bytes,
  72. key_bytes,
  73. passphrase_bytes,
  74. ) = _mtls_helper.get_client_ssl_credentials(generate_encrypted_key=True)
  75. with open(cert_path, "wb") as cert_file:
  76. cert_file.write(cert_bytes)
  77. with open(key_path, "wb") as key_file:
  78. key_file.write(key_bytes)
  79. except (exceptions.ClientCertError, OSError) as caught_exc:
  80. new_exc = exceptions.MutualTLSChannelError(caught_exc)
  81. raise new_exc from caught_exc
  82. return cert_path, key_path, passphrase_bytes
  83. return callback