0eeb87
From f6dc3cf39a4884657478a47894ce8a76ec9a72c5 Mon Sep 17 00:00:00 2001
0eeb87
From: Eduardo Otubo <otubo@redhat.com>
0eeb87
Date: Wed, 24 Jun 2020 07:34:29 +0200
0eeb87
Subject: [PATCH 1/4] ec2: Do not log IMDSv2 token values, instead use REDACTED
0eeb87
 (#219)
0eeb87
0eeb87
RH-Author: Eduardo Otubo <otubo@redhat.com>
0eeb87
Message-id: <20200505082940.18316-1-otubo@redhat.com>
0eeb87
Patchwork-id: 96264
0eeb87
O-Subject: [RHEL-7.9/RHEL-8.3 cloud-init PATCH] ec2: Do not log IMDSv2 token values, instead use REDACTED (#219)
0eeb87
Bugzilla: 1822343
0eeb87
RH-Acked-by: Cathy Avery <cavery@redhat.com>
0eeb87
RH-Acked-by: Mohammed Gamal <mgamal@redhat.com>
0eeb87
RH-Acked-by: Vitaly Kuznetsov <vkuznets@redhat.com>
0eeb87
0eeb87
Note: There's no RHEL-8.3/cloud-init-19.4 branch yet, but it should be
0eeb87
queued to be applied on top of it when it's created.
0eeb87
0eeb87
commit 87cd040ed8fe7195cbb357ed3bbf53cd2a81436c
0eeb87
Author: Ryan Harper <ryan.harper@canonical.com>
0eeb87
Date:   Wed Feb 19 15:01:09 2020 -0600
0eeb87
0eeb87
    ec2: Do not log IMDSv2 token values, instead use REDACTED (#219)
0eeb87
0eeb87
    Instead of logging the token values used log the headers and replace the actual
0eeb87
    values with the string 'REDACTED'.  This allows users to examine cloud-init.log
0eeb87
    and see that the IMDSv2 token header is being used but avoids leaving the value
0eeb87
    used in the log file itself.
0eeb87
0eeb87
    LP: #1863943
0eeb87
0eeb87
Signed-off-by: Eduardo Otubo <otubo@redhat.com>
0eeb87
Signed-off-by: Miroslav Rezanina <mrezanin@redhat.com>
0eeb87
---
0eeb87
 cloudinit/ec2_utils.py                      | 12 ++++++++--
0eeb87
 cloudinit/sources/DataSourceEc2.py          | 35 +++++++++++++++++++----------
0eeb87
 cloudinit/url_helper.py                     | 27 ++++++++++++++++------
0eeb87
 tests/unittests/test_datasource/test_ec2.py | 17 ++++++++++++++
0eeb87
 4 files changed, 70 insertions(+), 21 deletions(-)
0eeb87
0eeb87
diff --git a/cloudinit/ec2_utils.py b/cloudinit/ec2_utils.py
0eeb87
index 57708c1..34acfe8 100644
0eeb87
--- a/cloudinit/ec2_utils.py
0eeb87
+++ b/cloudinit/ec2_utils.py
0eeb87
@@ -142,7 +142,8 @@ def skip_retry_on_codes(status_codes, _request_args, cause):
0eeb87
 def get_instance_userdata(api_version='latest',
0eeb87
                           metadata_address='http://169.254.169.254',
0eeb87
                           ssl_details=None, timeout=5, retries=5,
0eeb87
-                          headers_cb=None, exception_cb=None):
0eeb87
+                          headers_cb=None, headers_redact=None,
0eeb87
+                          exception_cb=None):
0eeb87
     ud_url = url_helper.combine_url(metadata_address, api_version)
0eeb87
     ud_url = url_helper.combine_url(ud_url, 'user-data')
0eeb87
     user_data = ''
0eeb87
@@ -155,7 +156,8 @@ def get_instance_userdata(api_version='latest',
0eeb87
                                              SKIP_USERDATA_CODES)
0eeb87
         response = url_helper.read_file_or_url(
0eeb87
             ud_url, ssl_details=ssl_details, timeout=timeout,
0eeb87
-            retries=retries, exception_cb=exception_cb, headers_cb=headers_cb)
0eeb87
+            retries=retries, exception_cb=exception_cb, headers_cb=headers_cb,
0eeb87
+            headers_redact=headers_redact)
0eeb87
         user_data = response.contents
0eeb87
     except url_helper.UrlError as e:
0eeb87
         if e.code not in SKIP_USERDATA_CODES:
0eeb87
@@ -169,11 +171,13 @@ def _get_instance_metadata(tree, api_version='latest',
0eeb87
                            metadata_address='http://169.254.169.254',
0eeb87
                            ssl_details=None, timeout=5, retries=5,
0eeb87
                            leaf_decoder=None, headers_cb=None,
0eeb87
+                           headers_redact=None,
0eeb87
                            exception_cb=None):
0eeb87
     md_url = url_helper.combine_url(metadata_address, api_version, tree)
0eeb87
     caller = functools.partial(
0eeb87
         url_helper.read_file_or_url, ssl_details=ssl_details,
0eeb87
         timeout=timeout, retries=retries, headers_cb=headers_cb,
0eeb87
+        headers_redact=headers_redact,
0eeb87
         exception_cb=exception_cb)
0eeb87
 
0eeb87
     def mcaller(url):
0eeb87
@@ -197,6 +201,7 @@ def get_instance_metadata(api_version='latest',
0eeb87
                           metadata_address='http://169.254.169.254',
0eeb87
                           ssl_details=None, timeout=5, retries=5,
0eeb87
                           leaf_decoder=None, headers_cb=None,
0eeb87
+                          headers_redact=None,
0eeb87
                           exception_cb=None):
0eeb87
     # Note, 'meta-data' explicitly has trailing /.
0eeb87
     # this is required for CloudStack (LP: #1356855)
0eeb87
@@ -204,6 +209,7 @@ def get_instance_metadata(api_version='latest',
0eeb87
                                   metadata_address=metadata_address,
0eeb87
                                   ssl_details=ssl_details, timeout=timeout,
0eeb87
                                   retries=retries, leaf_decoder=leaf_decoder,
0eeb87
+                                  headers_redact=headers_redact,
0eeb87
                                   headers_cb=headers_cb,
0eeb87
                                   exception_cb=exception_cb)
0eeb87
 
0eeb87
@@ -212,12 +218,14 @@ def get_instance_identity(api_version='latest',
0eeb87
                           metadata_address='http://169.254.169.254',
0eeb87
                           ssl_details=None, timeout=5, retries=5,
0eeb87
                           leaf_decoder=None, headers_cb=None,
0eeb87
+                          headers_redact=None,
0eeb87
                           exception_cb=None):
0eeb87
     return _get_instance_metadata(tree='dynamic/instance-identity',
0eeb87
                                   api_version=api_version,
0eeb87
                                   metadata_address=metadata_address,
0eeb87
                                   ssl_details=ssl_details, timeout=timeout,
0eeb87
                                   retries=retries, leaf_decoder=leaf_decoder,
0eeb87
+                                  headers_redact=headers_redact,
0eeb87
                                   headers_cb=headers_cb,
0eeb87
                                   exception_cb=exception_cb)
0eeb87
 # vi: ts=4 expandtab
0eeb87
diff --git a/cloudinit/sources/DataSourceEc2.py b/cloudinit/sources/DataSourceEc2.py
0eeb87
index b9f346a..0f2bfef 100644
0eeb87
--- a/cloudinit/sources/DataSourceEc2.py
0eeb87
+++ b/cloudinit/sources/DataSourceEc2.py
0eeb87
@@ -31,6 +31,9 @@ STRICT_ID_DEFAULT = "warn"
0eeb87
 API_TOKEN_ROUTE = 'latest/api/token'
0eeb87
 API_TOKEN_DISABLED = '_ec2_disable_api_token'
0eeb87
 AWS_TOKEN_TTL_SECONDS = '21600'
0eeb87
+AWS_TOKEN_PUT_HEADER = 'X-aws-ec2-metadata-token'
0eeb87
+AWS_TOKEN_REQ_HEADER = AWS_TOKEN_PUT_HEADER + '-ttl-seconds'
0eeb87
+AWS_TOKEN_REDACT = [AWS_TOKEN_PUT_HEADER, AWS_TOKEN_REQ_HEADER]
0eeb87
 
0eeb87
 
0eeb87
 class CloudNames(object):
0eeb87
@@ -158,7 +161,8 @@ class DataSourceEc2(sources.DataSource):
0eeb87
         for api_ver in self.extended_metadata_versions:
0eeb87
             url = url_tmpl.format(self.metadata_address, api_ver)
0eeb87
             try:
0eeb87
-                resp = uhelp.readurl(url=url, headers=headers)
0eeb87
+                resp = uhelp.readurl(url=url, headers=headers,
0eeb87
+                                     headers_redact=AWS_TOKEN_REDACT)
0eeb87
             except uhelp.UrlError as e:
0eeb87
                 LOG.debug('url %s raised exception %s', url, e)
0eeb87
             else:
0eeb87
@@ -180,6 +184,7 @@ class DataSourceEc2(sources.DataSource):
0eeb87
                 self.identity = ec2.get_instance_identity(
0eeb87
                     api_version, self.metadata_address,
0eeb87
                     headers_cb=self._get_headers,
0eeb87
+                    headers_redact=AWS_TOKEN_REDACT,
0eeb87
                     exception_cb=self._refresh_stale_aws_token_cb).get(
0eeb87
                         'document', {})
0eeb87
             return self.identity.get(
0eeb87
@@ -205,7 +210,8 @@ class DataSourceEc2(sources.DataSource):
0eeb87
         LOG.debug('Fetching Ec2 IMDSv2 API Token')
0eeb87
         url, response = uhelp.wait_for_url(
0eeb87
             urls=urls, max_wait=1, timeout=1, status_cb=self._status_cb,
0eeb87
-            headers_cb=self._get_headers, request_method=request_method)
0eeb87
+            headers_cb=self._get_headers, request_method=request_method,
0eeb87
+            headers_redact=AWS_TOKEN_REDACT)
0eeb87
 
0eeb87
         if url and response:
0eeb87
             self._api_token = response
0eeb87
@@ -252,7 +258,8 @@ class DataSourceEc2(sources.DataSource):
0eeb87
             url, _ = uhelp.wait_for_url(
0eeb87
                 urls=urls, max_wait=url_params.max_wait_seconds,
0eeb87
                 timeout=url_params.timeout_seconds, status_cb=LOG.warning,
0eeb87
-                headers_cb=self._get_headers, request_method=request_method)
0eeb87
+                headers_redact=AWS_TOKEN_REDACT, headers_cb=self._get_headers,
0eeb87
+                request_method=request_method)
0eeb87
 
