|
| 1 | +import datetime |
| 2 | +import hashlib |
| 3 | +import hmac |
| 4 | +import json |
| 5 | +import string |
| 6 | + |
| 7 | +from kafka.errors import IllegalArgumentError |
| 8 | +from kafka.vendor.six.moves import urllib |
| 9 | + |
| 10 | + |
| 11 | +class AwsMskIamClient: |
| 12 | + UNRESERVED_CHARS = string.ascii_letters + string.digits + '-._~' |
| 13 | + |
| 14 | + def __init__(self, host, boto_session): |
| 15 | + """ |
| 16 | + Arguments: |
| 17 | + host (str): The hostname of the broker. |
| 18 | + boto_session (botocore.BotoSession) the boto session |
| 19 | + """ |
| 20 | + self.algorithm = 'AWS4-HMAC-SHA256' |
| 21 | + self.expires = '900' |
| 22 | + self.hashfunc = hashlib.sha256 |
| 23 | + self.headers = [ |
| 24 | + ('host', host) |
| 25 | + ] |
| 26 | + self.version = '2020_10_22' |
| 27 | + |
| 28 | + self.service = 'kafka-cluster' |
| 29 | + self.action = '{}:Connect'.format(self.service) |
| 30 | + |
| 31 | + now = datetime.datetime.utcnow() |
| 32 | + self.datestamp = now.strftime('%Y%m%d') |
| 33 | + self.timestamp = now.strftime('%Y%m%dT%H%M%SZ') |
| 34 | + |
| 35 | + self.host = host |
| 36 | + self.boto_session = boto_session |
| 37 | + |
| 38 | + # This will raise if the region can't be determined |
| 39 | + # Do this during init instead of waiting for failures downstream |
| 40 | + if self.region: |
| 41 | + pass |
| 42 | + |
| 43 | + @property |
| 44 | + def access_key(self): |
| 45 | + return self.boto_session.get_credentials().access_key |
| 46 | + |
| 47 | + @property |
| 48 | + def secret_key(self): |
| 49 | + return self.boto_session.get_credentials().secret_key |
| 50 | + |
| 51 | + @property |
| 52 | + def token(self): |
| 53 | + return self.boto_session.get_credentials().token |
| 54 | + |
| 55 | + @property |
| 56 | + def region(self): |
| 57 | + # Try to get the region information from the broker hostname |
| 58 | + for host in self.host.split(','): |
| 59 | + if 'amazonaws.com' in host: |
| 60 | + return host.split('.')[-3] |
| 61 | + |
| 62 | + # If the region can't be determined from hostname, try the boto session |
| 63 | + # This will only have a value if: |
| 64 | + # - `AWS_DEFAULT_REGION` environment variable is set |
| 65 | + # - `~/.aws/config` region variable is set |
| 66 | + region = self.boto_session.get_config_variable('region') |
| 67 | + if region: |
| 68 | + return region |
| 69 | + |
| 70 | + # Otherwise give up |
| 71 | + raise IllegalArgumentError('Could not determine region from broker host(s) or aws configuration') |
| 72 | + |
| 73 | + @property |
| 74 | + def _credential(self): |
| 75 | + return '{0.access_key}/{0._scope}'.format(self) |
| 76 | + |
| 77 | + @property |
| 78 | + def _scope(self): |
| 79 | + return '{0.datestamp}/{0.region}/{0.service}/aws4_request'.format(self) |
| 80 | + |
| 81 | + @property |
| 82 | + def _signed_headers(self): |
| 83 | + """ |
| 84 | + Returns (str): |
| 85 | + An alphabetically sorted, semicolon-delimited list of lowercase |
| 86 | + request header names. |
| 87 | + """ |
| 88 | + return ';'.join(sorted(k.lower() for k, _ in self.headers)) |
| 89 | + |
| 90 | + @property |
| 91 | + def _canonical_headers(self): |
| 92 | + """ |
| 93 | + Returns (str): |
| 94 | + A newline-delited list of header names and values. |
| 95 | + Header names are lowercased. |
| 96 | + """ |
| 97 | + return '\n'.join(map(':'.join, self.headers)) + '\n' |
| 98 | + |
| 99 | + @property |
| 100 | + def _canonical_request(self): |
| 101 | + """ |
| 102 | + Returns (str): |
| 103 | + An AWS Signature Version 4 canonical request in the format: |
| 104 | + <Method>\n |
| 105 | + <Path>\n |
| 106 | + <CanonicalQueryString>\n |
| 107 | + <CanonicalHeaders>\n |
| 108 | + <SignedHeaders>\n |
| 109 | + <HashedPayload> |
| 110 | + """ |
| 111 | + # The hashed_payload is always an empty string for MSK. |
| 112 | + hashed_payload = self.hashfunc(b'').hexdigest() |
| 113 | + return '\n'.join(( |
| 114 | + 'GET', |
| 115 | + '/', |
| 116 | + self._canonical_querystring, |
| 117 | + self._canonical_headers, |
| 118 | + self._signed_headers, |
| 119 | + hashed_payload, |
| 120 | + )) |
| 121 | + |
| 122 | + @property |
| 123 | + def _canonical_querystring(self): |
| 124 | + """ |
| 125 | + Returns (str): |
| 126 | + A '&'-separated list of URI-encoded key/value pairs. |
| 127 | + """ |
| 128 | + params = [] |
| 129 | + params.append(('Action', self.action)) |
| 130 | + params.append(('X-Amz-Algorithm', self.algorithm)) |
| 131 | + params.append(('X-Amz-Credential', self._credential)) |
| 132 | + params.append(('X-Amz-Date', self.timestamp)) |
| 133 | + params.append(('X-Amz-Expires', self.expires)) |
| 134 | + if self.token: |
| 135 | + params.append(('X-Amz-Security-Token', self.token)) |
| 136 | + params.append(('X-Amz-SignedHeaders', self._signed_headers)) |
| 137 | + |
| 138 | + return '&'.join(self._uriencode(k) + '=' + self._uriencode(v) for k, v in params) |
| 139 | + |
| 140 | + @property |
| 141 | + def _signing_key(self): |
| 142 | + """ |
| 143 | + Returns (bytes): |
| 144 | + An AWS Signature V4 signing key generated from the secret_key, date, |
| 145 | + region, service, and request type. |
| 146 | + """ |
| 147 | + key = self._hmac(('AWS4' + self.secret_key).encode('utf-8'), self.datestamp) |
| 148 | + key = self._hmac(key, self.region) |
| 149 | + key = self._hmac(key, self.service) |
| 150 | + key = self._hmac(key, 'aws4_request') |
| 151 | + return key |
| 152 | + |
| 153 | + @property |
| 154 | + def _signing_str(self): |
| 155 | + """ |
| 156 | + Returns (str): |
| 157 | + A string used to sign the AWS Signature V4 payload in the format: |
| 158 | + <Algorithm>\n |
| 159 | + <Timestamp>\n |
| 160 | + <Scope>\n |
| 161 | + <CanonicalRequestHash> |
| 162 | + """ |
| 163 | + canonical_request_hash = self.hashfunc(self._canonical_request.encode('utf-8')).hexdigest() |
| 164 | + return '\n'.join((self.algorithm, self.timestamp, self._scope, canonical_request_hash)) |
| 165 | + |
| 166 | + def _uriencode(self, msg): |
| 167 | + """ |
| 168 | + Arguments: |
| 169 | + msg (str): A string to URI-encode. |
| 170 | +
|
| 171 | + Returns (str): |
| 172 | + The URI-encoded version of the provided msg, following the encoding |
| 173 | + rules specified: https://github.com/aws/aws-msk-iam-auth#uriencode |
| 174 | + """ |
| 175 | + return urllib.parse.quote(msg, safe=self.UNRESERVED_CHARS) |
| 176 | + |
| 177 | + def _hmac(self, key, msg): |
| 178 | + """ |
| 179 | + Arguments: |
| 180 | + key (bytes): A key to use for the HMAC digest. |
| 181 | + msg (str): A value to include in the HMAC digest. |
| 182 | + Returns (bytes): |
| 183 | + An HMAC digest of the given key and msg. |
| 184 | + """ |
| 185 | + return hmac.new(key, msg.encode('utf-8'), digestmod=self.hashfunc).digest() |
| 186 | + |
| 187 | + def first_message(self): |
| 188 | + """ |
| 189 | + Returns (bytes): |
| 190 | + An encoded JSON authentication payload that can be sent to the |
| 191 | + broker. |
| 192 | + """ |
| 193 | + signature = hmac.new( |
| 194 | + self._signing_key, |
| 195 | + self._signing_str.encode('utf-8'), |
| 196 | + digestmod=self.hashfunc, |
| 197 | + ).hexdigest() |
| 198 | + msg = { |
| 199 | + 'version': self.version, |
| 200 | + 'host': self.host, |
| 201 | + 'user-agent': 'kafka-python', |
| 202 | + 'action': self.action, |
| 203 | + 'x-amz-algorithm': self.algorithm, |
| 204 | + 'x-amz-credential': self._credential, |
| 205 | + 'x-amz-date': self.timestamp, |
| 206 | + 'x-amz-signedheaders': self._signed_headers, |
| 207 | + 'x-amz-expires': self.expires, |
| 208 | + 'x-amz-signature': signature, |
| 209 | + } |
| 210 | + if self.token: |
| 211 | + msg['x-amz-security-token'] = self.token |
| 212 | + |
| 213 | + return json.dumps(msg, separators=(',', ':')).encode('utf-8') |
0 commit comments