2
0

auth.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  1. # Copyright (c) 2012-2013 LiuYC https://github.com/liuyichen/
  2. # Copyright 2012-2014 ksyun.com, Inc. or its affiliates. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License"). You
  5. # may not use this file except in compliance with the License. A copy of
  6. # the License is located at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # or in the "license" file accompanying this file. This file is
  11. # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
  12. # ANY KIND, either express or implied. See the License for the specific
  13. # language governing permissions and limitations under the License.
  14. import base64
  15. import datetime
  16. from hashlib import sha256
  17. from hashlib import sha1
  18. import hmac
  19. import logging
  20. from email.utils import formatdate
  21. from operator import itemgetter
  22. import functools
  23. import time
  24. import calendar
  25. from kscore.exceptions import NoCredentialsError
  26. from kscore.utils import normalize_url_path, percent_encode_sequence
  27. from kscore.compat import HTTPHeaders
  28. from kscore.compat import quote, unquote, urlsplit, parse_qs
  29. from kscore.compat import urlunsplit
  30. from kscore.compat import encodebytes
  31. from kscore.compat import six
  32. from kscore.compat import json
  33. logger = logging.getLogger(__name__)
  34. EMPTY_SHA256_HASH = (
  35. 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855')
  36. # This is the buffer size used when calculating sha256 checksums.
  37. # Experimenting with various buffer sizes showed that this value generally
  38. # gave the best result (in terms of performance).
  39. PAYLOAD_BUFFER = 1024 * 1024
  40. ISO8601 = '%Y-%m-%dT%H:%M:%SZ'
  41. SIGV4_TIMESTAMP = '%Y%m%dT%H%M%SZ'
  42. SIGNED_HEADERS_BLACKLIST = [
  43. 'expect',
  44. 'user-agent'
  45. ]
  46. class BaseSigner(object):
  47. REQUIRES_REGION = False
  48. def add_auth(self, request):
  49. raise NotImplementedError("add_auth")
  50. class SigV2Auth(BaseSigner):
  51. """
  52. Sign a request with Signature V2.
  53. """
  54. def __init__(self, credentials):
  55. self.credentials = credentials
  56. def calc_signature(self, request, params):
  57. logger.debug("Calculating signature using v2 auth.")
  58. split = urlsplit(request.url)
  59. path = split.path
  60. if len(path) == 0:
  61. path = '/'
  62. string_to_sign = '%s\n%s\n%s\n' % (request.method,
  63. split.netloc,
  64. path)
  65. lhmac = hmac.new(self.credentials.secret_key.encode('utf-8'),
  66. digestmod=sha256)
  67. pairs = []
  68. for key in sorted(params):
  69. # Any previous signature should not be a part of this
  70. # one, so we skip that particular key. This prevents
  71. # issues during retries.
  72. if key == 'Signature':
  73. continue
  74. value = six.text_type(params[key])
  75. pairs.append(quote(key.encode('utf-8'), safe='') + '=' +
  76. quote(value.encode('utf-8'), safe='-_~'))
  77. qs = '&'.join(pairs)
  78. string_to_sign += qs
  79. logger.debug('String to sign: %s', string_to_sign)
  80. lhmac.update(string_to_sign.encode('utf-8'))
  81. b64 = base64.b64encode(lhmac.digest()).strip().decode('utf-8')
  82. return (qs, b64)
  83. def add_auth(self, request):
  84. # The auth handler is the last thing called in the
  85. # preparation phase of a prepared request.
  86. # Because of this we have to parse the query params
  87. # from the request body so we can update them with
  88. # the sigv2 auth params.
  89. if self.credentials is None:
  90. raise NoCredentialsError
  91. if request.data:
  92. # POST
  93. params = request.data
  94. else:
  95. # GET
  96. params = request.param
  97. params['AWSAccessKeyId'] = self.credentials.access_key
  98. params['SignatureVersion'] = '2'
  99. params['SignatureMethod'] = 'HmacSHA256'
  100. params['Timestamp'] = time.strftime(ISO8601, time.gmtime())
  101. if self.credentials.token:
  102. params['SecurityToken'] = self.credentials.token
  103. qs, signature = self.calc_signature(request, params)
  104. params['Signature'] = signature
  105. return request
  106. class SigV3Auth(BaseSigner):
  107. def __init__(self, credentials):
  108. self.credentials = credentials
  109. def add_auth(self, request):
  110. if self.credentials is None:
  111. raise NoCredentialsError
  112. if 'Date' in request.headers:
  113. del request.headers['Date']
  114. request.headers['Date'] = formatdate(usegmt=True)
  115. if self.credentials.token:
  116. if 'X-Amz-Security-Token' in request.headers:
  117. del request.headers['X-Amz-Security-Token']
  118. request.headers['X-Amz-Security-Token'] = self.credentials.token
  119. new_hmac = hmac.new(self.credentials.secret_key.encode('utf-8'),
  120. digestmod=sha256)
  121. new_hmac.update(request.headers['Date'].encode('utf-8'))
  122. encoded_signature = encodebytes(new_hmac.digest()).strip()
  123. signature = ('AWS3-HTTPS AWSAccessKeyId=%s,Algorithm=%s,Signature=%s' %
  124. (self.credentials.access_key, 'HmacSHA256',
  125. encoded_signature.decode('utf-8')))
  126. if 'X-Amzn-Authorization' in request.headers:
  127. del request.headers['X-Amzn-Authorization']
  128. request.headers['X-Amzn-Authorization'] = signature
  129. class SigV4Auth(BaseSigner):
  130. """
  131. Sign a request with Signature V4.
  132. """
  133. REQUIRES_REGION = True
  134. def __init__(self, credentials, service_name, region_name):
  135. self.credentials = credentials
  136. # We initialize these value here so the unit tests can have
  137. # valid values. But these will get overriden in ``add_auth``
  138. # later for real requests.
  139. self._region_name = region_name
  140. self._service_name = service_name
  141. def _sign(self, key, msg, hex=False):
  142. if hex:
  143. sig = hmac.new(key, msg.encode('utf-8'), sha256).hexdigest()
  144. else:
  145. sig = hmac.new(key, msg.encode('utf-8'), sha256).digest()
  146. return sig
  147. def headers_to_sign(self, request):
  148. """
  149. Select the headers from the request that need to be included
  150. in the StringToSign.
  151. """
  152. header_map = HTTPHeaders()
  153. split = urlsplit(request.url)
  154. for name, value in request.headers.items():
  155. lname = name.lower()
  156. if lname not in SIGNED_HEADERS_BLACKLIST:
  157. header_map[lname] = value
  158. if 'host' not in header_map:
  159. header_map['host'] = split.netloc
  160. return header_map
  161. def canonical_query_string(self, request):
  162. # The query string can come from two parts. One is the
  163. # params attribute of the request. The other is from the request
  164. # url (in which case we have to re-split the url into its components
  165. # and parse out the query string component).
  166. if request.params:
  167. return self._canonical_query_string_params(request.params)
  168. else:
  169. return self._canonical_query_string_url(urlsplit(request.url))
  170. def _canonical_query_string_params(self, params):
  171. l = []
  172. for param in sorted(params):
  173. value = str(params[param])
  174. l.append('%s=%s' % (quote(param, safe='-_.~'),
  175. quote(value, safe='-_.~')))
  176. cqs = '&'.join(l)
  177. return cqs
  178. def _canonical_query_string_url(self, parts):
  179. canonical_query_string = ''
  180. if parts.query:
  181. # [(key, value), (key2, value2)]
  182. key_val_pairs = []
  183. for pair in parts.query.split('&'):
  184. key, _, value = pair.partition('=')
  185. key_val_pairs.append((key, value))
  186. sorted_key_vals = []
  187. # Sort by the key names, and in the case of
  188. # repeated keys, then sort by the value.
  189. for key, value in sorted(key_val_pairs):
  190. sorted_key_vals.append('%s=%s' % (key, value))
  191. canonical_query_string = '&'.join(sorted_key_vals)
  192. return canonical_query_string
  193. def canonical_headers(self, headers_to_sign):
  194. """
  195. Return the headers that need to be included in the StringToSign
  196. in their canonical form by converting all header keys to lower
  197. case, sorting them in alphabetical order and then joining
  198. them into a string, separated by newlines.
  199. """
  200. headers = []
  201. sorted_header_names = sorted(set(headers_to_sign))
  202. for key in sorted_header_names:
  203. value = ','.join(v.strip() for v in
  204. sorted(headers_to_sign.get_all(key)))
  205. headers.append('%s:%s' % (key, value))
  206. return '\n'.join(headers)
  207. def signed_headers(self, headers_to_sign):
  208. l = ['%s' % n.lower().strip() for n in set(headers_to_sign)]
  209. l = sorted(l)
  210. return ';'.join(l)
  211. def payload(self, request):
  212. if request.body and hasattr(request.body, 'seek'):
  213. position = request.body.tell()
  214. read_chunksize = functools.partial(request.body.read,
  215. PAYLOAD_BUFFER)
  216. checksum = sha256()
  217. for chunk in iter(read_chunksize, b''):
  218. checksum.update(chunk)
  219. hex_checksum = checksum.hexdigest()
  220. request.body.seek(position)
  221. return hex_checksum
  222. elif request.body:
  223. # The request serialization has ensured that
  224. # request.body is a bytes() type.
  225. return sha256(request.body).hexdigest()
  226. else:
  227. return EMPTY_SHA256_HASH
  228. def canonical_request(self, request):
  229. cr = [request.method.upper()]
  230. path = self._normalize_url_path(urlsplit(request.url).path)
  231. cr.append(path)
  232. cr.append(self.canonical_query_string(request))
  233. headers_to_sign = self.headers_to_sign(request)
  234. cr.append(self.canonical_headers(headers_to_sign) + '\n')
  235. cr.append(self.signed_headers(headers_to_sign))
  236. if 'X-Amz-Content-SHA256' in request.headers:
  237. body_checksum = request.headers['X-Amz-Content-SHA256']
  238. else:
  239. body_checksum = self.payload(request)
  240. cr.append(body_checksum)
  241. return '\n'.join(cr)
  242. def _normalize_url_path(self, path):
  243. normalized_path = quote(normalize_url_path(path), safe='/~')
  244. return normalized_path
  245. def scope(self, request):
  246. scope = [self.credentials.access_key]
  247. scope.append(request.context['timestamp'][0:8])
  248. scope.append(self._region_name)
  249. scope.append(self._service_name)
  250. scope.append('aws4_request')
  251. return '/'.join(scope)
  252. def credential_scope(self, request):
  253. scope = []
  254. scope.append(request.context['timestamp'][0:8])
  255. scope.append(self._region_name)
  256. scope.append(self._service_name)
  257. scope.append('aws4_request')
  258. return '/'.join(scope)
  259. def string_to_sign(self, request, canonical_request):
  260. """
  261. Return the canonical StringToSign as well as a dict
  262. containing the original version of all headers that
  263. were included in the StringToSign.
  264. """
  265. sts = ['AWS4-HMAC-SHA256']
  266. sts.append(request.context['timestamp'])
  267. sts.append(self.credential_scope(request))
  268. sts.append(sha256(canonical_request.encode('utf-8')).hexdigest())
  269. return '\n'.join(sts)
  270. def signature(self, string_to_sign, request):
  271. key = self.credentials.secret_key
  272. k_date = self._sign(('AWS4' + key).encode('utf-8'),
  273. request.context['timestamp'][0:8])
  274. k_region = self._sign(k_date, self._region_name)
  275. k_service = self._sign(k_region, self._service_name)
  276. k_signing = self._sign(k_service, 'aws4_request')
  277. return self._sign(k_signing, string_to_sign, hex=True)
  278. def add_auth(self, request):
  279. if self.credentials is None:
  280. raise NoCredentialsError
  281. datetime_now = datetime.datetime.utcnow()
  282. request.context['timestamp'] = datetime_now.strftime(SIGV4_TIMESTAMP)
  283. # This could be a retry. Make sure the previous
  284. # authorization header is removed first.
  285. self._modify_request_before_signing(request)
  286. canonical_request = self.canonical_request(request)
  287. logger.debug("Calculating signature using v4 auth.")
  288. logger.debug('CanonicalRequest:\n%s', canonical_request)
  289. string_to_sign = self.string_to_sign(request, canonical_request)
  290. logger.debug('StringToSign:\n%s', string_to_sign)
  291. signature = self.signature(string_to_sign, request)
  292. logger.debug('Signature:\n%s', signature)
  293. self._inject_signature_to_request(request, signature)
  294. def _inject_signature_to_request(self, request, signature):
  295. l = ['AWS4-HMAC-SHA256 Credential=%s' % self.scope(request)]
  296. headers_to_sign = self.headers_to_sign(request)
  297. l.append('SignedHeaders=%s' % self.signed_headers(headers_to_sign))
  298. l.append('Signature=%s' % signature)
  299. request.headers['Authorization'] = ', '.join(l)
  300. return request
  301. def _modify_request_before_signing(self, request):
  302. if 'Authorization' in request.headers:
  303. del request.headers['Authorization']
  304. self._set_necessary_date_headers(request)
  305. if self.credentials.token:
  306. if 'X-Amz-Security-Token' in request.headers:
  307. del request.headers['X-Amz-Security-Token']
  308. request.headers['X-Amz-Security-Token'] = self.credentials.token
  309. def _set_necessary_date_headers(self, request):
  310. # The spec allows for either the Date _or_ the X-Amz-Date value to be
  311. # used so we check both. If there's a Date header, we use the date
  312. # header. Otherwise we use the X-Amz-Date header.
  313. if 'Date' in request.headers:
  314. del request.headers['Date']
  315. datetime_timestamp = datetime.datetime.strptime(
  316. request.context['timestamp'], SIGV4_TIMESTAMP)
  317. request.headers['Date'] = formatdate(
  318. int(calendar.timegm(datetime_timestamp.timetuple())))
  319. if 'X-Amz-Date' in request.headers:
  320. del request.headers['X-Amz-Date']
  321. else:
  322. if 'X-Amz-Date' in request.headers:
  323. del request.headers['X-Amz-Date']
  324. request.headers['X-Amz-Date'] = request.context['timestamp']
  325. class S3SigV4Auth(SigV4Auth):
  326. def _modify_request_before_signing(self, request):
  327. super(S3SigV4Auth, self)._modify_request_before_signing(request)
  328. if 'X-Amz-Content-SHA256' in request.headers:
  329. del request.headers['X-Amz-Content-SHA256']
  330. request.headers['X-Amz-Content-SHA256'] = self.payload(request)
  331. def _normalize_url_path(self, path):
  332. # For S3, we do not normalize the path.
  333. return path
  334. class SigV4QueryAuth(SigV4Auth):
  335. DEFAULT_EXPIRES = 3600
  336. def __init__(self, credentials, service_name, region_name,
  337. expires=DEFAULT_EXPIRES):
  338. super(SigV4QueryAuth, self).__init__(credentials, service_name,
  339. region_name)
  340. self._expires = expires
  341. def _modify_request_before_signing(self, request):
  342. # Note that we're not including X-Amz-Signature.
  343. # From the docs: "The Canonical Query String must include all the query
  344. # parameters from the preceding table except for X-Amz-Signature.
  345. signed_headers = self.signed_headers(self.headers_to_sign(request))
  346. auth_params = {
  347. 'X-Amz-Algorithm': 'AWS4-HMAC-SHA256',
  348. 'X-Amz-Credential': self.scope(request),
  349. 'X-Amz-Date': request.context['timestamp'],
  350. 'X-Amz-Expires': self._expires,
  351. 'X-Amz-SignedHeaders': signed_headers,
  352. }
  353. if self.credentials.token is not None:
  354. auth_params['X-Amz-Security-Token'] = self.credentials.token
  355. # Now parse the original query string to a dict, inject our new query
  356. # params, and serialize back to a query string.
  357. url_parts = urlsplit(request.url)
  358. # parse_qs makes each value a list, but in our case we know we won't
  359. # have repeated keys so we know we have single element lists which we
  360. # can convert back to scalar values.
  361. query_dict = dict(
  362. [(k, v[0]) for k, v in parse_qs(url_parts.query).items()])
  363. # The spec is particular about this. It *has* to be:
  364. # https://<endpoint>?<operation params>&<auth params>
  365. # You can't mix the two types of params together, i.e just keep doing
  366. # new_query_params.update(op_params)
  367. # new_query_params.update(auth_params)
  368. # percent_encode_sequence(new_query_params)
  369. operation_params = ''
  370. if request.data:
  371. # We also need to move the body params into the query string.
  372. # request.data will be populated, for example, with query services
  373. # which normally form encode the params into the body.
  374. # This means that request.data is a dict() of the operation params.
  375. query_dict.update(request.data)
  376. request.data = ''
  377. if query_dict:
  378. operation_params = percent_encode_sequence(query_dict) + '&'
  379. new_query_string = (operation_params +
  380. percent_encode_sequence(auth_params))
  381. # url_parts is a tuple (and therefore immutable) so we need to create
  382. # a new url_parts with the new query string.
  383. # <part> - <index>
  384. # scheme - 0
  385. # netloc - 1
  386. # path - 2
  387. # query - 3 <-- we're replacing this.
  388. # fragment - 4
  389. p = url_parts
  390. new_url_parts = (p[0], p[1], p[2], new_query_string, p[4])
  391. request.url = urlunsplit(new_url_parts)
  392. def _inject_signature_to_request(self, request, signature):
  393. # Rather than calculating an "Authorization" header, for the query
  394. # param quth, we just append an 'X-Amz-Signature' param to the end
  395. # of the query string.
  396. request.url += '&X-Amz-Signature=%s' % signature
  397. class S3SigV4QueryAuth(SigV4QueryAuth):
  398. """S3 SigV4 auth using query parameters.
  399. This signer will sign a request using query parameters and signature
  400. version 4, i.e a "presigned url" signer.
  401. """
  402. def _normalize_url_path(self, path):
  403. # For S3, we do not normalize the path.
  404. return path
  405. def payload(self, request):
  406. # From the doc link above:
  407. # "You don't include a payload hash in the Canonical Request, because
  408. # when you create a presigned URL, you don't know anything about the
  409. # payload. Instead, you use a constant string "UNSIGNED-PAYLOAD".
  410. return "UNSIGNED-PAYLOAD"
  411. class S3SigV4PostAuth(SigV4Auth):
  412. """
  413. Presigns a s3 post
  414. """
  415. def add_auth(self, request):
  416. datetime_now = datetime.datetime.utcnow()
  417. request.context['timestamp'] = datetime_now.strftime(SIGV4_TIMESTAMP)
  418. fields = {}
  419. if request.context.get('s3-presign-post-fields', None) is not None:
  420. fields = request.context['s3-presign-post-fields']
  421. policy = {}
  422. conditions = []
  423. if request.context.get('s3-presign-post-policy', None) is not None:
  424. policy = request.context['s3-presign-post-policy']
  425. if policy.get('conditions', None) is not None:
  426. conditions = policy['conditions']
  427. policy['conditions'] = conditions
  428. fields['x-amz-algorithm'] = 'AWS4-HMAC-SHA256'
  429. fields['x-amz-credential'] = self.scope(request)
  430. fields['x-amz-date'] = request.context['timestamp']
  431. conditions.append({'x-amz-algorithm': 'AWS4-HMAC-SHA256'})
  432. conditions.append({'x-amz-credential': self.scope(request)})
  433. conditions.append({'x-amz-date': request.context['timestamp']})
  434. if self.credentials.token is not None:
  435. fields['x-amz-security-token'] = self.credentials.token
  436. conditions.append({'x-amz-security-token': self.credentials.token})
  437. # Dump the base64 encoded policy into the fields dictionary.
  438. fields['policy'] = base64.b64encode(
  439. json.dumps(policy).encode('utf-8')).decode('utf-8')
  440. fields['x-amz-signature'] = self.signature(fields['policy'], request)
  441. request.context['s3-presign-post-fields'] = fields
  442. request.context['s3-presign-post-policy'] = policy
  443. class HmacV1Auth(BaseSigner):
  444. # List of Query String Arguments of Interest
  445. QSAOfInterest = ['accelerate', 'acl', 'cors', 'defaultObjectAcl',
  446. 'location', 'logging', 'partNumber', 'policy',
  447. 'requestPayment', 'torrent',
  448. 'versioning', 'versionId', 'versions', 'website',
  449. 'uploads', 'uploadId', 'response-content-type',
  450. 'response-content-language', 'response-expires',
  451. 'response-cache-control', 'response-content-disposition',
  452. 'response-content-encoding', 'delete', 'lifecycle',
  453. 'tagging', 'restore', 'storageClass', 'notification',
  454. 'replication', 'requestPayment']
  455. def __init__(self, credentials, service_name=None, region_name=None):
  456. self.credentials = credentials
  457. def sign_string(self, string_to_sign):
  458. new_hmac = hmac.new(self.credentials.secret_key.encode('utf-8'),
  459. digestmod=sha1)
  460. new_hmac.update(string_to_sign.encode('utf-8'))
  461. return encodebytes(new_hmac.digest()).strip().decode('utf-8')
  462. def canonical_standard_headers(self, headers):
  463. interesting_headers = ['content-md5', 'content-type', 'date']
  464. hoi = []
  465. if 'Date' in headers:
  466. del headers['Date']
  467. headers['Date'] = self._get_date()
  468. for ih in interesting_headers:
  469. found = False
  470. for key in headers:
  471. lk = key.lower()
  472. if headers[key] is not None and lk == ih:
  473. hoi.append(headers[key].strip())
  474. found = True
  475. if not found:
  476. hoi.append('')
  477. return '\n'.join(hoi)
  478. def canonical_custom_headers(self, headers):
  479. hoi = []
  480. custom_headers = {}
  481. for key in headers:
  482. lk = key.lower()
  483. if headers[key] is not None:
  484. if lk.startswith('x-amz-'):
  485. custom_headers[lk] = ','.join(v.strip() for v in
  486. headers.get_all(key))
  487. sorted_header_keys = sorted(custom_headers.keys())
  488. for key in sorted_header_keys:
  489. hoi.append("%s:%s" % (key, custom_headers[key]))
  490. return '\n'.join(hoi)
  491. def unquote_v(self, nv):
  492. """
  493. TODO: Do we need this?
  494. """
  495. if len(nv) == 1:
  496. return nv
  497. else:
  498. return (nv[0], unquote(nv[1]))
  499. def canonical_resource(self, split, auth_path=None):
  500. # don't include anything after the first ? in the resource...
  501. # unless it is one of the QSA of interest, defined above
  502. # NOTE:
  503. # The path in the canonical resource should always be the
  504. # full path including the bucket name, even for virtual-hosting
  505. # style addressing. The ``auth_path`` keeps track of the full
  506. # path for the canonical resource and would be passed in if
  507. # the client was using virtual-hosting style.
  508. if auth_path is not None:
  509. buf = auth_path
  510. else:
  511. buf = split.path
  512. if split.query:
  513. qsa = split.query.split('&')
  514. qsa = [a.split('=', 1) for a in qsa]
  515. qsa = [self.unquote_v(a) for a in qsa
  516. if a[0] in self.QSAOfInterest]
  517. if len(qsa) > 0:
  518. qsa.sort(key=itemgetter(0))
  519. qsa = ['='.join(a) for a in qsa]
  520. buf += '?'
  521. buf += '&'.join(qsa)
  522. return buf
  523. def canonical_string(self, method, split, headers, expires=None,
  524. auth_path=None):
  525. cs = method.upper() + '\n'
  526. cs += self.canonical_standard_headers(headers) + '\n'
  527. custom_headers = self.canonical_custom_headers(headers)
  528. if custom_headers:
  529. cs += custom_headers + '\n'
  530. cs += self.canonical_resource(split, auth_path=auth_path)
  531. return cs
  532. def get_signature(self, method, split, headers, expires=None,
  533. auth_path=None):
  534. if self.credentials.token:
  535. del headers['x-amz-security-token']
  536. headers['x-amz-security-token'] = self.credentials.token
  537. string_to_sign = self.canonical_string(method,
  538. split,
  539. headers,
  540. auth_path=auth_path)
  541. logger.debug('StringToSign:\n%s', string_to_sign)
  542. return self.sign_string(string_to_sign)
  543. def add_auth(self, request):
  544. if self.credentials is None:
  545. raise NoCredentialsError
  546. logger.debug("Calculating signature using hmacv1 auth.")
  547. split = urlsplit(request.url)
  548. logger.debug('HTTP request method: %s', request.method)
  549. signature = self.get_signature(request.method, split,
  550. request.headers,
  551. auth_path=request.auth_path)
  552. self._inject_signature(request, signature)
  553. def _get_date(self):
  554. return formatdate(usegmt=True)
  555. def _inject_signature(self, request, signature):
  556. if 'Authorization' in request.headers:
  557. # We have to do this because request.headers is not
  558. # normal dictionary. It has the (unintuitive) behavior
  559. # of aggregating repeated setattr calls for the same
  560. # key value. For example:
  561. # headers['foo'] = 'a'; headers['foo'] = 'b'
  562. # list(headers) will print ['foo', 'foo'].
  563. del request.headers['Authorization']
  564. request.headers['Authorization'] = (
  565. "AWS %s:%s" % (self.credentials.access_key, signature))
  566. class HmacV1QueryAuth(HmacV1Auth):
  567. """
  568. Generates a presigned request for s3.
  569. #RESTAuthenticationQueryStringAuth
  570. """
  571. DEFAULT_EXPIRES = 3600
  572. def __init__(self, credentials, expires=DEFAULT_EXPIRES):
  573. self.credentials = credentials
  574. self._expires = expires
  575. def _get_date(self):
  576. return str(int(time.time() + int(self._expires)))
  577. def _inject_signature(self, request, signature):
  578. query_dict = {}
  579. query_dict['AWSAccessKeyId'] = self.credentials.access_key
  580. query_dict['Signature'] = signature
  581. for header_key in request.headers:
  582. lk = header_key.lower()
  583. # For query string requests, Expires is used instead of the
  584. # Date header.
  585. if header_key == 'Date':
  586. query_dict['Expires'] = request.headers['Date']
  587. # We only want to include relevant headers in the query string.
  588. # These can be anything that starts with x-amz, is Content-MD5,
  589. # or is Content-Type.
  590. elif lk.startswith('x-amz-') or lk in ['content-md5',
  591. 'content-type']:
  592. query_dict[lk] = request.headers[lk]
  593. # Combine all of the identified headers into an encoded
  594. # query string
  595. new_query_string = percent_encode_sequence(query_dict)
  596. # Create a new url with the presigned url.
  597. p = urlsplit(request.url)
  598. if p[3]:
  599. # If there was a pre-existing query string, we should
  600. # add that back before injecting the new query string.
  601. new_query_string ='%s&%s' % (p[3], new_query_string)
  602. new_url_parts = (p[0], p[1], p[2], new_query_string, p[4])
  603. request.url = urlunsplit(new_url_parts)
  604. class HmacV1PostAuth(HmacV1Auth):
  605. """
  606. Generates a presigned post for s3.
  607. """
  608. def add_auth(self, request):
  609. fields = {}
  610. if request.context.get('s3-presign-post-fields', None) is not None:
  611. fields = request.context['s3-presign-post-fields']
  612. policy = {}
  613. conditions = []
  614. if request.context.get('s3-presign-post-policy', None) is not None:
  615. policy = request.context['s3-presign-post-policy']
  616. if policy.get('conditions', None) is not None:
  617. conditions = policy['conditions']
  618. policy['conditions'] = conditions
  619. fields['AWSAccessKeyId'] = self.credentials.access_key
  620. if self.credentials.token is not None:
  621. fields['x-amz-security-token'] = self.credentials.token
  622. conditions.append({'x-amz-security-token': self.credentials.token})
  623. # Dump the base64 encoded policy into the fields dictionary.
  624. fields['policy'] = base64.b64encode(
  625. json.dumps(policy).encode('utf-8')).decode('utf-8')
  626. fields['signature'] = self.sign_string(fields['policy'])
  627. request.context['s3-presign-post-fields'] = fields
  628. request.context['s3-presign-post-policy'] = policy
  629. # Defined at the bottom instead of the top of the module because the Auth
  630. # classes weren't defined yet.
  631. AUTH_TYPE_MAPS = {
  632. 'v2': SigV2Auth,
  633. 'v4': SigV4Auth,
  634. 'v4-query': SigV4QueryAuth,
  635. 'v3': SigV3Auth,
  636. 'v3https': SigV3Auth,
  637. 's3': HmacV1Auth,
  638. 's3-query': HmacV1QueryAuth,
  639. 's3-presign-post': HmacV1PostAuth,
  640. 's3v4': S3SigV4Auth,
  641. 's3v4-query': S3SigV4QueryAuth,
  642. 's3v4-presign-post': S3SigV4PostAuth,
  643. }