mtls.py 3.9 KB

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