Google Chat API Integration

4,108 views
Skip to first unread message

Raj Vira

unread,
Oct 12, 2021, 4:33:41 AM10/12/21
to Wazuh mailing list
Hi Team, 

I was wondering if there is any way to generate alerts directly to Google chat via Webhooks just like slack?

Reference: https://documentation.wazuh.com/4.0/user-manual/manager/manual-integration.html#integration-with-external-apis

Thanks,
Raj Vira.

Juan Nicolás Asselle

unread,
Oct 12, 2021, 11:33:37 AM10/12/21
to Wazuh mailing list

Hi Raj,
First of all, thanks for using Wazuh.

I was able to make it work by following the next Google official tutorial: Using incoming webhooks. After following those steps, i used slack integration script as base for this new integration
1- Create /var/ossec/integrations/custom-gchat file in Wazuh Manager with the next content, replacing GCHAT_URI with the one generated by the Google tutorial

#!/usr/bin/env python
# Copyright (C) 2015-2021, Wazuh Inc.
#
# This program is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public
# License (version 2) as published by the FSF - Free Software
# Foundation.

import json
import sys
import time
import os
import httplib2

try:
import requests
from requests.auth import HTTPBasicAuth
except Exception as e:
print("No module 'requests' found. Install: pip install requests")
sys.exit(1)

# Global vars

GCHAT_URI = 'https://chat.googleapis.com/v1/spaces/XXXXX/messages?key=XXXX&token=XXXX'
debug_enabled = False
pwd = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
json_alert = {}
now = time.strftime("%a %b %d %H:%M:%S %Z %Y")

# Set paths
log_file = '{0}/logs/integrations.log'.format(pwd)

def main(args):
debug("# Starting")

# Read args
alert_file_location = args[1]
webhook = GCHAT_URI

debug("# Webhook")
debug(webhook)

debug("# File location")
debug(alert_file_location)

# Load alert. Parse JSON object.
with open(alert_file_location) as alert_file:
json_alert = json.load(alert_file)
debug("# Processing alert")
debug(json_alert)

debug("# Generating message")
msg = generate_msg(json_alert)
debug(msg)

debug("# Sending message")
send_msg(msg, webhook)

def debug(msg):
if debug_enabled:
msg = "{0}: {1}\n".format(now, msg)
print(msg)
f = open(log_file, "a")
f.write(msg)
f.close()

def generate_msg(alert):

title = alert['rule']['description'] if 'description' in alert['rule'] else "N/A"

cards = {'cards':[{'header':{'title':title}}]}

return json.dumps(cards)

def send_msg(msg, url):
headers = {'Content-Type': 'application/json; charset=UTF-8'}

http_obj = httplib2.Http()

response = http_obj.request(
uri=url,
method='POST',
headers=headers,
body=msg,
)
debug(response)

if __name__ == "__main__":
try:
# Read arguments
bad_arguments = False
if len(sys.argv) >= 4:
msg = '{0} {1} {2} {3} {4}'.format(
now,
sys.argv[1],
sys.argv[2],
sys.argv[3],
sys.argv[4] if len(sys.argv) > 4 else '',
)
debug_enabled = (len(sys.argv) > 4 and sys.argv[4] == 'debug')
else:
msg = '{0} Wrong arguments'.format(now)
bad_arguments = True

# Logging the call
f = open(log_file, 'a')
f.write(msg + '\n')
f.close()

if bad_arguments:
debug("# Exiting: Bad arguments.")
sys.exit(1)

# Main function
main(sys.argv)

except Exception as e:
debug(str(e))
raise

2- Change permissions and ownership: chmod 750 /var/ossec/integrations/custom-gchat; chown root:wazuh /var/ossec/integrations/custom-gchat
3- Add desired integration configuration block into Wazuh Manager’s ossec.conf

<integration>
  <name>custom-gchat</name>
  <level>10</level>
  <alert_format>json</alert_format>
</integration>

4- Restart Wazuh Manager
5- Enjoy!

Feel free to change generate_msg function to customize your message according your needs and Google Chat API message formats reference.

Regards,

Nico

Juan Nicolás Asselle

unread,
Oct 12, 2021, 11:49:58 AM10/12/21
to Wazuh mailing list

Hi Raj,

There was an indentation error while copy pasting python script. Here we go again

#!/usr/bin/env python
# Copyright (C) 2015-2021, Wazuh Inc.
#
# This program is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public
# License (version 2) as published by the FSF - Free Software
# Foundation.

import json
import sys
import time
import os
import httplib2

try:
    import requests
    from requests.auth import HTTPBasicAuth
except Exception as e:
    print("No module 'requests' found. Install: pip install requests")
    sys.exit(1)

# Global vars

Regards,
Nico

Raj Vira

unread,
Oct 13, 2021, 4:43:16 AM10/13/21
to Juan Nicolás Asselle, Wazuh mailing list
Hi Nico, 

Thank you so much for the script, I am receiving the desired alerts.

Warm regards,

Raj Vira

