Debian Codegraph @

puresasl/client.py

raw symbols SCIP
1 from functools import wraps
2 from warnings import warn
3
4 import puresasl.mechanisms as mech_mod
5 from puresasl import SASLError, QOP, SASLWarning
6
7
8 def _require_mech(f):
9 """
10 A utility decorator that ensures a mechanism has been chosen.
11 """
12 @wraps(f)
13 def wrapped(self, *args, **kwargs):
14 if not self._chosen_mech:
15 raise SASLError("A mechanism has not been chosen yet")
16 return f(self, *args, **kwargs)
17
18 return wrapped
19
20
21 class SASLClient(object):
22 """
23 A SASL client for one negotiation with a SASL server.
24
25 An new instance of this is typically created when establishing a connection
26 with a SASL server. The SASL mechanism may be chosen at creation time or
27 set later after a list of server-supported mechanisms has been discovered
28 using `:method:choose_mechanism()`.
29
30 Instances of this class do not directly communicate with the server (as
31 the communication protocol differs from service to service), but rather
32 relies on challenges from the server to be passed in and processed. When
33 initiating a new connection, this is done by passing challenges from the
34 server to the :meth:`process()` method until the server indicates that
35 SASL negotiation has completed and the `complete` attribute of the instance
36 is set to ``True``.
37
38 After the initial negotiation is complete, communication between the
39 server and client may need to be processed, depending on the 'quality of
40 service', which may call for signatures or encryption. To handle this,
41 messages from the server should be passed through :meth:`unwrap()`, and
42 messages outbound from the client to server should be passed through
43 :meth:`wrap()`.
44
45 Example usage::
46
47 >>> from puresasl.client import SASLClient
48 >>>
49 >>> sasl = SASLClient('somehost2', 'customprotocol')
50 >>> conn = get_connection_to('somehost2')
51 >>> available_mechs = conn.get_mechanisms()
52 >>> sasl.choose_mechanism(available_mechs, allow_anonymous=False)
53 >>> while True:
54 ... status, challenge = conn.get_challenge()
55 ... if status == 'COMPLETE':
56 ... break
57 ... elif status == 'OK':
58 ... response = sasl.process(challenge)
59 ... conn.send_response(response)
60 ... else:
61 ... raise Exception(status)
62 ...
63 >>> if not sasl.complete:
64 ... raise Exception("SASL negotiation did not complete")
65 >>>
66 >>> # begin normal communication
67 >>> encoded = conn.fetch_data()
68 >>> decoded = sasl.unwrap(encoded)
69 >>> response = process_data(decoded)
70 >>> conn.send_data(sasl.wrap(response))
71 """
72
73 def __init__(self, host, service=None, mechanism=None, authorization_id=None,
74 callback=None, qops=QOP.all, mutual_auth=False, max_buffer=65536,
75 **mechanism_props):
76 """
77 `host` is the name of the SASL server, typically an FQDN, and `service` is
78 usually the name of the protocol, such as `imap` or `http`.
79
80 `mechanism` may be the string name of a mechanism to use, like
81 'PLAIN' or 'GSSAPI'. If left as ``None``, :meth:`choose_mechanism`
82 must be used with a list of mechanisms that the server supports before
83 `process()` can be used.
84
85 Optionally, an `authorization_id` may be set if the mechanism and protocol
86 support authorization.
87
88 The allowed quality of protection (QoP) choices may be set with the `qops`
89 parameter, which should be an iterable of allowed options. Valid options
90 include 'auth' for no protection, 'auth-int' for integrity protection,
91 and 'auth-conf' for confidentiality protection. The strongest of these
92 that the server also supports will be chosen automatically. If the
93 server does not support any of these choices, a
94 :exc:`SASLProtocolException` will be raised.
95
96 If the chosen mechanism supports mutual authentication, which is
97 authentication of the server by the client, this may be set to
98 ``True`` to ensure that mutual authentication is performed.
99
100 A max buffer size may be set with `max_buffer`. If a max buffer size
101 is also set during negotiation by the server, the min of these two
102 values will be used.
103
104 Any other mechanism-specific properties may be set with
105 `**mechanism_props` and will automatically be passed in to the
106 mechanism's constructor. If any properties are required by the
107 mechanism during the course of negotiation have not been passed in
108 via `**mechanism_props`, the function passed in here as the `callback`
109 argument will be called with one argument, the name of the required
110 property. The `callback` function should return a value for that
111 property.
112 """
113 self.host = host
114 self.service = service
115 self.authorization_id = authorization_id
116 self.mechanism = mechanism
117 self.callback = callback
118 self.qops = set(qops)
119 self.mutual_auth = mutual_auth
120 self.max_buffer = max_buffer
121
122 self._mech_props = mechanism_props
123 if self.mechanism is not None:
124 try:
125 mech_class = mech_mod.mechanisms[mechanism]
126 except KeyError:
127 gssapi = mech_mod.GSSAPIMechanism.name
128 if mechanism == gssapi and not mech_mod.have_kerberos:
129 raise SASLError('kerberos module not installed, {0} '
130 'unavailable'.format(gssapi))
131 else:
132 raise SASLError('Unknown mechanism {0}'.format(mechanism))
133 self._chosen_mech = mech_class(self, **self._mech_props)
134 else:
135 self._chosen_mech = None
136
137 @_require_mech
138 def process(self, challenge=None):
139 """
140 Process a challenge from the server during SASL negotiation.
141 A response will be returned which should typically be sent to the
142 server to answer the challenge.
143
144 With some mechanisms and protocols, `process()` should be called
145 with a `challenge` of ``None`` to generate the first message
146 to be sent to the server.
147 """
148 return self._chosen_mech.process(challenge)
149
150 @_require_mech
151 def wrap(self, outgoing):
152 """
153 Wrap an outgoing message intended for the SASL server. Depending
154 on the negotiated quality of protection, this may result in the
155 message being signed, encrypted, or left unaltered.
156 """
157 return self._chosen_mech.wrap(outgoing)
158
159 @_require_mech
160 def unwrap(self, incoming):
161 """
162 Unwrap a message from the SASL server. Depending on the negotiated
163 quality of protection, this may check a signature, decrypt the message,
164 or leave the message unaltered.
165 """
166 return self._chosen_mech.unwrap(incoming)
167
168 @property
169 def complete(self):
170 """
171 Check to see if SASL negotiation has completed successfully, including
172 a mutual authentication check if the chosen mechanism supports that and
173 mutual authentication was requested via the `mutual_auth` parameter
174 for the `SASLClient` constructor.
175 """
176 if not self._chosen_mech:
177 raise SASLError("A mechanism has not been chosen yet")
178 return self._chosen_mech.complete
179
180 @_require_mech
181 def dispose(self):
182 """
183 Clear all sensitive data, such as passwords.
184 """
185 self._chosen_mech.dispose()
186
187 @property
188 @_require_mech
189 def qop(self):
190 return self._chosen_mech.qop
191
192 def choose_mechanism(self, mechanism_choices, allow_anonymous=True,
193 allow_plaintext=True, allow_active=True,
194 allow_dictionary=True):
195 """
196 Choose a mechanism from a list of mechanisms based on security
197 scores for mechanisms and required properties of the mechanism.
198
199 If `allow_anonymous` is ``False``, mechanisms that allow anonymous
200 authentication will not be considered.
201
202 If `allow_plaintext` is ``False``, mechanisms that transmit
203 sensitive information in plaintext (and are thus susceptible to
204 passive listening attacks) will not be considered.
205
206 If `allow_active` is ``False``, mechanisms that are susceptible
207 to active non-dictionary attacks (MITM, injection) will not be
208 considered.
209
210 If `allow_dictionary` is ``False, mechanisms that are susceptible
211 to passive dictionary attacks will not be considered.
212 """
213 gssapi = mech_mod.GSSAPIMechanism.name
214 if gssapi in mechanism_choices and not mech_mod.have_kerberos:
215 warn('kerberos module not installed, {0} will be ignored'.format(
216 gssapi), SASLWarning)
217
218 candidates = [mech_mod.mechanisms[choice]
219 for choice in mechanism_choices
220 if choice in mech_mod.mechanisms]
221
222 if not allow_anonymous:
223 candidates = [m for m in candidates if not m.allows_anonymous]
224 if not allow_plaintext:
225 candidates = [m for m in candidates if not m.uses_plaintext]
226 if not allow_active:
227 candidates = [m for m in candidates if m.active_safe]
228 if not allow_dictionary:
229 candidates = [m for m in candidates if m.dictionary_safe]
230
231 if not candidates:
232 raise SASLError("None of the mechanisms listed meet all "
233 "required properties")
234
235 # Pick the best mechanism based on its security score
236 mech_class = max(candidates, key=lambda mech: mech.score)
237 self.mechanism = mech_class.name
238 self._chosen_mech = mech_class(self, **self._mech_props)