Debian Codegraph @

src/spnego/auth.py

raw
1 # Copyright: (c) 2020, Jordan Borean (@jborean93) <[email protected]>
2 # MIT License (see LICENSE or https://opensource.org/licenses/MIT)
3
4 import typing
5
6 from spnego._context import ContextProxy, ContextReq
7 from spnego._credential import Credential, NTLMHash, unify_credentials
8 from spnego._credssp import CredSSPProxy
9 from spnego._gss import GSSAPIProxy
10 from spnego._negotiate import NegotiateProxy
11 from spnego._ntlm import NTLMProxy
12 from spnego._sspi import SSPIProxy
13 from spnego.channel_bindings import GssChannelBindings
14 from spnego.exceptions import NegotiateOptions
15
16
17 def _new_context(
18 username: typing.Optional[typing.Union[str, Credential, typing.List[Credential]]],
19 password: typing.Optional[str],
20 hostname: str,
21 service: str,
22 channel_bindings: typing.Optional[GssChannelBindings],
23 context_req: ContextReq,
24 protocol: str,
25 options: NegotiateOptions,
26 usage: str,
27 **kwargs: typing.Any,
28 ) -> ContextProxy:
29 proto = protocol.lower()
30 credentials = unify_credentials(username, password)
31 sspi_protocols = SSPIProxy.available_protocols(options=options)
32 gssapi_protocols = GSSAPIProxy.available_protocols(options=options)
33
34 # Unless otherwise specified, we always favour the platform implementations (SSPI/GSSAPI) if they are available.
35 # Otherwise fallback to the Python implementations (NegotiateProxy/NTLMProxy).
36 use_flags = (
37 NegotiateOptions.use_sspi
38 | NegotiateOptions.use_gssapi
39 | NegotiateOptions.use_negotiate
40 | NegotiateOptions.use_ntlm
41 )
42 use_specified = options & use_flags != 0
43
44 # Filter protocols that aren't compatible with the credentials provided.
45 sspi_remove = set()
46 for cred in credentials:
47 # NTLMHash cannot be used with SSPI. The code falls back to using NTLMProxy if this credential is present.
48 if isinstance(cred, NTLMHash):
49 sspi_remove.add("negotiate")
50 sspi_remove.add("ntlm")
51
52 if sspi_remove:
53 for protocol in sspi_remove:
54 if protocol in sspi_protocols:
55 sspi_protocols.remove(protocol)
56
57 proxy: typing.Type[typing.Union[CredSSPProxy, NTLMProxy, SSPIProxy, GSSAPIProxy, NegotiateProxy]]
58
59 # If the protocol is CredSSP then we can only use CredSSPProxy. The use_flags still control what underlying
60 # Negotiate auth is used in the CredSSP authentication process.
61 if proto == "credssp":
62 proxy = CredSSPProxy
63
64 elif options & NegotiateOptions.use_sspi or (not use_specified and proto in sspi_protocols):
65 proxy = SSPIProxy
66
67 elif options & NegotiateOptions.use_gssapi or (
68 not use_specified and (proto == "kerberos" or proto in gssapi_protocols)
69 ):
70 proxy = GSSAPIProxy
71
72 elif options & NegotiateOptions.use_negotiate or (not use_specified and proto == "negotiate"):
73 # If GSSAPI does not offer full negotiate support, use our own wrapper.
74 proxy = NegotiateProxy
75
76 elif options & NegotiateOptions.use_ntlm or (not use_specified and proto == "ntlm"):
77 # Finally if GSSAPI does not support ntlm, use our own wrapper.
78 proto = "ntlm" if proto == "negotiate" else proto
79 proxy = NTLMProxy
80
81 else:
82 raise ValueError("Invalid protocol specified '%s', must be kerberos, negotiate, or ntlm" % protocol)
83
84 return proxy(
85 username=credentials,
86 password=None,
87 hostname=hostname,
88 service=service,
89 channel_bindings=channel_bindings,
90 context_req=context_req,
91 usage=usage,
92 protocol=proto,
93 options=options,
94 **kwargs,
95 )
96
97
98 def client(
99 username: typing.Optional[typing.Union[str, Credential, typing.List[Credential]]] = None,
100 password: typing.Optional[str] = None,
101 hostname: str = "unspecified",
102 service: str = "host",
103 channel_bindings: typing.Optional[GssChannelBindings] = None,
104 context_req: ContextReq = ContextReq.default,
105 protocol: str = "negotiate",
106 options: NegotiateOptions = NegotiateOptions.none,
107 **kwargs: typing.Any,
108 ) -> ContextProxy:
109 """Create a client context to be used for authentication.
110
111 Credentials can be provides in 3 different ways:
112
113 * omitted entirely
114 * `username` set to a string with an optional password
115 * `username` set to a single or list of :class:`Credential` objects
116
117 If the credential is omitted the authentication protocol will use a
118 protocol specific mechanism to find the credential in some cache. If no
119 cache or credentials are found an exception is raised.
120
121 If `username` is a string but `password` is not defined then the provider
122 specific cache is used but for the principal specified. If `password` is
123 specified then a new credential is retrieved using the username/password
124 combiniation. Using both `username` and `password` is the same as using
125 :class:`Password` as a credential.
126
127 If `username` is a, or list of, `Credential` object the object(s) are
128 passed into the authentication implementation for use. The behaviour of
129 these credentials are defined by the authentication protocol
130 implementation that uses the credential(s). Currently the :class:`Passowrd`
131 credential is supported by all authentication protocols and is the same
132 as specifying the username/password as separate arugments.
133
134 The ``negotiate`` protocol can be given a list of credentials for each of
135 the sub auth protocols it negotiates to use. For example to have Negotiate
136 use a Kerberos CCache for Kerberos and an NT/LM hash value for NTLM the
137 following can be specified::
138
139 import spnego
140
141 credential = [
142 spnego.KerberosCCache(ccache="FILE:/tmp/my-ccache"),
143 spnego.NTLMHash(
144 username="user",
145 nt_hash="8ADB9B997580D69E69CAA2BBB68F4697",
146 )
147 ]
148 client = spnego.auth(credential, hostname="server")
149
150 In the example above, the negotiate protocol will attempt use the CCache
151 for Kerberos auth and fallback to the NT/LM hash for NTLM auth if
152 Kerberos fails. If a credential for a specific sub protocol is not
153 available then Negotiate will move onto the next available one.
154
155 Args:
156 username: The username/credential(s) to authenticate with. Certain providers can use a cache if omitted.
157 password: The password to authenticate with. Should only be specified when username is a string.
158 hostname: The principal part of the SPN. This is required for Kerberos auth to build the SPN.
159 service: The service part of the SPN. This is required for Kerberos auth to build the SPN.
160 channel_bindings: The optional :class:`spnego.channel_bindings.GssChannelBindings` for the context.
161 context_req: The :class:`spnego.ContextReq` flags to use when setting up the context.
162 protocol: The protocol to authenticate with, can be `ntlm`, `kerberos`, `negotiate`, or `credssp`.
163 options: The :class:`spnego.NegotiateOptions` that define pyspnego specific options to control the negotiation.
164 kwargs: Optional arguments to pass through to the authentiction context.
165
166 Returns:
167 ContextProxy: The context proxy for a client.
168 """
169 return _new_context(
170 username, password, hostname, service, channel_bindings, context_req, protocol, options, "initiate", **kwargs
171 )
172
173
174 def server(
175 hostname: str = "unspecified",
176 service: str = "host",
177 channel_bindings: typing.Optional[GssChannelBindings] = None,
178 context_req: ContextReq = ContextReq.default,
179 protocol: str = "negotiate",
180 options: NegotiateOptions = NegotiateOptions.none,
181 **kwargs: typing.Any,
182 ) -> ContextProxy:
183 """Create a server context to be used for authentication.
184
185 Args:
186 hostname: The principal part of the SPN. This is required for Kerberos auth to build the SPN.
187 service: The service part of the SPN. This is required for Kerberos auth to build the SPN.
188 channel_bindings: The optional :class:`spnego.channel_bindings.GssChannelBindings` for the context.
189 context_req: The :class:`spnego.ContextReq` flags to use when setting up the context.
190 protocol: The protocol to authenticate with, can be `ntlm`, `kerberos`, `negotiate`, or `credssp`.
191 options: The :class:`spnego.NegotiateOptions` that define pyspnego specific options to control the negotiation.
192 kwargs: Optional arguments to pass through to the authentiction context.
193
194 Returns:
195 ContextProxy: The context proxy for a client.
196 """
197 return _new_context(
198 None, None, hostname, service, channel_bindings, context_req, protocol, options, "accept", **kwargs
199 )