Associate Information Security Officer | IS Department

+91 7949006565 [ext :469] 

Acute Informatics Pvt. Ltd.| www.acuteinformatics.in


"CONFIDENTIALITY NOTICE: The information transmitted in this email and any attachments herein is confidential and is intended for the addressee(s) only. If you have received this email in error, please notify us immediately, delete the message from your computer system and destroy hard copies if any. If you are not the intended recipient, any unauthorized disclosure, copying, distribution, dissemination, publication, use of or access to the information contained herein is strictly prohibited. The obligation of confidentiality is a binding legal obligation, a proven breach of which will result in the imposition of damages. Although every effort has been made to ensure that this email is virus-free, it is recommended that you scan this email and any attachments thereto for viruses and Acute Informatics Pvt. Ltd. accepts no responsibility for any damage to the recipient’s system caused by this email and/or its attachments. Please note that messages to or from Acute Informatics Pvt. Ltd. may be monitored to ensure compliance with our policies."



--
You received this message because you are subscribed to the Google Groups "Wazuh mailing list" group.
To unsubscribe from this group and stop receiving emails from it, send an email to wazuh+un...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/wazuh/6e96990b-034d-47b1-b0be-219c934dfd4cn%40googlegroups.com.

Raj Vira

unread,
Oct 13, 2021, 5:19:07 AM10/13/21
to Juan Nicolás Asselle, Wazuh mailing list
Hi Nico,

Also to mention that Wazuh 4.0 does not have a Wazuh group in the server and while applying chown root:wazuh /var/ossec/integrations/custom-gchat I had to change it to group ossec.

 chown root:ossec /var/ossec/integrations/custom-gchat

Warm regards,

Raj Vira

Associate Information Security Officer | IS Department

+91 7949006565 [ext :469] 

Acute Informatics Pvt. Ltd.| www.acuteinformatics.in


"CONFIDENTIALITY NOTICE: The information transmitted in this email and any attachments herein is confidential and is intended for the addressee(s) only. If you have received this email in error, please notify us immediately, delete the message from your computer system and destroy hard copies if any. If you are not the intended recipient, any unauthorized disclosure, copying, distribution, dissemination, publication, use of or access to the information contained herein is strictly prohibited. The obligation of confidentiality is a binding legal obligation, a proven breach of which will result in the imposition of damages. Although every effort has been made to ensure that this email is virus-free, it is recommended that you scan this email and any attachments thereto for viruses and Acute Informatics Pvt. Ltd. accepts no responsibility for any damage to the recipient’s system caused by this email and/or its attachments. Please note that messages to or from Acute Informatics Pvt. Ltd. may be monitored to ensure compliance with our policies."


Matt Schenkman

unread,
Nov 22, 2021, 4:31:14 PM11/22/21
to Wazuh mailing list
Hey all,

I'm working through this nifty article and have everything setup... except it doesn't work.

This is the error I get: 
2021/11/22 16:12:40 wazuh-integratord: ERROR: Couldn't execute command (integrations /tmp/custom-gchat-v2-1637615560-149531200.alert    > /dev/null 2>&1). Check file and permissions.

I checked the 750 and did chmod. I installed python3 pip. Not sure what else to do. I turned on debugging in the custom integrator but get nothing extra in the logs except for 'wrong arguments' which looks to be stemming from the if __name__ == "__main__" line of the custom config. 

Thanks!

Juan Carlos

unread,
Nov 29, 2021, 5:10:59 AM11/29/21
to Wazuh mailing list
Hi Matt,
This error message will occur if the integrator daemon (which is run as the ossecm user which is part of the ossec user group) does not have execution permissions over the script.
I noticed that there was a typo in the instructions provided by my colleague, where the ownership information is set he used the wazuh group instead of ossec. In the future we will be migrating this group so he may have tested this in a development version of the software.
Running the following command should resolve your issue:
chown root:ossec /var/ossec/integrations/custom-gchat

Please let us know if you have any more questions.
Best Regards,
Juan Carlos Tello

Matt Schenkman

unread,
Dec 1, 2021, 11:38:15 AM12/1/21
to Wazuh mailing list
Thanks Juan. It was a bad symlink to Python. I corrected it by issuing a similar command to sudo ln -s /usr/bin/python3.4 /usr/bin/python to repair the link. The alerts I get from Wazuh to Gchat vary based on OS and I was wondering if there was a way to standardize?

Linux Example for SSH alert:

sshd: insecure connection attempt (scan).
hostname-test
Dec 1 15:41:42 hostname-test sshd[9553]: Did not receive identification string from <IP Address> port 59430

Windows Example for audit failure:

Windows audit failure event FCPAD02

Thanks in advance!


Juan Carlos

unread,
Dec 3, 2021, 9:19:42 AM12/3/21
to Wazuh mailing list
Hi Matt,
Great to know it's working now.
To avoid any python dependency issue you may modify the script to use Wazuh's bundled python instead of your system's. You can do this by changing the first line to be:
#!/var/ossec/framework/python/bin/python3

