├── Chapter 2 ├── Discover_domain_names.yar └── Custom_Wazuh_Rules_For_Sysmon.xml ├── Chapter 5 └── wfblock.ps1 ├── LICENSE ├── Chapter 3 ├── custom_thehive_bash_script_Wazuh..sh ├── theHive_Docker_Compose.yml └── custom_thehive_integration_Wazuh.py └── README.md /Chapter 2/Discover_domain_names.yar: -------------------------------------------------------------------------------- 1 | rule Discover_Domain_Names { 2 | 3 | meta: 4 | 5 | description = "Detects domain names in the target file" 6 | 7 | author = "Your Name" 8 | 9 | 10 | weight = 50 11 | 12 | 13 | 14 | strings: 15 | 16 | $domain_name_1 = /(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}/ nocase 17 | 18 | $domain_name_2 = /(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+(?:com|net|org|edu|gov|mil|int|arpa|info|biz|aero|name|coop|arpa|pro|museum)\b/ nocase 19 | 20 | 21 | 22 | condition: 23 | 24 | any of them 25 | 26 | } -------------------------------------------------------------------------------- /Chapter 5/wfblock.ps1: -------------------------------------------------------------------------------- 1 | #Author Rajneesh Gupta 2 | 3 | 4 | 5 | # Set ConfirmPreference to None to automatically answer "No" to confirmation prompts 6 | 7 | $ConfirmPreference = "None" 8 | 9 | 10 | 11 | # Define the rule name 12 | 13 | $ruleName = "BlockOutgoingTraffic" 14 | 15 | 16 | 17 | # Check if the rule already exists 18 | 19 | $existingRule = Get-NetFirewallRule | Where-Object {$_.Name -eq $ruleName} 20 | 21 | 22 | 23 | if ($existingRule -eq $null) { 24 | 25 | # Create a new outbound block rule 26 | 27 | New-NetFirewallRule -DisplayName $ruleName -Direction Outbound -Action Block -Enabled True 28 | 29 | Write-Host "Outgoing traffic is now blocked." 30 | 31 | } else { 32 | 33 | Write-Host "Outgoing traffic is already blocked." 34 | 35 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Packt 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Chapter 3/custom_thehive_bash_script_Wazuh..sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # Copyright (C) 2015-2020, Wazuh Inc. 4 | 5 | # Created by Wazuh, Inc. . 6 | 7 | # This program is free software; you can redistribute it and/or modify it under the terms of GP> 8 | 9 | WPYTHON_BIN="framework/python/bin/python3" 10 | 11 | SCRIPT_PATH_NAME="$0" 12 | 13 | DIR_NAME="$(cd $(dirname ${SCRIPT_PATH_NAME}); pwd -P)" 14 | 15 | SCRIPT_NAME="$(basename ${SCRIPT_PATH_NAME})" 16 | 17 | case ${DIR_NAME} in 18 | 19 | */active-response/bin | */wodles*) 20 | 21 | if [ -z "${WAZUH_PATH}" ]; then 22 | 23 | WAZUH_PATH="$(cd ${DIR_NAME}/../..; pwd)" 24 | 25 | fi 26 | 27 | PYTHON_SCRIPT="${DIR_NAME}/${SCRIPT_NAME}.py" 28 | 29 | ;; 30 | 31 | */bin) 32 | 33 | if [ -z "${WAZUH_PATH}" ]; then 34 | 35 | WAZUH_PATH="$(cd ${DIR_NAME}/..; pwd)" 36 | 37 | fi 38 | 39 | PYTHON_SCRIPT="${WAZUH_PATH}/framework/scripts/${SCRIPT_NAME}.py" 40 | 41 | ;; 42 | 43 | */integrations) 44 | 45 | if [ -z "${WAZUH_PATH}" ]; then 46 | 47 | WAZUH_PATH="$(cd ${DIR_NAME}/..; pwd)" 48 | 49 | fi 50 | 51 | PYTHON_SCRIPT="${DIR_NAME}/${SCRIPT_NAME}.py" 52 | 53 | ;; 54 | 55 | esac 56 | 57 | ${WAZUH_PATH}/${WPYTHON_BIN} ${PYTHON_SCRIPT} $@ -------------------------------------------------------------------------------- /Chapter 3/theHive_Docker_Compose.yml: -------------------------------------------------------------------------------- 1 | version: "3" 2 | 3 | services: 4 | 5 | thehive: 6 | 7 | image: strangebee/thehive:5.2 8 | 9 | depends_on: 10 | 11 | - cassandra 12 | 13 | - elasticsearch 14 | 15 | - minio 16 | 17 | - cortex 18 | 19 | mem_limit: 1500m 20 | 21 | ports: 22 | 23 | - "9000:9000" 24 | 25 | environment: 26 | 27 | - JVM_OPTS="-Xms1024M -Xmx1024M" 28 | 29 | command: 30 | 31 | - --secret 32 | 33 | - "mySecretForTheHive" 34 | 35 | - "--cql-hostnames" 36 | 37 | - "cassandra" 38 | 39 | - "--index-backend" 40 | 41 | - "elasticsearch" 42 | 43 | - "--es-hostnames" 44 | 45 | - "elasticsearch" 46 | 47 | - "--s3-endpoint" 48 | 49 | - "http://minio:9000" 50 | 51 | - "--s3-access-key" 52 | 53 | - "minioadmin" 54 | 55 | - "--s3-secret-key" 56 | 57 | - "minioadmin" 58 | 59 | - "--s3-bucket" 60 | 61 | - "thehive" 62 | 63 | - "--s3-use-path-access-style" 64 | 65 | - "--cortex-hostnames" 66 | 67 | - "cortex" 68 | 69 | - "--cortex-keys" 70 | 71 | # put cortex api key once cortex is bootstraped 72 | 73 | - "" 74 | 75 | 76 | 77 | cassandra: 78 | 79 | image: 'cassandra:4' 80 | 81 | mem_limit: 1600m 82 | 83 | ports: 84 | 85 | - "9042:9042" 86 | 87 | environment: 88 | 89 | - MAX_HEAP_SIZE=1024M 90 | 91 | - HEAP_NEWSIZE=1024M 92 | 93 | - CASSANDRA_CLUSTER_NAME=TheHive 94 | 95 | volumes: 96 | 97 | - cassandradata:/var/lib/cassandra 98 | 99 | restart: on-failure 100 | 101 | 102 | 103 | elasticsearch: 104 | 105 | image: docker.elastic.co/elasticsearch/elasticsearch:7.17.12 106 | 107 | mem_limit: 1500m 108 | 109 | ports: 110 | 111 | - "9200:9200" 112 | 113 | environment: 114 | 115 | - discovery.type=single-node 116 | 117 | - xpack.security.enabled=false 118 | 119 | volumes: 120 | 121 | - elasticsearchdata:/usr/share/elasticsearch/data 122 | 123 | 124 | 125 | minio: 126 | 127 | image: quay.io/minio/minio 128 | 129 | mem_limit: 512m 130 | 131 | command: ["minio", "server", "/data", "--console-address", ":9090"] 132 | 133 | environment: 134 | 135 | - MINIO_ROOT_USER=minioadmin 136 | 137 | - MINIO_ROOT_PASSWORD=minioadmin 138 | 139 | ports: 140 | 141 | - "9090:9090" 142 | 143 | volumes: 144 | 145 | - "miniodata:/data" 146 | 147 | 148 | 149 | cortex: 150 | 151 | image: thehiveproject/cortex:3.1.7 152 | 153 | depends_on: 154 | 155 | - elasticsearch 156 | 157 | environment: 158 | 159 | - job_directory=/tmp/cortex-jobs 160 | 161 | volumes: 162 | 163 | - /var/run/docker.sock:/var/run/docker.sock 164 | 165 | - /tmp/cortex-jobs:/tmp/cortex-jobs 166 | 167 | ports: 168 | 169 | - "9001:9001" 170 | 171 | 172 | 173 | volumes: 174 | 175 | miniodata: 176 | 177 | cassandradata: 178 | 179 | elasticsearchdata: -------------------------------------------------------------------------------- /Chapter 2/Custom_Wazuh_Rules_For_Sysmon.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 61650 8 | 9 | Sysmon - Event 22: DNS Query. 10 | 11 | no_full_log 12 | 13 | 14 | 15 | 16 | 17 | 61603 18 | 19 | no_full_log 20 | 21 | Sysmon - Event 1: Process creation. 22 | 23 | 24 | 25 | 26 | 27 | 61604 28 | 29 | no_full_log 30 | 31 | Sysmon - Event 2: A process changed a file creation time. 32 | 33 | 34 | 35 | 36 | 37 | 61605 38 | 39 | no_full_log 40 | 41 | Sysmon - Event 3: Network connection. 42 | 43 | 44 | 45 | 46 | 47 | 61606 48 | 49 | no_full_log 50 | 51 | Sysmon - Event 4: Sysmon service state changed. 52 | 53 | 54 | 55 | 56 | 57 | 61607 58 | 59 | no_full_log 60 | 61 | Sysmon - Event 5: Process terminated. 62 | 63 | 64 | 65 | 66 | 67 | 61608 68 | 69 | no_full_log 70 | 71 | Sysmon - Event 6: Driver loaded. 72 | 73 | 74 | 75 | 76 | 77 | 61609 78 | 79 | no_full_log 80 | 81 | Sysmon - Event 7: Image loaded. 82 | 83 | 84 | 85 | 86 | 87 | 61610 88 | 89 | no_full_log 90 | 91 | Sysmon - Event 8: CreateRemoteThread. 92 | 93 | 94 | 95 | 96 | 97 | 61611 98 | 99 | no_full_log 100 | 101 | Sysmon - Event 9: RawAccessRead. 102 | 103 | 104 | 105 | 106 | 107 | 61612 108 | 109 | no_full_log 110 | 111 | Sysmon - Event 10: ProcessAccess. 112 | 113 | 114 | 115 | 116 | 117 | 61613 118 | 119 | no_full_log 120 | 121 | Sysmon - Event 11: FileCreate. 122 | 123 | 124 | 125 | 126 | 127 | 61614 128 | 129 | no_full_log 130 | 131 | Sysmon - Event 12: RegistryEvent (Object create and delete). 132 | 133 | 134 | 135 | 136 | 137 | 61615 138 | 139 | no_full_log 140 | 141 | Sysmon - Event 13: RegistryEvent (Value Set). 142 | 143 | 144 | 145 | 146 | 147 | 61616 148 | 149 | no_full_log 150 | 151 | Sysmon - Event 14: RegistryEvent (Key and Value Rename). 152 | 153 | 154 | 155 | 156 | 157 | 61617 158 | 159 | no_full_log 160 | 161 | Sysmon - Event 15: FileCreateStreamHash. 162 | 163 | 164 | 165 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Security Monitoring with Wazuh 2 | 3 | 4 | 5 | This is the code repository for [Security Monitoring with Wazuh](https://www.packtpub.com/product/security-monitoring-with-wazuh/9781837632152?utm_source=github&utm_medium=repository&utm_campaign=9781837632152), published by Packt. 6 | 7 | **A hands-on guide to effective enterprise security using real-life use cases in Wazuh** 8 | 9 | ## What is this book about? 10 | Explore the implementation of Wazuh for effective security monitoring through use cases and demonstrations of how to integrate Wazuh with essential tools like OSSEC, TheHive, Cortex, and Shuffle. 11 | 12 | This book covers the following exciting features: 13 | * Find out how to set up an intrusion detection system with Wazuh 14 | * Get to grips with setting up a file integrity monitoring system 15 | * Deploy Malware Information Sharing Platform (MISP) for threat intelligence automation to detect indicators of compromise (IOCs) 16 | * Explore ways to integrate Shuffle, TheHive, and Cortex to set up security automation 17 | * Apply Wazuh and other open source tools to address your organization’s specific needs 18 | * Integrate Osquery with Wazuh to conduct threat hunting 19 | 20 | If you feel this book is for you, get your [copy](https://www.amazon.com/dp/1837632154) today! 21 | 22 | https://www.packtpub.com/ 24 | 25 | ## Instructions and Navigations 26 | All of the code is organized into folders. For example, Chapter 2. 27 | 28 | The code will look like the following: 29 | ``` 30 | 31 | 60009 32 | ^PowerShell$ 33 | 34 | ``` 35 | 36 | **Following is what you need for this book:** 37 | This book is for SOC analysts, security architects, and security engineers who want to set up open-source SOC with critical capabilities such as file integrity monitoring, security monitoring, threat intelligence automation, and cloud security monitoring. Managed service providers aiming to build a scalable security monitoring system for their clients will also find valuable insights in this book. Familiarity with basic IT, cybersecurity, cloud, and Linux concepts is necessary to get started. 38 | 39 | With the following software and hardware list you can run all code files present in the book (Chapter 1-9). 40 | ### Software and Hardware List 41 | | Chapter | Software required | OS required | 42 | | -------- | ------------------------------------ | ----------------------------------- | 43 | | 1-9 | Wazuh OVA | Windows, Mac OS X, and Linux (Any) | 44 | | 1-9 | Suricata IDS and Osquery | Windows, Mac OS X, and Linux (Any) | 45 | | 1-9 | VirusTotal | Windows, Mac OS X, and Linux (Any) | 46 | 47 | 48 | ### Related products 49 | * Practical Cybersecurity Architecture [[Packt]](https://www.packtpub.com/product/practical-cybersecurity-architecture-second-edition/9781837637164?utm_source=github&utm_medium=repository&utm_campaign=9781837637164) [[Amazon]](https://www.amazon.com/dp/1837637164) 50 | 51 | * Fuzzing Against the Machine [[Packt]](https://www.packtpub.com/product/fuzzing-against-the-machine/9781804614976?utm_source=github&utm_medium=repository&utm_campaign=9781804614976) [[Amazon]](https://www.amazon.com/dp/1804614971) 52 | 53 | ## Get to Know the Author 54 | **Rajneesh Gupta** 55 | With 11 years of experience, Rajneesh Gupta, a seasoned cybersecurity expert, specializes in open-source security, security monitoring, cloud security, security audit, and red-teaming exercises. Prior to this, he worked with Hewlett-Packard as security lead. A CISA-certified professional, he has played a pivotal role in building and automating Security Operation Centers (SOCs) for hundreds of businesses globally, conducting security audits, and guiding on frameworks and compliances. 56 | Rajneesh is also passionate about mentoring, having helped numerous individuals kickstart their careers in cybersecurity. He is also the author of Hands-On with Cybersecurity and Blockchain, which is popular across both security and blockchain communities. Outside of work, Rajneesh enjoys spending time in hill stations and playing volleyball. 57 | 58 | ## Other books by the author 59 | * [Hands-On Cybersecurity with Blockchain](https://www.packtpub.com/product/hands-on-cybersecurity-with-blockchain/9781788990189?utm_source=github&utm_medium=repository&utm_campaign=9781788990189) 60 | -------------------------------------------------------------------------------- /Chapter 3/custom_thehive_integration_Wazuh.py: -------------------------------------------------------------------------------- 1 | #!/var/ossec/framework/python/bin/python3 2 | 3 | import json 4 | 5 | import sys 6 | 7 | import os 8 | 9 | import re 10 | 11 | import logging 12 | 13 | import uuid 14 | 15 | from thehive4py.api import TheHiveApi 16 | 17 | from thehive4py.models import Alert, AlertArtifact 18 | 19 | #start user config 20 | 21 | # Global vars 22 | 23 | #threshold for wazuh rules level 24 | 25 | lvl_threshold=0 26 | 27 | #threshold for suricata rules level 28 | 29 | suricata_lvl_threshold=3 30 | 31 | debug_enabled = False 32 | 33 | #info about created alert 34 | 35 | info_enabled = True 36 | 37 | #end user config 38 | 39 | # Set paths 40 | 41 | pwd = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) 42 | 43 | log_file = '{0}/logs/integrations.log'.format(pwd) 44 | 45 | logger = logging.getLogger(__name__) 46 | 47 | #set logging level 48 | 49 | logger.setLevel(logging.WARNING) 50 | 51 | if info_enabled: 52 | 53 | logger.setLevel(logging.INFO) 54 | 55 | if debug_enabled: 56 | 57 | logger.setLevel(logging.DEBUG) 58 | 59 | # create the logging file handler 60 | 61 | fh = logging.FileHandler(log_file) 62 | 63 | formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 64 | 65 | fh.setFormatter(formatter) 66 | 67 | logger.addHandler(fh) 68 | 69 | 70 | 71 | def main(args): 72 | 73 | logger.debug('#start main') 74 | 75 | logger.debug('#get alert file location') 76 | 77 | alert_file_location = args[1] 78 | 79 | logger.debug('#get TheHive url') 80 | 81 | thive = args[3] 82 | 83 | logger.debug('#get TheHive api key') 84 | 85 | thive_api_key = args[2] 86 | 87 | thive_api = TheHiveApi(thive, thive_api_key ) 88 | 89 | logger.debug('#open alert file') 90 | 91 | w_alert = json.load(open(alert_file_location)) 92 | 93 | logger.debug('#alert data') 94 | 95 | logger.debug(str(w_alert)) 96 | 97 | logger.debug('#gen json to dot-key-text') 98 | 99 | alt = pr(w_alert,'',[]) 100 | 101 | logger.debug('#formatting description') 102 | 103 | format_alt = md_format(alt) 104 | 105 | logger.debug('#search artifacts') 106 | 107 | artifacts_dict = artifact_detect(format_alt) 108 | 109 | alert = generate_alert(format_alt, artifacts_dict, w_alert) 110 | 111 | logger.debug('#threshold filtering') 112 | 113 | if w_alert['rule']['groups']==['ids','suricata']: 114 | 115 | #checking the existence of the data.alert.severity field 116 | 117 | if 'data' in w_alert.keys(): 118 | 119 | if 'alert' in w_alert['data']: 120 | 121 | #checking the level of the source event 122 | 123 | if int(w_alert['data']['alert']['severity'])<=suricata_lvl_threshold: 124 | 125 | send_alert(alert, thive_api) 126 | 127 | elif int(w_alert['rule']['level'])>=lvl_threshold: 128 | 129 | #if the event is different from suricata AND suricata-event-type: alert check lvl_threshold 130 | 131 | send_alert(alert, thive_api) 132 | 133 | 134 | 135 | def pr(data,prefix, alt): 136 | 137 | for key,value in data.items(): 138 | 139 | if hasattr(value,'keys'): 140 | 141 | pr(value,prefix+'.'+str(key),alt=alt) 142 | 143 | else: 144 | 145 | alt.append((prefix+'.'+str(key)+'|||'+str(value))) 146 | 147 | return alt 148 | 149 | 150 | 151 | def md_format(alt,format_alt=''): 152 | 153 | md_title_dict = {} 154 | 155 | #sorted with first key 156 | 157 | for now in alt: 158 | 159 | now = now[1:] 160 | 161 | #fix first key last symbol 162 | 163 | dot = now.split('|||')[0].find('.') 164 | 165 | if dot==-1: 166 | 167 | md_title_dict[now.split('|||')[0]] =[now] 168 | 169 | else: 170 | 171 | if now[0:dot] in md_title_dict.keys(): 172 | 173 | (md_title_dict[now[0:dot]]).append(now) 174 | 175 | else: 176 | 177 | md_title_dict[now[0:dot]]=[now] 178 | 179 | for now in md_title_dict.keys(): 180 | 181 | format_alt+='### '+now.capitalize()+'\n'+'| key | val |\n| ------ | ------ |\n' 182 | 183 | for let in md_title_dict[now]: 184 | 185 | key,val = let.split('|||')[0],let.split('|||')[1] 186 | 187 | format_alt+='| **' + key + '** | ' + val + ' |\n' 188 | 189 | return format_alt 190 | 191 | 192 | 193 | def artifact_detect(format_alt): 194 | 195 | artifacts_dict = {} 196 | 197 | artifacts_dict['ip'] = re.findall(r'\d+\.\d+\.\d+\.\d+',format_alt) 198 | 199 | artifacts_dict['url'] = re.findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',format_alt) 200 | 201 | artifacts_dict['domain'] = [] 202 | 203 | for now in artifacts_dict['url']: artifacts_dict['domain'].append(now.split('//')[1].split('/')[0]) 204 | 205 | return artifacts_dict 206 | 207 | 208 | 209 | def generate_alert(format_alt, artifacts_dict,w_alert): 210 | 211 | #generate alert sourceRef 212 | 213 | sourceRef = str(uuid.uuid4())[0:6] 214 | 215 | artifacts = [] 216 | 217 | if 'agent' in w_alert.keys(): 218 | 219 | if 'ip' not in w_alert['agent'].keys(): 220 | 221 | w_alert['agent']['ip']='no agent ip' 222 | 223 | else: 224 | 225 | w_alert['agent'] = {'id':'no agent id', 'name':'no agent name'} 226 | 227 | for key,value in artifacts_dict.items(): 228 | 229 | for val in value: 230 | 231 | artifacts.append(AlertArtifact(dataType=key, data=val)) 232 | 233 | alert = Alert(title=w_alert['rule']['description'], 234 | 235 | tlp=2, 236 | 237 | tags=['wazuh', 238 | 239 | 'rule='+w_alert['rule']['id'], 240 | 241 | 'agent_name='+w_alert['agent']['name'], 242 | 243 | 'agent_id='+w_alert['agent']['id'], 244 | 245 | 'agent_ip='+w_alert['agent']['ip'],], 246 | 247 | description=format_alt , 248 | 249 | type='wazuh_alert', 250 | 251 | source='wazuh', 252 | 253 | sourceRef=sourceRef, 254 | 255 | artifacts=artifacts,) 256 | 257 | return alert 258 | 259 | 260 | 261 | def send_alert(alert, thive_api): 262 | 263 | response = thive_api.create_alert(alert) 264 | 265 | if response.status_code == 201: 266 | 267 | logger.info('Create TheHive alert: '+ str(response.json()['id'])) 268 | 269 | else: 270 | 271 | logger.error('Error create TheHive alert: {}/{}'.format(response.status_code, response.text)) 272 | 273 | 274 | 275 | if __name__ == "__main__": 276 | 277 | try: 278 | 279 | logger.debug('debug mode') # if debug enabled 280 | 281 | # Main function 282 | 283 | main(sys.argv) 284 | 285 | except Exception: 286 | 287 | logger.exception('EGOR') 288 | 289 | --------------------------------------------------------------------------------