← All N8N workflows
Data & databasesCodeGmailHtmlHTTP RequestIf

Suspicious_login_detection

Configured with Gmail, Html, HTTP Request, Postgres, and additional nodes. Review the connections and setup before adapting this template.

Workflow preview
TransformExtract relevant dataEdit FieldsTriggerNew /login eventWebhookRoutingUnknown threat?IfData storeGet last 10 logins fromthe same userPostgresWeb / APIQuery IP API1HTTP RequestRoutingNew location?IfWeb / APIParse User AgentHTTP RequestTransformMergeMergeRoutingNew Device/Browser?IfTransformComplete login infoMergeData storeQuery user by IDPostgresRoutingNew LocationNo OpRoutingNew Device/BrowserNo OpRoutingUser has email?IfTransformHTMLHtmlMessagingInform userGmailRoutingnoise?IfMessagingSlackSlackRoutingCheck trust levelSwitchRoutingCheck classificationSwitchRoutingriot?IfTransform🔴 Priority: HIGHEdit FieldsTransform🟡 Priority: MEDIUMEdit FieldsTransform🟢 Priority: LOWEdit FieldsWeb / APIGreyNoiseHTTP RequestWeb / APIIP APIHTTP RequestWeb / APIUserParserHTTP RequestTriggerWhen clicking "ExecuteWorkflow"Manual TriggerCodeExample eventCodeRoutingKnown, Do NothingNo OpRoutingKnown LocationNo OpRoutingOld Device/BrowserNo OpRoutingNot RiotNo Op

Node categories in this workflow

  • Transform
  • Trigger
  • Routing
  • Data store
  • Web / API
  • Messaging
  • Code

Icons describe general node roles, inferred from node types. Inspect the parameters for the configured action.

Drag to pan; use + and − to zoom. Reconstructed from the exported node positions; nothing runs here. Dashed lines represent non-main connections. Full node names and notes appear below.

How it works

The exported workflow contains the following configured nodes. Their connections are shown above; inspect the JSON for the complete logic, expressions, and external actions.

Workflow node names, types, and operations
NodeCategoryTypeOperation
Extract relevant dataTransformEdit FieldsSee node parameters
New /login eventTriggerWebhookSee node parameters
Unknown threat?RoutingIfSee node parameters
Get last 10 logins from the same userData storePostgresexecuteQuery
Query IP API1Web / APIHTTP RequestSee node parameters
New location?RoutingIfSee node parameters
Parse User AgentWeb / APIHTTP RequestSee node parameters
MergeTransformMergeSee node parameters
New Device/Browser?RoutingIfSee node parameters
Complete login infoTransformMergeSee node parameters
Query user by IDData storePostgresexecuteQuery
New LocationRoutingNo OpSee node parameters
New Device/BrowserRoutingNo OpSee node parameters
User has email?RoutingIfSee node parameters
HTMLTransformHtmlSee node parameters
Inform userMessagingGmailSee node parameters
noise?RoutingIfSee node parameters
SlackMessagingSlackSee node parameters
Check trust levelRoutingSwitchSee node parameters
Check classificationRoutingSwitchSee node parameters
riot?RoutingIfSee node parameters
🔴 Priority: HIGHTransformEdit FieldsSee node parameters
🟡 Priority: MEDIUMTransformEdit FieldsSee node parameters
🟢 Priority: LOWTransformEdit FieldsSee node parameters
GreyNoiseWeb / APIHTTP RequestSee node parameters
IP APIWeb / APIHTTP RequestSee node parameters
UserParserWeb / APIHTTP RequestSee node parameters
When clicking "Execute Workflow"TriggerManual TriggerSee node parameters
Example eventCodeCodeSee node parameters
Known, Do NothingRoutingNo OpSee node parameters
Known LocationRoutingNo OpSee node parameters
Old Device/BrowserRoutingNo OpSee node parameters
Not RiotRoutingNo OpSee node parameters

Setup

  1. Download the JSON and import it into an isolated n8n instance. Leave the workflow inactive.
  2. Connect your own credentials through n8n’s credential store. Replace REPLACE_WITH_* values with your resource identifiers.
  3. Inspect API destinations, Code nodes, database queries, file paths, and outbound actions.
  4. Run with synthetic data and harmless destinations. Enable triggers only after checking the actual outputs.

Requirements

An n8n instance with the listed node types and compatible versions. Service-connected workflows may require accounts, credentials, or paid APIs.

