signature.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852
  1. """
  2. This module is an implementation of `section 3.4`_ of RFC 5849.
  3. **Usage**
  4. Steps for signing a request:
  5. 1. Collect parameters from the request using ``collect_parameters``.
  6. 2. Normalize those parameters using ``normalize_parameters``.
  7. 3. Create the *base string URI* using ``base_string_uri``.
  8. 4. Create the *signature base string* from the above three components
  9. using ``signature_base_string``.
  10. 5. Pass the *signature base string* and the client credentials to one of the
  11. sign-with-client functions. The HMAC-based signing functions needs
  12. client credentials with secrets. The RSA-based signing functions needs
  13. client credentials with an RSA private key.
  14. To verify a request, pass the request and credentials to one of the verify
  15. functions. The HMAC-based signing functions needs the shared secrets. The
  16. RSA-based verify functions needs the RSA public key.
  17. **Scope**
  18. All of the functions in this module should be considered internal to OAuthLib,
  19. since they are not imported into the "oauthlib.oauth1" module. Programs using
  20. OAuthLib should not use directly invoke any of the functions in this module.
  21. **Deprecated functions**
  22. The "sign_" methods that are not "_with_client" have been deprecated. They may
  23. be removed in a future release. Since they are all internal functions, this
  24. should have no impact on properly behaving programs.
  25. .. _`section 3.4`: https://tools.ietf.org/html/rfc5849#section-3.4
  26. """
  27. import binascii
  28. import hashlib
  29. import hmac
  30. import ipaddress
  31. import logging
  32. import urllib.parse as urlparse
  33. import warnings
  34. from oauthlib.common import extract_params, safe_string_equals, urldecode
  35. from . import utils
  36. log = logging.getLogger(__name__)
  37. # ==== Common functions ==========================================
  38. def signature_base_string(
  39. http_method: str,
  40. base_str_uri: str,
  41. normalized_encoded_request_parameters: str) -> str:
  42. """
  43. Construct the signature base string.
  44. The *signature base string* is the value that is calculated and signed by
  45. the client. It is also independently calculated by the server to verify
  46. the signature, and therefore must produce the exact same value at both
  47. ends or the signature won't verify.
  48. The rules for calculating the *signature base string* are defined in
  49. section 3.4.1.1`_ of RFC 5849.
  50. .. _`section 3.4.1.1`: https://tools.ietf.org/html/rfc5849#section-3.4.1.1
  51. """
  52. # The signature base string is constructed by concatenating together,
  53. # in order, the following HTTP request elements:
  54. # 1. The HTTP request method in uppercase. For example: "HEAD",
  55. # "GET", "POST", etc. If the request uses a custom HTTP method, it
  56. # MUST be encoded (`Section 3.6`_).
  57. #
  58. # .. _`Section 3.6`: https://tools.ietf.org/html/rfc5849#section-3.6
  59. base_string = utils.escape(http_method.upper())
  60. # 2. An "&" character (ASCII code 38).
  61. base_string += '&'
  62. # 3. The base string URI from `Section 3.4.1.2`_, after being encoded
  63. # (`Section 3.6`_).
  64. #
  65. # .. _`Section 3.4.1.2`: https://tools.ietf.org/html/rfc5849#section-3.4.1.2
  66. # .. _`Section 3.6`: https://tools.ietf.org/html/rfc5849#section-3.6
  67. base_string += utils.escape(base_str_uri)
  68. # 4. An "&" character (ASCII code 38).
  69. base_string += '&'
  70. # 5. The request parameters as normalized in `Section 3.4.1.3.2`_, after
  71. # being encoded (`Section 3.6`).
  72. #
  73. # .. _`Sec 3.4.1.3.2`: https://tools.ietf.org/html/rfc5849#section-3.4.1.3.2
  74. # .. _`Section 3.6`: https://tools.ietf.org/html/rfc5849#section-3.6
  75. base_string += utils.escape(normalized_encoded_request_parameters)
  76. return base_string
  77. def base_string_uri(uri: str, host: str = None) -> str:
  78. """
  79. Calculates the _base string URI_.
  80. The *base string URI* is one of the components that make up the
  81. *signature base string*.
  82. The ``host`` is optional. If provided, it is used to override any host and
  83. port values in the ``uri``. The value for ``host`` is usually extracted from
  84. the "Host" request header from the HTTP request. Its value may be just the
  85. hostname, or the hostname followed by a colon and a TCP/IP port number
  86. (hostname:port). If a value for the``host`` is provided but it does not
  87. contain a port number, the default port number is used (i.e. if the ``uri``
  88. contained a port number, it will be discarded).
  89. The rules for calculating the *base string URI* are defined in
  90. section 3.4.1.2`_ of RFC 5849.
  91. .. _`section 3.4.1.2`: https://tools.ietf.org/html/rfc5849#section-3.4.1.2
  92. :param uri: URI
  93. :param host: hostname with optional port number, separated by a colon
  94. :return: base string URI
  95. """
  96. if not isinstance(uri, str):
  97. raise ValueError('uri must be a string.')
  98. # FIXME: urlparse does not support unicode
  99. output = urlparse.urlparse(uri)
  100. scheme = output.scheme
  101. hostname = output.hostname
  102. port = output.port
  103. path = output.path
  104. params = output.params
  105. # The scheme, authority, and path of the request resource URI `RFC3986`
  106. # are included by constructing an "http" or "https" URI representing
  107. # the request resource (without the query or fragment) as follows:
  108. #
  109. # .. _`RFC3986`: https://tools.ietf.org/html/rfc3986
  110. if not scheme:
  111. raise ValueError('missing scheme')
  112. # Per `RFC 2616 section 5.1.2`_:
  113. #
  114. # Note that the absolute path cannot be empty; if none is present in
  115. # the original URI, it MUST be given as "/" (the server root).
  116. #
  117. # .. _`RFC 2616 5.1.2`: https://tools.ietf.org/html/rfc2616#section-5.1.2
  118. if not path:
  119. path = '/'
  120. # 1. The scheme and host MUST be in lowercase.
  121. scheme = scheme.lower()
  122. # Note: if ``host`` is used, it will be converted to lowercase below
  123. if hostname is not None:
  124. hostname = hostname.lower()
  125. # 2. The host and port values MUST match the content of the HTTP
  126. # request "Host" header field.
  127. if host is not None:
  128. # NOTE: override value in uri with provided host
  129. # Host argument is equal to netloc. It means it's missing scheme.
  130. # Add it back, before parsing.
  131. host = host.lower()
  132. host = f"{scheme}://{host}"
  133. output = urlparse.urlparse(host)
  134. hostname = output.hostname
  135. port = output.port
  136. # 3. The port MUST be included if it is not the default port for the
  137. # scheme, and MUST be excluded if it is the default. Specifically,
  138. # the port MUST be excluded when making an HTTP request `RFC2616`_
  139. # to port 80 or when making an HTTPS request `RFC2818`_ to port 443.
  140. # All other non-default port numbers MUST be included.
  141. #
  142. # .. _`RFC2616`: https://tools.ietf.org/html/rfc2616
  143. # .. _`RFC2818`: https://tools.ietf.org/html/rfc2818
  144. if hostname is None:
  145. raise ValueError('missing host')
  146. # NOTE: Try guessing if we're dealing with IP or hostname
  147. try:
  148. hostname = ipaddress.ip_address(hostname)
  149. except ValueError:
  150. pass
  151. if isinstance(hostname, ipaddress.IPv6Address):
  152. hostname = f"[{hostname}]"
  153. elif isinstance(hostname, ipaddress.IPv4Address):
  154. hostname = f"{hostname}"
  155. if port is not None and not (0 < port <= 65535):
  156. raise ValueError('port out of range') # 16-bit unsigned ints
  157. if (scheme, port) in (('http', 80), ('https', 443)):
  158. netloc = hostname # default port for scheme: exclude port num
  159. elif port:
  160. netloc = f"{hostname}:{port}" # use hostname:port
  161. else:
  162. netloc = hostname
  163. v = urlparse.urlunparse((scheme, netloc, path, params, '', ''))
  164. # RFC 5849 does not specify which characters are encoded in the
  165. # "base string URI", nor how they are encoded - which is very bad, since
  166. # the signatures won't match if there are any differences. Fortunately,
  167. # most URIs only use characters that are clearly not encoded (e.g. digits
  168. # and A-Z, a-z), so have avoided any differences between implementations.
  169. #
  170. # The example from its section 3.4.1.2 illustrates that spaces in
  171. # the path are percent encoded. But it provides no guidance as to what other
  172. # characters (if any) must be encoded (nor how); nor if characters in the
  173. # other components are to be encoded or not.
  174. #
  175. # This implementation **assumes** that **only** the space is percent-encoded
  176. # and it is done to the entire value (not just to spaces in the path).
  177. #
  178. # This code may need to be changed if it is discovered that other characters
  179. # are expected to be encoded.
  180. #
  181. # Note: the "base string URI" returned by this function will be encoded
  182. # again before being concatenated into the "signature base string". So any
  183. # spaces in the URI will actually appear in the "signature base string"
  184. # as "%2520" (the "%20" further encoded according to section 3.6).
  185. return v.replace(' ', '%20')
  186. def collect_parameters(uri_query='', body=None, headers=None,
  187. exclude_oauth_signature=True, with_realm=False):
  188. """
  189. Gather the request parameters from all the parameter sources.
  190. This function is used to extract all the parameters, which are then passed
  191. to ``normalize_parameters`` to produce one of the components that make up
  192. the *signature base string*.
  193. Parameters starting with `oauth_` will be unescaped.
  194. Body parameters must be supplied as a dict, a list of 2-tuples, or a
  195. form encoded query string.
  196. Headers must be supplied as a dict.
  197. The rules where the parameters must be sourced from are defined in
  198. `section 3.4.1.3.1`_ of RFC 5849.
  199. .. _`Sec 3.4.1.3.1`: https://tools.ietf.org/html/rfc5849#section-3.4.1.3.1
  200. """
  201. if body is None:
  202. body = []
  203. headers = headers or {}
  204. params = []
  205. # The parameters from the following sources are collected into a single
  206. # list of name/value pairs:
  207. # * The query component of the HTTP request URI as defined by
  208. # `RFC3986, Section 3.4`_. The query component is parsed into a list
  209. # of name/value pairs by treating it as an
  210. # "application/x-www-form-urlencoded" string, separating the names
  211. # and values and decoding them as defined by W3C.REC-html40-19980424
  212. # `W3C-HTML-4.0`_, Section 17.13.4.
  213. #
  214. # .. _`RFC3986, Sec 3.4`: https://tools.ietf.org/html/rfc3986#section-3.4
  215. # .. _`W3C-HTML-4.0`: https://www.w3.org/TR/1998/REC-html40-19980424/
  216. if uri_query:
  217. params.extend(urldecode(uri_query))
  218. # * The OAuth HTTP "Authorization" header field (`Section 3.5.1`_) if
  219. # present. The header's content is parsed into a list of name/value
  220. # pairs excluding the "realm" parameter if present. The parameter
  221. # values are decoded as defined by `Section 3.5.1`_.
  222. #
  223. # .. _`Section 3.5.1`: https://tools.ietf.org/html/rfc5849#section-3.5.1
  224. if headers:
  225. headers_lower = {k.lower(): v for k, v in headers.items()}
  226. authorization_header = headers_lower.get('authorization')
  227. if authorization_header is not None:
  228. params.extend([i for i in utils.parse_authorization_header(
  229. authorization_header) if with_realm or i[0] != 'realm'])
  230. # * The HTTP request entity-body, but only if all of the following
  231. # conditions are met:
  232. # * The entity-body is single-part.
  233. #
  234. # * The entity-body follows the encoding requirements of the
  235. # "application/x-www-form-urlencoded" content-type as defined by
  236. # W3C.REC-html40-19980424 `W3C-HTML-4.0`_.
  237. # * The HTTP request entity-header includes the "Content-Type"
  238. # header field set to "application/x-www-form-urlencoded".
  239. #
  240. # .. _`W3C-HTML-4.0`: https://www.w3.org/TR/1998/REC-html40-19980424/
  241. # TODO: enforce header param inclusion conditions
  242. bodyparams = extract_params(body) or []
  243. params.extend(bodyparams)
  244. # ensure all oauth params are unescaped
  245. unescaped_params = []
  246. for k, v in params:
  247. if k.startswith('oauth_'):
  248. v = utils.unescape(v)
  249. unescaped_params.append((k, v))
  250. # The "oauth_signature" parameter MUST be excluded from the signature
  251. # base string if present.
  252. if exclude_oauth_signature:
  253. unescaped_params = list(filter(lambda i: i[0] != 'oauth_signature',
  254. unescaped_params))
  255. return unescaped_params
  256. def normalize_parameters(params) -> str:
  257. """
  258. Calculate the normalized request parameters.
  259. The *normalized request parameters* is one of the components that make up
  260. the *signature base string*.
  261. The rules for parameter normalization are defined in `section 3.4.1.3.2`_ of
  262. RFC 5849.
  263. .. _`Sec 3.4.1.3.2`: https://tools.ietf.org/html/rfc5849#section-3.4.1.3.2
  264. """
  265. # The parameters collected in `Section 3.4.1.3`_ are normalized into a
  266. # single string as follows:
  267. #
  268. # .. _`Section 3.4.1.3`: https://tools.ietf.org/html/rfc5849#section-3.4.1.3
  269. # 1. First, the name and value of each parameter are encoded
  270. # (`Section 3.6`_).
  271. #
  272. # .. _`Section 3.6`: https://tools.ietf.org/html/rfc5849#section-3.6
  273. key_values = [(utils.escape(k), utils.escape(v)) for k, v in params]
  274. # 2. The parameters are sorted by name, using ascending byte value
  275. # ordering. If two or more parameters share the same name, they
  276. # are sorted by their value.
  277. key_values.sort()
  278. # 3. The name of each parameter is concatenated to its corresponding
  279. # value using an "=" character (ASCII code 61) as a separator, even
  280. # if the value is empty.
  281. parameter_parts = ['{}={}'.format(k, v) for k, v in key_values]
  282. # 4. The sorted name/value pairs are concatenated together into a
  283. # single string by using an "&" character (ASCII code 38) as
  284. # separator.
  285. return '&'.join(parameter_parts)
  286. # ==== Common functions for HMAC-based signature methods =========
  287. def _sign_hmac(hash_algorithm_name: str,
  288. sig_base_str: str,
  289. client_secret: str,
  290. resource_owner_secret: str):
  291. """
  292. **HMAC-SHA256**
  293. The "HMAC-SHA256" signature method uses the HMAC-SHA256 signature
  294. algorithm as defined in `RFC4634`_::
  295. digest = HMAC-SHA256 (key, text)
  296. Per `section 3.4.2`_ of the spec.
  297. .. _`RFC4634`: https://tools.ietf.org/html/rfc4634
  298. .. _`section 3.4.2`: https://tools.ietf.org/html/rfc5849#section-3.4.2
  299. """
  300. # The HMAC-SHA256 function variables are used in following way:
  301. # text is set to the value of the signature base string from
  302. # `Section 3.4.1.1`_.
  303. #
  304. # .. _`Section 3.4.1.1`: https://tools.ietf.org/html/rfc5849#section-3.4.1.1
  305. text = sig_base_str
  306. # key is set to the concatenated values of:
  307. # 1. The client shared-secret, after being encoded (`Section 3.6`_).
  308. #
  309. # .. _`Section 3.6`: https://tools.ietf.org/html/rfc5849#section-3.6
  310. key = utils.escape(client_secret or '')
  311. # 2. An "&" character (ASCII code 38), which MUST be included
  312. # even when either secret is empty.
  313. key += '&'
  314. # 3. The token shared-secret, after being encoded (`Section 3.6`_).
  315. #
  316. # .. _`Section 3.6`: https://tools.ietf.org/html/rfc5849#section-3.6
  317. key += utils.escape(resource_owner_secret or '')
  318. # Get the hashing algorithm to use
  319. m = {
  320. 'SHA-1': hashlib.sha1,
  321. 'SHA-256': hashlib.sha256,
  322. 'SHA-512': hashlib.sha512,
  323. }
  324. hash_alg = m[hash_algorithm_name]
  325. # Calculate the signature
  326. # FIXME: HMAC does not support unicode!
  327. key_utf8 = key.encode('utf-8')
  328. text_utf8 = text.encode('utf-8')
  329. signature = hmac.new(key_utf8, text_utf8, hash_alg)
  330. # digest is used to set the value of the "oauth_signature" protocol
  331. # parameter, after the result octet string is base64-encoded
  332. # per `RFC2045, Section 6.8`.
  333. #
  334. # .. _`RFC2045, Sec 6.8`: https://tools.ietf.org/html/rfc2045#section-6.8
  335. return binascii.b2a_base64(signature.digest())[:-1].decode('utf-8')
  336. def _verify_hmac(hash_algorithm_name: str,
  337. request,
  338. client_secret=None,
  339. resource_owner_secret=None):
  340. """Verify a HMAC-SHA1 signature.
  341. Per `section 3.4`_ of the spec.
  342. .. _`section 3.4`: https://tools.ietf.org/html/rfc5849#section-3.4
  343. To satisfy `RFC2616 section 5.2`_ item 1, the request argument's uri
  344. attribute MUST be an absolute URI whose netloc part identifies the
  345. origin server or gateway on which the resource resides. Any Host
  346. item of the request argument's headers dict attribute will be
  347. ignored.
  348. .. _`RFC2616 section 5.2`: https://tools.ietf.org/html/rfc2616#section-5.2
  349. """
  350. norm_params = normalize_parameters(request.params)
  351. bs_uri = base_string_uri(request.uri)
  352. sig_base_str = signature_base_string(request.http_method, bs_uri,
  353. norm_params)
  354. signature = _sign_hmac(hash_algorithm_name, sig_base_str,
  355. client_secret, resource_owner_secret)
  356. match = safe_string_equals(signature, request.signature)
  357. if not match:
  358. log.debug('Verify HMAC failed: signature base string: %s', sig_base_str)
  359. return match
  360. # ==== HMAC-SHA1 =================================================
  361. def sign_hmac_sha1_with_client(sig_base_str, client):
  362. return _sign_hmac('SHA-1', sig_base_str,
  363. client.client_secret, client.resource_owner_secret)
  364. def verify_hmac_sha1(request, client_secret=None, resource_owner_secret=None):
  365. return _verify_hmac('SHA-1', request, client_secret, resource_owner_secret)
  366. def sign_hmac_sha1(base_string, client_secret, resource_owner_secret):
  367. """
  368. Deprecated function for calculating a HMAC-SHA1 signature.
  369. This function has been replaced by invoking ``sign_hmac`` with "SHA-1"
  370. as the hash algorithm name.
  371. This function was invoked by sign_hmac_sha1_with_client and
  372. test_signatures.py, but does any application invoke it directly? If not,
  373. it can be removed.
  374. """
  375. warnings.warn('use sign_hmac_sha1_with_client instead of sign_hmac_sha1',
  376. DeprecationWarning)
  377. # For some unknown reason, the original implementation assumed base_string
  378. # could either be bytes or str. The signature base string calculating
  379. # function always returned a str, so the new ``sign_rsa`` only expects that.
  380. base_string = base_string.decode('ascii') \
  381. if isinstance(base_string, bytes) else base_string
  382. return _sign_hmac('SHA-1', base_string,
  383. client_secret, resource_owner_secret)
  384. # ==== HMAC-SHA256 ===============================================
  385. def sign_hmac_sha256_with_client(sig_base_str, client):
  386. return _sign_hmac('SHA-256', sig_base_str,
  387. client.client_secret, client.resource_owner_secret)
  388. def verify_hmac_sha256(request, client_secret=None, resource_owner_secret=None):
  389. return _verify_hmac('SHA-256', request,
  390. client_secret, resource_owner_secret)
  391. def sign_hmac_sha256(base_string, client_secret, resource_owner_secret):
  392. """
  393. Deprecated function for calculating a HMAC-SHA256 signature.
  394. This function has been replaced by invoking ``sign_hmac`` with "SHA-256"
  395. as the hash algorithm name.
  396. This function was invoked by sign_hmac_sha256_with_client and
  397. test_signatures.py, but does any application invoke it directly? If not,
  398. it can be removed.
  399. """
  400. warnings.warn(
  401. 'use sign_hmac_sha256_with_client instead of sign_hmac_sha256',
  402. DeprecationWarning)
  403. # For some unknown reason, the original implementation assumed base_string
  404. # could either be bytes or str. The signature base string calculating
  405. # function always returned a str, so the new ``sign_rsa`` only expects that.
  406. base_string = base_string.decode('ascii') \
  407. if isinstance(base_string, bytes) else base_string
  408. return _sign_hmac('SHA-256', base_string,
  409. client_secret, resource_owner_secret)
  410. # ==== HMAC-SHA512 ===============================================
  411. def sign_hmac_sha512_with_client(sig_base_str: str,
  412. client):
  413. return _sign_hmac('SHA-512', sig_base_str,
  414. client.client_secret, client.resource_owner_secret)
  415. def verify_hmac_sha512(request,
  416. client_secret: str = None,
  417. resource_owner_secret: str = None):
  418. return _verify_hmac('SHA-512', request,
  419. client_secret, resource_owner_secret)
  420. # ==== Common functions for RSA-based signature methods ==========
  421. _jwt_rsa = {} # cache of RSA-hash implementations from PyJWT jwt.algorithms
  422. def _get_jwt_rsa_algorithm(hash_algorithm_name: str):
  423. """
  424. Obtains an RSAAlgorithm object that implements RSA with the hash algorithm.
  425. This method maintains the ``_jwt_rsa`` cache.
  426. Returns a jwt.algorithm.RSAAlgorithm.
  427. """
  428. if hash_algorithm_name in _jwt_rsa:
  429. # Found in cache: return it
  430. return _jwt_rsa[hash_algorithm_name]
  431. else:
  432. # Not in cache: instantiate a new RSAAlgorithm
  433. # PyJWT has some nice pycrypto/cryptography abstractions
  434. import jwt.algorithms as jwt_algorithms
  435. m = {
  436. 'SHA-1': jwt_algorithms.hashes.SHA1,
  437. 'SHA-256': jwt_algorithms.hashes.SHA256,
  438. 'SHA-512': jwt_algorithms.hashes.SHA512,
  439. }
  440. v = jwt_algorithms.RSAAlgorithm(m[hash_algorithm_name])
  441. _jwt_rsa[hash_algorithm_name] = v # populate cache
  442. return v
  443. def _prepare_key_plus(alg, keystr):
  444. """
  445. Prepare a PEM encoded key (public or private), by invoking the `prepare_key`
  446. method on alg with the keystr.
  447. The keystr should be a string or bytes. If the keystr is bytes, it is
  448. decoded as UTF-8 before being passed to prepare_key. Otherwise, it
  449. is passed directly.
  450. """
  451. if isinstance(keystr, bytes):
  452. keystr = keystr.decode('utf-8')
  453. return alg.prepare_key(keystr)
  454. def _sign_rsa(hash_algorithm_name: str,
  455. sig_base_str: str,
  456. rsa_private_key: str):
  457. """
  458. Calculate the signature for an RSA-based signature method.
  459. The ``alg`` is used to calculate the digest over the signature base string.
  460. For the "RSA_SHA1" signature method, the alg must be SHA-1. While OAuth 1.0a
  461. only defines the RSA-SHA1 signature method, this function can be used for
  462. other non-standard signature methods that only differ from RSA-SHA1 by the
  463. digest algorithm.
  464. Signing for the RSA-SHA1 signature method is defined in
  465. `section 3.4.3`_ of RFC 5849.
  466. The RSASSA-PKCS1-v1_5 signature algorithm used defined by
  467. `RFC3447, Section 8.2`_ (also known as PKCS#1), with the `alg` as the
  468. hash function for EMSA-PKCS1-v1_5. To
  469. use this method, the client MUST have established client credentials
  470. with the server that included its RSA public key (in a manner that is
  471. beyond the scope of this specification).
  472. .. _`section 3.4.3`: https://tools.ietf.org/html/rfc5849#section-3.4.3
  473. .. _`RFC3447, Section 8.2`: https://tools.ietf.org/html/rfc3447#section-8.2
  474. """
  475. # Get the implementation of RSA-hash
  476. alg = _get_jwt_rsa_algorithm(hash_algorithm_name)
  477. # Check private key
  478. if not rsa_private_key:
  479. raise ValueError('rsa_private_key required for RSA with ' +
  480. alg.hash_alg.name + ' signature method')
  481. # Convert the "signature base string" into a sequence of bytes (M)
  482. #
  483. # The signature base string, by definition, only contain printable US-ASCII
  484. # characters. So encoding it as 'ascii' will always work. It will raise a
  485. # ``UnicodeError`` if it can't encode the value, which will never happen
  486. # if the signature base string was created correctly. Therefore, using
  487. # 'ascii' encoding provides an extra level of error checking.
  488. m = sig_base_str.encode('ascii')
  489. # Perform signing: S = RSASSA-PKCS1-V1_5-SIGN (K, M)
  490. key = _prepare_key_plus(alg, rsa_private_key)
  491. s = alg.sign(m, key)
  492. # base64-encoded per RFC2045 section 6.8.
  493. #
  494. # 1. While b2a_base64 implements base64 defined by RFC 3548. As used here,
  495. # it is the same as base64 defined by RFC 2045.
  496. # 2. b2a_base64 includes a "\n" at the end of its result ([:-1] removes it)
  497. # 3. b2a_base64 produces a binary string. Use decode to produce a str.
  498. # It should only contain only printable US-ASCII characters.
  499. return binascii.b2a_base64(s)[:-1].decode('ascii')
  500. def _verify_rsa(hash_algorithm_name: str,
  501. request,
  502. rsa_public_key: str):
  503. """
  504. Verify a base64 encoded signature for a RSA-based signature method.
  505. The ``alg`` is used to calculate the digest over the signature base string.
  506. For the "RSA_SHA1" signature method, the alg must be SHA-1. While OAuth 1.0a
  507. only defines the RSA-SHA1 signature method, this function can be used for
  508. other non-standard signature methods that only differ from RSA-SHA1 by the
  509. digest algorithm.
  510. Verification for the RSA-SHA1 signature method is defined in
  511. `section 3.4.3`_ of RFC 5849.
  512. .. _`section 3.4.3`: https://tools.ietf.org/html/rfc5849#section-3.4.3
  513. To satisfy `RFC2616 section 5.2`_ item 1, the request argument's uri
  514. attribute MUST be an absolute URI whose netloc part identifies the
  515. origin server or gateway on which the resource resides. Any Host
  516. item of the request argument's headers dict attribute will be
  517. ignored.
  518. .. _`RFC2616 Sec 5.2`: https://tools.ietf.org/html/rfc2616#section-5.2
  519. """
  520. try:
  521. # Calculate the *signature base string* of the actual received request
  522. norm_params = normalize_parameters(request.params)
  523. bs_uri = base_string_uri(request.uri)
  524. sig_base_str = signature_base_string(
  525. request.http_method, bs_uri, norm_params)
  526. # Obtain the signature that was received in the request
  527. sig = binascii.a2b_base64(request.signature.encode('ascii'))
  528. # Get the implementation of RSA-with-hash algorithm to use
  529. alg = _get_jwt_rsa_algorithm(hash_algorithm_name)
  530. # Verify the received signature was produced by the private key
  531. # corresponding to the `rsa_public_key`, signing exact same
  532. # *signature base string*.
  533. #
  534. # RSASSA-PKCS1-V1_5-VERIFY ((n, e), M, S)
  535. key = _prepare_key_plus(alg, rsa_public_key)
  536. # The signature base string only contain printable US-ASCII characters.
  537. # The ``encode`` method with the default "strict" error handling will
  538. # raise a ``UnicodeError`` if it can't encode the value. So using
  539. # "ascii" will always work.
  540. verify_ok = alg.verify(sig_base_str.encode('ascii'), key, sig)
  541. if not verify_ok:
  542. log.debug('Verify failed: RSA with ' + alg.hash_alg.name +
  543. ': signature base string=%s' + sig_base_str)
  544. return verify_ok
  545. except UnicodeError:
  546. # A properly encoded signature will only contain printable US-ASCII
  547. # characters. The ``encode`` method with the default "strict" error
  548. # handling will raise a ``UnicodeError`` if it can't decode the value.
  549. # So using "ascii" will work with all valid signatures. But an
  550. # incorrectly or maliciously produced signature could contain other
  551. # bytes.
  552. #
  553. # This implementation treats that situation as equivalent to the
  554. # signature verification having failed.
  555. #
  556. # Note: simply changing the encode to use 'utf-8' will not remove this
  557. # case, since an incorrect or malicious request can contain bytes which
  558. # are invalid as UTF-8.
  559. return False
  560. # ==== RSA-SHA1 ==================================================
  561. def sign_rsa_sha1_with_client(sig_base_str, client):
  562. # For some reason, this function originally accepts both str and bytes.
  563. # This behaviour is preserved here. But won't be done for the newer
  564. # sign_rsa_sha256_with_client and sign_rsa_sha512_with_client functions,
  565. # which will only accept strings. The function to calculate a
  566. # "signature base string" always produces a string, so it is not clear
  567. # why support for bytes would ever be needed.
  568. sig_base_str = sig_base_str.decode('ascii')\
  569. if isinstance(sig_base_str, bytes) else sig_base_str
  570. return _sign_rsa('SHA-1', sig_base_str, client.rsa_key)
  571. def verify_rsa_sha1(request, rsa_public_key: str):
  572. return _verify_rsa('SHA-1', request, rsa_public_key)
  573. def sign_rsa_sha1(base_string, rsa_private_key):
  574. """
  575. Deprecated function for calculating a RSA-SHA1 signature.
  576. This function has been replaced by invoking ``sign_rsa`` with "SHA-1"
  577. as the hash algorithm name.
  578. This function was invoked by sign_rsa_sha1_with_client and
  579. test_signatures.py, but does any application invoke it directly? If not,
  580. it can be removed.
  581. """
  582. warnings.warn('use _sign_rsa("SHA-1", ...) instead of sign_rsa_sha1',
  583. DeprecationWarning)
  584. if isinstance(base_string, bytes):
  585. base_string = base_string.decode('ascii')
  586. return _sign_rsa('SHA-1', base_string, rsa_private_key)
  587. # ==== RSA-SHA256 ================================================
  588. def sign_rsa_sha256_with_client(sig_base_str: str, client):
  589. return _sign_rsa('SHA-256', sig_base_str, client.rsa_key)
  590. def verify_rsa_sha256(request, rsa_public_key: str):
  591. return _verify_rsa('SHA-256', request, rsa_public_key)
  592. # ==== RSA-SHA512 ================================================
  593. def sign_rsa_sha512_with_client(sig_base_str: str, client):
  594. return _sign_rsa('SHA-512', sig_base_str, client.rsa_key)
  595. def verify_rsa_sha512(request, rsa_public_key: str):
  596. return _verify_rsa('SHA-512', request, rsa_public_key)
  597. # ==== PLAINTEXT =================================================
  598. def sign_plaintext_with_client(_signature_base_string, client):
  599. # _signature_base_string is not used because the signature with PLAINTEXT
  600. # is just the secret: it isn't a real signature.
  601. return sign_plaintext(client.client_secret, client.resource_owner_secret)
  602. def sign_plaintext(client_secret, resource_owner_secret):
  603. """Sign a request using plaintext.
  604. Per `section 3.4.4`_ of the spec.
  605. The "PLAINTEXT" method does not employ a signature algorithm. It
  606. MUST be used with a transport-layer mechanism such as TLS or SSL (or
  607. sent over a secure channel with equivalent protections). It does not
  608. utilize the signature base string or the "oauth_timestamp" and
  609. "oauth_nonce" parameters.
  610. .. _`section 3.4.4`: https://tools.ietf.org/html/rfc5849#section-3.4.4
  611. """
  612. # The "oauth_signature" protocol parameter is set to the concatenated
  613. # value of:
  614. # 1. The client shared-secret, after being encoded (`Section 3.6`_).
  615. #
  616. # .. _`Section 3.6`: https://tools.ietf.org/html/rfc5849#section-3.6
  617. signature = utils.escape(client_secret or '')
  618. # 2. An "&" character (ASCII code 38), which MUST be included even
  619. # when either secret is empty.
  620. signature += '&'
  621. # 3. The token shared-secret, after being encoded (`Section 3.6`_).
  622. #
  623. # .. _`Section 3.6`: https://tools.ietf.org/html/rfc5849#section-3.6
  624. signature += utils.escape(resource_owner_secret or '')
  625. return signature
  626. def verify_plaintext(request, client_secret=None, resource_owner_secret=None):
  627. """Verify a PLAINTEXT signature.
  628. Per `section 3.4`_ of the spec.
  629. .. _`section 3.4`: https://tools.ietf.org/html/rfc5849#section-3.4
  630. """
  631. signature = sign_plaintext(client_secret, resource_owner_secret)
  632. match = safe_string_equals(signature, request.signature)
  633. if not match:
  634. log.debug('Verify PLAINTEXT failed')
  635. return match