· 7 years ago · Aug 31, 2018, 12:42 AM
1# AWS Version 4 signing example
2
3# EC2 API (DescribeRegions)
4
5# See: http://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html
6# This version makes a GET request and passes the signature
7# in the Authorization header.
8import sys, os, base64, datetime, hashlib, hmac
9import requests # pip install requests
10
11# ************* REQUEST VALUES *************
12method = 'GET'
13service = 'ec2'
14host = 'ec2.amazonaws.com'
15region = 'us-east-1'
16endpoint = 'https://ec2.amazonaws.com'
17request_parameters = 'Action=DescribeRegions&Version=2013-10-15'
18
19# Key derivation functions. See:
20# http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python
21def sign(key, msg):
22 return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()
23
24def getSignatureKey(key, dateStamp, regionName, serviceName):
25 kDate = sign(('AWS4' + key).encode('utf-8'), dateStamp)
26 kRegion = sign(kDate, regionName)
27 kService = sign(kRegion, serviceName)
28 kSigning = sign(kService, 'aws4_request')
29 return kSigning
30
31# Read AWS access key from env. variables or configuration file. Best practice is NOT
32# to embed credentials in code.
33access_key = ""
34secret_key = ""
35if access_key is None or secret_key is None:
36 print ('No access key is available.')
37 sys.exit()
38
39# Create a date for headers and the credential string
40t = datetime.datetime.utcnow()
41amzdate = t.strftime('%Y%m%dT%H%M%SZ')
42datestamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scope
43
44
45# ************* TASK 1: CREATE A CANONICAL REQUEST *************
46# http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
47
48# Step 1 is to define the verb (GET, POST, etc.)--already done.
49
50# Step 2: Create canonical URI--the part of the URI from domain to query
51# string (use '/' if no path)
52canonical_uri = '/'
53
54# Step 3: Create the canonical query string. In this example (a GET request),
55# request parameters are in the query string. Query string values must
56# be URL-encoded (space=%20). The parameters must be sorted by name.
57# For this example, the query string is pre-formatted in the request_parameters variable.
58canonical_querystring = request_parameters
59
60# Step 4: 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 that there is a trailing \n.
63canonical_headers = 'host:' + host + '\n' + 'x-amz-date:' + amzdate + '\n'
64
65# Step 5: Create the list of signed headers. This lists the headers
66# in the canonical_headers list, delimited with ";" and in alpha order.
67# Note: The request can include any headers; canonical_headers and
68# signed_headers lists those that you want to be included in the
69# hash of the request. "Host" and "x-amz-date" are always required.
70signed_headers = 'host;x-amz-date'
71
72# Step 6: Create payload hash (hash of the request body content). For GET
73# requests, the payload is an empty string ("").
74payload_hash = hashlib.sha256(''.encode("utf-8")).hexdigest()
75
76# Step 7: Combine elements to create canonical request
77canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash
78
79
80# ************* TASK 2: CREATE THE STRING TO SIGN*************
81# Match the algorithm to the hashing algorithm you use, either SHA-1 or
82# SHA-256 (recommended)
83algorithm = 'AWS4-HMAC-SHA256'
84credential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request'
85string_to_sign = algorithm + '\n' + amzdate + '\n' + credential_scope + '\n' + hashlib.sha256(canonical_request.encode("utf-8")).hexdigest()
86
87
88# ************* TASK 3: CALCULATE THE SIGNATURE *************
89# Create the signing key using the function defined above.
90signing_key = getSignatureKey(secret_key, datestamp, region, service)
91
92# Sign the string_to_sign using the signing_key
93signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()
94
95
96# ************* TASK 4: ADD SIGNING INFORMATION TO THE REQUEST *************
97# The signing information can be either in a query string value or in
98# a header named Authorization. This code shows how to use a header.
99# Create authorization header and add to request headers
100authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature
101
102# The request can include any headers, but MUST include "host", "x-amz-date",
103# and (for this scenario) "Authorization". "host" and "x-amz-date" must
104# be included in the canonical_headers and signed_headers, as noted
105# earlier. Order here is not significant.
106# Python note: The 'host' header is added automatically by the Python 'requests' library.
107headers = {'x-amz-date':amzdate, 'Authorization':authorization_header}
108
109
110# ************* SEND THE REQUEST *************
111request_url = endpoint + '?' + canonical_querystring
112
113print ('\nBEGIN REQUEST++++++++++++++++++++++++++++++++++++')
114print ('Request URL = ' + request_url)
115r = requests.get(request_url, headers=headers)
116
117print ('\nRESPONSE++++++++++++++++++++++++++++++++++++')
118print ('Response code: %d\n' % r.status_code)
119print (r.text)
120print (headers)