Credential types declared in the source

  • gmailOAuth2
  • httpHeaderAuth
  • httpQueryAuth
  • postgres
  • slackApi

Workflow notes

🚦 Advanced Threat Prioritization with GreyNoise Data

🚦 Advanced Threat Prioritization with GreyNoise Data

In this section of the workflow, the integration of GreyNoise data, particularly in the GreyNoise node, plays a pivotal role in refining the threat prioritization process. This node's interaction with GreyNoise ensures that each alert is given an appropriate level of attention, based on the nature of the IP address involved.

  • GreyNoise Analysis for Inbound Threats: When the GreyNoise node identifies an IP address, it queries GreyNoise, considering both NOISE and RIOT datasets (More here). The response from this node guides the subsequent steps:
    • High Priority for Unknown IPs: The Check trust level and Check classification nodes act here. If GreyNoise has no data on the IP (noise:false, riot:false), the priority is set high in the 🔴 Priority: HIGH node. This indicates a potential targeted attack, requiring immediate analyst review.
    • Low to Medium Priority for Common Business Services: IPs identified as part of common business services (riot:true), depending on their trust level and operation status, are assigned low to medium priority by the 🟡 Priority: MEDIUM and 🟢 Priority: LOW nodes. This reflects a lower risk of malicious activity.
  • Classification-Based Prioritization: The workflow also considers the GreyNoise classification of the IP (malicious, benign, unknown) in the Check classification node:
    • Malicious IPs: Medium-high priority, suggesting opportunistic but potentially harmful activity, set in the 🔴 Priority: HIGH node.
    • Benign IPs: Low priority, as these are usually harmless scans by known actors, designated in the 🟢 Priority: LOW node.
    • Unknown IPs: Low-medium priority, indicating possibly innocuous but unverified activity, managed by the 🟡 Priority: MEDIUM node.
  • Additional Context for Outbound Threats: For outbound connections, the workflow prioritizes alerts based on whether the IP is a known service provider or a known device scanning the internet, as interpreted by the GreyNoise node. High priority is assigned to outbound connections to scanning devices in the 🔴 Priority: HIGH node, indicating potentially unwanted behavior.

This approach, leveraging GreyNoise's advanced data analytics, showcases n8n's capability to deliver sophisticated cybersecurity solutions. By integrating this intelligent prioritization mechanism, the workflow ensures that your security team focuses on the most pressing threats first, enhancing overall security posture.

Authentication - No Free Tier Available

To set your API key for GreyNoise, open the GreyNoise node, and add a new authentication credential. Choose Generic Credential Type then Header Auth. Lastly, under Credential for Header Auth set the name to key and value to your api key.

📢 Slack Notification for Alert Dissemination

📢 Slack Notification for Alert Dissemination

The Slack node plays a crucial role in alert communication. It ensures that once a threat is identified and prioritized, the relevant information is quickly disseminated to your security team via Slack.

  • Timely Alert Notifications: The Slack node is configured to send detailed alerts to a specified Slack channel. These alerts include critical information such as the priority level, user ID, IP address, timestamp, and user agent of the suspicious login attempt. It ensures that your team is promptly informed about potential threats, allowing for quick action to mitigate risks.
  • Integration of Data from Previous Nodes: This node adeptly utilizes data extracted and processed by earlier nodes like Extract relevant data. It enriches the Slack message with this detailed information, providing a comprehensive overview of the threat.
  • Direct Link to GreyNoise Analysis: Additionally, the Slack message includes a direct link to the GreyNoise visualization for the IP in question. This link, crafted using data from the Extract relevant data node, allows team members to quickly access in-depth information about the IP, facilitating a faster and more informed response.

This approach demonstrates n8n's ability to integrate seamlessly with communication tools like Slack, ensuring that cybersecurity teams are always informed and ready to respond to threats efficiently.

🔄 Synthesizing Data for Comprehensive Analysis

🔄 Synthesizing Data for Comprehensive Analysis

The Complete login info node serves as a crucial juncture, integrating data from multiple sources for a detailed analysis of each login attempt.

  • Combining Multiple Data Streams: The Complete login info node merges information from the GreyNoise, IP API, and UserParser nodes. This process creates a comprehensive dataset by combining threat intelligence from GreyNoise, geolocation details from IP-API, and user agent information from UserParser.
  • Enhanced Context for Security Analysis: By amalgamating data from these varied sources, the workflow gains a multi-faceted view of each login attempt. This enriched context is essential for identifying potential security threats with higher precision.
  • Efficient Workflow Structure: The integration of these diverse data points exemplifies n8n's efficiency in managing complex workflows. By funneling various streams of information into a single node, the workflow ensures that all relevant data is considered in unison during the analysis phase.
  • Informing Subsequent Workflow Steps: The dataset prepared by the Complete login info node lays the groundwork for further steps in the workflow. It provides the necessary context for nodes that follow, such as the Unknown threat? and Get last 10 logins from the same user nodes, to make informed decisions based on a holistic view of the login event.
