| 1 |
# Copyright (C) 2014 Red Hat, Inc. |
| 2 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 3 |
|
| 4 |
import base64 |
| 5 |
import logging |
| 6 |
import re |
| 7 |
import secrets |
| 8 |
|
| 9 |
logger = logging.getLogger(__name__) |
| 10 |
|
| 11 |
|
| 12 |
def parse_type(challenge: str) -> tuple[str, str]: |
| 13 |
"""Extract the auth type from a challenge string. |
| 14 |
|
| 15 |
Returns (type, remainder) where type is lowercased. |
| 16 |
Raises ValueError if the challenge is invalid. |
| 17 |
""" |
| 18 |
logger.debug("parsing type from challenge %r", challenge) |
| 19 |
|
| 20 |
auth_type, *remainder = re.split(r"[: ] *", challenge, maxsplit=1) |
| 21 |
if not auth_type: |
| 22 |
raise ValueError('invalid "authorize" message') |
| 23 |
|
| 24 |
logger.debug("parsed type %r, remainder %r", auth_type, remainder) |
| 25 |
return auth_type.lower(), remainder[0] if remainder else "" |
| 26 |
|
| 27 |
|
| 28 |
def parse_subject(challenge: str) -> tuple[str, str]: |
| 29 |
"""Extract the subject from a challenge string (after the type). |
| 30 |
|
| 31 |
Returns (subject, remainder). |
| 32 |
Raises ValueError if the challenge is invalid. |
| 33 |
""" |
| 34 |
logger.debug("parsing subject from challenge %r", challenge) |
| 35 |
|
| 36 |
_, after_type = parse_type(challenge) |
| 37 |
|
| 38 |
subject, *remainder = re.split(r"[: ] *", after_type, maxsplit=1) |
| 39 |
if not subject: |
| 40 |
raise ValueError('invalid "authorize" message "challenge": no subject') |
| 41 |
|
| 42 |
logger.debug("parsed subject %r, remainder %r", subject, remainder) |
| 43 |
return subject, remainder[0] if remainder else "" |
| 44 |
|
| 45 |
|
| 46 |
def parse_basic(challenge: str) -> tuple[str, str, str]: |
| 47 |
"""Parse a Basic auth challenge. |
| 48 |
|
| 49 |
Returns (user, password, known_hosts). |
| 50 |
The format is: Basic base64(user:password\0known_hosts) |
| 51 |
Raises ValueError if the challenge is invalid. |
| 52 |
""" |
| 53 |
logger.debug("parsing basic auth from %r", challenge) |
| 54 |
|
| 55 |
auth_type, remainder = parse_type(challenge) |
| 56 |
if auth_type != "basic": |
| 57 |
raise ValueError("invalid prefix in Basic header") |
| 58 |
|
| 59 |
token, _, _ = remainder.partition(" ") |
| 60 |
if not token: |
| 61 |
logger.debug("empty basic auth token") |
| 62 |
return "", "", "" |
| 63 |
|
| 64 |
try: |
| 65 |
decoded = base64.b64decode(token).decode("utf-8") |
| 66 |
except ValueError as exc: |
| 67 |
raise ValueError("invalid base64 data in Basic header") from exc |
| 68 |
|
| 69 |
if ":" not in decoded: |
| 70 |
raise ValueError("invalid base64 data in Basic header") |
| 71 |
|
| 72 |
user_password, _, known_hosts = decoded.partition("\0") |
| 73 |
user, _, password = user_password.partition(":") |
| 74 |
logger.debug("parsed basic auth for user %r", user) |
| 75 |
return user, password, known_hosts |
| 76 |
|
| 77 |
|
| 78 |
def build_basic( |
| 79 |
user: str | None, password: str | None, known_hosts: str | None = None |
| 80 |
) -> str: |
| 81 |
"""Build a Basic auth response string. |
| 82 |
|
| 83 |
Format: Basic base64(user:password\0known_hosts) |
| 84 |
""" |
| 85 |
user = user or "" |
| 86 |
password = password or "" |
| 87 |
logger.debug("building basic auth for user %r", user) |
| 88 |
|
| 89 |
content = f"{user}:{password}" |
| 90 |
if known_hosts: |
| 91 |
content = f"{content}\0{known_hosts}" |
| 92 |
encoded = base64.b64encode(content.encode("utf-8")).decode("ascii") |
| 93 |
return f"Basic {encoded}" |
| 94 |
|
| 95 |
|
| 96 |
def parse_negotiate(challenge: str) -> bytes: |
| 97 |
"""Parse a Negotiate auth challenge. |
| 98 |
|
| 99 |
Returns the decoded token bytes. |
| 100 |
Raises ValueError if the challenge is invalid. |
| 101 |
""" |
| 102 |
logger.debug("parsing negotiate auth from %r", challenge) |
| 103 |
|
| 104 |
auth_type, remainder = parse_type(challenge) |
| 105 |
if auth_type != "negotiate": |
| 106 |
raise ValueError("invalid prefix in Negotiate header") |
| 107 |
|
| 108 |
token, _, _ = remainder.partition(" ") |
| 109 |
|
| 110 |
try: |
| 111 |
data = base64.b64decode(token) |
| 112 |
except ValueError as exc: |
| 113 |
raise ValueError("invalid base64 data in Negotiate header") from exc |
| 114 |
|
| 115 |
logger.debug("parsed negotiate token of length %r", len(data)) |
| 116 |
return data |
| 117 |
|
| 118 |
|
| 119 |
def build_negotiate(data: bytes | None) -> str: |
| 120 |
"""Build a Negotiate auth response string.""" |
| 121 |
if not data: |
| 122 |
logger.debug("building empty negotiate response") |
| 123 |
return "Negotiate" |
| 124 |
|
| 125 |
logger.debug("building negotiate response for %r bytes", len(data)) |
| 126 |
encoded = base64.b64encode(data).decode("ascii") |
| 127 |
return f"Negotiate {encoded}" |
| 128 |
|
| 129 |
|
| 130 |
def parse_x_conversation(challenge: str) -> tuple[str, str]: |
| 131 |
"""Parse an X-Conversation challenge. |
| 132 |
|
| 133 |
Returns (conversation_id, prompt). |
| 134 |
Raises ValueError if the challenge is invalid. |
| 135 |
""" |
| 136 |
logger.debug("parsing x-conversation from %r", challenge) |
| 137 |
|
| 138 |
auth_type, _ = parse_type(challenge) |
| 139 |
if auth_type != "x-conversation": |
| 140 |
raise ValueError("invalid prefix in X-Conversation header") |
| 141 |
|
| 142 |
conversation, remainder = parse_subject(challenge) |
| 143 |
|
| 144 |
token, _, _ = remainder.partition(" ") |
| 145 |
|
| 146 |
try: |
| 147 |
prompt = base64.b64decode(token).decode("utf-8") if token else "" |
| 148 |
except ValueError as exc: |
| 149 |
raise ValueError("invalid base64 data in X-Conversation header") from exc |
| 150 |
|
| 151 |
logger.debug("parsed x-conversation %r with prompt %r", conversation, prompt) |
| 152 |
return conversation, prompt |
| 153 |
|
| 154 |
|
| 155 |
def build_x_conversation( |
| 156 |
prompt: str | None, conversation: str | None = None |
| 157 |
) -> tuple[str, str]: |
| 158 |
"""Build an X-Conversation challenge string. |
| 159 |
|
| 160 |
If conversation is None, generates a new one. |
| 161 |
Returns (response_string, conversation_id). |
| 162 |
Raises ValueError if conversation is empty string. |
| 163 |
""" |
| 164 |
prompt = prompt or "" |
| 165 |
logger.debug( |
| 166 |
"building x-conversation with prompt %r, conversation %r", prompt, conversation |
| 167 |
) |
| 168 |
|
| 169 |
if conversation is None: |
| 170 |
conversation = secrets.token_urlsafe(16) |
| 171 |
logger.debug("generated new conversation id %r", conversation) |
| 172 |
|
| 173 |
if not conversation: |
| 174 |
raise ValueError("invalid conversation nonce") |
| 175 |
|
| 176 |
if prompt: |
| 177 |
encoded = base64.b64encode(prompt.encode("utf-8")).decode("ascii") |
| 178 |
response = f"X-Conversation {conversation} {encoded}" |
| 179 |
else: |
| 180 |
response = f"X-Conversation {conversation}" |
| 181 |
|
| 182 |
return response, conversation |