File size: 15,913 Bytes
8247f19 | 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 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 | # Patch-overlapping Python context after the fix
## `keylime/registrar_common.py` — `class:UnprotectedHandler` (lines 204-477)
```python
class UnprotectedHandler(BaseHandler):
def do_HEAD(self) -> None:
"""HEAD not supported"""
web_util.echo_json_response(self, 405, "HEAD not supported")
def do_PATCH(self) -> None:
"""PATCH not supported"""
web_util.echo_json_response(self, 405, "PATCH not supported")
def do_GET(self) -> None:
"""This method handles the GET requests to the unprotected side of the Registrar Server
Currently the only supported path is /versions which shows the supported API versions
"""
rest_params = web_util.get_restful_params(self.path)
if rest_params is None:
web_util.echo_json_response(self, 405, "Not Implemented: Use /version/ interface")
return
if "version" not in rest_params:
web_util.echo_json_response(self, 400, "URI not supported")
logger.warning("GET agent returning 400 response. URI not supported: %s", self.path)
return
version_info = {
"current_version": keylime_api_version.current_version(),
"supported_versions": keylime_api_version.all_versions(),
}
web_util.echo_json_response(self, 200, "Success", version_info)
@staticmethod
def get_network_params(
json_body: Dict[str, Any], agent_id: str
) -> Tuple[Optional[str], Optional[int], Optional[str]]:
# Validate ip and port
ip = json_body.get("ip")
if ip is not None:
try:
ipaddress.ip_address(ip)
except ValueError:
logger.warning("Contact ip for agent %s is not a valid ip got: %s.", agent_id, ip)
ip = None
port = json_body.get("port")
if port is not None:
try:
port = int(port)
if port < 1 or port > 65535:
logger.warning(
"Contact port for agent %s is not a number between 1 and 65535 got: %s.", agent_id, port
)
port = None
except ValueError:
logger.warning("Contact port for agent %s is not a valid number got: %s.", agent_id, port)
port = None
mtls_cert = json_body.get("mtls_cert")
if mtls_cert is None or mtls_cert == "disabled":
logger.warning("Agent %s did not send a mTLS certificate. Most operations will not work!", agent_id)
return ip, port, mtls_cert
def do_POST(self) -> None:
"""This method handles the POST requests to add agents to the Registrar Server.
Currently, only agents resources are available for POSTing, i.e. /agents. All other POST uri's
will return errors. POST requests require an an agent_id identifying the agent to add, and json
block sent in the body with 2 entries: ek and aik.
"""
session = SessionManager().make_session(engine)
_, agent_id = self._validate_input("POST", True)
if not agent_id:
return
try:
content_length = int(self.headers.get("Content-Length", 0))
if content_length == 0:
web_util.echo_json_response(self, 400, "Expected non zero content length")
logger.warning("POST for %s returning 400 response. Expected non zero content length.", agent_id)
return
post_body = self.rfile.read(content_length)
json_body = json.loads(post_body)
ekcert = json_body["ekcert"]
aik_tpm = json_body["aik_tpm"]
if ekcert is None or ekcert == "emulator":
logger.warning("Agent %s did not submit an ekcert", agent_id)
ek_tpm = json_body["ek_tpm"]
else:
if "ek_tpm" in json_body:
# This would mean the agent submitted both a non-None ekcert, *and*
# an ek_tpm... We can deal with it by just ignoring the ek_tpm they sent
logger.warning("Overriding ek_tpm for agent %s from ekcert", agent_id)
# If there's an EKCert, we just overwrite their ek_tpm
# Note, we don't validate the EKCert here, other than the implicit
# "is it a valid x509 cert" check. So it's still untrusted.
# This will be validated by the tenant.
cert = cert_utils.x509_der_cert(base64.b64decode(ekcert))
pubkey = cert.public_key()
assert isinstance(pubkey, (rsa.RSAPublicKey, ec.EllipticCurvePublicKey))
ek_tpm = base64.b64encode(tpm2_objects.ek_low_tpm2b_public_from_pubkey(pubkey)).decode()
aik_attrs = tpm2_objects.get_tpm2b_public_object_attributes(
base64.b64decode(aik_tpm),
)
if aik_attrs != tpm2_objects.AK_EXPECTED_ATTRS:
web_util.echo_json_response(self, 400, "Invalid AK attributes")
logger.warning(
"Agent %s submitted AIK with invalid attributes! %s (provided) != %s (expected)",
agent_id,
tpm2_objects.object_attributes_description(aik_attrs),
tpm2_objects.object_attributes_description(tpm2_objects.AK_EXPECTED_ATTRS),
)
return
# try to encrypt the AIK
aik_enc = Tpm.encryptAIK(
agent_id,
base64.b64decode(ek_tpm),
base64.b64decode(aik_tpm),
)
if aik_enc is None:
logger.warning("Agent %s failed encrypting AIK", agent_id)
web_util.echo_json_response(self, 400, "Error: failed encrypting AK")
return
blob, key = aik_enc
# special behavior if we've registered this uuid before
regcount = 1
try:
agent = session.query(RegistrarMain).filter_by(agent_id=agent_id).first()
except NoResultFound:
agent = None
except SQLAlchemyError as e:
logger.error("SQLAlchemy Error: %s", e)
raise
if agent is not None:
# keep track of how many ek-ekcerts have registered on this uuid
assert isinstance(agent.regcount, int)
regcount = agent.regcount
if agent.ek_tpm != ek_tpm or agent.ekcert != ekcert: # pyright: ignore
logger.warning("WARNING: Overwriting previous registration for this UUID with new ek-ekcert pair!")
regcount += 1
# force overwrite
logger.info("Overwriting previous registration for this UUID.")
try:
session.query(RegistrarMain).filter_by(agent_id=agent_id).delete()
session.commit()
except SQLAlchemyError as e:
logger.error("SQLAlchemy Error: %s", e)
raise
# Check for ip and port and mTLS cert
contact_ip, contact_port, mtls_cert = UnprotectedHandler.get_network_params(json_body, agent_id)
# Add values to database
d: Dict[str, Any] = {
"agent_id": agent_id,
"ek_tpm": ek_tpm,
"aik_tpm": aik_tpm,
"ekcert": ekcert,
"ip": contact_ip,
"mtls_cert": mtls_cert,
"port": contact_port,
"virtual": int(ekcert == "virtual"),
"active": int(False),
"key": key,
"provider_keys": {},
"regcount": regcount,
}
try:
session.add(RegistrarMain(**d))
session.commit()
except SQLAlchemyError as e:
logger.error("SQLAlchemy Error: %s", e)
raise
if rmc:
try:
rmc.record_create(d, None, None)
except Exception as e:
logger.error("Durable Attestation Error: %s", e)
raise
response = {
"blob": blob,
}
web_util.echo_json_response(self, 200, "Success", response)
logger.info("POST returning key blob for agent_id: %s", agent_id)
except Exception as e:
web_util.echo_json_response(self, 400, f"Error: {str(e)}")
logger.warning("POST for %s returning 400 response. Error: %s", agent_id, e)
logger.exception(e)
def do_PUT(self) -> None:
"""This method handles the PUT requests to add agents to the Registrar Server.
Currently, only agents resources are available for PUTing, i.e. /agents. All other PUT uri's
will return errors.
"""
session = SessionManager().make_session(engine)
_, agent_id = self._validate_input("PUT", True)
if not agent_id:
return
try:
content_length = int(self.headers.get("Content-Length", 0))
if content_length == 0:
web_util.echo_json_response(self, 400, "Expected non zero content length")
logger.warning("PUT for %s returning 400 response. Expected non zero content length.", agent_id)
return
post_body = self.rfile.read(content_length)
json_body = json.loads(post_body)
auth_tag = json_body["auth_tag"]
try:
agent = session.query(RegistrarMain).filter_by(agent_id=agent_id).first()
except NoResultFound as e:
raise Exception("attempting to activate agent before requesting " f"registrar for {agent_id}") from e
except SQLAlchemyError as e:
logger.error("SQLAlchemy Error: %s", e)
raise
assert agent
assert isinstance(agent.key, str)
ex_mac = crypto.do_hmac(agent.key.encode(), agent_id)
if ex_mac == auth_tag:
try:
session.query(RegistrarMain).filter(RegistrarMain.agent_id == agent_id).update(
{"active": int(True)}
)
session.commit()
except SQLAlchemyError as e:
logger.error("SQLAlchemy Error: %s", e)
raise
else:
if agent_id and session.query(RegistrarMain).filter_by(agent_id=agent_id).delete():
try:
session.commit()
except SQLAlchemyError as e:
logger.error("SQLAlchemy Error: %s", e)
raise
raise Exception(
f"Auth tag {auth_tag} for agent {agent_id} does not match expected value. The agent has been deleted from database, and a restart of it will be required"
)
web_util.echo_json_response(self, 200, "Success")
logger.info("PUT activated: %s", agent_id)
except Exception as e:
web_util.echo_json_response(self, 400, f"Error: {str(e)}")
logger.warning("PUT for %s returning 400 response. Error: %s", agent_id, e)
logger.exception(e)
return
def do_DELETE(self) -> None:
"""DELETE not supported"""
web_util.echo_json_response(self, 405, "DELETE not supported")
# pylint: disable=W0622
def log_message(self, format: str, *args: Any) -> None:
return
```
## `keylime/registrar_common.py` — `function:UnprotectedHandler.get_network_params` (lines 235-265)
```python
def get_network_params(
json_body: Dict[str, Any], agent_id: str
) -> Tuple[Optional[str], Optional[int], Optional[str]]:
# Validate ip and port
ip = json_body.get("ip")
if ip is not None:
try:
ipaddress.ip_address(ip)
except ValueError:
logger.warning("Contact ip for agent %s is not a valid ip got: %s.", agent_id, ip)
ip = None
port = json_body.get("port")
if port is not None:
try:
port = int(port)
if port < 1 or port > 65535:
logger.warning(
"Contact port for agent %s is not a number between 1 and 65535 got: %s.", agent_id, port
)
port = None
except ValueError:
logger.warning("Contact port for agent %s is not a valid number got: %s.", agent_id, port)
port = None
mtls_cert = json_body.get("mtls_cert")
if mtls_cert is None or mtls_cert == "disabled":
logger.warning("Agent %s did not send a mTLS certificate. Most operations will not work!", agent_id)
return ip, port, mtls_cert
```
## `keylime/registrar_common.py` — `function:UnprotectedHandler.do_PUT` (lines 408-469)
```python
def do_PUT(self) -> None:
"""This method handles the PUT requests to add agents to the Registrar Server.
Currently, only agents resources are available for PUTing, i.e. /agents. All other PUT uri's
will return errors.
"""
session = SessionManager().make_session(engine)
_, agent_id = self._validate_input("PUT", True)
if not agent_id:
return
try:
content_length = int(self.headers.get("Content-Length", 0))
if content_length == 0:
web_util.echo_json_response(self, 400, "Expected non zero content length")
logger.warning("PUT for %s returning 400 response. Expected non zero content length.", agent_id)
return
post_body = self.rfile.read(content_length)
json_body = json.loads(post_body)
auth_tag = json_body["auth_tag"]
try:
agent = session.query(RegistrarMain).filter_by(agent_id=agent_id).first()
except NoResultFound as e:
raise Exception("attempting to activate agent before requesting " f"registrar for {agent_id}") from e
except SQLAlchemyError as e:
logger.error("SQLAlchemy Error: %s", e)
raise
assert agent
assert isinstance(agent.key, str)
ex_mac = crypto.do_hmac(agent.key.encode(), agent_id)
if ex_mac == auth_tag:
try:
session.query(RegistrarMain).filter(RegistrarMain.agent_id == agent_id).update(
{"active": int(True)}
)
session.commit()
except SQLAlchemyError as e:
logger.error("SQLAlchemy Error: %s", e)
raise
else:
if agent_id and session.query(RegistrarMain).filter_by(agent_id=agent_id).delete():
try:
session.commit()
except SQLAlchemyError as e:
logger.error("SQLAlchemy Error: %s", e)
raise
raise Exception(
f"Auth tag {auth_tag} for agent {agent_id} does not match expected value. The agent has been deleted from database, and a restart of it will be required"
)
web_util.echo_json_response(self, 200, "Success")
logger.info("PUT activated: %s", agent_id)
except Exception as e:
web_util.echo_json_response(self, 400, f"Error: {str(e)}")
logger.warning("PUT for %s returning 400 response. Error: %s", agent_id, e)
logger.exception(e)
return
```
|