📍 Assessing Login Location Anomalies

📍 Assessing Login Location Anomalies

The nodes following Get last 10 logins from the same user are dedicated to analyzing login location patterns to identify any anomalies.

  • Fetching Historical Login Data: The Get last 10 logins from the same user node queries a Postgres database to retrieve the last 10 login records for a user. This data forms the baseline for identifying unusual login locations.

  • Comparing Current and Historical Geolocation Data: The Query IP API1 node fetches the geolocation data for the current login attempt. This data is then compared with historical login locations in the New location? node.

  • Identifying Location Anomalies: The New location? node checks if the city from the current login is different from the cities in the user's login history. This comparison is crucial to detect any unusual login patterns, such as logins from new, potentially suspicious locations.

  • Routing Based on Location Consistency: Depending on whether the current login location matches historical patterns, the workflow branches to either the New Location or Known Location nodes. The New Location node triggers when a login from a new city is detected, indicating a potential security risk. Conversely, the Known Location node is activated when the login location is consistent with historical data, suggesting a regular login pattern.

📧 Notifying Users About Unusual Login Attempts

📧 Notifying Users About Unusual Login Attempts

In the final section of the "Suspicious Login Detection" workflow, the nodes User has email?, HTML, and Inform user work together to notify users about unusual login attempts, enhancing the security and responsiveness of the system.

  • Verifying Email Availability: After fetching user details with Query user by ID, the User has email? node checks if the user has an email address on record. This verification is crucial to ensure that the notification process proceeds only for users with valid email addresses.

  • Crafting the Notification Message: The HTML node is responsible for creating the email content. It generates a well-formatted HTML message informing the user of a recent login from a new device or location. The message includes details like username, timestamp, location, and device information, providing the user with specific insights into the login activity.

  • Sending the Email Alert: Finally, the Inform user node sends out the email notification. This node uses Gmail to dispatch the message crafted by the HTML node to the user's email address obtained in the previous steps.

  • Enhancing User Awareness and Security: By notifying users of unusual login activities, the workflow not only enhances security but also empowers users to take immediate action if the login was not authorized. This could include steps like changing their password or contacting the security team.

🧩 Querying User Details for Enhanced Context

🧩 Querying User Details for Enhanced Context

The Query user by ID node plays a key role in gathering additional user-specific information to provide enhanced context for the security analysis.

  • User Information Retrieval: The Query user by ID node interacts with a Postgres database to fetch detailed information about the user whose ID is associated with the current login attempt. This information is crucial for understanding the user's profile and access patterns.

  • Integrating with Location and Device Analysis: This node is triggered following alerts from either the New Location or New Device/Browser nodes. These alerts indicate that the current login attempt is potentially suspicious due to a new location or device/browser being used.

  • Enriching Security Insight: By querying detailed user data, the workflow gains a deeper understanding of the user's normal access patterns and profiles. This information can be instrumental in differentiating between legitimate user behavior and potential unauthorized access.

Workflow Overview

Workflow Overview

Experience enhanced cybersecurity with the Suspicious Login Detection workflow in n8n, your go-to solution for real-time monitoring and rapid response to suspicious login activities. This workflow is versatile, with both manual and automated webhook triggers to suit your testing and operational needs.

This this GreyNoise guide was used to design the architecture of this workflow and can serve as a guide for making your own version of this workflow.

Key features include:

  • Data Extraction: Seamlessly extracts crucial data like IP addresses and user IDs from login events.
  • Triple-Threat Analysis: Splits into three paths for thorough scrutiny, using GreyNoise for IP trust assessment, IP-API for geolocation insights, and UserParser for user agent details.
  • Prioritized Alerts: Assigns alert priorities and swiftly notifies via Slack, ensuring immediate attention to high-risk activities.
  • In-depth Investigation: Cross-references login history for anomalies and flags potential threats, keeping your security team a step ahead.

Easy to set up and adaptable, this n8n workflow is a powerhouse tool for safeguarding your digital environment.

