/
s3request.py
1572 lines (1364 loc) · 59.7 KB
/
s3request.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2014 OpenStack Foundation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import base64
import binascii
from collections import defaultdict, OrderedDict
from email.header import Header
from hashlib import sha1, sha256, md5
import hmac
import re
import six
# pylint: disable-msg=import-error
from six.moves.urllib.parse import quote, unquote, parse_qsl
import string
from swift.common.utils import split_path, json, get_swift_info, \
close_if_possible
from swift.common import swob
from swift.common.http import HTTP_OK, HTTP_CREATED, HTTP_ACCEPTED, \
HTTP_NO_CONTENT, HTTP_UNAUTHORIZED, HTTP_FORBIDDEN, HTTP_NOT_FOUND, \
HTTP_CONFLICT, HTTP_UNPROCESSABLE_ENTITY, HTTP_REQUEST_ENTITY_TOO_LARGE, \
HTTP_PARTIAL_CONTENT, HTTP_NOT_MODIFIED, HTTP_PRECONDITION_FAILED, \
HTTP_REQUESTED_RANGE_NOT_SATISFIABLE, HTTP_LENGTH_REQUIRED, \
HTTP_BAD_REQUEST, HTTP_REQUEST_TIMEOUT, HTTP_SERVICE_UNAVAILABLE, \
is_success
from swift.common.constraints import check_utf8
from swift.proxy.controllers.base import get_container_info, \
headers_to_container_info
from swift.common.request_helpers import check_path_header
from swift.common.middleware.s3api.controllers import ServiceController, \
ObjectController, AclController, MultiObjectDeleteController, \
LocationController, LoggingStatusController, PartController, \
UploadController, UploadsController, VersioningController, \
UnsupportedController, S3AclController, BucketController
from swift.common.middleware.s3api.s3response import AccessDenied, \
InvalidArgument, InvalidDigest, BucketAlreadyOwnedByYou, \
RequestTimeTooSkewed, S3Response, SignatureDoesNotMatch, \
BucketAlreadyExists, BucketNotEmpty, EntityTooLarge, \
InternalError, NoSuchBucket, NoSuchKey, PreconditionFailed, InvalidRange, \
MissingContentLength, InvalidStorageClass, S3NotImplemented, InvalidURI, \
MalformedXML, InvalidRequest, RequestTimeout, InvalidBucketName, \
BadDigest, AuthorizationHeaderMalformed, \
AuthorizationQueryParametersError, ServiceUnavailable
from swift.common.middleware.s3api.exception import NotS3Request, \
BadSwiftRequest
from swift.common.middleware.s3api.utils import utf8encode, \
S3Timestamp, mktime, MULTIUPLOAD_SUFFIX
from swift.common.middleware.s3api.subresource import decode_acl, encode_acl
from swift.common.middleware.s3api.utils import sysmeta_header, \
validate_bucket_name
from swift.common.middleware.s3api.acl_utils import handle_acl_header
# List of sub-resources that must be maintained as part of the HMAC
# signature string.
ALLOWED_SUB_RESOURCES = sorted([
'acl', 'delete', 'lifecycle', 'location', 'logging', 'notification',
'partNumber', 'policy', 'requestPayment', 'torrent', 'uploads', 'uploadId',
'versionId', 'versioning', 'versions', 'website',
'response-cache-control', 'response-content-disposition',
'response-content-encoding', 'response-content-language',
'response-content-type', 'response-expires', 'cors', 'tagging', 'restore'
])
MAX_32BIT_INT = 2147483647
SIGV2_TIMESTAMP_FORMAT = '%Y-%m-%dT%H:%M:%S'
SIGV4_X_AMZ_DATE_FORMAT = '%Y%m%dT%H%M%SZ'
SERVICE = 's3' # useful for mocking out in tests
def _header_strip(value):
# S3 seems to strip *all* control characters
if value is None:
return None
stripped = _header_strip.re.sub('', value)
if value and not stripped:
# If there's nothing left after stripping,
# behave as though it wasn't provided
return None
return stripped
_header_strip.re = re.compile('^[\x00-\x20]*|[\x00-\x20]*$')
def _header_acl_property(resource):
"""
Set and retrieve the acl in self.headers
"""
def getter(self):
return getattr(self, '_%s' % resource)
def setter(self, value):
self.headers.update(encode_acl(resource, value))
setattr(self, '_%s' % resource, value)
def deleter(self):
self.headers[sysmeta_header(resource, 'acl')] = ''
return property(getter, setter, deleter,
doc='Get and set the %s acl property' % resource)
class HashingInput(object):
"""
wsgi.input wrapper to verify the hash of the input as it's read.
"""
def __init__(self, reader, content_length, hasher, expected_hex_hash):
self._input = reader
self._to_read = content_length
self._hasher = hasher()
self._expected = expected_hex_hash
def read(self, size=None):
chunk = self._input.read(size)
self._hasher.update(chunk)
self._to_read -= len(chunk)
short_read = bool(chunk) if size is None else (len(chunk) < size)
if self._to_read < 0 or (short_read and self._to_read) or (
self._to_read == 0 and
self._hasher.hexdigest() != self._expected):
self.close()
# Since we don't return the last chunk, the PUT never completes
raise swob.HTTPUnprocessableEntity(
'The X-Amz-Content-SHA56 you specified did not match '
'what we received.')
return chunk
def close(self):
close_if_possible(self._input)
class SigV4Mixin(object):
"""
A request class mixin to provide S3 signature v4 functionality
"""
def check_signature(self, secret):
secret = utf8encode(secret)
user_signature = self.signature
derived_secret = b'AWS4' + secret
for scope_piece in self.scope.values():
derived_secret = hmac.new(
derived_secret, scope_piece.encode('utf8'), sha256).digest()
valid_signature = hmac.new(
derived_secret, self.string_to_sign, sha256).hexdigest()
return user_signature == valid_signature
@property
def _is_query_auth(self):
return 'X-Amz-Credential' in self.params
@property
def timestamp(self):
"""
Return timestamp string according to the auth type
The difference from v2 is v4 have to see 'X-Amz-Date' even though
it's query auth type.
"""
if not self._timestamp:
try:
if self._is_query_auth and 'X-Amz-Date' in self.params:
# NOTE(andrey-mp): Date in Signature V4 has different
# format
timestamp = mktime(
self.params['X-Amz-Date'], SIGV4_X_AMZ_DATE_FORMAT)
else:
if self.headers.get('X-Amz-Date'):
timestamp = mktime(
self.headers.get('X-Amz-Date'),
SIGV4_X_AMZ_DATE_FORMAT)
else:
timestamp = mktime(self.headers.get('Date'))
except (ValueError, TypeError):
raise AccessDenied('AWS authentication requires a valid Date '
'or x-amz-date header')
if timestamp < 0:
raise AccessDenied('AWS authentication requires a valid Date '
'or x-amz-date header')
try:
self._timestamp = S3Timestamp(timestamp)
except ValueError:
# Must be far-future; blame clock skew
raise RequestTimeTooSkewed()
return self._timestamp
def _validate_expire_param(self):
"""
Validate X-Amz-Expires in query parameter
:raises: AccessDenied
:raises: AuthorizationQueryParametersError
:raises: AccessDenined
"""
err = None
try:
expires = int(self.params['X-Amz-Expires'])
except KeyError:
raise AccessDenied()
except ValueError:
err = 'X-Amz-Expires should be a number'
else:
if expires < 0:
err = 'X-Amz-Expires must be non-negative'
elif expires >= 2 ** 63:
err = 'X-Amz-Expires should be a number'
elif expires > 604800:
err = ('X-Amz-Expires must be less than a week (in seconds); '
'that is, the given X-Amz-Expires must be less than '
'604800 seconds')
if err:
raise AuthorizationQueryParametersError(err)
if int(self.timestamp) + expires < S3Timestamp.now():
raise AccessDenied('Request has expired')
def _parse_credential(self, credential_string):
parts = credential_string.split("/")
# credential must be in following format:
# <access-key-id>/<date>/<AWS-region>/<AWS-service>/aws4_request
if not parts[0] or len(parts) != 5:
raise AccessDenied()
return dict(zip(['access', 'date', 'region', 'service', 'terminal'],
parts))
def _parse_query_authentication(self):
"""
Parse v4 query authentication
- version 4:
'X-Amz-Credential' and 'X-Amz-Signature' should be in param
:raises: AccessDenied
:raises: AuthorizationHeaderMalformed
"""
if self.params.get('X-Amz-Algorithm') != 'AWS4-HMAC-SHA256':
raise InvalidArgument('X-Amz-Algorithm',
self.params.get('X-Amz-Algorithm'))
try:
cred_param = self._parse_credential(
self.params['X-Amz-Credential'])
sig = self.params['X-Amz-Signature']
if not sig:
raise AccessDenied()
except KeyError:
raise AccessDenied()
try:
signed_headers = self.params['X-Amz-SignedHeaders']
except KeyError:
# TODO: make sure if is it malformed request?
raise AuthorizationHeaderMalformed()
self._signed_headers = set(signed_headers.split(';'))
invalid_messages = {
'date': 'Invalid credential date "%s". This date is not the same '
'as X-Amz-Date: "%s".',
'region': "Error parsing the X-Amz-Credential parameter; "
"the region '%s' is wrong; expecting '%s'",
'service': 'Error parsing the X-Amz-Credential parameter; '
'incorrect service "%s". This endpoint belongs to "%s".',
'terminal': 'Error parsing the X-Amz-Credential parameter; '
'incorrect terminal "%s". This endpoint uses "%s".',
}
for key in ('date', 'region', 'service', 'terminal'):
if cred_param[key] != self.scope[key]:
kwargs = {}
if key == 'region':
kwargs = {'region': self.scope['region']}
raise AuthorizationQueryParametersError(
invalid_messages[key] % (cred_param[key], self.scope[key]),
**kwargs)
return cred_param['access'], sig
def _parse_header_authentication(self):
"""
Parse v4 header authentication
- version 4:
'X-Amz-Credential' and 'X-Amz-Signature' should be in param
:raises: AccessDenied
:raises: AuthorizationHeaderMalformed
"""
auth_str = self.headers['Authorization']
cred_param = self._parse_credential(auth_str.partition(
"Credential=")[2].split(',')[0])
sig = auth_str.partition("Signature=")[2].split(',')[0]
if not sig:
raise AccessDenied()
signed_headers = auth_str.partition(
"SignedHeaders=")[2].split(',', 1)[0]
if not signed_headers:
# TODO: make sure if is it Malformed?
raise AuthorizationHeaderMalformed()
invalid_messages = {
'date': 'Invalid credential date "%s". This date is not the same '
'as X-Amz-Date: "%s".',
'region': "The authorization header is malformed; the region '%s' "
"is wrong; expecting '%s'",
'service': 'The authorization header is malformed; incorrect '
'service "%s". This endpoint belongs to "%s".',
'terminal': 'The authorization header is malformed; incorrect '
'terminal "%s". This endpoint uses "%s".',
}
for key in ('date', 'region', 'service', 'terminal'):
if cred_param[key] != self.scope[key]:
kwargs = {}
if key == 'region':
kwargs = {'region': self.scope['region']}
raise AuthorizationHeaderMalformed(
invalid_messages[key] % (cred_param[key], self.scope[key]),
**kwargs)
self._signed_headers = set(signed_headers.split(';'))
return cred_param['access'], sig
def _canonical_query_string(self):
return '&'.join(
'%s=%s' % (swob.wsgi_quote(key, safe='-_.~'),
swob.wsgi_quote(value, safe='-_.~'))
for key, value in sorted(self.params.items())
if key not in ('Signature', 'X-Amz-Signature')).encode('ascii')
def _headers_to_sign(self):
"""
Select the headers from the request that need to be included
in the StringToSign.
:return : dict of headers to sign, the keys are all lower case
"""
if 'headers_raw' in self.environ: # eventlet >= 0.19.0
# See https://github.com/eventlet/eventlet/commit/67ec999
headers_lower_dict = defaultdict(list)
for key, value in self.environ['headers_raw']:
headers_lower_dict[key.lower().strip()].append(
' '.join(_header_strip(value or '').split()))
headers_lower_dict = {k: ','.join(v)
for k, v in headers_lower_dict.items()}
else: # mostly-functional fallback
headers_lower_dict = dict(
(k.lower().strip(), ' '.join(_header_strip(v or '').split()))
for (k, v) in six.iteritems(self.headers))
if 'host' in headers_lower_dict and re.match(
'Boto/2.[0-9].[0-2]',
headers_lower_dict.get('user-agent', '')):
# Boto versions < 2.9.3 strip the port component of the host:port
# header, so detect the user-agent via the header and strip the
# port if we detect an old boto version.
headers_lower_dict['host'] = \
headers_lower_dict['host'].split(':')[0]
headers_to_sign = [
(key, value) for key, value in sorted(headers_lower_dict.items())
if key in self._signed_headers]
if len(headers_to_sign) != len(self._signed_headers):
# NOTE: if we are missing the header suggested via
# signed_header in actual header, it results in
# SignatureDoesNotMatch in actual S3 so we can raise
# the error immediately here to save redundant check
# process.
raise SignatureDoesNotMatch()
return headers_to_sign
def _canonical_uri(self):
"""
It won't require bucket name in canonical_uri for v4.
"""
return swob.wsgi_to_bytes(self.environ.get('RAW_PATH_INFO', self.path))
def _canonical_request(self):
# prepare 'canonical_request'
# Example requests are like following:
#
# GET
# /
# Action=ListUsers&Version=2010-05-08
# content-type:application/x-www-form-urlencoded; charset=utf-8
# host:iam.amazonaws.com
# x-amz-date:20150830T123600Z
#
# content-type;host;x-amz-date
# e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
#
# 1. Add verb like: GET
cr = [swob.wsgi_to_bytes(self.method.upper())]
# 2. Add path like: /
path = self._canonical_uri()
cr.append(path)
# 3. Add query like: Action=ListUsers&Version=2010-05-08
cr.append(self._canonical_query_string())
# 4. Add headers like:
# content-type:application/x-www-form-urlencoded; charset=utf-8
# host:iam.amazonaws.com
# x-amz-date:20150830T123600Z
headers_to_sign = self._headers_to_sign()
cr.append(b''.join(swob.wsgi_to_bytes('%s:%s\n' % (key, value))
for key, value in headers_to_sign))
# 5. Add signed headers into canonical request like
# content-type;host;x-amz-date
cr.append(b';'.join(swob.wsgi_to_bytes(k) for k, v in headers_to_sign))
# 6. Add payload string at the tail
if 'X-Amz-Credential' in self.params:
# V4 with query parameters only
hashed_payload = 'UNSIGNED-PAYLOAD'
elif 'X-Amz-Content-SHA256' not in self.headers:
msg = 'Missing required header for this request: ' \
'x-amz-content-sha256'
raise InvalidRequest(msg)
else:
hashed_payload = self.headers['X-Amz-Content-SHA256']
if hashed_payload != 'UNSIGNED-PAYLOAD':
if self.content_length == 0:
if hashed_payload != sha256().hexdigest():
raise BadDigest(
'The X-Amz-Content-SHA56 you specified did not '
'match what we received.')
elif self.content_length:
self.environ['wsgi.input'] = HashingInput(
self.environ['wsgi.input'],
self.content_length,
sha256,
hashed_payload)
# else, length not provided -- Swift will kick out a
# 411 Length Required which will get translated back
# to a S3-style response in S3Request._swift_error_codes
cr.append(swob.wsgi_to_bytes(hashed_payload))
return b'\n'.join(cr)
@property
def scope(self):
return OrderedDict([
('date', self.timestamp.amz_date_format.split('T')[0]),
('region', self.location),
('service', SERVICE),
('terminal', 'aws4_request'),
])
def _string_to_sign(self):
"""
Create 'StringToSign' value in Amazon terminology for v4.
"""
return b'\n'.join([
b'AWS4-HMAC-SHA256',
self.timestamp.amz_date_format.encode('ascii'),
'/'.join(self.scope.values()).encode('utf8'),
sha256(self._canonical_request()).hexdigest().encode('ascii')])
def signature_does_not_match_kwargs(self):
kwargs = super(SigV4Mixin, self).signature_does_not_match_kwargs()
cr = self._canonical_request()
kwargs.update({
'canonical_request': cr,
'canonical_request_bytes': ' '.join(
format(ord(c), '02x') for c in cr.decode('latin1')),
})
return kwargs
def get_request_class(env, s3_acl):
"""
Helper function to find a request class to use from Map
"""
if s3_acl:
request_classes = (S3AclRequest, SigV4S3AclRequest)
else:
request_classes = (S3Request, SigV4Request)
req = swob.Request(env)
if 'X-Amz-Credential' in req.params or \
req.headers.get('Authorization', '').startswith(
'AWS4-HMAC-SHA256 '):
# This is an Amazon SigV4 request
return request_classes[1]
else:
# The others using Amazon SigV2 class
return request_classes[0]
class S3Request(swob.Request):
"""
S3 request object.
"""
bucket_acl = _header_acl_property('container')
object_acl = _header_acl_property('object')
def __init__(self, env, app=None, slo_enabled=True, storage_domain='',
location='us-east-1', force_request_log=False,
dns_compliant_bucket_names=True, allow_multipart_uploads=True,
allow_no_owner=False):
# NOTE: app and allow_no_owner are not used by this class, need for
# compatibility of S3acl
swob.Request.__init__(self, env)
self.storage_domain = storage_domain
self.location = location
self.force_request_log = force_request_log
self.dns_compliant_bucket_names = dns_compliant_bucket_names
self.allow_multipart_uploads = allow_multipart_uploads
self._timestamp = None
self.access_key, self.signature = self._parse_auth_info()
self.bucket_in_host = self._parse_host()
self.container_name, self.object_name = self._parse_uri()
self._validate_headers()
# Lock in string-to-sign now, before we start messing with query params
self.string_to_sign = self._string_to_sign()
self.environ['s3api.auth_details'] = {
'access_key': self.access_key,
'signature': self.signature,
'string_to_sign': self.string_to_sign,
'check_signature': self.check_signature,
}
self.account = None
self.user_id = None
self.slo_enabled = slo_enabled
# Avoids that swift.swob.Response replaces Location header value
# by full URL when absolute path given. See swift.swob for more detail.
self.environ['swift.leave_relative_location'] = True
def check_signature(self, secret):
secret = utf8encode(secret)
user_signature = self.signature
valid_signature = base64.b64encode(hmac.new(
secret, self.string_to_sign, sha1).digest()).strip()
if not six.PY2:
valid_signature = valid_signature.decode('ascii')
return user_signature == valid_signature
@property
def timestamp(self):
"""
S3Timestamp from Date header. If X-Amz-Date header specified, it
will be prior to Date header.
:return : S3Timestamp instance
"""
if not self._timestamp:
try:
if self._is_query_auth and 'Timestamp' in self.params:
# If Timestamp specified in query, it should be prior
# to any Date header (is this right?)
timestamp = mktime(
self.params['Timestamp'], SIGV2_TIMESTAMP_FORMAT)
else:
timestamp = mktime(
self.headers.get('X-Amz-Date',
self.headers.get('Date')))
except ValueError:
raise AccessDenied('AWS authentication requires a valid Date '
'or x-amz-date header')
if timestamp < 0:
raise AccessDenied('AWS authentication requires a valid Date '
'or x-amz-date header')
try:
self._timestamp = S3Timestamp(timestamp)
except ValueError:
# Must be far-future; blame clock skew
raise RequestTimeTooSkewed()
return self._timestamp
@property
def _is_header_auth(self):
return 'Authorization' in self.headers
@property
def _is_query_auth(self):
return 'AWSAccessKeyId' in self.params
def _parse_host(self):
storage_domain = self.storage_domain
if not storage_domain:
return None
if not storage_domain.startswith('.'):
storage_domain = '.' + storage_domain
if 'HTTP_HOST' in self.environ:
given_domain = self.environ['HTTP_HOST']
elif 'SERVER_NAME' in self.environ:
given_domain = self.environ['SERVER_NAME']
else:
return None
port = ''
if ':' in given_domain:
given_domain, port = given_domain.rsplit(':', 1)
if given_domain.endswith(storage_domain):
return given_domain[:-len(storage_domain)]
return None
def _parse_uri(self):
if not check_utf8(swob.wsgi_to_str(self.environ['PATH_INFO'])):
raise InvalidURI(self.path)
if self.bucket_in_host:
obj = self.environ['PATH_INFO'][1:] or None
return self.bucket_in_host, obj
bucket, obj = self.split_path(0, 2, True)
if bucket and not validate_bucket_name(
bucket, self.dns_compliant_bucket_names):
# Ignore GET service case
raise InvalidBucketName(bucket)
return (bucket, obj)
def _parse_query_authentication(self):
"""
Parse v2 authentication query args
TODO: make sure if 0, 1, 3 is supported?
- version 0, 1, 2, 3:
'AWSAccessKeyId' and 'Signature' should be in param
:return: a tuple of access_key and signature
:raises: AccessDenied
"""
try:
access = self.params['AWSAccessKeyId']
expires = self.params['Expires']
sig = self.params['Signature']
except KeyError:
raise AccessDenied()
if not all([access, sig, expires]):
raise AccessDenied()
return access, sig
def _parse_header_authentication(self):
"""
Parse v2 header authentication info
:returns: a tuple of access_key and signature
:raises: AccessDenied
"""
auth_str = self.headers['Authorization']
if not auth_str.startswith('AWS ') or ':' not in auth_str:
raise AccessDenied()
# This means signature format V2
access, sig = auth_str.split(' ', 1)[1].rsplit(':', 1)
return access, sig
def _parse_auth_info(self):
"""Extract the access key identifier and signature.
:returns: a tuple of access_key and signature
:raises: NotS3Request
"""
if self._is_query_auth:
self._validate_expire_param()
return self._parse_query_authentication()
elif self._is_header_auth:
self._validate_dates()
return self._parse_header_authentication()
else:
# if this request is neither query auth nor header auth
# s3api regard this as not s3 request
raise NotS3Request()
def _validate_expire_param(self):
"""
Validate Expires in query parameters
:raises: AccessDenied
"""
# Expires header is a float since epoch
try:
ex = S3Timestamp(float(self.params['Expires']))
except (KeyError, ValueError):
raise AccessDenied()
if S3Timestamp.now() > ex:
raise AccessDenied('Request has expired')
if ex >= 2 ** 31:
raise AccessDenied(
'Invalid date (should be seconds since epoch): %s' %
self.params['Expires'])
def _validate_dates(self):
"""
Validate Date/X-Amz-Date headers for signature v2
:raises: AccessDenied
:raises: RequestTimeTooSkewed
"""
date_header = self.headers.get('Date')
amz_date_header = self.headers.get('X-Amz-Date')
if not date_header and not amz_date_header:
raise AccessDenied('AWS authentication requires a valid Date '
'or x-amz-date header')
# Anyways, request timestamp should be validated
epoch = S3Timestamp(0)
if self.timestamp < epoch:
raise AccessDenied()
# If the standard date is too far ahead or behind, it is an
# error
delta = 60 * 5
if abs(int(self.timestamp) - int(S3Timestamp.now())) > delta:
raise RequestTimeTooSkewed()
def _validate_headers(self):
if 'CONTENT_LENGTH' in self.environ:
try:
if self.content_length < 0:
raise InvalidArgument('Content-Length',
self.content_length)
except (ValueError, TypeError):
raise InvalidArgument('Content-Length',
self.environ['CONTENT_LENGTH'])
value = _header_strip(self.headers.get('Content-MD5'))
if value is not None:
if not re.match('^[A-Za-z0-9+/]+={0,2}$', value):
# Non-base64-alphabet characters in value.
raise InvalidDigest(content_md5=value)
try:
self.headers['ETag'] = binascii.b2a_hex(
binascii.a2b_base64(value))
except binascii.error:
# incorrect padding, most likely
raise InvalidDigest(content_md5=value)
if len(self.headers['ETag']) != 32:
raise InvalidDigest(content_md5=value)
if self.method == 'PUT' and any(h in self.headers for h in (
'If-Match', 'If-None-Match',
'If-Modified-Since', 'If-Unmodified-Since')):
raise S3NotImplemented(
'Conditional object PUTs are not supported.')
if 'X-Amz-Copy-Source' in self.headers:
try:
check_path_header(self, 'X-Amz-Copy-Source', 2, '')
except swob.HTTPException:
msg = 'Copy Source must mention the source bucket and key: ' \
'sourcebucket/sourcekey'
raise InvalidArgument('x-amz-copy-source',
self.headers['X-Amz-Copy-Source'],
msg)
if 'x-amz-metadata-directive' in self.headers:
value = self.headers['x-amz-metadata-directive']
if value not in ('COPY', 'REPLACE'):
err_msg = 'Unknown metadata directive.'
raise InvalidArgument('x-amz-metadata-directive', value,
err_msg)
if 'x-amz-storage-class' in self.headers:
# Only STANDARD is supported now.
if self.headers['x-amz-storage-class'] != 'STANDARD':
raise InvalidStorageClass()
if 'x-amz-mfa' in self.headers:
raise S3NotImplemented('MFA Delete is not supported.')
sse_value = self.headers.get('x-amz-server-side-encryption')
if sse_value is not None:
if sse_value not in ('aws:kms', 'AES256'):
raise InvalidArgument(
'x-amz-server-side-encryption', sse_value,
'The encryption method specified is not supported')
encryption_enabled = get_swift_info(admin=True)['admin'].get(
'encryption', {}).get('enabled')
if not encryption_enabled or sse_value != 'AES256':
raise S3NotImplemented(
'Server-side encryption is not supported.')
if 'x-amz-website-redirect-location' in self.headers:
raise S3NotImplemented('Website redirection is not supported.')
# https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-streaming.html
# describes some of what would be required to support this
if any(['aws-chunked' in self.headers.get('content-encoding', ''),
'STREAMING-AWS4-HMAC-SHA256-PAYLOAD' == self.headers.get(
'x-amz-content-sha256', ''),
'x-amz-decoded-content-length' in self.headers]):
raise S3NotImplemented('Transfering payloads in multiple chunks '
'using aws-chunked is not supported.')
if 'x-amz-tagging' in self.headers:
raise S3NotImplemented('Object tagging is not supported.')
@property
def body(self):
"""
swob.Request.body is not secure against malicious input. It consumes
too much memory without any check when the request body is excessively
large. Use xml() instead.
"""
raise AttributeError("No attribute 'body'")
def xml(self, max_length):
"""
Similar to swob.Request.body, but it checks the content length before
creating a body string.
"""
te = self.headers.get('transfer-encoding', '')
te = [x.strip() for x in te.split(',') if x.strip()]
if te and (len(te) > 1 or te[-1] != 'chunked'):
raise S3NotImplemented('A header you provided implies '
'functionality that is not implemented',
header='Transfer-Encoding')
ml = self.message_length()
if ml and ml > max_length:
raise MalformedXML()
if te or ml:
# Limit the read similar to how SLO handles manifests
body = self.body_file.read(max_length)
else:
# No (or zero) Content-Length provided, and not chunked transfer;
# no body. Assume zero-length, and enforce a required body below.
return None
return body
def check_md5(self, body):
if 'HTTP_CONTENT_MD5' not in self.environ:
raise InvalidRequest('Missing required header for this request: '
'Content-MD5')
digest = base64.b64encode(md5(body).digest()).strip().decode('ascii')
if self.environ['HTTP_CONTENT_MD5'] != digest:
raise BadDigest(content_md5=self.environ['HTTP_CONTENT_MD5'])
def _copy_source_headers(self):
env = {}
for key, value in self.environ.items():
if key.startswith('HTTP_X_AMZ_COPY_SOURCE_'):
env[key.replace('X_AMZ_COPY_SOURCE_', '')] = value
return swob.HeaderEnvironProxy(env)
def check_copy_source(self, app):
"""
check_copy_source checks the copy source existence and if copying an
object to itself, for illegal request parameters
:returns: the source HEAD response
"""
try:
src_path = self.headers['X-Amz-Copy-Source']
except KeyError:
return None
if '?' in src_path:
src_path, qs = src_path.split('?', 1)
query = parse_qsl(qs, True)
if not query:
pass # ignore it
elif len(query) > 1 or query[0][0] != 'versionId':
raise InvalidArgument('X-Amz-Copy-Source',
self.headers['X-Amz-Copy-Source'],
'Unsupported copy source parameter.')
elif query[0][1] != 'null':
# TODO: once we support versioning, we'll need to translate
# src_path to the proper location in the versions container
raise S3NotImplemented('Versioning is not yet supported')
self.headers['X-Amz-Copy-Source'] = src_path
src_path = unquote(src_path)
src_path = src_path if src_path.startswith('/') else ('/' + src_path)
src_bucket, src_obj = split_path(src_path, 0, 2, True)
headers = swob.HeaderKeyDict()
headers.update(self._copy_source_headers())
src_resp = self.get_response(app, 'HEAD', src_bucket, src_obj,
headers=headers)
if src_resp.status_int == 304: # pylint: disable-msg=E1101
raise PreconditionFailed()
self.headers['X-Amz-Copy-Source'] = \
'/' + self.headers['X-Amz-Copy-Source'].lstrip('/')
source_container, source_obj = \
split_path(self.headers['X-Amz-Copy-Source'], 1, 2, True)
if (self.container_name == source_container and
self.object_name == source_obj and
self.headers.get('x-amz-metadata-directive',
'COPY') == 'COPY'):
raise InvalidRequest("This copy request is illegal "
"because it is trying to copy an "
"object to itself without "
"changing the object's metadata, "
"storage class, website redirect "
"location or encryption "
"attributes.")
return src_resp
def _canonical_uri(self):
"""
Require bucket name in canonical_uri for v2 in virtual hosted-style.
"""
raw_path_info = self.environ.get('RAW_PATH_INFO', self.path)
if self.bucket_in_host:
raw_path_info = '/' + self.bucket_in_host + raw_path_info
return raw_path_info
def _string_to_sign(self):
"""
Create 'StringToSign' value in Amazon terminology for v2.
"""
amz_headers = {}
buf = [swob.wsgi_to_bytes(wsgi_str) for wsgi_str in [
self.method,
_header_strip(self.headers.get('Content-MD5')) or '',
_header_strip(self.headers.get('Content-Type')) or '']]
if 'headers_raw' in self.environ: # eventlet >= 0.19.0
# See https://github.com/eventlet/eventlet/commit/67ec999
amz_headers = defaultdict(list)
for key, value in self.environ['headers_raw']:
key = key.lower()
if not key.startswith('x-amz-'):
continue
amz_headers[key.strip()].append(value.strip())
amz_headers = dict((key, ','.join(value))
for key, value in amz_headers.items())
else: # mostly-functional fallback
amz_headers = dict((key.lower(), value)
for key, value in self.headers.items()
if key.lower().startswith('x-amz-'))
if self._is_header_auth:
if 'x-amz-date' in amz_headers:
buf.append(b'')
elif 'Date' in self.headers:
buf.append(swob.wsgi_to_bytes(self.headers['Date']))
elif self._is_query_auth:
buf.append(swob.wsgi_to_bytes(self.params['Expires']))
else:
# Should have already raised NotS3Request in _parse_auth_info,
# but as a sanity check...
raise AccessDenied()
for key, value in sorted(amz_headers.items()):
buf.append(swob.wsgi_to_bytes("%s:%s" % (key, value)))
path = self._canonical_uri()
if self.query_string:
path += '?' + self.query_string
params = []
if '?' in path:
path, args = path.split('?', 1)
for key, value in sorted(self.params.items()):
if key in ALLOWED_SUB_RESOURCES:
params.append('%s=%s' % (key, value) if value else key)
if params:
buf.append(swob.wsgi_to_bytes('%s?%s' % (path, '&'.join(params))))
else:
buf.append(swob.wsgi_to_bytes(path))
return b'\n'.join(buf)
def signature_does_not_match_kwargs(self):
return {
'a_w_s_access_key_id': self.access_key,
'string_to_sign': self.string_to_sign,
'signature_provided': self.signature,
'string_to_sign_bytes': ' '.join(
format(ord(c), '02x')
for c in self.string_to_sign.decode('latin1')),
}
@property