0eeb87
             if url:
0eeb87
                 metadata_address = url2base[url]
0eeb87
@@ -420,6 +427,7 @@ class DataSourceEc2(sources.DataSource):
0eeb87
         if not self.wait_for_metadata_service():
0eeb87
             return {}
0eeb87
         api_version = self.get_metadata_api_version()
0eeb87
+        redact = AWS_TOKEN_REDACT
0eeb87
         crawled_metadata = {}
0eeb87
         if self.cloud_name == CloudNames.AWS:
0eeb87
             exc_cb = self._refresh_stale_aws_token_cb
0eeb87
@@ -429,14 +437,17 @@ class DataSourceEc2(sources.DataSource):
0eeb87
         try:
0eeb87
             crawled_metadata['user-data'] = ec2.get_instance_userdata(
0eeb87
                 api_version, self.metadata_address,
0eeb87
-                headers_cb=self._get_headers, exception_cb=exc_cb_ud)
0eeb87
+                headers_cb=self._get_headers, headers_redact=redact,
0eeb87
+                exception_cb=exc_cb_ud)
0eeb87
             crawled_metadata['meta-data'] = ec2.get_instance_metadata(
0eeb87
                 api_version, self.metadata_address,
0eeb87
-                headers_cb=self._get_headers, exception_cb=exc_cb)
0eeb87
+                headers_cb=self._get_headers, headers_redact=redact,
0eeb87
+                exception_cb=exc_cb)
0eeb87
             if self.cloud_name == CloudNames.AWS:
0eeb87
                 identity = ec2.get_instance_identity(
0eeb87
                     api_version, self.metadata_address,
0eeb87
-                    headers_cb=self._get_headers, exception_cb=exc_cb)
0eeb87
+                    headers_cb=self._get_headers, headers_redact=redact,
0eeb87
+                    exception_cb=exc_cb)
0eeb87
                 crawled_metadata['dynamic'] = {'instance-identity': identity}
0eeb87
         except Exception:
0eeb87
             util.logexc(
0eeb87
@@ -455,11 +466,12 @@ class DataSourceEc2(sources.DataSource):
0eeb87
         if self.cloud_name != CloudNames.AWS:
0eeb87
             return None
0eeb87
         LOG.debug("Refreshing Ec2 metadata API token")
0eeb87
-        request_header = {'X-aws-ec2-metadata-token-ttl-seconds': seconds}
0eeb87
+        request_header = {AWS_TOKEN_REQ_HEADER: seconds}
0eeb87
         token_url = '{}/{}'.format(self.metadata_address, API_TOKEN_ROUTE)
0eeb87
         try:
0eeb87
-            response = uhelp.readurl(
0eeb87
-                token_url, headers=request_header, request_method="PUT")
0eeb87
+            response = uhelp.readurl(token_url, headers=request_header,
0eeb87
+                                     headers_redact=AWS_TOKEN_REDACT,
0eeb87
+                                     request_method="PUT")
0eeb87
         except uhelp.UrlError as e:
0eeb87
             LOG.warning(
0eeb87
                 'Unable to get API token: %s raised exception %s',
0eeb87
@@ -500,8 +512,7 @@ class DataSourceEc2(sources.DataSource):
0eeb87
                                                  API_TOKEN_DISABLED):
0eeb87
             return {}
0eeb87
         # Request a 6 hour token if URL is API_TOKEN_ROUTE
0eeb87
-        request_token_header = {
0eeb87
-            'X-aws-ec2-metadata-token-ttl-seconds': AWS_TOKEN_TTL_SECONDS}
0eeb87
+        request_token_header = {AWS_TOKEN_REQ_HEADER: AWS_TOKEN_TTL_SECONDS}
0eeb87
         if API_TOKEN_ROUTE in url:
0eeb87
             return request_token_header
0eeb87
         if not self._api_token:
0eeb87
@@ -511,7 +522,7 @@ class DataSourceEc2(sources.DataSource):
0eeb87
             self._api_token = self._refresh_api_token()
0eeb87
             if not self._api_token:
0eeb87
                 return {}
0eeb87
-        return {'X-aws-ec2-metadata-token': self._api_token}
0eeb87
+        return {AWS_TOKEN_PUT_HEADER: self._api_token}
0eeb87
 
0eeb87
 
0eeb87
 class DataSourceEc2Local(DataSourceEc2):
0eeb87
diff --git a/cloudinit/url_helper.py b/cloudinit/url_helper.py
0eeb87
index 1496a47..3e7de9f 100644
0eeb87
--- a/cloudinit/url_helper.py
0eeb87
+++ b/cloudinit/url_helper.py
0eeb87
@@ -8,6 +8,7 @@
0eeb87
 #
0eeb87
 # This file is part of cloud-init. See LICENSE file for license information.
0eeb87
 
0eeb87
+import copy
0eeb87
 import json
0eeb87
 import os
0eeb87
 import requests
0eeb87
@@ -41,6 +42,7 @@ else:
0eeb87
 SSL_ENABLED = False
0eeb87
 CONFIG_ENABLED = False  # This was added in 0.7 (but taken out in >=1.0)
0eeb87
 _REQ_VER = None
0eeb87
+REDACTED = 'REDACTED'
0eeb87
 try:
0eeb87
     from distutils.version import LooseVersion
0eeb87
     import pkg_resources
0eeb87
@@ -199,9 +201,9 @@ def _get_ssl_args(url, ssl_details):
0eeb87
 
0eeb87
 
0eeb87
 def readurl(url, data=None, timeout=None, retries=0, sec_between=1,
0eeb87
-            headers=None, headers_cb=None, ssl_details=None,
0eeb87
-            check_status=True, allow_redirects=True, exception_cb=None,
0eeb87
-            session=None, infinite=False, log_req_resp=True,
0eeb87
+            headers=None, headers_cb=None, headers_redact=None,
0eeb87
+            ssl_details=None, check_status=True, allow_redirects=True,
0eeb87
+            exception_cb=None, session=None, infinite=False, log_req_resp=True,
0eeb87
             request_method=None):
0eeb87
     """Wrapper around requests.Session to read the url and retry if necessary
0eeb87
 
0eeb87
@@ -217,6 +219,7 @@ def readurl(url, data=None, timeout=None, retries=0, sec_between=1,
0eeb87
     :param headers: Optional dict of headers to send during request
0eeb87
     :param headers_cb: Optional callable returning a dict of values to send as
0eeb87
         headers during request
0eeb87
+    :param headers_redact: Optional list of header names to redact from the log
0eeb87
     :param ssl_details: Optional dict providing key_file, ca_certs, and
0eeb87
         cert_file keys for use on in ssl connections.
0eeb87
     :param check_status: Optional boolean set True to raise when HTTPError
0eeb87
@@ -243,6 +246,8 @@ def readurl(url, data=None, timeout=None, retries=0, sec_between=1,
0eeb87
     req_args['method'] = request_method
0eeb87
     if timeout is not None:
0eeb87
         req_args['timeout'] = max(float(timeout), 0)
0eeb87
+    if headers_redact is None:
0eeb87
+        headers_redact = []
0eeb87
     # It doesn't seem like config
0eeb87
     # was added in older library versions (or newer ones either), thus we
0eeb87
     # need to manually do the retries if it wasn't...
0eeb87
@@ -287,6 +292,12 @@ def readurl(url, data=None, timeout=None, retries=0, sec_between=1,
0eeb87
             if k == 'data':
0eeb87
                 continue
0eeb87
             filtered_req_args[k] = v
0eeb87
+            if k == 'headers':
0eeb87
+                for hkey, _hval in v.items():
0eeb87
+                    if hkey in headers_redact:
0eeb87
+                        filtered_req_args[k][hkey] = (
0eeb87
+                            copy.deepcopy(req_args[k][hkey]))
0eeb87
+                        filtered_req_args[k][hkey] = REDACTED
0eeb87
         try:
0eeb87
 
0eeb87
             if log_req_resp:
0eeb87
@@ -339,8 +350,8 @@ def readurl(url, data=None, timeout=None, retries=0, sec_between=1,
0eeb87
     return None  # Should throw before this...
0eeb87
 
0eeb87
 
0eeb87
-def wait_for_url(urls, max_wait=None, timeout=None,
0eeb87
-                 status_cb=None, headers_cb=None, sleep_time=1,
0eeb87
+def wait_for_url(urls, max_wait=None, timeout=None, status_cb=None,
0eeb87
+                 headers_cb=None, headers_redact=None, sleep_time=1,
0eeb87
                  exception_cb=None, sleep_time_cb=None, request_method=None):
0eeb87
     """
0eeb87
     urls:      a list of urls to try
0eeb87
@@ -352,6 +363,7 @@ def wait_for_url(urls, max_wait=None, timeout=None,
0eeb87
     status_cb: call method with string message when a url is not available
0eeb87
     headers_cb: call method with single argument of url to get headers
0eeb87
                 for request.
0eeb87
+    headers_redact: a list of header names to redact from the log
0eeb87
     exception_cb: call method with 2 arguments 'msg' (per status_cb) and
0eeb87
                   'exception', the exception that occurred.
0eeb87
     sleep_time_cb: call method with 2 arguments (response, loop_n) that
0eeb87
@@ -415,8 +427,9 @@ def wait_for_url(urls, max_wait=None, timeout=None,
0eeb87
                     headers = {}
0eeb87
 
0eeb87
                 response = readurl(
0eeb87
-                    url, headers=headers, timeout=timeout,
0eeb87
-                    check_status=False, request_method=request_method)
0eeb87
+                    url, headers=headers, headers_redact=headers_redact,
0eeb87
+                    timeout=timeout, check_status=False,
0eeb87
+                    request_method=request_method)
0eeb87
                 if not response.contents:
0eeb87
                     reason = "empty response [%s]" % (response.code)
0eeb87
                     url_exc = UrlError(ValueError(reason), code=response.code,
0eeb87
diff --git a/tests/unittests/test_datasource/test_ec2.py b/tests/unittests/test_datasource/test_ec2.py
0eeb87
index 34a089f..bd5bd4c 100644
0eeb87
--- a/tests/unittests/test_datasource/test_ec2.py
0eeb87
+++ b/tests/unittests/test_datasource/test_ec2.py
0eeb87
@@ -429,6 +429,23 @@ class TestEc2(test_helpers.HttprettyTestCase):
0eeb87
         self.assertTrue(ds.get_data())
0eeb87
         self.assertFalse(ds.is_classic_instance())
0eeb87
 
0eeb87
+    def test_aws_token_redacted(self):
0eeb87
+        """Verify that aws tokens are redacted when logged."""
0eeb87
+        ds = self._setup_ds(
0eeb87
+            platform_data=self.valid_platform_data,
0eeb87
+            sys_cfg={'datasource': {'Ec2': {'strict_id': False}}},
0eeb87
+            md={'md': DEFAULT_METADATA})
0eeb87
+        self.assertTrue(ds.get_data())
0eeb87
+        all_logs = self.logs.getvalue().splitlines()
0eeb87
+        REDACT_TTL = "'X-aws-ec2-metadata-token-ttl-seconds': 'REDACTED'"
0eeb87
+        REDACT_TOK = "'X-aws-ec2-metadata-token': 'REDACTED'"
0eeb87
+        logs_with_redacted_ttl = [log for log in all_logs if REDACT_TTL in log]
0eeb87
+        logs_with_redacted = [log for log in all_logs if REDACT_TOK in log]
0eeb87
+        logs_with_token = [log for log in all_logs if 'API-TOKEN' in log]
0eeb87
+        self.assertEqual(1, len(logs_with_redacted_ttl))
0eeb87
+        self.assertEqual(79, len(logs_with_redacted))
0eeb87
+        self.assertEqual(0, len(logs_with_token))
0eeb87
+
0eeb87
     @mock.patch('cloudinit.net.dhcp.maybe_perform_dhcp_discovery')
0eeb87
     def test_valid_platform_with_strict_true(self, m_dhcp):
0eeb87
         """Valid platform data should return true with strict_id true."""
0eeb87
-- 
0eeb87
1.8.3.1
0eeb87