Chat
Search
Ithy Logo

Solution for Sending Automated Email Notifications on Tenable Scans Without SMTP Authentication

Effective methods to analyze Tenable scans and notify owners despite infrastructure limitations.

email notification setup

Key Takeaways

  • Leverage API-based Email Services: Utilize services like SendGrid or Mailgun to send emails without relying on SMTP authentication.
  • Implement Internal SMTP Relay: Set up a relay server to dispatch emails from trusted sources without requiring authentication.
  • Explore Alternative Notification Channels: Use platforms such as Slack, Microsoft Teams, or SMS for additional or temporary notification methods.

Introduction

When tasked with automating the process of analyzing upcoming Tenable scans and notifying application owners, infrastructure limitations such as disabled SMTP authentication can pose significant challenges. This comprehensive guide explores alternative solutions to achieve these objectives without relying on traditional SMTP authentication or Microsoft Graph API.

Analyzing Upcoming Tenable Scans

Utilizing the Tenable API

To automate the analysis of upcoming Tenable scans, leverage the Tenable API. The following steps outline how to fetch and process scan data:

1. Authenticate with the Tenable API

Generate an API access key from the Tenable platform to authenticate your requests.

2. Fetch Scheduled Scans

Use endpoints such as GET /scans and GET /scans/{scan_id} to retrieve scan schedules and details.

3. Filter Scans Occurring in the Next 24 Hours

Process the retrieved scan data to identify scans scheduled within the next 24 hours. This can be achieved by comparing the scheduled time with the current date and time.

Example: Fetching and Filtering Scans in Python


import requests
from datetime import datetime, timedelta

# Configure Tenable API credentials
API_KEY = 'your_tenable_api_key'
HEADERS = {
    'X-ApiKeys': f'accessKey={API_KEY}; secretKey=your_secret_key',
    'Content-Type': 'application/json'
}

def get_upcoming_scans():
    response = requests.get('https://cloud.tenable.com/scans', headers=HEADERS)
    scans = response.json().get('scans', [])
    upcoming_scans = []
    now = datetime.utcnow()
    next_24_hours = now + timedelta(hours=24)
    
    for scan in scans:
        scheduled_time = datetime.strptime(scan['schedule']['start'], '%Y-%m-%dT%H:%M:%S.%fZ')
        if now <= scheduled_time <= next_24_hours:
            upcoming_scans.append(scan)
    
    return upcoming_scans

# Example usage
upcoming_scans = get_upcoming_scans()
for scan in upcoming_scans:
    print(f"Scan ID: {scan['id']}, Scheduled At: {scan['schedule']['start']}")
  

Sending Email Notifications Without SMTP Authentication

1. API-Based Email Services

API-based email services offer a robust alternative to traditional SMTP authentication. These services provide RESTful APIs secured with API keys or OAuth tokens, ensuring secure and authenticated email transmission.

Popular API-Based Email Services

Service Authentication Features Documentation
SendGrid API Keys, OAuth Email sending, tracking, templates SendGrid Docs
Mailgun API Keys Email sending, validation, analytics Mailgun Docs
Amazon SES API Keys, IAM Roles Scalable email sending, tracking Amazon SES Docs

Implementation Example: Using SendGrid in Python


import os
import sendgrid
from sendgrid.helpers.mail import Mail

def send_notification(to_email, subject, content):
    sg = sendgrid.SendGridAPIClient(api_key=os.getenv('SENDGRID_API_KEY'))
    mail = Mail(
        from_email='your_team_email@example.com',
        to_emails=to_email,
        subject=subject,
        html_content=content
    )
    response = sg.send(mail)
    return response.status_code

# Example usage
status = send_notification(
    'owner@example.com',
    'Upcoming Tenable Scan Alert',
    '<p>Your application is scheduled for a Tenable scan within the next 24 hours.</p>'
)
print(f"Email sent with status code: {status}")
  

Implementation Example: Using Mailgun in Python


import requests

def send_notification(to_email, subject, content):
    api_key = 'your_mailgun_api_key'
    domain = 'your_mailgun_domain'
    sender = 'your_team_email@example.com'
    
    return requests.post(
        f"https://api.mailgun.net/v3/{domain}/messages",
        auth=("api", api_key),
        data={
            "from": sender,
            "to": to_email,
            "subject": subject,
            "html": content
        }
    ).status_code

# Example usage
status = send_notification(
    'owner@example.com',
    'Upcoming Tenable Scan Alert',
    '<p>Your application is scheduled for a Tenable scan within the next 24 hours.</p>'
)
print(f"Email sent with status code: {status}")
  

2. Implementing an Internal SMTP Relay

If API-based services are not preferable, setting up an internal SMTP relay can bypass the need for SMTP authentication by allowing trusted sources to send emails through the relay server.

Steps to Set Up an Internal SMTP Relay

  1. Deploy a Mail Server: Install a lightweight mail server like Postfix on an internal server.
  2. Configure Relay Permissions: Set the server to accept emails from trusted IP addresses or specific sources without requiring authentication.
  3. Update Script SMTP Settings: Modify your script to use the internal relay server’s address and port.
  4. Test the Configuration: Send test emails to ensure the relay is functioning correctly.

Example: Configuring Postfix as an SMTP Relay


# Install Postfix
sudo apt-get update
sudo apt-get install postfix

# During installation, choose "Satellite system" and set the relay host accordingly.

# Edit the Postfix configuration
sudo nano /etc/postfix/main.cf

# Add or modify the following lines:
relayhost = [your.internal.smtp.relay]:25
mynetworks = 127.0.0.1, [your.trusted.ip.address]/32

# Restart Postfix to apply changes
sudo systemctl restart postfix
  

