1"""
2oauthlib.oauth1.rfc5849
3~~~~~~~~~~~~~~
4
5This module is an implementation of various logic needed
6for signing and checking OAuth 1.0 RFC 5849 requests.
7
8It supports all three standard signature methods defined in RFC 5849:
9
10- HMAC-SHA1
11- RSA-SHA1
12- PLAINTEXT
13
14It also supports signature methods that are not defined in RFC 5849. These are
15based on the standard ones but replace SHA-1 with the more secure SHA-256:
16
17- HMAC-SHA256
18- RSA-SHA256
19
20"""
21import base64
22import hashlib
23import logging
24import urllib.parse as urlparse
25
26from oauthlib.common import (
27 Request, generate_nonce, generate_timestamp, log_safe, to_unicode,
28 urlencode,
29)
30
31from . import parameters, signature
32
33log = logging.getLogger(__name__)
34
35# Available signature methods
36#
37# Note: SIGNATURE_HMAC and SIGNATURE_RSA are kept for backward compatibility
38# with previous versions of this library, when it the only HMAC-based and
39# RSA-based signature methods were HMAC-SHA1 and RSA-SHA1. But now that it
40# supports other hashing algorithms besides SHA1, explicitly identifying which
41# hashing algorithm is being used is recommended.
42#
43# Note: if additional values are defined here, don't forget to update the
44# imports in "../__init__.py" so they are available outside this module.
45
46SIGNATURE_HMAC_SHA1 = "HMAC-SHA1"
47SIGNATURE_HMAC_SHA256 = "HMAC-SHA256"
48SIGNATURE_HMAC_SHA512 = "HMAC-SHA512"
49SIGNATURE_HMAC = SIGNATURE_HMAC_SHA1 # deprecated variable for HMAC-SHA1
50
51SIGNATURE_RSA_SHA1 = "RSA-SHA1"
52SIGNATURE_RSA_SHA256 = "RSA-SHA256"
53SIGNATURE_RSA_SHA512 = "RSA-SHA512"
54SIGNATURE_RSA = SIGNATURE_RSA_SHA1 # deprecated variable for RSA-SHA1
55
56SIGNATURE_PLAINTEXT = "PLAINTEXT"
57
58SIGNATURE_METHODS = (
59 SIGNATURE_HMAC_SHA1,
60 SIGNATURE_HMAC_SHA256,
61 SIGNATURE_HMAC_SHA512,
62 SIGNATURE_RSA_SHA1,
63 SIGNATURE_RSA_SHA256,
64 SIGNATURE_RSA_SHA512,
65 SIGNATURE_PLAINTEXT
66)
67
68SIGNATURE_TYPE_AUTH_HEADER = 'AUTH_HEADER'
69SIGNATURE_TYPE_QUERY = 'QUERY'
70SIGNATURE_TYPE_BODY = 'BODY'
71
72CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded'
73
74
75class Client:
76
77 """A client used to sign OAuth 1.0 RFC 5849 requests."""
78 SIGNATURE_METHODS = {
79 SIGNATURE_HMAC_SHA1: signature.sign_hmac_sha1_with_client,
80 SIGNATURE_HMAC_SHA256: signature.sign_hmac_sha256_with_client,
81 SIGNATURE_HMAC_SHA512: signature.sign_hmac_sha512_with_client,
82 SIGNATURE_RSA_SHA1: signature.sign_rsa_sha1_with_client,
83 SIGNATURE_RSA_SHA256: signature.sign_rsa_sha256_with_client,
84 SIGNATURE_RSA_SHA512: signature.sign_rsa_sha512_with_client,
85 SIGNATURE_PLAINTEXT: signature.sign_plaintext_with_client
86 }
87
88 @classmethod
89 def register_signature_method(cls, method_name, method_callback):
90 cls.SIGNATURE_METHODS[method_name] = method_callback
91
92 def __init__(self, client_key,
93 client_secret=None,
94 resource_owner_key=None,
95 resource_owner_secret=None,
96 callback_uri=None,
97 signature_method=SIGNATURE_HMAC_SHA1,
98 signature_type=SIGNATURE_TYPE_AUTH_HEADER,
99 rsa_key=None, verifier=None, realm=None,
100 encoding='utf-8', decoding=None,
101 nonce=None, timestamp=None):
102 """Create an OAuth 1 client.
103
104 :param client_key: Client key (consumer key), mandatory.
105 :param resource_owner_key: Resource owner key (oauth token).
106 :param resource_owner_secret: Resource owner secret (oauth token secret).
107 :param callback_uri: Callback used when obtaining request token.
108 :param signature_method: SIGNATURE_HMAC, SIGNATURE_RSA or SIGNATURE_PLAINTEXT.
109 :param signature_type: SIGNATURE_TYPE_AUTH_HEADER (default),
110 SIGNATURE_TYPE_QUERY or SIGNATURE_TYPE_BODY
111 depending on where you want to embed the oauth
112 credentials.
113 :param rsa_key: RSA key used with SIGNATURE_RSA.
114 :param verifier: Verifier used when obtaining an access token.
115 :param realm: Realm (scope) to which access is being requested.
116 :param encoding: If you provide non-unicode input you may use this
117 to have oauthlib automatically convert.
118 :param decoding: If you wish that the returned uri, headers and body
119 from sign be encoded back from unicode, then set
120 decoding to your preferred encoding, i.e. utf-8.
121 :param nonce: Use this nonce instead of generating one. (Mainly for testing)
122 :param timestamp: Use this timestamp instead of using current. (Mainly for testing)
123 """
124 # Convert to unicode using encoding if given, else assume unicode
125 def encode(x):
126 return to_unicode(x, encoding) if encoding else x
127
128 self.client_key = encode(client_key)
129 self.client_secret = encode(client_secret)
130 self.resource_owner_key = encode(resource_owner_key)
131 self.resource_owner_secret = encode(resource_owner_secret)
132 self.signature_method = encode(signature_method)
133 self.signature_type = encode(signature_type)
134 self.callback_uri = encode(callback_uri)
135 self.rsa_key = encode(rsa_key)
136 self.verifier = encode(verifier)
137 self.realm = encode(realm)
138 self.encoding = encode(encoding)
139 self.decoding = encode(decoding)
140 self.nonce = encode(nonce)
141 self.timestamp = encode(timestamp)
142
143 def __repr__(self):
144 attrs = vars(self).copy()
145 attrs['client_secret'] = '****' if attrs['client_secret'] else None
146 attrs['rsa_key'] = '****' if attrs['rsa_key'] else None
147 attrs[
148 'resource_owner_secret'] = '****' if attrs['resource_owner_secret'] else None
149 attribute_str = ', '.join('{}={}'.format(k, v) for k, v in attrs.items())
150 return '<{} {}>'.format(self.__class__.__name__, attribute_str)
151
152 def get_oauth_signature(self, request):
153 """Get an OAuth signature to be used in signing a request
154
155 To satisfy `section 3.4.1.2`_ item 2, if the request argument's
156 headers dict attribute contains a Host item, its value will
157 replace any netloc part of the request argument's uri attribute
158 value.
159
160 .. _`section 3.4.1.2`: https://tools.ietf.org/html/rfc5849#section-3.4.1.2
161 """
162 if self.signature_method == SIGNATURE_PLAINTEXT:
163 # fast-path
164 return signature.sign_plaintext(self.client_secret,
165 self.resource_owner_secret)
166
167 uri, headers, body = self._render(request)
168
169 collected_params = signature.collect_parameters(
170 uri_query=urlparse.urlparse(uri).query,
171 body=body,
172 headers=headers)
173 log.debug("Collected params: %s.", log_safe(collected_params))
174
175 normalized_params = signature.normalize_parameters(collected_params)
176 normalized_uri = signature.base_string_uri(uri, headers.get('Host', None))
177 log.debug("Normalized params: %s.", log_safe(normalized_params))
178 log.debug("Normalized URI: {}".format(normalized_uri))
179
180 base_string = signature.signature_base_string(request.http_method,
181 normalized_uri, normalized_params)
182
183 log.debug("Signing: signature base string: %s.", log_safe(base_string))
184
185 if self.signature_method not in self.SIGNATURE_METHODS:
186 raise ValueError('Invalid signature method.')
187
188 sig = self.SIGNATURE_METHODS[self.signature_method](base_string, self)
189
190 log.debug("Signature: %s.", log_safe(sig))
191 return sig
192
193 def get_oauth_params(self, request):
194 """Get the basic OAuth parameters to be used in generating a signature.
195 """
196 nonce = (generate_nonce()
197 if self.nonce is None else self.nonce)
198 timestamp = (generate_timestamp()
199 if self.timestamp is None else self.timestamp)
200 params = [
201 ('oauth_nonce', nonce),
202 ('oauth_timestamp', timestamp),
203 ('oauth_version', '1.0'),
204 ('oauth_signature_method', self.signature_method),
205 ('oauth_consumer_key', self.client_key),
206 ]
207 if self.resource_owner_key:
208 params.append(('oauth_token', self.resource_owner_key))
209 if self.callback_uri:
210 params.append(('oauth_callback', self.callback_uri))
211 if self.verifier:
212 params.append(('oauth_verifier', self.verifier))
213
214 # providing body hash for requests other than x-www-form-urlencoded
215 # as described in https://tools.ietf.org/html/draft-eaton-oauth-bodyhash-00#section-4.1.1
216 # 4.1.1. When to include the body hash
217 # * [...] MUST NOT include an oauth_body_hash parameter on requests with form-encoded request bodies
218 # * [...] SHOULD include the oauth_body_hash parameter on all other requests.
219 # Note that SHA-1 is vulnerable. The spec acknowledges that in https://tools.ietf.org/html/draft-eaton-oauth-bodyhash-00#section-6.2
220 # At this time, no further effort has been made to replace SHA-1 for the OAuth Request Body Hash extension.
221 content_type = request.headers.get('Content-Type', None)
222 content_type_eligible = content_type and content_type.find('application/x-www-form-urlencoded') < 0
223 if request.body is not None and content_type_eligible:
224 params.append(('oauth_body_hash', base64.b64encode(hashlib.sha1(request.body.encode('utf-8')).digest()).decode('utf-8'))) # noqa: S324
225
226 return params
227
228 def _render(self, request, formencode=False, realm=None):
229 """Render a signed request according to signature type
230
231 Returns a 3-tuple containing the request URI, headers, and body.
232
233 If the formencode argument is True and the body contains parameters, it
234 is escaped and returned as a valid formencoded string.
235 """
236 # TODO what if there are body params on a header-type auth?
237 # TODO what if there are query params on a body-type auth?
238
239 uri, headers, body = request.uri, request.headers, request.body
240
241 # TODO: right now these prepare_* methods are very narrow in scope--they
242 # only affect their little thing. In some cases (for example, with
243 # header auth) it might be advantageous to allow these methods to touch
244 # other parts of the request, like the headers—so the prepare_headers
245 # method could also set the Content-Type header to x-www-form-urlencoded
246 # like the spec requires. This would be a fundamental change though, and
247 # I'm not sure how I feel about it.
248 if self.signature_type == SIGNATURE_TYPE_AUTH_HEADER:
249 headers = parameters.prepare_headers(
250 request.oauth_params, request.headers, realm=realm)
251 elif self.signature_type == SIGNATURE_TYPE_BODY and request.decoded_body is not None:
252 body = parameters.prepare_form_encoded_body(
253 request.oauth_params, request.decoded_body)
254 if formencode:
255 body = urlencode(body)
256 headers['Content-Type'] = 'application/x-www-form-urlencoded'
257 elif self.signature_type == SIGNATURE_TYPE_QUERY:
258 uri = parameters.prepare_request_uri_query(
259 request.oauth_params, request.uri)
260 else:
261 raise ValueError('Unknown signature type specified.')
262
263 return uri, headers, body
264
265 def sign(self, uri, http_method='GET', body=None, headers=None, realm=None):
266 """Sign a request
267
268 Signs an HTTP request with the specified parts.
269
270 Returns a 3-tuple of the signed request's URI, headers, and body.
271 Note that http_method is not returned as it is unaffected by the OAuth
272 signing process. Also worth noting is that duplicate parameters
273 will be included in the signature, regardless of where they are
274 specified (query, body).
275
276 The body argument may be a dict, a list of 2-tuples, or a formencoded
277 string. The Content-Type header must be 'application/x-www-form-urlencoded'
278 if it is present.
279
280 If the body argument is not one of the above, it will be returned
281 verbatim as it is unaffected by the OAuth signing process. Attempting to
282 sign a request with non-formencoded data using the OAuth body signature
283 type is invalid and will raise an exception.
284
285 If the body does contain parameters, it will be returned as a properly-
286 formatted formencoded string.
287
288 Body may not be included if the http_method is either GET or HEAD as
289 this changes the semantic meaning of the request.
290
291 All string data MUST be unicode or be encoded with the same encoding
292 scheme supplied to the Client constructor, default utf-8. This includes
293 strings inside body dicts, for example.
294 """
295 # normalize request data
296 request = Request(uri, http_method, body, headers,
297 encoding=self.encoding)
298
299 # sanity check
300 content_type = request.headers.get('Content-Type', None)
301 multipart = content_type and content_type.startswith('multipart/')
302 should_have_params = content_type == CONTENT_TYPE_FORM_URLENCODED
303 has_params = request.decoded_body is not None
304 # 3.4.1.3.1. Parameter Sources
305 # [Parameters are collected from the HTTP request entity-body, but only
306 # if [...]:
307 # * The entity-body is single-part.
308 if multipart and has_params:
309 raise ValueError(
310 "Headers indicate a multipart body but body contains parameters.")
311 # * The entity-body follows the encoding requirements of the
312 # "application/x-www-form-urlencoded" content-type as defined by
313 # [W3C.REC-html40-19980424].
314 elif should_have_params and not has_params:
315 raise ValueError(
316 "Headers indicate a formencoded body but body was not decodable.")
317 # * The HTTP request entity-header includes the "Content-Type"
318 # header field set to "application/x-www-form-urlencoded".
319 elif not should_have_params and has_params:
320 raise ValueError(
321 "Body contains parameters but Content-Type header was {} "
322 "instead of {}".format(content_type or "not set",
323 CONTENT_TYPE_FORM_URLENCODED))
324
325 # 3.5.2. Form-Encoded Body
326 # Protocol parameters can be transmitted in the HTTP request entity-
327 # body, but only if the following REQUIRED conditions are met:
328 # o The entity-body is single-part.
329 # o The entity-body follows the encoding requirements of the
330 # "application/x-www-form-urlencoded" content-type as defined by
331 # [W3C.REC-html40-19980424].
332 # o The HTTP request entity-header includes the "Content-Type" header
333 # field set to "application/x-www-form-urlencoded".
334 elif self.signature_type == SIGNATURE_TYPE_BODY and not (
335 should_have_params and has_params and not multipart):
336 raise ValueError(
337 'Body signatures may only be used with form-urlencoded content')
338
339 # We amend https://tools.ietf.org/html/rfc5849#section-3.4.1.3.1
340 # with the clause that parameters from body should only be included
341 # in non GET or HEAD requests. Extracting the request body parameters
342 # and including them in the signature base string would give semantic
343 # meaning to the body, which it should not have according to the
344 # HTTP 1.1 spec.
345 elif http_method.upper() in ('GET', 'HEAD') and has_params:
346 raise ValueError('GET/HEAD requests should not include body.')
347
348 # generate the basic OAuth parameters
349 request.oauth_params = self.get_oauth_params(request)
350
351 # generate the signature
352 request.oauth_params.append(
353 ('oauth_signature', self.get_oauth_signature(request)))
354
355 # render the signed request and return it
356 uri, headers, body = self._render(request, formencode=True,
357 realm=(realm or self.realm))
358
359 if self.decoding:
360 log.debug('Encoding URI, headers and body to %s.', self.decoding)
361 uri = uri.encode(self.decoding)
362 body = body.encode(self.decoding) if body else body
363 new_headers = {}
364 for k, v in headers.items():
365 new_headers[k.encode(self.decoding)] = v.encode(self.decoding)
366 headers = new_headers
367 return uri, headers, body