▶️Initial Trigger: Detecting Suspicious Logins

The initial trigger of this workflow is the detection of new login events. This is achieved through a combination of a webhook (New /login event node), set to trigger upon a new /login event, and a manual trigger (When clicking "Execute Workflow" node) for testing purposes. The webhook is configured to receive data from login events, capturing vital information such as IP addresses and user details.

This setup is crucial for real-time monitoring of login activities. As soon as a login event occurs, the workflow springs into action, extracting and processing the relevant data using the Extract relevant data node.

🌐 IP Geolocation with IP-API

🌐 IP Geolocation with IP-API

The IP API node in the "Suspicious Login Detection" workflow adds crucial geolocation context to login events. It queries IP-API for geographical data on the IP address extracted earlier.

  • Geographical Insight: This node provides geographical details like country, region, and city, helping to identify unusual login locations that might signal a security risk.
  • Enhanced Security Analysis: The geographical data aids in assessing the legitimacy of login attempts, adding a valuable layer to the security analysis.

Authentication - Free Tier Available (45 requests/min)

This endpoint is limited to 45 requests per minute from an IP address.

If you go over the limit your requests will be throttled (HTTP 429) until your rate limit window is reset. If you constantly go over the limit your IP address will be banned for 1 hour.

No authentication needed, Click here to view documentation.

🔄 Merging Geolocation and User Agent Data

🔄 Merging Geolocation and User Agent Data

In the "Suspicious Login Detection" workflow, the Merge node plays a pivotal role in synthesizing information from the IP API and UserParser nodes.

  • Data Integration: The Merge node combines data from two key sources: geolocation details from the IP API node and user agent information from the UserParser node. This integration offers a comprehensive view of each login event.

  • Comprehensive Analysis: By merging geolocation and user agent data, the workflow gains a fuller understanding of the context behind each login attempt, crucial for accurately assessing security risks.

  • Efficient Workflow Design: The use of the Merge node demonstrates n8n's efficient handling of diverse data streams, ensuring that all relevant information is brought together for a cohesive analysis.

Authentication - Free Tier Available (10000 calls / month)

This endpoint is limited to 500 calls / day.

To set your API key for UserParser, open the UserParser HTTP Request node, and add a new authentication credential. Choose Generic Credential Type then Query Auth. Lastly, under Credential for Query Auth set the name to api_key and value to your api key.

Click here to view documentation.

📱 Identifying Device and Browser Anomalies

📱 Identifying Device and Browser Anomalies

the Parse User Agent and New Device/Browser? nodes focus on detecting anomalies in device and browser usage for login events.

  • Parsing User Agent Data: The Parse User Agent node uses the UserParser API to analyze the user agent string from the current login attempt. This node extracts detailed information about the browser, operating system, and device type used for the login, offering crucial insights into the login environment.

  • Comparing with Historical Data: After parsing the user agent data, the workflow proceeds to the New Device/Browser? node. This node compares the current login's device and browser details against the user's historical data (retrieved by the Get last 10 logins from the same user node) to check for any discrepancies.

  • Detecting New Device or Browser Use: The New Device/Browser? node checks if there's a change in the browser name, operating system, or device type. A change might indicate that the current login is being attempted from a new device or browser, which could be a sign of unauthorized access.

  • Routing Based on Device and Browser Consistency: The workflow bifurcates based on this analysis. If a new device or browser is detected, the flow moves to the New Device/Browser node, suggesting potential security risks. Conversely, if the device and browser match historical patterns, the Old Device/Browser node is activated, indicating a routine login.

Suspicious_login_detection

Suspicious_login_detection

Purpose and structure

This folder contains the Suspicious_login_detection workflow. Its executable nodes use code, gmail, html, httpRequest, if, manualTrigger, merge, noOp, postgres, set, slack, switch, webhook. The table and connection map below are derived from the JSON, not an inferred guarantee of behavior.

Setup

Import inactive. Configure your own credentials and replace REPLACE_WITH_* values. Review external destinations and Code nodes before running.

Entry points

New /login event, When clicking "Execute Workflow"

Verification

Sanitized source candidate; not runtime-tested. This overview is generated from node metadata. Read the folder README for the connection map, credential types, and license.

Attribution

https://github.com/Zie619/n8n-workflows/blob/94007c1445d9258a7da116646b79473e7c7c3282/workflows/Postgres/2014_Postgres_Webhook_Automation_Webhook.json MIT; preserve source notices.

More in Data & databases