Predict the output
What do the three checks print?
import ipaddress
import socket
from urllib.parse import urlsplit
def safe_target(url: str) -> bool:
parts = urlsplit(url)
if parts.scheme != "https" or not parts.hostname:
return False
infos = socket.getaddrinfo(parts.hostname, 443)
for info in infos:
ip = ipaddress.ip_address(info[4][0])
if not ip.is_global:
return False
return True
print(safe_target("https://169.254.169.254/latest/meta-data/"))
print(safe_target("http://example.com/"))
print(safe_target("https://127.0.0.1/admin"))Hint 1 of 1
What does is_global say about 169.254.x.x?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A False, False, False
Correct. Link-local metadata IP, plain http, and loopback are all rejected.
The check needs https, then resolves the name and refuses any address that isn't global. The metadata address is link-local, the second URL is plain http, and 127.0.0.1 is loopback, so all three fail.
Why not the others?
- B
True,False,False. 169.254.169.254 is link-local, not global. - C
False,True,False. The scheme must be https. - D
False,False,True. 127.0.0.1 is loopback.