· 8 years ago · Dec 15, 2017, 11:36 AM
1# AWS Version 4 signing example
2
3# IAM API (CreateUser)
4
5# See: http://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html
6# This version makes a GET request and passes request parameters
7# and authorization information in the query string
8import sys, os, base64, datetime, hashlib, hmac, urllib
9import requests # pip install requests
10
11# ************* REQUEST VALUES *************
12method = 'GET'
13service = 'sqs'
14host = 'sqs.us-east-1.amazonaws.com'
15region = 'us-east-1'
16endpoint = 'https://sqs.us-east-1.amazonaws.com/1234567890/nome-da-queue'
17
18# Key derivation functions. See:
19# http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python
20def sign(key, msg):
21 return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()
22
23def getSignatureKey(key, dateStamp, regionName, serviceName):
24 kDate = sign(('AWS4' + key).encode('utf-8'), dateStamp)
25 kRegion = sign(kDate, regionName)
26 kService = sign(kRegion, serviceName)
27 kSigning = sign(kService, 'aws4_request')
28 return kSigning
29
30# Read AWS access key from env. variables or configuration file. Best practice is NOT
31# to embed credentials in code.
32# access_key = os.environ.get('AWS_ACCESS_KEY_ID')
33# secret_key = os.environ.get('AWS_SECRET_ACCESS_KEY')
34access_key = 'CHAVE_DE_ACESSO'
35secret_key = 'CHAVE_ULTRA_SECRETA'
36
37if access_key is None or secret_key is None:
38 print('No access key is available.')
39 sys.exit()
40
41# Create a date for headers and the credential string
42t = datetime.datetime.utcnow()
43amz_date = t.strftime('%Y%m%dT%H%M%SZ') # Format date as YYYYMMDD'T'HHMMSS'Z'
44datestamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scope
45
46
47# ************* TASK 1: CREATE A CANONICAL REQUEST *************
48# http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
49
50# Because almost all information is being passed in the query string,
51# the order of these steps is slightly different than examples that
52# use an authorization header.
53
54# Step 1: Define the verb (GET, POST, etc.)--already done.
55
56# Step 2: Create canonical URI--the part of the URI from domain to query
57# string (use '/' if no path)
58canonical_uri = '/'
59
60# Step 3: Create the canonical headers and signed headers. Header names
61# must be trimmed and lowercase, and sorted in code point order from
62# low to high. Note trailing \n in canonical_headers.
63# signed_headers is the list of headers that are being included
64# as part of the signing process. For requests that use query strings,
65# only "host" is included in the signed headers.
66canonical_headers = 'host:' + host + '\n'
67signed_headers = 'host'
68
69# Match the algorithm to the hashing algorithm you use, either SHA-1 or
70# SHA-256 (recommended)
71algorithm = 'AWS4-HMAC-SHA256'
72credential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request'
73
74# Step 4: Create the canonical query string. In this example, request
75# parameters are in the query string. Query string values must
76# be URL-encoded (space=%20). The parameters must be sorted by name.
77canonical_querystring = 'Action=ReceiveMessage&Version=2012-11-05'
78canonical_querystring += '&X-Amz-Algorithm=AWS4-HMAC-SHA256'
79canonical_querystring += '&X-Amz-Credential=' + urllib.quote_plus(access_key + '/' + credential_scope)
80canonical_querystring += '&X-Amz-Date=' + amz_date
81canonical_querystring += '&X-Amz-Expires=30'
82canonical_querystring += '&X-Amz-SignedHeaders=' + signed_headers
83
84# Step 5: Create payload hash. For GET requests, the payload is an
85# empty string ("").
86payload_hash = hashlib.sha256(''.encode('utf-8')).hexdigest()
87
88# Step 6: Combine elements to create create canonical request
89canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash
90
91
92# ************* TASK 2: CREATE THE STRING TO SIGN*************
93string_to_sign = algorithm + '\n' + amz_date + '\n' + credential_scope + '\n' + hashlib.sha256(canonical_request.encode('utf-8')).hexdigest()
94
95
96# ************* TASK 3: CALCULATE THE SIGNATURE *************
97# Create the signing key
98signing_key = getSignatureKey(secret_key, datestamp, region, service)
99
100# Sign the string_to_sign using the signing_key
101signature = hmac.new(signing_key, (string_to_sign).encode("utf-8"), hashlib.sha256).hexdigest()
102
103
104# ************* TASK 4: ADD SIGNING INFORMATION TO THE REQUEST *************
105# The auth information can be either in a query string
106# value or in a header named Authorization. This code shows how to put
107# everything into a query string.
108canonical_querystring += '&X-Amz-Signature=' + signature
109
110
111# ************* SEND THE REQUEST *************
112# The 'host' header is added automatically by the Python 'request' lib. But it
113# must exist as a header in the request.
114request_url = endpoint + "?" + canonical_querystring
115
116print('\nBEGIN REQUEST++++++++++++++++++++++++++++++++++++')
117print('Request URL = ' + request_url)
118r = requests.get(request_url)
119
120print('\nRESPONSE++++++++++++++++++++++++++++++++++++')
121print('Response code: %d\n' % r.status_code)
122print(r.text)