· 5 years ago · Mar 04, 2020, 04:16 PM
1# Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2#
3# This file is licensed under the Apache License, Version 2.0 (the "License").
4# You may not use this file except in compliance with the License. A copy of the
5# License is located at
6#
7# http://aws.amazon.com/apache2.0/
8#
9# This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
10# OF ANY KIND, either express or implied. See the License for the specific
11# language governing permissions and limitations under the License.
12#
13# ABOUT THIS PYTHON SAMPLE: This sample is part of the AWS General Reference
14# Signing AWS API Requests top available at
15# https://docs.aws.amazon.com/general/latest/gr/sigv4-signed-request-examples.html
16#
17
18# AWS Version 4 signing example
19
20# EC2 API (DescribeRegions)
21
22# See: http://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html
23# This version makes a GET request and passes the signature
24# in the Authorization header.
25import sys, os, base64, datetime, hashlib, hmac
26import requests # pip install requests
27
28# ************* REQUEST VALUES *************
29method = 'GET'
30service = 'iam'
31host = 'ec2.amazonaws.com'
32region = 'us-east-1'
33endpoint = 'https://ec2.amazonaws.com'
34request_parameters = 'Action=DescribeRegions&Version=2013-10-15'
35
36# Key derivation functions. See:
37# http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python
38def sign(key, msg):
39 return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()
40
41def getSignatureKey(key, dateStamp, regionName, serviceName):
42 kDate = sign(('AWS4' + key).encode('utf-8'), dateStamp)
43 kRegion = sign(kDate, regionName)
44 kService = sign(kRegion, serviceName)
45 kSigning = sign(kService, 'aws4_request')
46 return kSigning
47
48# Read AWS access key from env. variables or configuration file. Best practice is NOT
49# to embed credentials in code.
50access_key = 'my_access_key'
51secret_key = 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY'
52if access_key is None or secret_key is None:
53 print('No access key is available.')
54 sys.exit()
55
56# Create a date for headers and the credential string
57# t = datetime.datetime.utcnow()
58t = datetime.datetime(2015, 8, 30, 1, 2, 3)
59amzdate = t.strftime('%Y%m%dT%H%M%SZ')
60datestamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scope
61
62
63# ************* TASK 1: CREATE A CANONICAL REQUEST *************
64# http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
65
66# Step 1 is to define the verb (GET, POST, etc.)--already done.
67
68# Step 2: Create canonical URI--the part of the URI from domain to query
69# string (use '/' if no path)
70canonical_uri = '/'
71
72# Step 3: Create the canonical query string. In this example (a GET request),
73# request parameters are in the query string. Query string values must
74# be URL-encoded (space=%20). The parameters must be sorted by name.
75# For this example, the query string is pre-formatted in the request_parameters variable.
76canonical_querystring = request_parameters
77
78# Step 4: Create the canonical headers and signed headers. Header names
79# must be trimmed and lowercase, and sorted in code point order from
80# low to high. Note that there is a trailing \n.
81canonical_headers = 'host:' + host + '\n' + 'x-amz-date:' + amzdate + '\n'
82
83# Step 5: Create the list of signed headers. This lists the headers
84# in the canonical_headers list, delimited with ";" and in alpha order.
85# Note: The request can include any headers; canonical_headers and
86# signed_headers lists those that you want to be included in the
87# hash of the request. "Host" and "x-amz-date" are always required.
88signed_headers = 'host;x-amz-date'
89
90# Step 6: Create payload hash (hash of the request body content). For GET
91# requests, the payload is an empty string ("").
92payload_hash = hashlib.sha256(('').encode('utf-8')).hexdigest()
93
94# Step 7: Combine elements to create canonical request
95canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash
96
97
98# ************* TASK 2: CREATE THE STRING TO SIGN*************
99# Match the algorithm to the hashing algorithm you use, either SHA-1 or
100# SHA-256 (recommended)
101algorithm = 'AWS4-HMAC-SHA256'
102credential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request'
103string_to_sign = algorithm + '\n' + amzdate + '\n' + credential_scope + '\n' + hashlib.sha256(canonical_request.encode('utf-8')).hexdigest()
104
105# ************* TASK 3: CALCULATE THE SIGNATURE *************
106# Create the signing key using the function defined above.
107signing_key = getSignatureKey(secret_key, datestamp, region, service)
108
109# Sign the string_to_sign using the signing_key
110signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()
111
112
113# ************* TASK 4: ADD SIGNING INFORMATION TO THE REQUEST *************
114# The signing information can be either in a query string value or in
115# a header named Authorization. This code shows how to use a header.
116# Create authorization header and add to request headers
117authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature
118
119# The request can include any headers, but MUST include "host", "x-amz-date",
120# and (for this scenario) "Authorization". "host" and "x-amz-date" must
121# be included in the canonical_headers and signed_headers, as noted
122# earlier. Order here is not significant.
123# Python note: The 'host' header is added automatically by the Python 'requests' library.
124headers = {'x-amz-date':amzdate, 'Authorization':authorization_header}
125
126
127# ************* SEND THE REQUEST *************
128request_url = endpoint + '?' + canonical_querystring
129
130print('\nBEGIN REQUEST++++++++++++++++++++++++++++++++++++')
131print('Request URL = ' + request_url)
132print('headers = ', headers)
133# r = requests.get(request_url, headers=headers)
134
135# print('\nRESPONSE++++++++++++++++++++++++++++++++++++')
136# print('Response code: %d\n' % r.status_code)
137# print(r.text)
138
139
140
141
142print("----")
143
144a = sign(sign(sign(sign(b"AWS4" + secret_key.encode(),"20150830"),"us-east-1"),"iam"),"aws4_request")
145print(a)
146
147str_to_sign = '''AWS4-HMAC-SHA256
14820150830T123600Z
14920150830/us-east-1/iam/aws4_request
150f536975d06c0309214f805bb90ccff089219ecd68b2577efef23edd43b7e1a59'''
151print(sign(a, str_to_sign).hex())