Debian Codegraph @

src/spnego/_credential.py

raw
1 # Copyright: (c) 2021, Jordan Borean (@jborean93) <[email protected]>
2 # MIT License (see LICENSE or https://opensource.org/licenses/MIT)
3
4 """Credentials that can be used by a client.
5
6 These are the various credentials that can be used as a client to authenticate
7 with a service. See the docstring for each credential type to identify what
8 credentials are usable for each authenticaton protocol.
9 """
10
11 import dataclasses
12 import typing
13
14 from spnego._ntlm_raw.crypto import is_ntlm_hash
15 from spnego.exceptions import InvalidCredentialError, NoCredentialError
16
17 # FUTURE: Add Anonymous credential class
18
19
20 @dataclasses.dataclass
21 class Password:
22 """Plaintext username and password credential.
23
24 This is the simple username and password credential that is supported by
25 all authentication protocols.
26
27 Attributes:
28 username: The username.
29 password: The password for the user.
30 """
31
32 username: str
33 password: str = dataclasses.field(repr=False)
34
35 @property
36 def supported_protocols(self) -> typing.List[str]:
37 """List of protocols the credential can be used for."""
38 return ["credssp", "kerberos", "ntlm"]
39
40
41 @dataclasses.dataclass
42 class CredentialCache:
43 """Cached credential.
44
45 Uses the provider specific cached credential. Can also specify a username
46 to select a specific cached credential.
47
48 Attributes:
49 username: Optional username used to select a specific credential in the
50 cache.
51 """
52
53 username: typing.Optional[str] = None
54
55 @property
56 def supported_protocols(self) -> typing.List[str]:
57 return ["kerberos", "ntlm"]
58
59
60 @dataclasses.dataclass
61 class NTLMHash:
62 """NTLM LM/NT Hash credential.
63
64 Used with :class:`NTLMProxy` for NTLM authentication backed by an NT and/or
65 LM hash value. In modern iterations of NTLM only the NT hash needs to be
66 specified and LM is ignored but both can be specified and the NTLM code
67 will use them as necessary.
68
69 Attributes:
70 username: The username the hashes are for.
71 lm_hash: The LM hash as a hex string, can be `None` in most cases.
72 nt_hash: The NT hash as a hex string.
73 """
74
75 username: str
76 lm_hash: typing.Optional[str] = dataclasses.field(default=None, repr=False)
77 nt_hash: typing.Optional[str] = dataclasses.field(default=None, repr=False)
78
79 @property
80 def supported_protocols(self) -> typing.List[str]:
81 """List of protocols the credential can be used for."""
82 return ["ntlm"]
83
84
85 @dataclasses.dataclass
86 class KerberosKeytab:
87 """Kerberos Keytab Credential.
88
89 Used with :class:`GSSAPIProxy` for Kerberos authentication. It is used to
90 retrieve a Kerberos ticket using a keytab for authentication rather than a
91 password. The keytab value is specified in the form ``TYPE:RESIDUAL`` where
92 the ``TYPE`` supported is down to the installed Kerberos/GSSAPI
93 implementation and ``RESIDUAL`` is a value specific to the type. Common
94 types are:
95
96 FILE: The value is the path to a keytab.
97 MEMORY: The value is a unique identifier to a keytab stored in memory
98 of the current process. It must be resolvable by the linked GSSAPI
99 provider that this library uses.
100
101 There are other ccache types but they are mostly platform or GSSAPI
102 implementation specific.
103
104 .. Note:
105 This only works on Linux, Windows does not have the concept of a
106 keytab.
107
108 Attributes:
109 keytab: The keytab to use for authentication. The path will not be
110 expanded of have variables substituted so should be the absolute
111 path to the keytab.
112 principal: The Kerberos principal to get the credential for. Should be
113 in the UPN form `[email protected]`. Set to `None` to use the
114 first keytab entry.
115 """
116
117 keytab: str
118 principal: typing.Optional[str] = None
119
120 @property
121 def supported_protocols(self) -> typing.List[str]:
122 """List of protocols the credential can be used for."""
123 return ["kerberos"]
124
125
126 @dataclasses.dataclass
127 class KerberosCCache:
128 """Kerberos CCache Credential.
129
130 Used with :class:`GSSAPIProxy` for Kerberos authentication. It is used to
131 specify the credential cache that has the stored Kerberos credential for
132 authentication. The ccache value is specified in the form ``TYPE:RESIDUAL``
133 where the ``TYPE`` supported is down to the installed Kerberos/GSSAPI
134 implementation and ``RESIDUAL`` is a value specific to the type. Common
135 types are:
136
137 DIR: The value is the path to a directory containing a collection of
138 `FILE` caches.
139 FILE: The value is the path to an individual cache.
140 MEMORY: The value is a unique identifier to a cache stored in memory of
141 the current process. It must be resolvable by the linked GSSAPI
142 provider that this library uses.
143
144 There are other ccache types but they are mostly platform or GSSAPI
145 implementation specific.
146
147 .. Note:
148 This only works on Linux, Windows does not have the concept of
149 separate CCaches.
150
151 Attributes:
152 ccache: The ccache in the form ``TYPE:RESIDUAL`` to use for a Kerberos
153 credential. The path will not be expanded of have variables
154 substituted so should be the absolute path to the ccache.
155 principal: Optional principal to get in the credential cache specified.
156 """
157
158 ccache: str
159 principal: typing.Optional[str] = None
160
161 @property
162 def supported_protocols(self) -> typing.List[str]:
163 """List of protocols the credential can be used for."""
164 return ["kerberos"]
165
166
167 # FUTURE: Expose this as an official credential
168 # @dataclasses.dataclass
169 # class CredSSPSmartCard:
170 # """CredSSP Smart Card Credential.
171
172 # Used with :class:`CredSSPProxy` for CredSSP authentication. It is used to
173 # delegate a smart card credential to the peer rather than a
174 # username/password. It must be supplied with another NTLM/Kerberos supported
175 # credential as this is only used for the delegation part of the CredSSP
176 # authentication process.
177
178 # The values are modeled after `MS-CSSP TSSmartCardCreds`_.
179
180 # Attributes:
181 # pin: The user's smart card PIN.
182 # key_spec: The specification of the user's smart card.
183 # card_name: The name of the smart card.
184 # reader_name: The name of the smart card reader.
185 # container_name: Name of the certificate container.
186 # csp_name: Name of the CSP.
187 # user_hint: The user's account hint.
188 # domain_hint: The user's domain name hint.
189
190 # .. _MS-CSSP TSSmartCardCreds:
191 # https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-cssp/4251d165-cf01-4513-a5d8-39ee4a98b7a4
192 # """
193 # pin: bytes
194 # key_spec: int
195 # card_name: typing.Optional[bytes] = None
196 # reader_name: typing.Optional[bytes] = None
197 # container_name: typing.Optional[bytes] = None
198 # csp_name: typing.Optional[bytes] = None
199 # user_hint: typing.Optional[bytes] = None
200 # domain_hint: typing.Optional[bytes] = None
201
202 # @property
203 # def supported_protocols(self) -> typing.List[str]:
204 # return ["credssp"]
205
206
207 # @dataclasses.dataclass
208 # class CredSSPRemoteGuardPackage:
209 # """CredSSP Remote Guard Credential.
210
211 # Used with :class:`CredSSPProxy` for CredSSP authentication. It is used to
212 # delegate credential protected by `Remote Credential Guard`_. It must be
213 # supplied with another NTLM/Kerberos supported credential as this is only
214 # used for the delegation part of the CredSSP authentication process.
215 # Multiple instance of this can be passed in with the first entry being the
216 # logon credential and the remaining instances being the supplemental
217 # credentials.
218
219 # The values are modeled after `MS-CSSP TSRemoteGuardPackageCred`_.
220
221 # .. _Remote Credential Guard:
222 # https://docs.microsoft.com/en-us/windows/security/identity-protection/remote-credential-guard
223
224 # .. _MS-CSSP TSRemoteGuardPackageCred:
225 # https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-cssp/173eee44-1a2c-463f-b909-c15db01e68d7
226 # """
227 # package_name: str
228 # cred_buffer: bytes
229
230 # @property
231 # def supported_protocols(self) -> typing.List[str]:
232 # return ["credssp"]
233
234
235 Credential = typing.Union[CredentialCache, KerberosCCache, KerberosKeytab, NTLMHash, Password]
236
237
238 def unify_credentials(
239 username: typing.Optional[typing.Union[str, Credential, typing.List[Credential]]] = None,
240 password: typing.Optional[str] = None,
241 required_protocol: typing.Optional[str] = None,
242 ) -> typing.List[Credential]:
243 """Process user input credentials.
244
245 Converts the user facing credential input into a list of credentials that
246 is known by spnego. Also filters out any duplicate credentials/ones that
247 are rendered obsolete by any ones preceding it. For example NTLMHash won't
248 be used if it's specified after Password in the credential list.
249
250 Args:
251 username: The username or list of credentials to process.
252 password: The password for username when it's a string.
253 required_protocol: Optionally checks that at least 1 credential must
254 support the protocol specified.
255
256 Returns:
257 typing.List[Credential]: A list of credentials based on the free-form
258 input.
259 """
260 if username:
261 if isinstance(username, str):
262 if not password:
263 username = [CredentialCache(username=username)]
264 elif is_ntlm_hash(password):
265 lm, nt = password.split(":", 1)
266 username = [NTLMHash(username=username, lm_hash=lm, nt_hash=nt)]
267 else:
268 username = [Password(username=username, password=password)]
269
270 elif not isinstance(username, list):
271 username = [username]
272
273 else:
274 username = [CredentialCache()]
275
276 credentials: typing.List[Credential] = []
277 used_protocols: typing.Set[str] = set()
278 for cred in username:
279 if not isinstance(cred, (CredentialCache, KerberosCCache, KerberosKeytab, NTLMHash, Password)):
280 raise InvalidCredentialError(
281 context_msg="Invalid username/credential specified, must be a string or Credential object."
282 )
283
284 # Remove any credential that only implements protocols that are already covered by one before it.
285 # FUTURE: This might be problematic with the CredSSP ones
286 cred_useful = False
287 for cred_protocol in cred.supported_protocols:
288 if cred_protocol not in used_protocols:
289 used_protocols.add(cred_protocol)
290 cred_useful = True
291
292 if cred_useful:
293 credentials.append(cred)
294
295 if required_protocol and required_protocol not in used_protocols:
296 found_protocols = ", ".join(sorted(used_protocols))
297 raise NoCredentialError(
298 context_msg=f"A credential for {required_protocol} is needed but only found "
299 f"credentials for {found_protocols}"
300 )
301
302 return credentials