Updating the Python Script to Use the Internal Relay


import smtplib
from email.mime.text import MIMEText

def send_notification(to_email, subject, content):
    msg = MIMEText(content)
    msg['Subject'] = subject
    msg['From'] = 'your_team_email@example.com'
    msg['To'] = to_email

    with smtplib.SMTP('your.internal.smtp.relay', 25) as server:
        server.send_message(msg)
        return "Email sent successfully."

# Example usage
status = send_notification(
    'owner@example.com',
    'Upcoming Tenable Scan Alert',
    '<p>Your application is scheduled for a Tenable scan within the next 24 hours.</p>'
)
print(status)
  

3. Utilizing Azure Communication Services

Azure Communication Services offer a modern approach to sending emails through secure APIs. Once your cloud tenant is operational, this can be integrated seamlessly with your existing Azure infrastructure.

Steps to Use Azure Communication Services Email

  1. Set Up Azure Communication Services Resource: Create an Email resource in your Azure subscription.
  2. Register Your Application: Use Azure AD to register your application and obtain necessary permissions.
  3. Integrate the Email SDK: Incorporate the Azure Communication Services Email SDK into your script to send emails.

Example: Sending Email with Azure Communication Services in Python


from azure.communication.email import EmailClient, EmailContent, EmailAddress, EmailMessage

def send_notification(to_email, subject, content):
    connection_string = "your_connection_string"
    client = EmailClient.from_connection_string(connection_string)
    
    message = EmailMessage(
        sender="your_team_email@yourdomain.com",
        content=EmailContent(
            subject=subject,
            plain_text=content
        ),
        recipients=[EmailAddress(email=to_email)]
    )
    
    response = client.send(message)
    return response.status

# Example usage
status = send_notification(
    'owner@example.com',
    'Upcoming Tenable Scan Alert',
    'Your application is scheduled for a Tenable scan within the next 24 hours.'
)
print(f"Email sent with status: {status}")
  

Exploring Alternative Notification Channels

1. Collaboration Platforms

Platforms like Slack and Microsoft Teams offer APIs that can be leveraged to send notifications directly to relevant channels or users.

Using Slack Webhooks


import requests

def send_slack_notification(webhook_url, message):
    payload = {"text": message}
    response = requests.post(webhook_url, json=payload)
    return response.status_code

# Example usage
status = send_slack_notification(
    'https://hooks.slack.com/services/your/webhook/url',
    'Upcoming Tenable Scan Alert: Your application is scheduled for a scan within the next 24 hours.'
)
print(f"Slack notification sent with status code: {status}")
  

Using Microsoft Teams Webhooks


import requests

def send_teams_notification(webhook_url, message):
    headers = {'Content-Type': 'application/json'}
    payload = {"text": message}
    response = requests.post(webhook_url, json=payload, headers=headers)
    return response.status_code

# Example usage
status = send_teams_notification(
    'https://outlook.office.com/webhook/your/webhook/url',
    'Upcoming Tenable Scan Alert: Your application is scheduled for a scan within the next 24 hours.'
)
print(f"Teams notification sent with status code: {status}")
  

2. SMS Notifications

For immediate attention, SMS notifications can be sent using services like Twilio.

Example: Sending SMS with Twilio in Python


from twilio.rest import Client

def send_sms(to_number, message):
    account_sid = 'your_twilio_account_sid'
    auth_token = 'your_twilio_auth_token'
    client = Client(account_sid, auth_token)
    
    message = client.messages.create(
        body=message,
        from_='+1234567890',
        to=to_number
    )
    return message.sid

# Example usage
sid = send_sms(
    '+0987654321',
    'Upcoming Tenable Scan Alert: Your application is scheduled for a scan within the next 24 hours.'
)
print(f"SMS sent with SID: {sid}")
  

Hosting and Scheduling the Script

1. On-Premise Server or Virtual Machine

Host the script on an on-premise server or a virtual machine to maintain control over the execution environment.

2. Scheduling the Script

Use scheduling tools to automate the daily execution of the script.

Using Cron Jobs on Linux


# Open the crontab editor
crontab -e

# Add the following line to run the script daily at 8 AM
0 8 * * * /usr/bin/python3 /path/to/your/script.py
  

Using Task Scheduler on Windows


# Open Task Scheduler and create a new task
# Set the trigger to daily at your desired time
# Configure the action to run the Python script
  

Security Considerations

1. Secure Storage of API Keys

Ensure that API keys and credentials are stored securely, preferably using environment variables or secure vaults, to prevent unauthorized access.

2. Compliance with Organizational Policies

Verify that the chosen solutions comply with your organization’s security policies and data protection regulations to avoid potential compliance issues.

3. Implement Robust Error Handling

Incorporate error handling mechanisms within your scripts to manage failures in API calls or email sends, potentially including retry strategies or fallback options.


Future-Proof Solutions

Transitioning to Microsoft Graph API

Once your cloud tenant is operational, consider migrating to the Microsoft Graph API for a more integrated and supported email sending solution within the Azure ecosystem.

Scalability and Flexibility

Design your script to be easily adaptable for future workflows or to incorporate additional notification channels as needed, ensuring long-term scalability.


Conclusion

Despite the limitations posed by disabled SMTP authentication and the unavailability of Microsoft Graph API, there are robust alternative solutions to automate the analysis of Tenable scans and notify application owners. By leveraging API-based email services such as SendGrid or Mailgun, setting up an internal SMTP relay, or exploring alternative notification channels like Slack and SMS, you can achieve your objectives efficiently. Additionally, ensuring secure handling of credentials and compliance with organizational policies will fortify your solution against potential vulnerabilities.

References


Last updated January 16, 2025
Ask Ithy AI
Export Article
Delete Article