-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy path_mtls.py
More file actions
186 lines (150 loc) · 6.34 KB
/
_mtls.py
File metadata and controls
186 lines (150 loc) · 6.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# -*- coding: utf-8 -*-
#
# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Mutual TLS for Google Compute Engine metadata server."""
from dataclasses import dataclass, field
import enum
import logging
import os
from pathlib import Path
import ssl
from urllib.parse import urlparse, urlunparse
import requests
from requests.adapters import HTTPAdapter
from google.auth import environment_vars, exceptions
_LOGGER = logging.getLogger(__name__)
_WINDOWS_OS_NAME = "nt"
# MDS mTLS certificate paths based on OS.
# Documentation to well known locations can be found at:
# https://cloud.google.com/compute/docs/metadata/overview#https-mds-certificates
_WINDOWS_MTLS_COMPONENTS_BASE_PATH = Path("C:/ProgramData/Google/ComputeEngine")
_MTLS_COMPONENTS_BASE_PATH = Path("/run/google-mds-mtls")
def _get_mds_root_crt_path():
if os.name == _WINDOWS_OS_NAME:
return _WINDOWS_MTLS_COMPONENTS_BASE_PATH / "mds-mtls-root.crt"
else:
return _MTLS_COMPONENTS_BASE_PATH / "root.crt"
def _get_mds_client_combined_cert_path():
if os.name == _WINDOWS_OS_NAME:
return _WINDOWS_MTLS_COMPONENTS_BASE_PATH / "mds-mtls-client.key"
else:
return _MTLS_COMPONENTS_BASE_PATH / "client.key"
@dataclass
class MdsMtlsConfig:
ca_cert_path: Path = field(
default_factory=_get_mds_root_crt_path
) # path to CA certificate
client_combined_cert_path: Path = field(
default_factory=_get_mds_client_combined_cert_path
) # path to file containing client certificate and key
def mds_mtls_certificates_exist(mds_mtls_config: MdsMtlsConfig):
"""Checks if the mTLS certificates exist.
Args:
mds_mtls_config (MdsMtlsConfig): The mTLS configuration containing the
paths to the CA and client certificates.
Returns:
bool: True if both certificates exist, False otherwise.
"""
return os.path.exists(mds_mtls_config.ca_cert_path) and os.path.exists(
mds_mtls_config.client_combined_cert_path
)
class MdsMtlsMode(enum.Enum):
"""MDS mTLS mode. Used to configure connection behavior when connecting to MDS.
STRICT: Always use HTTPS/mTLS. If certificates are not found locally, an error will be returned.
NONE: Never use mTLS. Requests will use regular HTTP.
DEFAULT: Use mTLS if certificates are found locally, otherwise use regular HTTP.
"""
STRICT = "strict"
NONE = "none"
DEFAULT = "default"
def _parse_mds_mode():
"""Parses the GCE_METADATA_MTLS_MODE environment variable."""
mode_str = os.environ.get(
environment_vars.GCE_METADATA_MTLS_MODE, "default"
).lower()
try:
return MdsMtlsMode(mode_str)
except ValueError:
raise ValueError(
"Invalid value for GCE_METADATA_MTLS_MODE. Must be one of 'strict', 'none', or 'default'."
)
def should_use_mds_mtls(
mode: MdsMtlsMode, mds_mtls_config: MdsMtlsConfig = MdsMtlsConfig()
) -> bool:
"""Determines if mTLS should be used for the metadata server.
Args:
mode (MdsMtlsMode): The mTLS mode configured for the metadata server,
parsed from the GCE_METADATA_MTLS_MODE environment variable.
mds_mtls_config (MdsMtlsConfig): The mTLS configuration containing the
paths to the CA and client certificates.
Returns:
bool: True if mTLS should be used, False otherwise.
Raises:
google.auth.exceptions.MutualTLSChannelError: if mTLS is required (STRICT mode)
but certificates are missing.
"""
if mode == MdsMtlsMode.STRICT:
if not mds_mtls_certificates_exist(mds_mtls_config):
raise exceptions.MutualTLSChannelError(
"mTLS certificates not found in strict mode."
)
return True
if mode == MdsMtlsMode.NONE:
return False
return mds_mtls_certificates_exist(mds_mtls_config)
class MdsMtlsAdapter(HTTPAdapter):
"""An HTTP adapter that uses mTLS for the metadata server."""
def __init__(
self, mds_mtls_config: MdsMtlsConfig = MdsMtlsConfig(), *args, **kwargs
):
self.ssl_context = ssl.create_default_context()
self.ssl_context.load_verify_locations(cafile=mds_mtls_config.ca_cert_path)
self.ssl_context.load_cert_chain(
certfile=mds_mtls_config.client_combined_cert_path
)
super(MdsMtlsAdapter, self).__init__(*args, **kwargs)
def init_poolmanager(self, *args, **kwargs):
kwargs["ssl_context"] = self.ssl_context
return super(MdsMtlsAdapter, self).init_poolmanager(*args, **kwargs)
def proxy_manager_for(self, *args, **kwargs):
kwargs["ssl_context"] = self.ssl_context
return super(MdsMtlsAdapter, self).proxy_manager_for(*args, **kwargs)
def send(self, request, **kwargs):
# If we are in strict mode, always use mTLS (no HTTP fallback)
if _parse_mds_mode() == MdsMtlsMode.STRICT:
return super(MdsMtlsAdapter, self).send(request, **kwargs)
# In default mode, attempt mTLS first, then fallback to HTTP on failure
try:
response = super(MdsMtlsAdapter, self).send(request, **kwargs)
response.raise_for_status()
return response
except (
ssl.SSLError,
requests.exceptions.SSLError,
requests.exceptions.HTTPError,
) as e:
_LOGGER.warning(
"mTLS connection to Compute Engine Metadata server failed. "
"Falling back to standard HTTP. Reason: %s",
e,
)
# Fallback to standard HTTP
parsed_original_url = urlparse(request.url)
http_fallback_url = urlunparse(parsed_original_url._replace(scheme="http"))
request.url = http_fallback_url
# Use a standard HTTPAdapter for the fallback
http_adapter = HTTPAdapter()
return http_adapter.send(request, **kwargs)