|
| 1 | +import os, boto3, json |
| 2 | +import urllib.request, urllib.parse |
| 3 | +from urllib.error import HTTPError |
| 4 | +import logging |
| 5 | + |
| 6 | +from botocore.exceptions import ClientError |
| 7 | + |
| 8 | +client = boto3.client('ecr') |
| 9 | +logger = logging.getLogger() |
| 10 | + |
| 11 | + |
| 12 | +def get_all_image_data(repository): |
| 13 | + """ |
| 14 | + Gets a list of dicts with Image tags and latest scan results. |
| 15 | +
|
| 16 | + :param repository: |
| 17 | + :return: [{'imageTags': ['1.0.70'], 'imageScanStatus': {'HIGH': 21, 'MEDIUM': 127, 'INFORMATIONAL': 115, }}] |
| 18 | + """ |
| 19 | + images = [] |
| 20 | + levels = os.environ['RISK_LEVELS'] |
| 21 | + |
| 22 | + try: |
| 23 | + response = client.describe_images(repositoryName=repository, filter={ |
| 24 | + 'tagStatus': 'TAGGED' |
| 25 | + })['imageDetails'] |
| 26 | + except ClientError as c: |
| 27 | + logger.error("Failed to get result from describe images with, client error: {}".format(c)) |
| 28 | + return [] |
| 29 | + |
| 30 | + for image in response: |
| 31 | + image_data = {} |
| 32 | + try: |
| 33 | + image_data['imageTags'] = image['imageTags'] |
| 34 | + except KeyError: |
| 35 | + image_data['imageTags'] = 'IMAGE UNTAGGED' |
| 36 | + try: |
| 37 | + image_data['imageScanStatus'] = image['imageScanFindingsSummary']['findingSeverityCounts'] |
| 38 | + except KeyError: |
| 39 | + logger.error('FAILED TO RETRIEVE LATEST SCAN STATUS for image {}'.format(image_data['imageTags'])) |
| 40 | + continue |
| 41 | + |
| 42 | + if len(levels) > 0: |
| 43 | + image_data['imageScanStatus'] = {key: value for key, value in image_data['imageScanStatus'].items() if key in levels} |
| 44 | + |
| 45 | + if len(image_data['imageScanStatus']) > 0: |
| 46 | + images.append(image_data) |
| 47 | + |
| 48 | + return images |
| 49 | + |
| 50 | + |
| 51 | +def get_all_repositories(): |
| 52 | + """ |
| 53 | + Gets a list of ECR repository string names. |
| 54 | + :return: ['repository1', 'repository2', 'repository3'] |
| 55 | + """ |
| 56 | + repositories = [] |
| 57 | + response = client.describe_repositories()['repositories'] |
| 58 | + for repository in response: |
| 59 | + repositories.append(repository['repositoryName']) |
| 60 | + return repositories |
| 61 | + |
| 62 | + |
| 63 | +def get_scan_results(): |
| 64 | + repositories = get_all_repositories() |
| 65 | + all_images = {} |
| 66 | + for repository in repositories: |
| 67 | + all_images[repository] = get_all_image_data(repository) |
| 68 | + return all_images |
| 69 | + |
| 70 | + |
| 71 | +def convert_scan_dict_to_string(scan_dict): |
| 72 | + """ |
| 73 | + converts parsed ImageScanStatus dictionary to string. |
| 74 | + :param scan_dict: {'HIGH': 64, 'MEDIUM': 269, 'INFORMATIONAL': 157, 'LOW': 127, 'CRITICAL': 17, 'UNDEFINED': 6} |
| 75 | + :return: HIGH 64, MEDIUM 269, INFORMATIONAL 157, LOW 127, CRITICAL 17, UNDEFINED 6 |
| 76 | + """ |
| 77 | + result = '' |
| 78 | + |
| 79 | + if not scan_dict: |
| 80 | + return result |
| 81 | + try: |
| 82 | + for key, value in scan_dict.items(): |
| 83 | + result = result + key + " " + str(value) + ", " |
| 84 | + except AttributeError: |
| 85 | + return "Failed to retrieve repository scan results" |
| 86 | + |
| 87 | + return result[:len(result)-2] |
| 88 | + |
| 89 | + |
| 90 | +def convert_image_scan_status(repository_scan_results): |
| 91 | + repository_scan_block_list = [] |
| 92 | + for image in sorted(repository_scan_results, key=lambda imageScanResult: imageScanResult['imageTags'][0], |
| 93 | + reverse=True): |
| 94 | + image_block = dict() |
| 95 | + image_block["image"] = image['imageTags'][0] |
| 96 | + image_block["vulnerabilities"] = convert_scan_dict_to_string((image['imageScanStatus'])) |
| 97 | + repository_scan_block_list.append(image_block) |
| 98 | + return repository_scan_block_list |
| 99 | + |
| 100 | + |
| 101 | +def create_image_scan_slack_block(repository, repository_scan_block_list): |
| 102 | + |
| 103 | + blocks = [] |
| 104 | + |
| 105 | + # Generate slack messages for image scan results. |
| 106 | + for image in repository_scan_block_list: |
| 107 | + blocks.append( |
| 108 | + { |
| 109 | + "type": "section", |
| 110 | + "text": { |
| 111 | + "type": "mrkdwn", |
| 112 | + "text": "*`{}:{}`* vulnerabilities: {}".format(repository, image['image'], image['vulnerabilities']) |
| 113 | + } |
| 114 | + } |
| 115 | + ) |
| 116 | + return blocks |
| 117 | + |
| 118 | + |
| 119 | +# Send a message to a slack channel |
| 120 | +def notify_slack(slack_block): |
| 121 | + slack_url = os.environ['SLACK_WEBHOOK_URL'] |
| 122 | + slack_channel = os.environ['SLACK_CHANNEL'] |
| 123 | + slack_username = os.environ['SLACK_USERNAME'] |
| 124 | + slack_emoji = os.environ['SLACK_EMOJI'] |
| 125 | + |
| 126 | + payload = { |
| 127 | + "channel": slack_channel, |
| 128 | + "username": slack_username, |
| 129 | + "icon_emoji": slack_emoji, |
| 130 | + "blocks": slack_block |
| 131 | + } |
| 132 | + |
| 133 | + data = urllib.parse.urlencode({"payload": json.dumps(payload)}).encode("utf-8") |
| 134 | + req = urllib.request.Request(slack_url) |
| 135 | + |
| 136 | + try: |
| 137 | + result = urllib.request.urlopen(req, data) |
| 138 | + return json.dumps({"code": result.getcode(), "info": result.info().as_string()}) |
| 139 | + |
| 140 | + except HTTPError as e: |
| 141 | + logging.error("{}: result".format(e)) |
| 142 | + return json.dumps({"code": e.getcode(), "info": e.info().as_string()}) |
| 143 | + |
| 144 | + |
| 145 | +def lambda_handler(event, context): |
| 146 | + |
| 147 | + scan_results = get_scan_results() |
| 148 | + |
| 149 | + for repository, values in scan_results.items(): |
| 150 | + if len(values) > 0: |
| 151 | + repository_scan_results = convert_image_scan_status(values) |
| 152 | + slack_block = create_image_scan_slack_block(repository, repository_scan_results) |
| 153 | + else: |
| 154 | + continue |
| 155 | + |
| 156 | + if len(slack_block) > 0: |
| 157 | + try: |
| 158 | + response = notify_slack(slack_block=slack_block) |
| 159 | + if json.loads(response)["code"] != 200: |
| 160 | + logger.error("Error: received status {} for slack_block {}".format(json.loads(response)["info"], slack_block)) |
| 161 | + except Exception as e: |
| 162 | + logger.error(msg=e) |
0 commit comments