I also noticed the script provided by my colleague used the httplib2 library which is not as commonly present, so I modified the script to use requests instead.

Regarding alert standardization, yes, you may either specify the fields that you're interested in seeing by modifying the generate_msg function and adjusting it to your specific needs. From the examples you show it seems you have added hostname and full_log as additional fields already, however most Windows events do not include full_log as the event is fully decoded and indexed as separate fields by way of the EventChannel internal decoder.

You can for example generate a message that highlights key fields like rule description, level, id and event location and then send the full content of the alert like so:
def generate_msg(alert):
    title  = alert['rule']['description']
    subtitle = 'Rule: {}, Level: {}, Agent: {}'.format(alert['rule']['id'],alert['rule']['level'],alert['agent']['name'])
    text = '<font color="#ff0000"><b>{title}</b></font>\n<font color="#00a9e5">{subtitle}</font>\n<b>Full alert:</b>{alert}'.format(title=title,subtitle=subtitle,alert=json.dumps(alert,indent=4))
    cards = {"cards": [{"sections": [{"widgets": [{"textParagraph": {"text": text}}]}]}]}
    return json.dumps(cards)


Note that Google Chat does allow you to add many formatting options, for more information you can see:

You can find attached the script edited to remove the dependency on external python and use this more complex message format.

Let me know if you have any more questions.
Best Regards,
Juan Carlos Tello
custom-gchat

Milton Matamala

unread,
Jan 9, 2022, 3:57:26 AM1/9/22
to Wazuh mailing list
Hello!

I currently have version 4.2.1 of Wazuh, I followed all the steps for the integration but I still do not receive the alerts in Google Chats, when I check the log I get this message:

ERROR: Invalid integration: 'google_chat'. Not currently supported.

Does anyone know what the event is due to?

Matt Schenkman

unread,
Jan 9, 2022, 7:53:22 AM1/9/22
to Milton Matamala, Wazuh mailing list
Did you install the python dependencies with pip? They're usually in the commented out portion at the top. I had to install pip first, then the dependencies.



You received this message because you are subscribed to a topic in the Google Groups "Wazuh mailing list" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/wazuh/Qf17CexqJ6U/unsubscribe.
To unsubscribe from this group and all its topics, send an email to wazuh+un...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/wazuh/8416550b-8025-4f41-ad44-7a16c4508bb5n%40googlegroups.com.

Milton Matamala

unread,
Jan 9, 2022, 12:46:10 PM1/9/22
to Wazuh mailing list
Hi Matt

Yes I installed the necessary dependencies, I even have the VirusTotal integration which occupies almost the same dependencies. I test with the script that appears in the webhook documentation with python Google Chat Developer and it works correctly.

-rwxr-x---  1 root ossec  845 Jan  9 05:11 google_chat
-rwxr-x---  1 root ossec 2923 Jan  9 06:23 google_chat.py

google_chat.sh
custom-gchat.py

Matt Schenkman

unread,
Jan 9, 2022, 3:07:36 PM1/9/22
to Milton Matamala, Wazuh mailing list
Can you check the wazuh logs? I know the integration log doesn't show much, but hopefully the wazuh syslog will show you more. otherwise you can try grepping the syslog for wazuh.



--
Matt Schenkman
IT Operations Manager
FCP Euro

m. 347.416.NERD
e.  matt.sc...@fcpeuro.com
w. fcpeuro.com
 
facebooklinkedintwitteryoutubefacebooklinkedin
Every Part You Buy Is GUARANTEED FOR LIFE

Juan Carlos

unread,
Jan 10, 2022, 5:10:38 AM1/10/22
to Wazuh mailing list
Hi Milton,

All custom integrations must have a filename that begins with the string custom- so you may name your file custom-google_chat and use this name in the integration's configuration.


Best Regards,
Juan Carlos Tello

Milton Matamala

unread,
Jan 10, 2022, 6:31:45 AM1/10/22
to Juan Carlos, Wazuh mailing list
Hello Juan Carlos,

Thank you very much for the answer, indeed I had misspelled the name of the script, now I receive the alerts without problems in Google Chat.

Regards. :)

sumanth koppula

unread,
Oct 24, 2024, 1:35:30 AM10/24/24
to Wazuh | Mailing List
Hello Everyone, 

I have followed the steps from this chain, created the files and added the integration to the ossec.conf. I am not receiving the alerts on the google chat space. Please find the screenshots for reference.
scripts.png

Scripts - 
custom-gchat
custom-gchat.png

#!/usr/bin/env python
# Copyright (C) 2015-2021, Wazuh Inc.
#
# This program is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public
# License (version 2) as published by the FSF - Free Software
# Foundation.

import json
import sys
import time
import os
import httplib2

try:
    import requests
    from requests.auth import HTTPBasicAuth
except Exception as e:
    print("No module 'requests' found. Install: pip install requests")
    sys.exit(1)

# Global vars
GCHAT_URI = '<webhook>'
custom-gchat.py
Reply all
Reply to author
Forward
0 new messages