├── docs ├── images │ ├── image.png │ └── image2.png └── usage.md ├── lib ├── constants.py ├── rule_engine.py ├── metadata.py ├── rules.py ├── utils.py ├── handler.py └── fetch.py ├── trailshark-profile ├── dfilter_buttons ├── preferences └── colorfilters ├── install-plugin.sh ├── readme.md ├── .gitignore ├── aws └── template.yaml ├── trailshark-capture.py ├── trailshark-plugin ├── json.lua └── cloudtrail-formatter.lua └── LICENSE /docs/images/image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Aqua-Nautilus/TrailShark/HEAD/docs/images/image.png -------------------------------------------------------------------------------- /docs/images/image2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Aqua-Nautilus/TrailShark/HEAD/docs/images/image2.png -------------------------------------------------------------------------------- /lib/constants.py: -------------------------------------------------------------------------------- 1 | STOP_TRAIL = True 2 | EXTCAP_VERSION = '0.1.0' 3 | DLT_USER1 = 148 4 | DEFAULT_REGION = 'eu-west-1' 5 | DEFAULT_METHOD = 's3' 6 | DEFAULT_INTERVAL = 10 7 | DEFAULT_PROFILE= 'default' -------------------------------------------------------------------------------- /trailshark-profile/dfilter_buttons: -------------------------------------------------------------------------------- 1 | # This file is automatically generated, DO NOT MODIFY. 2 | "TRUE","Made By Recorder","(cloudtrail.madeByRecorder == \x221\x22)","" 3 | "TRUE","Derivative Event","(cloudtrail.derivativeEvent == \x221\x22)","" 4 | -------------------------------------------------------------------------------- /trailshark-profile/preferences: -------------------------------------------------------------------------------- 1 | gui.column.format: 2 | "Time", "%t", 3 | "Source", "%Cus:cloudtrail.sourceIPAddress:0:R", 4 | "Event Name", "%Cus:cloudtrail.eventName:0:R", 5 | "Region", "%Cus:cloudtrail.awsRegion:0:R", 6 | "Destination", "%Cus:cloudtrail.eventSource:0:R", 7 | "User Agent", "%Cus:cloudtrail.userAgent:0:R" 8 | -------------------------------------------------------------------------------- /docs/usage.md: -------------------------------------------------------------------------------- 1 | ## Usage 2 | Run Wireshark & Configure aws credentials 3 | ![alt text](images/image.png) 4 | 5 | If you have SSO login to yours account just use, 6 | ```bash 7 | aws configure sso 8 | ``` 9 | 10 | You can also use for defualt user, 11 | ```bash 12 | aws configure 13 | ``` 14 | ## Configurations 15 | By default, the tool stops and starts the trail it creates. If you want it to be always on, change `lib/constants.py`. 16 | 17 | ## Custom Filters 18 | ![alt text](images/image2.png) 19 | 20 | ### Made By Recorder 21 | We created a custom filter based on the role you use to record. Using this, you are able to view only the events made by your role. 22 | 23 | ### Derivative Event 24 | Using this filter, you can view events that were triggered by AWS in response to other events or due to running services. -------------------------------------------------------------------------------- /lib/rule_engine.py: -------------------------------------------------------------------------------- 1 | # lib/rule_engine.py 2 | 3 | from typing import Dict, Any, List 4 | from lib.rules import enrichment_rules, custom_event_rules 5 | from lib.metadata import AwsMetadata 6 | 7 | class RuleEngine: 8 | def __init__(self, metadata: AwsMetadata): 9 | self.metadata = metadata 10 | 11 | def enrich_event(self, event: Dict[str, Any]): 12 | """Apply enrichment rules to the event.""" 13 | for rule_func in enrichment_rules: 14 | rule_func(event, self.metadata) 15 | 16 | def generate_custom_events(self, event: Dict[str, Any]) -> List[Dict[str, Any]]: 17 | """Generate custom events based on the event.""" 18 | custom_events = [] 19 | for rule_func in custom_event_rules: 20 | custom_event = rule_func(event, self.metadata) 21 | if custom_event: 22 | custom_events.append(custom_event) 23 | return custom_events -------------------------------------------------------------------------------- /install-plugin.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Copy the Python extcap interface to the Wireshark extcap directory 4 | cp trailshark-capture.py ~/.local/lib/wireshark/extcap/ 5 | 6 | # Copy the entire 'lib' directory, preserving attributes, to the Wireshark extcap lib directory 7 | cp -rf lib/* ~/.local/lib/wireshark/extcap/lib/ 8 | 9 | # Set read, write, and execute permissions recursively for the extcap lib directory 10 | chmod -R +x ~/.local/lib/wireshark/extcap/lib 11 | 12 | # Make the trailshark-capture.py script executable 13 | chmod +x ~/.local/lib/wireshark/extcap/trailshark-capture.py 14 | 15 | # Copy all Lua scripts to the Wireshark plugins directory 16 | cp trailshark-plugin/*.lua ~/.local/lib/wireshark/plugins/ 17 | 18 | # Create the Wireshark profiles directory if it does not exist 19 | mkdir -p ~/.config/wireshark/profiles 20 | 21 | # Copy the trailshark-profile directory to the Wireshark profiles directory 22 | cp -r trailshark-profile ~/.config/wireshark/profiles/ 23 | -------------------------------------------------------------------------------- /lib/metadata.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | class AwsMetadata: 4 | def __init__(self): 5 | self.s3_client = boto3.client('s3') 6 | self.sts_client = boto3.client('sts') 7 | self.buckets = self.get_buckets() 8 | self.username = self.get_username() 9 | self.account_id = self.get_account_id() 10 | 11 | def get_buckets(self): 12 | """Retrieve and return a list of bucket names.""" 13 | response = self.s3_client.list_buckets() 14 | buckets = [bucket['Name'] for bucket in response['Buckets']] 15 | return buckets 16 | 17 | def get_username(self): 18 | """Retrieve and return the AWS user ARN.""" 19 | try: 20 | identity = self.sts_client.get_caller_identity() 21 | return identity['Arn'] 22 | except Exception as e: 23 | print(f"Error fetching user ARN: {e}") 24 | exit() 25 | 26 | def get_account_id(self): 27 | """Retrieve and return the AWS account ID.""" 28 | try: 29 | identity = self.sts_client.get_caller_identity() 30 | return identity['Account'] 31 | except Exception as e: 32 | print(f"Error fetching account ID: {e}") 33 | exit() -------------------------------------------------------------------------------- /trailshark-profile/colorfilters: -------------------------------------------------------------------------------- 1 | # DO NOT EDIT THIS FILE! 2 | # This file was created by Wireshark 3 | 4 | # Operations by Amazon Services 5 | @ERRORS (DARK_RED)@(cloudtrail.errorCode)@[65535, 65535, 65535][65535, 10000, 10000] 6 | 7 | # Get Events - Retrieval Operations 8 | @Get Event (BLUE)@cloudtrail.eventName matches "^Get"@[45000, 55000, 60000][1000, 5000, 15000] 9 | @Batch Event (BLUE)@cloudtrail.eventName matches "^Batch"@[45000, 55000, 60000][1000, 5000, 15000] 10 | 11 | # Create Events - Creation Operations 12 | @Create Event (GREEN)@cloudtrail.eventName matches "^Create"@[34000, 65535, 34000][500, 20000, 500] 13 | 14 | # Put Events - Update Operations 15 | @Put Event (GREEN)@cloudtrail.eventName matches "^Put"@[34000, 65535, 34000][500, 20000, 500] 16 | 17 | # Update Events - Update Operations 18 | @Update Event (GREEN)@cloudtrail.eventName matches "^Update"@[34000, 65535, 34000][500, 20000, 500] 19 | 20 | # Delete Events - Deletion Operations 21 | #@Delete Event (RED)@cloudtrail.eventName matches "^Delete"@[65535, 20000, 20000][5000, 1000, 1000] 22 | @Unknown Bucket (RED)@cloudtrail.eventName matches "^UnknownBucket"@[65535, 20000, 20000][5000, 1000, 1000] 23 | 24 | # Describe Events - Information Retrieval 25 | @Describe Event (PURPLE)@cloudtrail.eventName matches "^Describe"@[58000, 50000, 65535][15000, 5000, 20000] 26 | 27 | # List Events - Listing Operations 28 | @List Event (PURPLE)@cloudtrail.eventName matches "^List"@[58000, 50000, 65535][15000, 5000, 20000] 29 | 30 | # Head Events - Header Information 31 | @Head Event (PURPLE)@cloudtrail.eventName matches "^Head"@[58000, 50000, 65535][15000, 5000, 20000] 32 | 33 | # Operations by Amazon Services 34 | @Operations By Amazon (ORAGE)@(cloudtrail.sourceIPAddress matches "aws.com$") && (cloudtrail.userIdentity.type == "AWSService")@[65535, 40000, 10000][8000, 8000, 8000] 35 | -------------------------------------------------------------------------------- /lib/rules.py: -------------------------------------------------------------------------------- 1 | # lib/rules.py 2 | 3 | from typing import Dict, Any 4 | from lib.metadata import AwsMetadata 5 | 6 | enrichment_rules = [] 7 | custom_event_rules = [] 8 | 9 | def enrichment(func): 10 | enrichment_rules.append(func) 11 | return func 12 | 13 | def rule(func): 14 | custom_event_rules.append(func) 15 | return func 16 | 17 | def custom_event(func): 18 | custom_event_rules.append(func) 19 | return func 20 | 21 | @enrichment 22 | def enrich_made_by_recorder(event: Dict[str, Any], metadata: AwsMetadata): 23 | """Enrich event with 'madeByRecorder' flag.""" 24 | if event.get('userIdentity', {}).get('arn') == metadata.username: 25 | event['madeByRecorder'] = 1 26 | else: 27 | event['madeByRecorder'] = 0 28 | 29 | @enrichment 30 | def enrich_derivative_event(event: Dict[str, Any], metadata: AwsMetadata): 31 | """Enrich event with 'derivativeEvent' flag.""" 32 | if (event['madeByRecorder'] and 33 | (event.get('userAgent', '').endswith('com') or event.get('userAgent') == 'AWS Internal')) or \ 34 | (event.get('eventSource', '').endswith('com') and 35 | event.get('sourceIPAddress', '').endswith('com') and 36 | event.get('sourceIPAddress') != event.get('eventSource')): 37 | event['derivativeEvent'] = 1 38 | else: 39 | event['derivativeEvent'] = 0 40 | 41 | @rule 42 | def unknown_bucket_rule(event: Dict[str, Any], metadata: AwsMetadata): 43 | """Generate custom event for unknown buckets.""" 44 | parameters = event.get('requestParameters') 45 | if parameters and parameters.get("bucketName") and parameters["bucketName"] not in metadata.buckets: 46 | metadata.buckets.append(parameters["bucketName"]) 47 | unknown_bucket_event = { 48 | 'eventName': "UnknownBucket(Rule)", 49 | 'requestParameters': parameters["bucketName"], 50 | 'madeByRecorder': event['madeByRecorder'] 51 | } 52 | return unknown_bucket_event 53 | return None 54 | 55 | @enrichment 56 | def shadow_resource_created(event: Dict[str, Any], metadata: AwsMetadata): 57 | """Modify eventName if a shadow resource is created.""" 58 | event_name = event.get('eventName', '') 59 | if (('Put' in event_name or 'Create' in event_name) and event.get('derivativeEvent') == 1): 60 | new_event_name = f"ShadowResourceCreated - {event_name.replace('Create', '').replace('Put', '').strip()}" 61 | event['eventName'] = new_event_name -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # TrailShark 2 | 3 | ## Overview 4 | The TrailShark Capture Utility seamlessly integrates with Wireshark, facilitating the capture of AWS CloudTrail logs directly into Wireshark for near-real-time analysis. This tool can be used for debugging AWS API calls and played a pivotal role in our "Bucket Monopoly Research" project. By leveraging this utility, we were able to understand the internal API calls made by AWS, leading to the discovery of critical vulnerabilities across different services. This insight is invaluable for enhancing security measures and understanding AWS service interactions more deeply. 5 | 6 | 7 | ## Features 8 | - CloudTrail Log Capture: Enables capturing of CloudTrail logs directly from AWS S3 or CloudWatch for comprehensive monitoring. (Tool has the capability ) 9 | - Advanced Filtering: Offers custom filters, fields, and color-coding options to highlight interesting or significant events, making analysis more intuitive and efficient. 10 | - Custom Event: Supports the creation of custom events derived from existing ones, allowing for more detailed and targeted analysis of event chains and their impacts. 11 | 12 | ## Prerequisites 13 | Note: The plugin has been tested on Linux and macOS, but it should work on Windows as well. 14 | 15 | - Wireshark 16 | - Python 3.x 17 | - boto3 library 18 | 19 | ## Installation 20 | First, deploy the CloudFormation template to create the CloudTrail trail and configure S3 to store logs. 21 | 22 | ```bash 23 | aws cloudformation create-stack --stack-name TrailShark --template-body aws/template.yaml --region {REGION} 24 | ``` 25 | 26 | Run the following script to install the wireshark plugin 27 | ```bash 28 | ./install-plugin.sh 29 | ``` 30 | 31 | ## Usage 32 | [Usage Guide](docs/usage.md) 33 | 34 | ## Contributing 35 | Contributions to this project are welcome. Please ensure to follow the existing code style and add unit tests for any new or changed functionality. 36 | 37 | 38 | ## Known Issues 39 | - Sorting of Events: Events are not automatically sorted due to the inherent delays associated with how CloudTrail logs events. These delays vary depending on the region and the specific AWS service involved. Users can manually sort events using the GUI. 40 | - 1-2 minute delay in event sending due to CloudTrail capabilities (that's why it's near-real-time). 41 | - The tool offers two options for pulling data: S3, which is slower, and CloudWatch, which may experience event losses under stress. Choose the best option for your research. 42 | 43 | ## External Resources 44 | - [Logray Tool by Sysdig](https://blog.wireshark.org/tag/cloudtrail/) - A heartfelt appreciation to the creators of Logray, a tool developed by Sysdig based on Falco. Their work offers a similar functionality to ours and provides valuable insights into the use of CloudTrail logging. We recognize and commend their innovative approach and contributions to the community. 45 | - [Wireshark](https://github.com/wireshark/wireshark) 46 | 47 | ## Disclaimer 48 | We created this tool for internal research purposes and decided to share it with the community to provide more options for working with CloudTrail. 49 | 50 | ## License 51 | [LICENSE](LICENSE) -------------------------------------------------------------------------------- /lib/utils.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime, timezone 2 | import struct 3 | from typing import Any, BinaryIO, Dict, List, NoReturn 4 | from botocore.exceptions import ClientError 5 | from lib.constants import * 6 | import boto3 7 | def get_fake_pcap_header() -> bytearray: 8 | header = bytearray() 9 | header += struct.pack(' int: 20 | # Parse the timestamp and explicitly set it as UTC 21 | utc_time = datetime.strptime(log_parsed['eventTime'], '%Y-%m-%dT%H:%M:%SZ').replace(tzinfo=timezone.utc) 22 | # Convert the UTC datetime to a timestamp 23 | timestamp = int(utc_time.timestamp()) 24 | return timestamp 25 | 26 | 27 | def write_event(ts: int, event: bytes, extcap_pipe: BinaryIO): 28 | packet = bytearray() 29 | 30 | caplen = len(event) 31 | timestamp_secs = ts#int(ts / 1000000000) 32 | timestamp_usecs = int((ts % 1000000000) / 1000) 33 | 34 | packet += struct.pack(' int: 51 | return cls.id_map[call] 52 | 53 | def __str__(self) -> str: 54 | string = 'arg {number=%d}{call=%s}{display=%s}{type=%s}' % (self.number, self.call, self.display, self.type) 55 | for arg, val in self.kwargs.items(): 56 | string += '{%s=%s}' % (arg, str(val)) 57 | 58 | return string 59 | 60 | 61 | def show_config(): 62 | args: List[ConfigArg] = [ 63 | ConfigArg(call='--profile', display='Profile AWS credentials', type='string', default=DEFAULT_PROFILE), 64 | ConfigArg(call='--region', display='AWS region (Where you deployed trailshark)', type='string', default=DEFAULT_REGION), 65 | ConfigArg(call='--method', display='Log pulling method (s3 or cloudwatch)', type='string', default=DEFAULT_METHOD), 66 | ConfigArg(call='--interval', display='Interval between log pulling', type='integer', default=DEFAULT_INTERVAL), 67 | ] 68 | 69 | 70 | for arg in args: 71 | print(str(arg)) 72 | 73 | 74 | def stop_capture(is_error: bool = False): 75 | global region 76 | if STOP_TRAIL: 77 | stop_trail(region) 78 | stop_flag.set() 79 | os._exit(1) 80 | 81 | def exit_cb(_signum, _frame): 82 | stop_capture(is_error=False) 83 | 84 | def cloudtrail_capture(args: argparse.Namespace): 85 | global region 86 | if args.profile != 'defualt': 87 | boto3.setup_default_session(profile_name=args.profile) 88 | 89 | # Setup metadata and handler (omitted for brevity) 90 | region = args.region 91 | start_trail(region) 92 | metadata = AwsMetadata() 93 | handler = Handler(args=args, metadata=metadata,stop_flag=stop_flag, fetcher=args.method, interval=args.interval) 94 | 95 | if not args.fifo: 96 | raise('no output pipe provided') 97 | 98 | signal.signal(signal.SIGINT, exit_cb) 99 | signal.signal(signal.SIGTERM, exit_cb) 100 | 101 | # Start the process 102 | thread = threading.Thread(target=handler.main_loop) 103 | thread.start() 104 | 105 | def main(): 106 | parser = argparse.ArgumentParser(prog=os.path.basename(__file__), description='Capture CloudTrail events') 107 | 108 | # extcap arguments 109 | parser.add_argument('--extcap-interfaces', help='Provide a list of interfaces to capture from', action='store_true') 110 | parser.add_argument('--extcap-version', help='Shows the version of this utility', nargs='?', default='') 111 | parser.add_argument('--extcap-config', help='Provide a list of configurations for the given interface', action='store_true') 112 | parser.add_argument('--extcap-interface', help='Provide the interface to capture from') 113 | parser.add_argument('--extcap-dlts', help='Provide a list of dlts for the given interface', action='store_true') 114 | parser.add_argument('--capture', help='Start the capture routine', action='store_true') 115 | parser.add_argument('--fifo', help='Use together with capture to provide the fifo to dump data to') 116 | 117 | # custom arguments 118 | parser.add_argument('--profile',default=DEFAULT_PROFILE, type=str) 119 | parser.add_argument('--region',default=DEFAULT_REGION, type=str) 120 | parser.add_argument('--method',default=DEFAULT_METHOD, type=str) 121 | parser.add_argument('--interval',default=DEFAULT_INTERVAL, type=int) 122 | 123 | args = parser.parse_args() 124 | 125 | if args.extcap_version and not args.extcap_interfaces: 126 | show_version() 127 | sys.exit(0) 128 | 129 | if args.extcap_interfaces or args.extcap_interface is None: 130 | show_interfaces() 131 | sys.exit(0) 132 | 133 | if not args.extcap_interfaces and args.extcap_interface is None: 134 | parser.exit('An interface must be provided or the selection must be displayed') 135 | 136 | if args.extcap_config: 137 | show_config() 138 | elif args.extcap_dlts: 139 | show_dlts() 140 | elif args.capture: 141 | cloudtrail_capture(args) 142 | 143 | sys.exit(0) 144 | 145 | 146 | if __name__ == '__main__': 147 | try: 148 | main() 149 | # any exception needs to be raised 150 | except Exception as e: 151 | sys.stderr.write(e) 152 | sys.stderr.write("Please re-enter a valid profile or validate your AWS credentials, and ensure that you have the necessary policy in place.\n") 153 | stop_capture(is_error=True) 154 | -------------------------------------------------------------------------------- /trailshark-plugin/json.lua: -------------------------------------------------------------------------------- 1 | -- 2 | -- json.lua 3 | -- 4 | -- Copyright (c) 2020 rxi 5 | -- 6 | -- Permission is hereby granted, free of charge, to any person obtaining a copy of 7 | -- this software and associated documentation files (the "Software"), to deal in 8 | -- the Software without restriction, including without limitation the rights to 9 | -- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 10 | -- of the Software, and to permit persons to whom the Software is furnished to do 11 | -- so, subject to the following conditions: 12 | -- 13 | -- The above copyright notice and this permission notice shall be included in all 14 | -- copies or substantial portions of the Software. 15 | -- 16 | -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | -- SOFTWARE. 23 | -- 24 | 25 | local json = { _version = "0.1.2" } 26 | 27 | ------------------------------------------------------------------------------- 28 | -- Encode 29 | ------------------------------------------------------------------------------- 30 | 31 | local encode 32 | 33 | local escape_char_map = { 34 | [ "\\" ] = "\\", 35 | [ "\"" ] = "\"", 36 | [ "\b" ] = "b", 37 | [ "\f" ] = "f", 38 | [ "\n" ] = "n", 39 | [ "\r" ] = "r", 40 | [ "\t" ] = "t", 41 | } 42 | 43 | local escape_char_map_inv = { [ "/" ] = "/" } 44 | for k, v in pairs(escape_char_map) do 45 | escape_char_map_inv[v] = k 46 | end 47 | 48 | 49 | local function escape_char(c) 50 | return "\\" .. (escape_char_map[c] or string.format("u%04x", c:byte())) 51 | end 52 | 53 | 54 | local function encode_nil(val) 55 | return "null" 56 | end 57 | 58 | 59 | local function encode_table(val, stack) 60 | local res = {} 61 | stack = stack or {} 62 | 63 | -- Circular reference? 64 | if stack[val] then error("circular reference") end 65 | 66 | stack[val] = true 67 | 68 | if rawget(val, 1) ~= nil or next(val) == nil then 69 | -- Treat as array -- check keys are valid and it is not sparse 70 | local n = 0 71 | for k in pairs(val) do 72 | if type(k) ~= "number" then 73 | error("invalid table: mixed or invalid key types") 74 | end 75 | n = n + 1 76 | end 77 | if n ~= #val then 78 | error("invalid table: sparse array") 79 | end 80 | -- Encode 81 | for i, v in ipairs(val) do 82 | table.insert(res, encode(v, stack)) 83 | end 84 | stack[val] = nil 85 | return "[" .. table.concat(res, ",") .. "]" 86 | 87 | else 88 | -- Treat as an object 89 | for k, v in pairs(val) do 90 | if type(k) ~= "string" then 91 | error("invalid table: mixed or invalid key types") 92 | end 93 | table.insert(res, encode(k, stack) .. ":" .. encode(v, stack)) 94 | end 95 | stack[val] = nil 96 | return "{" .. table.concat(res, ",") .. "}" 97 | end 98 | end 99 | 100 | 101 | local function encode_string(val) 102 | return '"' .. val:gsub('[%z\1-\31\\"]', escape_char) .. '"' 103 | end 104 | 105 | 106 | local function encode_number(val) 107 | -- Check for NaN, -inf and inf 108 | if val ~= val or val <= -math.huge or val >= math.huge then 109 | error("unexpected number value '" .. tostring(val) .. "'") 110 | end 111 | return string.format("%.14g", val) 112 | end 113 | 114 | 115 | local type_func_map = { 116 | [ "nil" ] = encode_nil, 117 | [ "table" ] = encode_table, 118 | [ "string" ] = encode_string, 119 | [ "number" ] = encode_number, 120 | [ "boolean" ] = tostring, 121 | } 122 | 123 | 124 | encode = function(val, stack) 125 | local t = type(val) 126 | local f = type_func_map[t] 127 | if f then 128 | return f(val, stack) 129 | end 130 | error("unexpected type '" .. t .. "'") 131 | end 132 | 133 | 134 | function json.encode(val) 135 | return ( encode(val) ) 136 | end 137 | 138 | 139 | ------------------------------------------------------------------------------- 140 | -- Decode 141 | ------------------------------------------------------------------------------- 142 | 143 | local parse 144 | 145 | local function create_set(...) 146 | local res = {} 147 | for i = 1, select("#", ...) do 148 | res[ select(i, ...) ] = true 149 | end 150 | return res 151 | end 152 | 153 | local space_chars = create_set(" ", "\t", "\r", "\n") 154 | local delim_chars = create_set(" ", "\t", "\r", "\n", "]", "}", ",") 155 | local escape_chars = create_set("\\", "/", '"', "b", "f", "n", "r", "t", "u") 156 | local literals = create_set("true", "false", "null") 157 | 158 | local literal_map = { 159 | [ "true" ] = true, 160 | [ "false" ] = false, 161 | [ "null" ] = nil, 162 | } 163 | 164 | 165 | local function next_char(str, idx, set, negate) 166 | for i = idx, #str do 167 | if set[str:sub(i, i)] ~= negate then 168 | return i 169 | end 170 | end 171 | return #str + 1 172 | end 173 | 174 | 175 | local function decode_error(str, idx, msg) 176 | local line_count = 1 177 | local col_count = 1 178 | for i = 1, idx - 1 do 179 | col_count = col_count + 1 180 | if str:sub(i, i) == "\n" then 181 | line_count = line_count + 1 182 | col_count = 1 183 | end 184 | end 185 | error( string.format("%s at line %d col %d", msg, line_count, col_count) ) 186 | end 187 | 188 | 189 | local function codepoint_to_utf8(n) 190 | -- http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&id=iws-appendixa 191 | local f = math.floor 192 | if n <= 0x7f then 193 | return string.char(n) 194 | elseif n <= 0x7ff then 195 | return string.char(f(n / 64) + 192, n % 64 + 128) 196 | elseif n <= 0xffff then 197 | return string.char(f(n / 4096) + 224, f(n % 4096 / 64) + 128, n % 64 + 128) 198 | elseif n <= 0x10ffff then 199 | return string.char(f(n / 262144) + 240, f(n % 262144 / 4096) + 128, 200 | f(n % 4096 / 64) + 128, n % 64 + 128) 201 | end 202 | error( string.format("invalid unicode codepoint '%x'", n) ) 203 | end 204 | 205 | 206 | local function parse_unicode_escape(s) 207 | local n1 = tonumber( s:sub(1, 4), 16 ) 208 | local n2 = tonumber( s:sub(7, 10), 16 ) 209 | -- Surrogate pair? 210 | if n2 then 211 | return codepoint_to_utf8((n1 - 0xd800) * 0x400 + (n2 - 0xdc00) + 0x10000) 212 | else 213 | return codepoint_to_utf8(n1) 214 | end 215 | end 216 | 217 | 218 | local function parse_string(str, i) 219 | local res = "" 220 | local j = i + 1 221 | local k = j 222 | 223 | while j <= #str do 224 | local x = str:byte(j) 225 | 226 | if x < 32 then 227 | decode_error(str, j, "control character in string") 228 | 229 | elseif x == 92 then -- `\`: Escape 230 | res = res .. str:sub(k, j - 1) 231 | j = j + 1 232 | local c = str:sub(j, j) 233 | if c == "u" then 234 | local hex = str:match("^[dD][89aAbB]%x%x\\u%x%x%x%x", j + 1) 235 | or str:match("^%x%x%x%x", j + 1) 236 | or decode_error(str, j - 1, "invalid unicode escape in string") 237 | res = res .. parse_unicode_escape(hex) 238 | j = j + #hex 239 | else 240 | if not escape_chars[c] then 241 | decode_error(str, j - 1, "invalid escape char '" .. c .. "' in string") 242 | end 243 | res = res .. escape_char_map_inv[c] 244 | end 245 | k = j + 1 246 | 247 | elseif x == 34 then -- `"`: End of string 248 | res = res .. str:sub(k, j - 1) 249 | return res, j + 1 250 | end 251 | 252 | j = j + 1 253 | end 254 | 255 | decode_error(str, i, "expected closing quote for string") 256 | end 257 | 258 | 259 | local function parse_number(str, i) 260 | local x = next_char(str, i, delim_chars) 261 | local s = str:sub(i, x - 1) 262 | local n = tonumber(s) 263 | if not n then 264 | decode_error(str, i, "invalid number '" .. s .. "'") 265 | end 266 | return n, x 267 | end 268 | 269 | 270 | local function parse_literal(str, i) 271 | local x = next_char(str, i, delim_chars) 272 | local word = str:sub(i, x - 1) 273 | if not literals[word] then 274 | decode_error(str, i, "invalid literal '" .. word .. "'") 275 | end 276 | return literal_map[word], x 277 | end 278 | 279 | 280 | local function parse_array(str, i) 281 | local res = {} 282 | local n = 1 283 | i = i + 1 284 | while 1 do 285 | local x 286 | i = next_char(str, i, space_chars, true) 287 | -- Empty / end of array? 288 | if str:sub(i, i) == "]" then 289 | i = i + 1 290 | break 291 | end 292 | -- Read token 293 | x, i = parse(str, i) 294 | res[n] = x 295 | n = n + 1 296 | -- Next token 297 | i = next_char(str, i, space_chars, true) 298 | local chr = str:sub(i, i) 299 | i = i + 1 300 | if chr == "]" then break end 301 | if chr ~= "," then decode_error(str, i, "expected ']' or ','") end 302 | end 303 | return res, i 304 | end 305 | 306 | 307 | local function parse_object(str, i) 308 | local res = {} 309 | i = i + 1 310 | while 1 do 311 | local key, val 312 | i = next_char(str, i, space_chars, true) 313 | -- Empty / end of object? 314 | if str:sub(i, i) == "}" then 315 | i = i + 1 316 | break 317 | end 318 | -- Read key 319 | if str:sub(i, i) ~= '"' then 320 | decode_error(str, i, "expected string for key") 321 | end 322 | key, i = parse(str, i) 323 | -- Read ':' delimiter 324 | i = next_char(str, i, space_chars, true) 325 | if str:sub(i, i) ~= ":" then 326 | decode_error(str, i, "expected ':' after key") 327 | end 328 | i = next_char(str, i + 1, space_chars, true) 329 | -- Read value 330 | val, i = parse(str, i) 331 | -- Set 332 | res[key] = val 333 | -- Next token 334 | i = next_char(str, i, space_chars, true) 335 | local chr = str:sub(i, i) 336 | i = i + 1 337 | if chr == "}" then break end 338 | if chr ~= "," then decode_error(str, i, "expected '}' or ','") end 339 | end 340 | return res, i 341 | end 342 | 343 | 344 | local char_func_map = { 345 | [ '"' ] = parse_string, 346 | [ "0" ] = parse_number, 347 | [ "1" ] = parse_number, 348 | [ "2" ] = parse_number, 349 | [ "3" ] = parse_number, 350 | [ "4" ] = parse_number, 351 | [ "5" ] = parse_number, 352 | [ "6" ] = parse_number, 353 | [ "7" ] = parse_number, 354 | [ "8" ] = parse_number, 355 | [ "9" ] = parse_number, 356 | [ "-" ] = parse_number, 357 | [ "t" ] = parse_literal, 358 | [ "f" ] = parse_literal, 359 | [ "n" ] = parse_literal, 360 | [ "[" ] = parse_array, 361 | [ "{" ] = parse_object, 362 | } 363 | 364 | 365 | parse = function(str, idx) 366 | local chr = str:sub(idx, idx) 367 | local f = char_func_map[chr] 368 | if f then 369 | return f(str, idx) 370 | end 371 | decode_error(str, idx, "unexpected character '" .. chr .. "'") 372 | end 373 | 374 | 375 | function json.decode(str) 376 | if type(str) ~= "string" then 377 | error("expected argument of type string, got " .. type(str)) 378 | end 379 | local res, idx = parse(str, next_char(str, 1, space_chars, true)) 380 | idx = next_char(str, idx, space_chars, true) 381 | if idx <= #str then 382 | decode_error(str, idx, "trailing garbage") 383 | end 384 | return res 385 | end 386 | 387 | 388 | return json -------------------------------------------------------------------------------- /trailshark-plugin/cloudtrail-formatter.lua: -------------------------------------------------------------------------------- 1 | json = require("json") 2 | 3 | -- Define the CloudTrail protocol 4 | local p_cloudtrail = Proto("cloudtrail", "AWS CloudTrail") 5 | 6 | -- Define the protocol fields including nested fields 7 | local field_defs = { 8 | requestParameters_formatted = "requestParameters_formatted", 9 | responseElements_formatted = "responseElements_formatted", 10 | info = "info", 11 | link = "link", 12 | errorCode = "errorCode", 13 | errorMessage = "errorMessage", 14 | madeByRecorder = "madeByRecorder", 15 | derivativeEvent = "derivativeEvent", 16 | eventVersion = "eventVersion", 17 | eventTime = "eventTime", 18 | eventSource = "destination", 19 | eventName = "eventName", 20 | awsRegion = "awsRegion", 21 | sourceIPAddress = "source", 22 | userAgent = "userAgent", 23 | requestID = "requestID", 24 | eventID = "eventID", 25 | readOnly = "readOnly", 26 | eventType = "eventType", 27 | managementEvent = "managementEvent", 28 | recipientAccountId = "recipientAccountId", 29 | eventCategory = "eventCategory", 30 | userIdentity = "userIdentity", 31 | ["userIdentity.arn"] = "arn", 32 | ["userIdentity.name"] = "name", 33 | ["userIdentity.type"] = "type", 34 | ["userIdentity.principalId"] = "principalId", 35 | ["userIdentity.accountId"] = "accountId", 36 | ["userIdentity.accessKeyId"] = "accessKeyId", 37 | ["userIdentity.sessionContext"] = "sessionContext", 38 | ["userIdentity.sessionContext.sessionIssuer"] = "sessionIssuer", 39 | ["userIdentity.sessionContext.sessionIssuer.type"] = "type", 40 | ["userIdentity.sessionContext.sessionIssuer.principalId"] = "principalId", 41 | ["userIdentity.sessionContext.sessionIssuer.arn"] = "arn", 42 | ["userIdentity.sessionContext.sessionIssuer.accountId"] = "accountId", 43 | ["userIdentity.sessionContext.sessionIssuer.userName"] = "userName", 44 | ["userIdentity.sessionContext.attributes"] = "attributes", 45 | ["userIdentity.sessionContext.attributes.creationDate"] = "creationDate", 46 | ["userIdentity.sessionContext.attributes.mfaAuthenticated"] = "mfaAuthenticated", 47 | ["userIdentity.invokedBy"] = "invokedBy", 48 | ["userIdentity.userName"] = "userName", 49 | requestParameters = "requestParameters", 50 | ["requestParameters.maxResults"] = "maxResults", 51 | ["requestParameters.includeAllInstances"] = "includeAllInstances", 52 | ["requestParameters"] = "requestParameters", 53 | ["requestParameters.template"] = "template", 54 | ["requestParameters.maxRecords"] = "maxRecords", 55 | ["requestParameters.includeShared"] = "includeShared", 56 | ["requestParameters.startTime"] = "startTime", 57 | ["requestParameters.endTime"] = "endTime", 58 | ["requestParameters.roleArn"] = "roleArn", 59 | ["requestParameters.roleSessionName"] = "roleSessionName", 60 | ["requestParameters.durationSeconds"] = "durationSeconds", 61 | ["requestParameters.externalId"] = "externalId", 62 | ["requestParameters.encryptionAlgorithm"] = "encryptionAlgorithm", 63 | ["requestParameters.paginationToken"] = "paginationToken", 64 | ["requestParameters.resourcesPerPage"] = "resourcesPerPage", 65 | ["requestParameters.resourceTypeFilters"] = "resourceTypeFilters", 66 | ["requestParameters.startDate"] = "startDate", 67 | ["requestParameters.endDate"] = "endDate", 68 | ["requestParameters.masterRegion"] = "masterRegion", 69 | ["requestParameters.functionVersion"] = "functionVersion", 70 | ["requestParameters.maxItems"] = "maxItems", 71 | ["requestParameters.instanceId"] = "instanceId", 72 | ["requestParameters.stateMachineArn"] = "stateMachineArn", 73 | ["requestParameters.minimumStartTime"] = "minimumStartTime", 74 | ["requestParameters.tableName"] = "tableName", 75 | ["requestParameters.bucketName"] = "bucketName", 76 | ["requestParameters.Host"] = "Host", 77 | ["requestParameters.x-amz-acl"] = "x-amz-acl", 78 | ["requestParameters.x-amz-server-side-encryption"] = "x-amz-server-side-encryption", 79 | ["requestParameters.key"] = "key", 80 | ["requestParameters.instanceProfileName"] = "instanceProfileName", 81 | ["requestParameters.x-id"] = "x-id", 82 | ["requestParameters.tagging"] = "tagging", 83 | ["requestParameters.autoScalingGroupNames"] = "autoScalingGroupNames", 84 | ["requestParameters.pageSize"] = "pageSize", 85 | ["requestParameters.agentVersion"] = "agentVersion", 86 | ["requestParameters.agentStatus"] = "agentStatus", 87 | ["requestParameters.platformType"] = "platformType", 88 | ["requestParameters.platformName"] = "platformName", 89 | ["requestParameters.platformVersion"] = "platformVersion", 90 | ["requestParameters.iPAddress"] = "iPAddress", 91 | ["requestParameters.computerName"] = "computerName", 92 | ["requestParameters.agentName"] = "agentName", 93 | ["requestParameters.availabilityZone"] = "availabilityZone", 94 | ["requestParameters.availabilityZoneId"] = "availabilityZoneId", 95 | ["requestParameters.sSMConnectionChannel"] = "sSMConnectionChannel", 96 | ["requestParameters.loadBalancerArn"] = "loadBalancerArn", 97 | ["requestParameters.listenerArn"] = "listenerArn", 98 | ["requestParameters.lookupAttributes"] = "lookupAttributes", 99 | ["requestParameters.partNumber"] = "partNumber", 100 | ["requestParameters.uploadId"] = "uploadId", 101 | ["requestParameters.encoding-type"] = "encoding-type", 102 | ["requestParameters.prefix"] = "prefix", 103 | ["requestParameters.uploads"] = "uploads", 104 | ["requestParameters.roleName"] = "roleName", 105 | ["requestParameters.targetGroupArn"] = "targetGroupArn", 106 | ["requestParameters.location"] = "location", 107 | ["requestParameters.includePublic"] = "includePublic", 108 | ["requestParameters.sAMLAssertionID"] = "sAMLAssertionID", 109 | ["requestParameters.principalArn"] = "principalArn", 110 | ["requestParameters.aggregateField"] = "aggregateField", 111 | ["requestParameters.name"] = "name", 112 | ["requestParameters.input"] = "input", 113 | ["requestParameters.logGroupName"] = "logGroupName", 114 | ["requestParameters.logStreamName"] = "logStreamName", 115 | ["requestParameters.unmask"] = "unmask", 116 | ["requestParameters.limit"] = "limit", 117 | ["requestParameters.allRegions"] = "allRegions", 118 | ["requestParameters.Type"] = "Type", 119 | ["requestParameters.eventCategory"] = "eventCategory", 120 | ["requestParameters.resourceIdList"] = "resourceIdList", 121 | ["requestParameters.trailName"] = "trailName", 122 | ["requestParameters.secretId"] = "secretId", 123 | ["requestParameters.dBInstanceIdentifier"] = "dBInstanceIdentifier", 124 | ["requestParameters.marker"] = "marker", 125 | ["requestParameters.acl"] = "acl", 126 | ["requestParameters.resourceArns"] = "resourceArns", 127 | ["requestParameters.cluster"] = "cluster", 128 | ["requestParameters.dBSnapshotIdentifier"] = "dBSnapshotIdentifier", 129 | ["requestParameters.numberOfBytes"] = "numberOfBytes", 130 | ["requestParameters.keyId"] = "keyId", 131 | ["requestParameters.resourceName"] = "resourceName", 132 | ["requestParameters.policy"] = "policy", 133 | ["requestParameters.showCacheNodeInfo"] = "showCacheNodeInfo", 134 | ["requestParameters.stackStatusFilter"] = "stackStatusFilter", 135 | ["requestParameters.list-type"] = "list-type", 136 | ["requestParameters.max-keys"] = "max-keys", 137 | ["requestParameters.filters"] = "filters", 138 | ["requestParameters.queryExecutionId"] = "queryExecutionId", 139 | ["requestParameters.queryString"] = "queryString", 140 | ["requestParameters.clientRequestToken"] = "clientRequestToken", 141 | ["requestParameters.nextToken"] = "nextToken", 142 | ["requestParameters.streamName"] = "streamName", 143 | ["requestParameters.checkId"] = "checkId", 144 | ["requestParameters.type"] = "type", 145 | ["requestParameters.fileSystemId"] = "fileSystemId", 146 | ["requestParameters.forAccount"] = "forAccount", 147 | ["requestParameters.catalogId"] = "catalogId", 148 | ["requestParameters.entries"] = "entries", 149 | ["requestParameters.supportedPermissionTypes"] = "supportedPermissionTypes", 150 | ["requestParameters.returnBaseTablesForViews"] = "returnBaseTablesForViews", 151 | ["requestParameters.X-Amz-Date"] = "X-Amz-Date", 152 | ["requestParameters.X-Amz-Algorithm"] = "X-Amz-Algorithm", 153 | ["requestParameters.X-Amz-SignedHeaders"] = "X-Amz-SignedHeaders", 154 | ["requestParameters.X-Amz-Content-Sha256"] = "X-Amz-Content-Sha256", 155 | ["requestParameters.X-Amz-Expires"] = "X-Amz-Expires", 156 | ["requestParameters.fetch-owner"] = "fetch-owner", 157 | ["requestParameters.resource"] = "resource", 158 | ["requestParameters.lifecycle"] = "lifecycle", 159 | ["requestParameters.clusters"] = "clusters", 160 | ["requestParameters.include"] = "include", 161 | ["requestParameters.addonName"] = "addonName", 162 | ["requestParameters.stackName"] = "stackName", 163 | ["requestParameters.restApiId"] = "restApiId", 164 | ["requestParameters.cors"] = "cors", 165 | ["requestParameters.logging"] = "logging", 166 | ["requestParameters.notification"] = "notification", 167 | ["requestParameters.versioning"] = "versioning", 168 | ["requestParameters.website"] = "website", 169 | ["requestParameters.requestPayment"] = "requestPayment", 170 | ["requestParameters.accelerate"] = "accelerate", 171 | ["requestParameters.encryption"] = "encryption", 172 | ["requestParameters.replication"] = "replication", 173 | ["requestParameters.publicAccessBlock"] = "publicAccessBlock", 174 | ["requestParameters.object-lock"] = "object-lock", 175 | ["requestParameters.streamARN"] = "streamARN", 176 | ["requestParameters.keySpec"] = "keySpec", 177 | ["requestParameters.functionName"] = "functionName", 178 | ["requestParameters.language"] = "language", 179 | ["requestParameters.GroupName"] = "GroupName", 180 | ["requestParameters.Filters"] = "Filters", 181 | ["requestParameters.tagFilters"] = "tagFilters", 182 | ["requestParameters.origin"] = "origin", 183 | ["requestParameters.dryRun"] = "dryRun", 184 | ["requestParameters.utterance"] = "utterance", 185 | ["requestParameters.conversationId"] = "conversationId", 186 | ["requestParameters.workGroup"] = "workGroup", 187 | ["requestParameters.includePreviewFeatures"] = "includePreviewFeatures", 188 | ["requestParameters.includeDeprecatedFeaturesAccess"] = "includeDeprecatedFeaturesAccess", 189 | ["requestParameters.includeDeprecatedRuntimeDetails"] = "includeDeprecatedRuntimeDetails", 190 | ["requestParameters.includeUnreservedConcurrentExecutionsMinimum"] = "includeUnreservedConcurrentExecutionsMinimum", 191 | ["requestParameters.includeBlacklistedFeatures"] = "includeBlacklistedFeatures", 192 | ["requestParameters.qualifier"] = "qualifier", 193 | responseElements = "responseElements", 194 | ["responseElements.x-amz-server-side-encryption"] = "x-amz-server-side-encryption", 195 | ["responseElements.x-amz-expiration"] = "x-amz-expiration", 196 | ["responseElements.x-amz-version-id"] = "x-amz-version-id", 197 | ["responseElements.subject"] = "subject", 198 | ["responseElements.subjectType"] = "subjectType", 199 | ["responseElements.issuer"] = "issuer", 200 | ["responseElements.audience"] = "audience", 201 | ["responseElements.nameQualifier"] = "nameQualifier", 202 | ["responseElements.executionArn"] = "executionArn", 203 | ["responseElements.startDate"] = "startDate", 204 | ["responseElements.packedPolicySize"] = "packedPolicySize", 205 | ["responseElements.queryExecutionId"] = "queryExecutionId", 206 | ["responseElements.requestId"] = "requestId", 207 | ["responseElements.keyId"] = "keyId", 208 | ["responseElements.subjectFromWebIdentityToken"] = "subjectFromWebIdentityToken", 209 | ["responseElements.provider"] = "provider", 210 | ["responseElements.credentials"] = "credentials", 211 | ["responseElements.credentials.accessKeyId"] = "accessKeyId", 212 | ["responseElements.credentials.sessionToken"] = "sessionToken", 213 | ["responseElements.credentials.expiration"] = "expiration", 214 | ["responseElements.assumedRoleUser"] = "assumedRoleUser", 215 | ["responseElements.assumedRoleUser.assumedRoleId"] = "assumedRoleId", 216 | ["responseElements.assumedRoleUser.arn"] = "arn", 217 | additionalEventData = "additionalEventData", 218 | ["additionalEventData.grantId"] = "grantId", 219 | ["additionalEventData.SignatureVersion"] = "SignatureVersion", 220 | ["additionalEventData.CipherSuite"] = "CipherSuite", 221 | ["additionalEventData.bytesTransferredIn"] = "bytesTransferredIn", 222 | ["additionalEventData.SSEApplied"] = "SSEApplied", 223 | ["additionalEventData.AuthenticationMethod"] = "AuthenticationMethod", 224 | ["additionalEventData.x-amz-id-2"] = "x-amz-id-2", 225 | ["additionalEventData.bytesTransferredOut"] = "bytesTransferredOut" 226 | } 227 | 228 | 229 | 230 | -- Initialize ProtoFields dynamically from field definitions 231 | local fields = {} 232 | for key, label in pairs(field_defs) do 233 | fields[key] = ProtoField.string('cloudtrail.' .. key, label) 234 | end 235 | p_cloudtrail.fields = fields 236 | 237 | -- Function to recursively add fields to the subtree 238 | local function addFieldsToSubtree(subtree, data, prefix) 239 | prefix = prefix or "" 240 | for key, value in pairs(data) do 241 | local field_key = prefix .. key 242 | local protoField = fields[field_key] 243 | if protoField then 244 | if type(value) == "table" then 245 | -- Create a subtree for nested JSON objects 246 | local nestedSubtree = subtree:add(protoField, key) 247 | addFieldsToSubtree(nestedSubtree, value, field_key .. ".") 248 | else 249 | -- Add the actual data as a field in the subtree 250 | subtree:add(protoField, tostring(value)) 251 | end 252 | end 253 | end 254 | end 255 | 256 | -- Function to add the specific information only when eventID is not null 257 | local function addInformation(subtree, data) 258 | local region = data.awsRegion or "unknown-region" 259 | local eventid = data.eventID 260 | if eventid then -- Check if eventid is not nil or empty 261 | local url = string.format("https://%s.console.aws.amazon.com/cloudtrailv2/home?region=%s#/events/%s", region, region, eventid) 262 | subtree:add(fields.link, url) 263 | end 264 | end 265 | 266 | 267 | function format_nested_object(obj) 268 | if type(obj) == "table" then 269 | local parts = {} 270 | for k, v in pairs(obj) do 271 | parts[#parts + 1] = string.format('"%s":%s', k, format_nested_object(v)) 272 | end 273 | return "{" .. table.concat(parts, ",") .. "}" 274 | else 275 | -- Handle strings by adding quotes and escaping internal quotes 276 | if type(obj) == "string" then 277 | return string.format('"%s"', obj:gsub('"', '\\"')) 278 | else 279 | return tostring(obj) 280 | end 281 | end 282 | end 283 | 284 | 285 | function add_formatted_json(subtree, data) 286 | subtree:add(fields.requestParameters_formatted, format_nested_object(data.requestParameters)) 287 | subtree:add(fields.responseElements_formatted, format_nested_object(data.responseElements)) 288 | 289 | end 290 | -- Dissector function to parse the packet data 291 | function p_cloudtrail.dissector(buf, pinfo, tree) 292 | local subtree = tree:add(p_cloudtrail, buf(0, -1)) 293 | local status, data = pcall(json.decode, buf:bytes():raw()) 294 | 295 | if status then 296 | addFieldsToSubtree(subtree, data) 297 | addInformation(subtree, data) 298 | add_formatted_json(subtree, data) 299 | else 300 | subtree:add_expert_info(PI_MALFORMED, PI_ERROR, "Error decoding JSON: " .. data) 301 | end 302 | end 303 | 304 | -- Register the dissector to a specific encapsulation type 305 | local wtap_encap_table = DissectorTable.get("wtap_encap") 306 | wtap_encap_table:add(wtap.USER1, p_cloudtrail) 307 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | --------------------------------------------------------------------------------