# tirreno for developers Crash course for new tirreno developers ### Welcome Welcome and thank you for your interest in tirreno [security framework](https://www.tirreno.com). The tirreno community is open and we welcome contributions of code and ideas. tirreno is available in three editions: - **Community Edition** (open-source): For developer teams that want to add a security layer to self-hosted applications. Get started today without getting into complex business relationships. Licensed under GNU Affero General Public License v3 (AGPL-3.0). - **Enterprise Edition**: Enterprise Edition helps bring sovereign security into organizations where on-premises data have critical meaning. Dedicated assistance for your SOC, product, and risk teams. - **White-label Edition**: White-label is for businesses that want to offer security products built on the tirreno framework to their clients under their own brand. tirreno runs on your infrastructure, or even in your edge product. For Enterprise and White-label editions, contact team@tirreno.com. Here is some basic information for new developers to get up and running quickly: * Here is an overview of the [system architecture](#system-architecture) * Here is an overview of the tirreno [coding standards](#contributing) * Here is [administration guide](https://github.com/tirrenotechnologies/ADMIN.md) * Here is [API reference](https://github.com/tirrenotechnologies/API.md) of the built-in `tirreno('…')` API used to build custom pages * Here is an overview of [how to customize tirreno](#risk-rules--customization) for your needs * The easiest way to get started on development is documented in [local development setup](#local-development-setup) * Contributed code should be released under the GNU Affero General Public License v3 (AGPL-3.0) * To get started, feel free to introduce yourself at the [Mattermost community](https://chat.tirreno.com) or email the team at team@tirreno.com --- ## Table of contents 1. [System architecture](#system-architecture) - [Introduction](#introduction) - [Overview](#overview) - [Directory structure](#directory-structure) - [Configuration reference](#configuration-reference) - [Access control](#access-control) 2. [API integration](#api-integration) - [Official tracker libraries](#official-tracker-libraries) - [Sensor API reference](#sensor-api-reference) 3. [Integration guide](#integration-guide) - [Why send events to tirreno?](#why-send-events-to-tirreno) - [Integration planning](#integration-planning) - [Security considerations](#security-considerations) - [Quick start](#quick-start) - [Event tracking best practices](#event-tracking-best-practices) - [Send all logged-in user events](#send-all-logged-in-user-events) - [Protecting the registration](#protecting-the-registration) - [Protecting the login](#protecting-the-login) - [Auto-ban abusive users](#auto-ban-abusive-users) - [Field audit trail](#field-audit-trail) - [Testing your integration](#testing-your-integration) 4. [Risk rules & customization](#risk-rules--customization) - [Rule presets](#rule-presets) - [Rule organization](#rule-organization) - [Built-in rules](#built-in-rules) - [Developing custom rules](#developing-custom-rules) - [Ruler operators reference](#ruler-operators-reference) - [Rule context attributes](#rule-context-attributes) - [Suspicious pattern lists](#suspicious-pattern-lists) - [Custom pages](#custom-pages) 5. [Contributing](#contributing) - [Source code](#source-code) - [Before you start](#before-you-start) - [Contributor license agreement (CLA)](#contributor-license-agreement-cla) - [Git workflow](#git-workflow) - [Local development setup](#local-development-setup) - [Code quality tools](#code-quality-tools) - [PHP coding standards](#php-coding-standards) - [Internationalization (i18n)](#internationalization-i18n) - [JavaScript coding standards](#javascript-coding-standards) - [File formatting](#file-formatting) - [Code comments](#code-comments) - [Commit messages](#commit-messages) - [Line endings](#line-endings) - [Testing](#testing) 6. [Resources](#resources) 7. [Found a mistake?](#found-a-mistake) --- ## System architecture ### Introduction tirreno is an open-source framework for building security into your application. ### Overview ``` ┌────────────┐ request ┌─────────────────┐ POST /sensor/ ┌─────────────────┐ │ Entity │ ─────────────────▶ │ Your App │ ────────────────────────▶│ tirreno │ └────────────┘ │ (allow/deny) │◀──────────────────────── │ + Risk scoring │ └─────────────────┘ response │ + Rule engine │ │ + Blacklist │ └─────────────────┘ ``` Your application sends entity events (logins, registrations, page views, field changes) to tirreno. tirreno analyzes the events, calculates risk scores, and can automatically blacklist suspicious entity. Your app can query the blacklist API to block bad actors in real-time. ### Directory structure ``` tirreno/ │ ├── .github/ # GitHub configuration │ ├── workflows/ # CI/CD workflows │ │ └── ci.yml # PHPUnit, PHPStan, PHP_CodeSniffer │ └── actions/ # Custom GitHub actions │ └── setup-php/ │ ├── tests/ # Test suites (PHPUnit) │ ├── Unit/ # Unit tests (Assets, Models, Rules, Utils) │ └── Support/ # Test doubles and helpers │ ├── app/ # Application code │ ├── Assets/ # Base classes for rules and custom context │ │ ├── Rule.php # Abstract Rule class │ │ ├── Context.php # Abstract custom Context class │ │ └── Constants.php │ │ │ ├── Controllers/ # Request handlers │ │ ├── Api/ # API controllers │ │ │ ├── Blacklist.php # Blacklist API │ │ │ └── Endpoint.php # API endpoint handler │ │ ├── Pages/ # Page controllers (render pages) │ │ │ ├── Cron.php # Cron entry point (/cron) │ │ │ ├── Login.php │ │ │ ├── Signup.php │ │ │ ├── Users.php │ │ │ └── ... │ │ ├── Services/ # Page business logic │ │ │ ├── Context.php # Rule context builder │ │ │ ├── Rules.php │ │ │ └── ... │ │ ├── Data.php # AJAX data endpoints │ │ └── Navigation.php # Navigation controller │ │ │ ├── Core/ # Core container, page classes and services │ │ ├── Container.php │ │ ├── Page.php │ │ ├── FileBasedPage.php # Custom pages from assets/pages/ │ │ └── Services/ │ │ │ ├── Crons/ # Background job handlers │ │ ├── Base.php # Base cron class │ │ ├── BaseQueue.php # Base queue handler │ │ ├── BatchedNewEvents.php │ │ ├── EnrichmentQueueHandler.php │ │ ├── RiskScoreQueueHandler.php │ │ └── ... # Other cron jobs │ │ │ ├── Dictionary/ # Internationalization (i18n) │ │ ├── en.php # Dictionary entry point │ │ └── en/ # English translations │ │ ├── Additional/ # Per-page translations loaded on demand │ │ ├── Pages/ # Page-specific translations │ │ ├── Parts/ # Component translations │ │ ├── Errors.php # Error messages │ │ └── All.php # Combined translations │ │ │ ├── Entities/ # Entity objects (User, Ip, Device, Event, ...) │ │ │ ├── Interfaces/ # PHP interfaces │ │ ├── ApiKeyAccessAuthorizationInterface.php │ │ ├── ApiKeyAccountAccessAuthorizationInterface.php │ │ └── FraudFlagUpdaterInterface.php │ │ │ ├── Models/ # Database models (extend Base) │ │ ├── Base.php # Base class with execQuery() │ │ ├── Device.php # Device/user-agent model │ │ ├── Api/ # API models │ │ ├── Chart/ # Chart data models │ │ ├── Context/ # Rule context data models │ │ ├── Enrichment/ # Enrichment models │ │ ├── Grid/ # Grid data models │ │ ├── Query/ # Query builder │ │ ├── Search/ # Global search models │ │ ├── TopTen/ # Dashboard top-ten models │ │ ├── UserDetails/ # Entity details models │ │ └── ... # Other models │ │ │ ├── Updates/ # Database migration handlers │ │ │ ├── Utils/ # Utility classes │ │ ├── Assets/ # Loaders for rules, presets, pages, lists │ │ │ └── Lists/ # Built-in default pattern lists │ │ ├── Http/ # HTTP client │ │ ├── ApiKeys.php # API key utilities │ │ ├── Constants.php # Application constants │ │ ├── DictManager.php # Additional dictionary loader │ │ ├── Logger.php # Logging utilities │ │ ├── Rules.php # Rule utilities │ │ ├── Variables.php # Configuration/environment variables │ │ └── ... # Other utilities │ │ │ └── Views/ # Response renderers (Frontend, Json, Xml) │ ├── assets/ # Static assets, rules and customization points │ ├── dashboard/ # Dashboard constants │ ├── rules/ # Rules engine │ │ ├── core/ # Core rule definitions and presets │ │ └── custom/ # Custom rules, context and presets │ ├── lists/ # Suspicious pattern lists │ │ ├── url.php # URL attack patterns │ │ ├── user-agent.php # User agent patterns │ │ ├── ai-bot.php # AI agent/bot user agent substrings │ │ ├── asn.php # Suspicious ASN numbers │ │ ├── email.php # Email patterns │ │ └── file-extensions.php # File extension categories │ ├── pages/ # Custom pages │ │ └── views/ # Custom page templates │ └── logs/ # Application logs │ ├── config/ # Configuration files │ ├── config.ini # Main configuration │ ├── routes.ini # Route definitions │ ├── apiEndpoints.ini # API endpoint definitions │ ├── crons.ini # Cron job configuration │ └── local/ # Local overrides (config.local.ini) │ ├── install/ # Web-based installation wizard │ ├── index.php # DELETE AFTER INSTALLATION │ └── install.sql # Database schema │ ├── libs/ # Third-party libraries (vendor) │ ├── sensor/ # API endpoint for event ingestion │ ├── tmp/ # Temporary files, cache │ ├── ui/ # Frontend UI │ ├── css/ # Stylesheets │ ├── images/ # Static images │ │ ├── icons/ │ │ └── flags/ │ ├── js/ # JavaScript files │ │ ├── endpoints/ # Page entry points │ │ ├── pages/ # Page controllers │ │ │ ├── Base.js # Base page class │ │ │ ├── Ips.js # IPs page │ │ │ ├── Events.js # Events page │ │ │ └── ... # Other pages │ │ ├── parts/ # Reusable components │ │ │ ├── button/ # Action button components │ │ │ ├── grid/ # Data grid components │ │ │ ├── chart/ # Chart components (uPlot) │ │ │ ├── panel/ # Detail panel components │ │ │ ├── choices/ # Filter components (Choices.js) │ │ │ ├── details/ # Detail view components │ │ │ ├── popup/ # Popup/modal components │ │ │ ├── utils/ # Utility modules │ │ │ │ ├── Constants.js │ │ │ │ ├── DataSource.js │ │ │ │ ├── Date.js │ │ │ │ ├── ErrorHandler.js │ │ │ │ ├── Event.js │ │ │ │ ├── Functions.js │ │ │ │ └── String.js │ │ │ └── ... # Other components │ │ └── vendor/ # Third-party JS libraries │ │ ├── jquery-3.6.0/ │ │ ├── datatables-2.3.2/ │ │ ├── uPlot-1.6.18/ │ │ ├── choices-10.2.0/ │ │ ├── jvectormap-2.0.5/ │ │ ├── tooltipster-master-4.2.8/ │ │ ├── accept-language-parser-1.5.0/ │ │ └── devbridge-jquery-autocomplete-1.5.0/ │ └── templates/ # HTML templates │ ├── layout.html # Base layout │ ├── internalTemplate.html # Wrapper for logged-in pages │ ├── externalTemplate.html # Wrapper for login/signup pages │ ├── pages/ # Page templates │ │ ├── events.html │ │ ├── ip.html │ │ ├── users.html │ │ ├── login.html │ │ ├── signup.html │ │ └── ... │ ├── parts/ # Component templates │ │ ├── internalHeader.html │ │ ├── internalFooter.html │ │ ├── leftMenu.html │ │ ├── notification.html │ │ ├── forms/ │ │ ├── home/ │ │ ├── panel/ │ │ ├── popups/ │ │ ├── tables/ │ │ ├── widgets/ │ │ └── choices/ │ └── snippets/ # Code snippets (cURL, PHP, Python, Node.js) │ ├── index.php # Application entry point ├── .htaccess # Apache URL rewriting rules ├── .profile # Environment profile ├── .phpstorm.meta.php # PhpStorm IDE metadata ├── app.json # Platform deployment manifest ├── composer.json # PHP dependencies ├── composer.lock # Locked dependency versions ├── cron.json # Cron job definitions ├── phpcs.xml # PHP CodeSniffer configuration ├── phpstan.neon # PHPStan configuration ├── phpunit.xml # PHPUnit configuration ├── eslint.config.js # JavaScript linting configuration │ ├── CHANGELOG.md # Version history ├── CODE_OF_CONDUCT.md # Community guidelines ├── LICENSE # AGPL-3.0 license ├── LEGALNOTICE.md # Legal notices ├── README.md # Project overview ├── RELEASE_NOTES.md # Release notes ├── SECURITY.md # Security policy ├── FILE_ID.DIZ # BBS-style file description └── robots.txt # Search engine directives ``` ### Configuration reference All settings, environment variables and debug levels are documented in the administration guide: [Environment variables](https://github.com/tirrenotechnologies/ADMIN.md#environment-variables) and [Debug levels](https://github.com/tirrenotechnologies/ADMIN.md#debug-levels). ### Access control Roles and permissions are documented in [Access control](https://github.com/tirrenotechnologies/ADMIN.md#access-control) in the administration guide. --- ## API integration Event ingestion happens through sensors that collect the events, and they all get into the queue. Then, when the cron starts (in loop-until-drained), it defines the entities that had actions since the last cron run, updates statistics, and calculates the context that is used by the active rules to determine a final risk score for each entity. ### Official tracker libraries Use one of these: | Language | Install | |----------|---------| | **PHP** | `composer require tirreno/tirreno-tracker` | | **Python** | `pip install tirreno_tracker` | | **Node.js** | `npm install @tirreno/tirreno-tracker` | | **WordPress** | Upload the plugin to WordPress, activate it, then enter your Tracking ID and tirreno URL | Repos: [PHP](https://github.com/tirrenotechnologies/tirreno-php-tracker), [Python](https://github.com/tirrenotechnologies/tirreno-python-tracker), [Node.js](https://github.com/tirrenotechnologies/tirreno-nodejs-tracker), [WordPress](https://github.com/tirrenotechnologies/tirreno-wordpress-tracker) ### Sensor API reference #### Endpoint ``` POST /sensor/ Content-Type: application/x-www-form-urlencoded Api-Key: YOUR_TRACKING_ID ``` **Note:** The API uses form-urlencoded format, not JSON. **Optional headers:** | Header | Description | |--------|-------------| | `X-Request-Id` | Trace ID (up to 36 characters) stored with the event, or with the rejected request if validation fails | **Command line:** the sensor can also be called from the CLI, passing the Tracking ID and event fields as long options: ```bash php sensor/index.php --apiKey=YOUR_TRACKING_ID --userName=user123 --ipAddress=203.0.113.50 \ --url=/login --eventTime="2024-12-08 14:30:00.000" --eventType=account_login ``` #### Required parameters | Parameter | Description | |-----------|-------------| | `userName` | Unique user ID (max 100 chars) | | `ipAddress` | IPv4/IPv6 address (invalid IPs default to `0.0.0.0`) | | `url` | URL path (max 2047 chars) | | `eventTime` | UTC timestamp `Y-m-d H:i:s.v`; `Y-m-d H:i:s` and `Y-m-d H:i:s.u` are also accepted (an invalid value is replaced with the current UTC time) | #### Optional parameters | Parameter | Type | Description | |-----------|------|-------------| | `emailAddress` | string | Email address (max 255 chars). Validated and converted to lowercase | | `userAgent` | string | Browser UA (max 511 chars) | | `firstName` | string | User's first name (max 100 chars) | | `lastName` | string | User's last name (max 100 chars) | | `fullName` | string | User's whole name (max 100 chars) | | `pageTitle` | string | Title of visited page (max 255 chars) | | `phoneNumber` | string | User's phone number (max 19 chars) | | `httpReferer` | string | Referer HTTP header value (max 2047 chars) | | `httpMethod` | string | HTTP method: `GET`, `POST`, `HEAD`, `PUT`, `DELETE`, `PATCH`, `TRACE`, `CONNECT`, `OPTIONS`, `LINK`, `UNLINK` | | `httpCode` | string | HTTP response status code (must be numeric, defaults to `0`) | | `browserLanguage` | string | Detected browser language (max 255 chars) | | `eventType` | string | One of the event types listed below. Defaults to `page_view`, or `page_error` if httpCode >= 400 | | `userCreated` | string | User creation timestamp (`Y-m-d H:i:s` or `Y-m-d H:i:s.v`) | | `payload` | array | Event details for `page_search` and `account_email_change` events | | `fieldHistory` | array | Field edit history for `field_edit` events | **Note:** Maximum length for all other parameters is 100 characters unless specified above. Parameters exceeding max length are truncated. #### Event types Default: `page_view` (or `page_error` if `httpCode` >= 400) | Type | Description | |------|-------------| | `page_view` | Page visit (default) | | `page_edit` | Page modification | | `page_delete` | Page deletion | | `page_search` | Search query | | `page_error` | Error page | | `account_login` | User authentication | | `account_logout` | Session end | | `account_login_fail` | Failed login attempt | | `account_registration` | New account creation | | `account_email_change` | Email address change | | `account_password_change` | Password change | | `account_edit` | Account profile modification | | `field_edit` | Data modification | #### Payload parameter For `page_search` events: ```json { "eventType": "page_search", "payload": { "field_id": 179280, "value": "search query", "field_name": "Country" } } ``` | Field | Required | Description | |-------|----------|-------------| | `field_id` | Yes | Unique identifier for the search field | | `value` | Yes | The search query string | | `field_name` | No | Human-readable field name | For `account_email_change` events: ```json { "eventType": "account_email_change", "payload": { "new_value": "new@example.com", "old_value": "old@example.com" } } ``` | Field | Required | Description | |-------|----------|-------------| | `new_value` | Yes | The new email address | | `old_value` | No | The previous email address | #### Field history parameter Required for `field_edit` events. Must be an array of field change objects: ```json { "eventType": "field_edit", "fieldHistory": [ { "field_id": 179283, "new_value": "Paris", "field_name": "User city", "old_value": "London", "parent_id": "", "parent_name": "" } ] } ``` | Field | Required | Description | |-------|----------|-------------| | `field_id` | Yes | Unique identifier for the field | | `new_value` | Yes | The new field value | | `field_name` | No | Human-readable field name | | `old_value` | No | The previous field value | | `parent_id` | No | Parent record ID (for nested data) | | `parent_name` | No | Parent record name | **Note:** Missing required fields default to `"unknown"`. All values are converted to strings. #### Response codes | Response | Meaning | |----------|---------| | 204, no body | Event accepted | | 200, empty body | Request rejected: missing or unknown Tracking ID, or a required field is missing. The reason is written to the web server error log | | 429 | Rate limited (see [Rate limiting](#rate-limiting)) | | 500 | Server error | | 403 | Wrong endpoint, e.g., `/sensor` without the trailing slash | Successful requests (2xx) return no response body. #### Rate limiting The sensor has a leaky bucket rate limiter, applied per Tracking ID: at most `LEAKY_BUCKET_RPS × LEAKY_BUCKET_WINDOW` requests are accepted within the window (defaults: `10` requests per second, `20` seconds). Requests over the limit get `429` and appear in the Logbook as **Rate limit exceeded**. Setting either value to `0` disables the limit; see [Environment variables](https://github.com/tirrenotechnologies/ADMIN.md#environment-variables) for how to set them. #### Blacklist API Check if an entity is blacklisted. The value is matched against entity IDs (`userName`) only; IP addresses, emails and phone numbers are not looked up. **Request:** ``` POST /api/v1/blacklist/search Content-Type: application/json Api-Key: YOUR_TRACKING_ID { "value": "user123" } ``` **Response:** ```json { "value": "user123", "blacklisted": false } ``` The response is JSON. A missing or unknown Tracking ID returns `401`. The examples in this guide use `$blacklistService->isBlacklisted($value)` (`blacklist_service.is_blacklisted()` in Python, `blacklistService.isBlacklisted()` in Node.js). It stands for your own small wrapper that sends this request and returns the `blacklisted` field; define it before using the examples. #### Logbook event types The Logbook statuses and columns are described in [Logbook](https://github.com/tirrenotechnologies/OPERATOR.md#logbook) in the user guide. --- ## Integration guide This section covers integrating tirreno into your application. ### Why send events to tirreno? tirreno analyzes user events to detect threats and calculate risk scores. Use cases: - **Security monitoring:** Detect account takeover, brute force attacks, suspicious behavior - **Threat hunting:** Search for indicators of compromise across user activity - **Insider threats:** Spot unusual employee behavior, potential data exfiltration - **Compliance:** Activity logs and field audit trail for GDPR, SOC 2, PCI-DSS - **Forensics:** Investigate incidents with full session history - **Risk scoring:** Calculate entity trust scores from behavior patterns tirreno tracks per-entity metrics: devices per day, IPs per day, sessions, events per session. ### Integration planning > **Enterprise Edition:** For internal applications we recommend to use existing integrations. Check the list of available integrations or contact tirreno at team@tirreno.com for further details. #### What to track | Vector | How tirreno Detects | Events | |--------------|---------------------|--------| | Stolen credentials | Multiple IPs, unusual locations | `account_login`, `account_login_fail` | | Account sharing | Concurrent sessions, device changes | `page_view`, `account_login` | | Fake accounts | Disposable emails, VPN/proxy | `account_registration` | | Data scraping | High volume, bot signatures | `page_view`, `page_search` | | Privilege abuse | Off-hours, sensitive operations | `account_edit`, `field_edit` | #### Where to integrate **Minimum:** - Login/logout - Failed login attempts - Registration - Password/email changes **Recommended:** - Authenticated page views - Search queries - Data modifications - File downloads/exports - Admin actions #### Data you need | Data | Source | Required | |------|--------|----------| | User ID | Auth system | Yes | | IP address | Request headers | Yes | | URL | Request path | Yes | | Timestamp | Server time (UTC) | Yes | | Email | User profile | Recommended | | User agent | Headers | Recommended | #### Technical notes **Performance:** - Use async/non-blocking HTTP calls - Set 3-5 second timeouts - Queue events during high traffic - Don't block user actions on tirreno response **Reliability:** - Implement retry with exponential backoff - Fail open (allow user action if tirreno unavailable) - Log failed events locally for debugging **Privacy:** - Never send passwords or tokens - Hash sensitive IDs if needed - Document data collection in privacy policy - Consider GDPR requirements for EU users **Scalability:** - One event per significant user action - Batch events where appropriate - Monitor tirreno logbook for errors ### Security considerations When integrating tirreno, follow these security best practices: 1. **Install in private environment** Deploy tirreno in a private network with controlled access 2. **Protect your Tracking ID** Store in environment variables, never in code 3. **Use HTTPS** Always send events over encrypted connections 4. **Don't log sensitive data** Never include passwords, tokens, or PII in event payloads 5. **Fail open on errors** Don't block users if tirreno is temporarily unavailable 6. **Set timeouts** Use 3-5 second timeouts to prevent login delays 7. **Validate on your side** tirreno is for monitoring, not input validation 8. **Send timestamps in UTC** All `eventTime` values must be in UTC. Configure your tirreno instance timezone during initial setup or in Settings → Time zone. The dashboard will display events in your configured timezone, but all data sent via the API must use UTC ### Quick start > **Important:** tirreno must be integrated on the backend only. Never send events from frontend JavaScript or mobile apps. Client-side code can be inspected, modified, or bypassed entirely — attackers could disable tracking, forge events, or extract your Tracking ID. Backend integration ensures event data cannot be tampered with and your API credentials remain secure. The fastest way to integrate tirreno is using an official tracker library. **cURL (raw API):** ```bash curl -X POST https://your-tirreno-instance.com/sensor/ \ -H "Content-Type: application/x-www-form-urlencoded" \ -H "Api-Key: your-tracking-id" \ -d "userName=user123" \ -d "emailAddress=user@example.com" \ -d "ipAddress=192.168.1.100" \ -d "url=/login" \ -d "eventTime=2024-12-08 14:30:00.000" \ -d "eventType=page_view" ``` **PHP:** Requirements: `cURL` PHP extension Installation: ``` composer require tirreno/tirreno-tracker ``` Or manually via file download: ```php require_once("TirrenoTracker.php"); ``` Usage: ```php setUserName("johndoe42") ->setIpAddress("1.1.1.1") ->setUrl("/login") ->setUserAgent("Mozilla/5.0 (X11; Linux x86_64)") ->setEventTypeAccountLogin(); // Set optional params $tracker->setFirstName("John") ->setBrowserLanguage("fr-FR,fr;q=0.9") ->setHttpMethod("POST"); // Track event $tracker->track(); ``` **Python:** ```bash pip install tirreno_tracker ``` ```python from tirreno_tracker import Tracker tracker = Tracker('https://your-tirreno-instance.com', 'your-tracking-id') # Track a login event = tracker.create_event() event.set_user_name(user_id) \ .set_email_address(user_email) \ .set_ip_address(ip_address) \ .set_url(url_path) \ .set_user_agent(user_agent) \ .set_event_type_account_login() tracker.track(event) ``` **Node.js:** ```bash npm install @tirreno/tirreno-tracker ``` ```javascript import Tracker from '@tirreno/tirreno-tracker'; const tracker = new Tracker('https://your-tirreno-instance.com', 'your-tracking-id'); // Track a registration const event = tracker.createEvent(); event.setUserName(userId) .setEmailAddress(userEmail) .setIpAddress(ipAddress) .setUrl(urlPath) .setUserAgent(userAgent) .setEventTypeAccountRegistration(); await tracker.track(event); ``` ### Event tracking best practices #### Which events to track **Essential events (always track):** | Event | When to Track | Why It Matters | |-------|---------------|----------------| | `account_login` | Successful authentication | Detect account takeover | | `account_login_fail` | Failed login attempts | Detect brute force attacks | | `account_registration` | New account creation | Detect fake account creation | | `account_password_change` | Password updates | Detect account compromise | | `account_email_change` | Email changes | Detect account hijacking | **Recommended events:** | Event | When to Track | Why It Matters | |-------|---------------|----------------| | `page_view` | Key page visits | Behavioral analysis | | `page_edit` | Content modifications | Detect malicious edits | | `page_search` | Search queries | Detect reconnaissance | | `page_error` | 4xx/5xx errors | Detect scanning/attacks | | `field_edit` | Data modification | Field audit trail | #### Data quality guidelines 1. **Consistent user identifiers:** ```php // Good - use permanent ID $tracker->setUserName((string) $user->id); // Bad - don't use changing values $tracker->setUserName($user->email); // Emails can change ``` 2. **Accurate timestamps:** The tracker libraries automatically set `eventTime` to the current UTC timestamp with milliseconds when you call `track()`. For manual timestamp handling, use the format `Y-m-d H:i:s.v`: ```php // PHP - include milliseconds // (date() has no milliseconds and uses the server time zone, so use DateTime in UTC) $eventTime = (new DateTime('now', new DateTimeZone('UTC')))->format('Y-m-d H:i:s.v'); // 2024-01-15 10:30:45.123 ``` 3. **Real IP addresses:** ```php // Good - trust proxy headers only when the request comes from your own proxy; // any client can send X-Forwarded-For function getRealIp(array $trustedProxies = ['10.0.0.1']): string { $remoteAddr = $_SERVER['REMOTE_ADDR']; if (in_array($remoteAddr, $trustedProxies, true)) { foreach (['HTTP_CF_CONNECTING_IP', 'HTTP_X_FORWARDED_FOR'] as $header) { if (!empty($_SERVER[$header])) { return trim(explode(',', $_SERVER[$header])[0]); } } } return $remoteAddr; } $tracker->setIpAddress(getRealIp()); ``` 4. **Complete user agent:** ```php // Good - full user agent $tracker->setUserAgent($_SERVER['HTTP_USER_AGENT']); // Bad - truncated $tracker->setUserAgent(substr($_SERVER['HTTP_USER_AGENT'], 0, 50)); ``` ### Send all logged-in user events Track page views and actions from authenticated users. **PHP:** ```php session_start(); if (isset($_SESSION['user_id'])) { $tracker->setUserName((string) $_SESSION['user_id']) ->setEmailAddress($_SESSION['user_email']) ->setIpAddress($_SERVER['REMOTE_ADDR']) ->setUrl($_SERVER['REQUEST_URI']) ->setUserAgent($_SERVER['HTTP_USER_AGENT'] ?? '') ->setHttpMethod($_SERVER['REQUEST_METHOD']) ->setEventTypePageView(); $tracker->track(); } ``` **Node.js:** ```javascript if (userId) { const event = tracker.createEvent(); event.setUserName(userId) .setEmailAddress(userEmail) .setIpAddress(ipAddress) .setUrl(urlPath) .setUserAgent(userAgent) .setHttpMethod(httpMethod) .setHttpCode(httpCode.toString()) .setEventTypePageView(); await tracker.track(event); } ``` **Python:** ```python if user_id: event = tracker.create_event() event.set_user_name(str(user_id)) \ .set_email_address(user_email) \ .set_ip_address(ip_address) \ .set_url(url_path) \ .set_user_agent(user_agent) \ .set_http_method(http_method) \ .set_http_code(str(http_code)) \ .set_event_type_page_view() tracker.track(event) ``` ### Protecting the registration Protect your registration flow from fake accounts, bots, and abuse. #### Track registration events **PHP:** ```php $userId = createUser($_POST['email'], $_POST['password'], $_POST['name']); $tracker->setUserName((string) $userId) ->setEmailAddress($_POST['email']) ->setFullName($_POST['name']) ->setIpAddress($_SERVER['REMOTE_ADDR']) ->setUrl('/register') ->setUserAgent($_SERVER['HTTP_USER_AGENT'] ?? '') ->setEventTypeAccountRegistration(); $tracker->track(); header('Location: /dashboard'); ``` **Python:** ```python user_id = create_user(email, password, name) event = tracker.create_event() event.set_user_name(str(user_id)) \ .set_email_address(email) \ .set_full_name(name) \ .set_ip_address(ip_address) \ .set_url('/register') \ .set_user_agent(user_agent) \ .set_event_type_account_registration() tracker.track(event) ``` **Node.js:** ```javascript const userId = await createUser(email, password, name); const event = tracker.createEvent(); event.setUserName(userId.toString()) .setEmailAddress(email) .setFullName(name) .setIpAddress(ipAddress) .setUrl('/register') .setUserAgent(userAgent) .setEventTypeAccountRegistration(); await tracker.track(event); ``` ### Protecting the login Secure your login flow against brute force attacks and credential stuffing. #### Track login events **PHP:** ```php $email = $_POST['email']; $password = $_POST['password']; $user = authenticateUser($email, $password); if (!$user) { // Track failed login $tracker->setUserName($email) ->setEmailAddress($email) ->setIpAddress($_SERVER['REMOTE_ADDR']) ->setUrl('/login') ->setUserAgent($_SERVER['HTTP_USER_AGENT'] ?? '') ->setEventTypeAccountLoginFail(); $tracker->track(); die('Invalid credentials'); } // Track successful login $tracker->setUserName((string) $user['id']) ->setEmailAddress($user['email']) ->setIpAddress($_SERVER['REMOTE_ADDR']) ->setUrl('/login') ->setUserAgent($_SERVER['HTTP_USER_AGENT'] ?? '') ->setEventTypeAccountLogin(); $tracker->track(); session_start(); $_SESSION['user_id'] = $user['id']; header('Location: /dashboard'); ``` **Python:** ```python user = authenticate_user(email, password) if not user: # Track failed login event = tracker.create_event() event.set_user_name(email) \ .set_email_address(email) \ .set_ip_address(ip_address) \ .set_url('/login') \ .set_user_agent(user_agent) \ .set_event_type_account_login_fail() tracker.track(event) # Return error else: # Track successful login event = tracker.create_event() event.set_user_name(str(user['id'])) \ .set_email_address(user['email']) \ .set_ip_address(ip_address) \ .set_url('/login') \ .set_user_agent(user_agent) \ .set_event_type_account_login() tracker.track(event) ``` **Node.js:** ```javascript const user = await authenticateUser(email, password); if (!user) { // Track failed login const event = tracker.createEvent(); event.setUserName(email) .setEmailAddress(email) .setIpAddress(ipAddress) .setUrl('/login') .setUserAgent(userAgent) .setEventTypeAccountLoginFail(); await tracker.track(event); // Return error } else { // Track successful login const event = tracker.createEvent(); event.setUserName(user.id.toString()) .setEmailAddress(user.email) .setIpAddress(ipAddress) .setUrl('/login') .setUserAgent(userAgent) .setEventTypeAccountLogin(); await tracker.track(event); } ``` #### Block blacklisted users Check the blacklist API before allowing login: ```php $email = $_POST['email']; $password = $_POST['password']; // Block known attackers before authentication // (matches accounts tracked with the email as userName, e.g. failed logins below) if ($blacklistService->isBlacklisted($email)) { die('Invalid credentials'); } $user = authenticateUser($email, $password); if (!$user) { $tracker->setUserName($email) ->setEmailAddress($email) ->setIpAddress($_SERVER['REMOTE_ADDR']) ->setUrl('/login') ->setUserAgent($_SERVER['HTTP_USER_AGENT'] ?? '') ->setEventTypeAccountLoginFail(); $tracker->track(); die('Invalid credentials'); } // Also check authenticated user if ($blacklistService->isBlacklisted((string) $user['id'])) { die('Invalid credentials'); } // Track successful login $tracker->setUserName((string) $user['id']) ->setEmailAddress($user['email']) ->setIpAddress($_SERVER['REMOTE_ADDR']) ->setUrl('/login') ->setUserAgent($_SERVER['HTTP_USER_AGENT'] ?? '') ->setEventTypeAccountLogin(); $tracker->track(); session_start(); $_SESSION['user_id'] = $user['id']; header('Location: /dashboard'); ``` ### Auto-ban abusive users tirreno's rules analyze IP addresses, devices and behaviour, and entities below the **Auto-blacklisting** threshold are blacklisted automatically. Block them in your application with the [Blacklist API](#blacklist-api). **Note:** The Blacklist API matches entity IDs (`userName`) only, so blocking by IP address is not currently supported. #### Configure threshold settings Before implementing auto-ban, configure and test the **Thresholds settings** on the **Rules engine** page, as described in [Thresholds settings](https://github.com/tirrenotechnologies/OPERATOR.md#thresholds-settings) in the user guide. #### Middleware for blocking blacklisted users **PHP:** ```php session_start(); if (isset($_SESSION['user_id']) && $blacklistService->isBlacklisted((string) $_SESSION['user_id'])) { http_response_code(403); die('Access denied'); } ``` **Python:** ```python if user_id and blacklist_service.is_blacklisted(str(user_id)): # Return 403 Access denied pass ``` **Node.js:** ```javascript if (userId && await blacklistService.isBlacklisted(userId.toString())) { // Return 403 Access denied } ``` ### Field audit trail Field changes appear on the **Field history** page of the tirreno dashboard. Track changes to important user fields for compliance, security, and regulatory requirements. The `fieldHistory` parameter allows you to send detailed change records. #### Field history format Each field change object has these properties: | Property | Required | Type | Description | |----------|----------|------|-------------| | `field_id` | Yes | int/string | Unique identifier for the field | | `new_value` | Yes | string | New value | | `field_name` | No | string | Human-readable field name | | `old_value` | No | string | Previous value | | `parent_id` | No | string | Parent record ID (for nested data) | | `parent_name` | No | string | Parent record name | **Note:** Missing required fields default to `"unknown"`. All values are converted to strings. **Note:** The Python tracker does not support `parent_id` and `parent_name`. ### Testing your integration #### Manual testing checklist 1. **Verify API connectivity:** ```bash curl -X POST https://your-tirreno.com/sensor/ \ -H "Api-Key: your-tracking-id" \ -d "userName=test-user-123" \ -d "emailAddress=test@example.com" \ -d "ipAddress=203.0.113.50" \ -d "url=/test" \ -d "userAgent=Mozilla/5.0 Test" \ -d "eventTime=2024-12-08 01:01:00.000" \ -d "eventType=page_view" ``` 2. **Check the Logbook:** - Navigate to **Logbook** in the left menu and confirm your request has the **Success** status (see [Logbook](https://github.com/tirrenotechnologies/OPERATOR.md#logbook) in the user guide) 3. **Check the Entities page:** - Navigate to **Entities** to see the tracked entity - Verify the entity details and events are correctly recorded 4. **Verify event types:** - Test each event type you plan to use - Confirm events appear in the correct entity timeline --- ## Risk rules & customization tirreno is designed to be customized for your specific security needs. The two main customization points are: 1. **Custom rules** Create detection rules based on user behavior 2. **Suspicious pattern lists** Adjust URL, user agent, and email pattern detection ### Rule presets Rule presets and rule weights are console controls, described in [Rules settings reset](https://github.com/tirrenotechnologies/OPERATOR.md#rules-settings-reset) and [Rule weights](https://github.com/tirrenotechnologies/OPERATOR.md#rule-weights) in the user guide. Preset files live in `assets/rules/core/preset-*.php`; custom presets can be added to `assets/rules/custom/`. ### Rule organization Rules are organized by **namespace** (core vs custom) and **category** (prefix letter). **Namespaces:** | Namespace | Directory | Description | |-----------|-----------|-------------| | `\Tirreno\Rules\Core` | `assets/rules/core/` | Built-in rules (112 rules) | | `\Tirreno\Rules\Custom` | `assets/rules/custom/` | Your custom rules | **Rule categories by prefix:** | Prefix | Category | Example | |--------|----------|---------| | A | Account takeover | A01–A08 | | B | Behaviour | B01–B26 | | C | Country | C01–C16 | | D | Device | D01–D13 | | E | Email | E01–E30 | | I | IP | I01–I13 | | P | Phone | P01–P04 | | R | Reuse/Blacklist | R01–R03 | | X | Custom/Extra | X01, X02, ... | Custom rules must use the `X` prefix (e.g., `X01.php`, `X02.php`). Core rule prefixes (A–R) are reserved. ### Built-in rules tirreno includes standard detection rules organized by category: #### Account takeover (A01-A08) | Rule | Name | Description | |------|------|-------------| | A01 | Multiple login fail | User failed to login multiple times in a short term | | A02 | Login failed on new device | User failed to login with new device | | A03 | New device and new country | User logged in with new device from new location | | A04 | New device and new subnet | User logged in with new device from new subnet | | A05 | Password change on new device | User changed their password on new device | | A06 | Password change in new country | User changed their password in new country | | A07 | Password change in new subnet | User changed their password in new subnet | | A08 | Browser language changed | User accessed the account with new browser language | #### Behaviour (B01-B26) | Rule | Name | Description | |------|------|-------------| | B01 | Multiple countries | IP addresses are located in diverse countries | | B02 | User has changed a password | The user has changed their password | | B03 | User has changed an email | The user has changed their email | | B04 | Multiple 5xx errors | User made multiple requests which evoked internal server error | | B05 | Multiple 4xx errors | User made multiple requests which cannot be fulfilled | | B06 | Potentially vulnerable URL | User made a request to suspicious URL | | B07 | User's full name contains digits | Full name contains digits | | B08 | Dormant account (30 days) | Account has been inactive for 30 days | | B09 | Dormant account (90 days) | Account has been inactive for 90 days | | B10 | Dormant account (1 year) | Account has been inactive for a year | | B11 | New account (1 day) | Account has been created today | | B12 | New account (1 week) | Account has been created this week | | B13 | New account (1 month) | Account has been created this month | | B14 | Aged account (>30 days) | Account has been created over 30 days ago | | B15 | Aged account (>90 days) | Account has been created over 90 days ago | | B16 | Aged account (>180 days) | Account has been created over 180 days ago | | B17 | Single country | IP addresses are located in a single country | | B18 | HEAD request | HTTP request HEAD method is often used by bots | | B19 | Night time requests | User was active from midnight till 5 a.m. | | B20 | Multiple countries in one session | User's country changed in less than 30 minutes | | B21 | Multiple devices in one session | User's device changed in less than 30 minutes | | B22 | Multiple IP addresses in one session | User's IP changed in less than 30 minutes | | B23 | User's full name contains space or hyphen | Full name contains space or hyphen | | B24 | Empty referer | User made a request without a referer | | B25 | Unauthorized request | User made a successful request without authorization | | B26 | Single event sessions | User had sessions with only one event | #### Country (C01-C16) | Rule | Name | Description | |------|------|-------------| | C01 | Nigeria IP address | IP address located in Nigeria | | C02 | India IP address | IP address located in India | | C03 | China IP address | IP address located in China | | C04 | Brazil IP address | IP address located in Brazil | | C05 | Pakistan IP address | IP address located in Pakistan | | C06 | Indonesia IP address | IP address located in Indonesia | | C07 | Venezuela IP address | IP address located in Venezuela | | C08 | South Africa IP address | IP address located in South Africa | | C09 | Philippines IP address | IP address located in Philippines | | C10 | Romania IP address | IP address located in Romania | | C11 | Russia IP address | IP address located in Russia | | C12 | European IP address | IP address located in European Union | | C13 | North America IP address | IP address located in Canada or USA | | C14 | Australia IP address | IP address located in Australia | | C15 | UAE IP address | IP address located in United Arab Emirates | | C16 | Japan IP address | IP address located in Japan | #### Device (D01-D13) | Rule | Name | Description | |------|------|-------------| | D01 | Device is unknown | User has manipulated device information | | D02 | Device is Linux | Linux OS, increased risk of crawler bot | | D03 | Device is bot | User agent identified as a bot | | D04 | Rare browser device | User operates device with uncommon browser | | D05 | Rare OS device | User operates device with uncommon OS | | D06 | Multiple devices per user | User accesses account using multiple devices | | D07 | Several desktop devices | User accesses account using different OS desktop devices | | D08 | Two or more phone devices | User accesses account using numerous phone devices | | D09 | Old browser | User accesses account using an old browser version | | D10 | Potentially vulnerable User-Agent | User made a request with suspicious User-Agent | | D11 | Empty User-Agent | User made a request with empty User-Agent | | D12 | Empty browser language | User made a request with empty browser language | | D13 | Device is AI bot | User made a request via AI bot (`assets/lists/ai-bot.php`) | #### Email (E01-E30) | Rule | Name | Description | |------|------|-------------| | E01 | Invalid email format | Invalid email format | | E02 | New domain and no breaches | Email belongs to recently created domain with no breach history | | E03 | Suspicious words in email | Email contains auto-generated mailbox patterns | | E04 | Numeric email name | Email username consists entirely of numbers | | E05 | Special characters in email | Email has unusually high number of special characters | | E06 | Consecutive digits in email | Email includes at least two consecutive digits | | E07 | Long email username | Email username exceeds average length | | E08 | Long domain name | Email domain name is too long | | E09 | Free email provider | Email belongs to free provider | | E10 | The website is unavailable | Domain's website seems to be inactive | | E11 | Disposable email | Disposable email addresses are temporary | | E12 | Free email and no breaches | Email belongs to free provider with no breach history | | E13 | New domain | Domain name was registered recently | | E14 | No MX record | Email's domain has no MX record | | E15 | No breaches for email | Email was not involved in any data breaches | | E16 | Domain appears in spam lists | Email appears in spam lists | | E17 | Free email and spam | Email appears in spam lists and is from free provider | | E19 | Multiple emails changed | User has changed their email | | E20 | Established domain (> 3 year old) | Email belongs to domain registered at least 3 years ago | | E21 | No vowels in email | Email username does not contain any vowels | | E22 | No consonants in email | Email username does not contain any consonants | | E23 | Educational domain (.edu) | Email belongs to educational domain | | E24 | Government domain (.gov) | Email belongs to government domain | | E25 | Military domain (.mil) | Email belongs to military domain | | E26 | iCloud mailbox | Email belongs to Apple domains (icloud.com, me.com, mac.com) | | E27 | Email breaches | Email appears in data breaches | | E28 | No digits in email | Email address does not include digits | | E29 | Old breach (>3 years) | Earliest data breach appeared more than 3 years ago | | E30 | Domain with average rank | Email domain has Tranco rank between 100,000 and 4,000,000 | **Note:** E18 is reserved for future use. #### IP (I01-I13) | Rule | Name | Description | |------|------|-------------| | I01 | IP belongs to TOR | IP assigned to The Onion Router network | | I02 | IP hosting domain | Higher risk of crawler bot | | I03 | IP appears in spam list | User may have exhibited unwanted activity before | | I04 | Shared IP | Multiple users detected on same IP address | | I05 | IP belongs to commercial VPN | User tries to hide real location | | I06 | IP belongs to datacenter | User is utilizing an ISP datacenter | | I07 | IP belongs to Apple Relay | IP belongs to iCloud Private Relay | | I08 | IP belongs to Starlink | IP belongs to SpaceX satellite network | | I09 | Numerous IPs | User accesses account with numerous IP addresses | | I10 | Only residential IPs | User uses only residential IP addresses | | I11 | Single network | IP addresses belong to one network | | I12 | IP belongs to LAN | IP address belongs to local access network | | I13 | IP belongs to suspicious ASN | IP address belongs to ASN marked as suspicious (`assets/lists/asn.php`) | #### Phone (P01-P04) | Rule | Name | Description | |------|------|-------------| | P01 | Invalid phone format | User provided incorrect phone number | | P02 | Phone country mismatch | Phone number country is not among user's login countries | | P03 | Shared phone number | User provided a phone number shared with another user | | P04 | Valid phone | User provided correct phone number | #### Reuse/blacklist (R01-R03) | Rule | Name | Description | |------|------|-------------| | R01 | IP in blacklist | This IP address appears in the blacklist | | R02 | Email in blacklist | This email address appears in the blacklist | | R03 | Phone in blacklist | This phone number appears in the blacklist | ### Developing custom rules Custom rules are placed in `assets/rules/custom/` with filenames `X01.php`, `X02.php`, etc. Each rule must: * Use namespace `Tirreno\Rules\Custom` * Extend `\Tirreno\Assets\Rule` * Define constants: `NAME`, `DESCRIPTION`, `ATTRIBUTES` * Implement `defineCondition(): \Ruler\Operator\LogicalOperator` (the return type is required by the abstract parent method) Optionally, a rule can override `prepareParams(array $params): array` to compute additional values from the context before the condition is evaluated (see core rule `A03` for an example). #### Example rule See `assets/rules/custom/X03.example.php` for a complete example: ```php rb->logicalAnd( $this->rb['extra_one_digit_userid']->equalTo(true), ); } } ``` #### Custom context For rules that need custom data, create a Context class in `assets/rules/custom/Context.php`. See `Context.example.php`: ```php getRequestParams($accountIds, $apiKey); $query = ( "SELECT event_account.id AS id, event_account.userid AS extra_userid FROM event_account WHERE event_account.id IN ({$placeHolders}) AND event_account.key = :api_key" ); return $this->execQuery($query, $params); } } ``` **Note:** Property types must match the parent class: `$uniqueValues` is declared as `?bool` and `$tableName` as `string`. An untyped redeclaration causes a fatal error. #### Testing rules 1. **Refresh rules:** After creating or modifying rules, go to the **Rules engine** page and click **Refresh** at the bottom of the page to apply your changes 2. **Test a rule:** Select a rule and click the **Play** button (▷) to see how many entities are triggered by the rule 3. **Match rate:** The percentage shown indicates how many of the tested entities match the rule (e.g., "22%" means 22% of the tested entities trigger this rule). The number of entities tested is set by `CHECK_RULE_USERS_LIMIT` in `config/config.ini` (default: 1000) ### Ruler operators reference The rules engine uses ruler/ruler for condition evaluation. Available operators in `defineCondition()`: | Operator | Description | Example | |----------|-------------|---------| | `equalTo` | Exact match | `$this->rb['ea_total_country']->equalTo(1)` | | `notEqualTo` | Not equal | `$this->rb['eip_tor']->notEqualTo(true)` | | `greaterThan` | Greater than | `$this->rb['ea_total_ip']->greaterThan(9)` | | `greaterThanOrEqualTo` | Greater or equal | `$this->rb['ea_days_since_last_visit']->greaterThanOrEqualTo(30)` | | `lessThan` | Less than | `$this->rb['ea_days_since_account_creation']->lessThan(7)` | | `lessThanOrEqualTo` | Less or equal | `$this->rb['eup_device_count']->lessThanOrEqualTo(1)` | | `stringContains` | Substring match | `$this->rb['le_email']->stringContains('test')` | | `stringContainsInsensitive` | Case-insensitive substring | `$this->rb['le_domain_part']->stringContainsInsensitive('mail')` | | `startsWith` | Prefix match | `$this->rb['ea_userid']->startsWith('test_')` | | `endsWith` | Suffix match | `$this->rb['le_email']->endsWith('.edu')` | | `sameAs` | Strict comparison of two values (`===`); two empty values also match | `$this->rb['ea_userid']->sameAs($this->rb['le_email'])` | **Logical operators:** ```php // AND - all conditions must be true $this->rb->logicalAnd( $this->rb['eip_tor']->equalTo(true), $this->rb['ea_days_since_account_creation']->lessThan(7) ); // OR - at least one condition must be true $this->rb->logicalOr( $this->rb['eip_vpn']->equalTo(true), $this->rb['eip_tor']->equalTo(true) ); // NOT - negate a condition $this->rb->logicalNot( $this->rb['le_has_no_data_breaches']->equalTo(true) ); ``` ### Rule context attributes When writing custom rules, the following attributes are available in the `defineCondition()` method. Access them via `$this->rb['attribute_name']`. Attributes of type `array` hold one value per event, IP address or device. Reduce them to a single value in `prepareParams()` (for example with `in_array()` or `count()`) before using them in a condition; string operators such as `startsWith` throw an error on arrays. #### Event attributes (event_) From Event context: | Attribute | Type | Description | |-----------|------|-------------| | `event_ip` | array | IP IDs per event | | `event_url_string` | array | URLs per event | | `event_device` | array | Device IDs per event | | `event_type` | array | Event types | | `event_http_code` | array | HTTP response codes | | `event_http_method` | array | HTTP methods | | `event_device_created` | array | Device creation timestamps | | `event_device_lastseen` | array | Device last seen timestamps | Derived event attributes: | Attribute | Type | Description | |-----------|------|-------------| | `event_email_changed` | bool | User changed email in recent events | | `event_password_changed` | bool | User changed password in recent events | | `event_http_method_head` | bool | HEAD request detected | | `event_empty_referer` | bool | Request had empty referer | | `event_multiple_5xx_http` | int | Count of 5xx server errors | | `event_multiple_4xx_http` | int | Count of 4xx client errors | | `event_2xx_http` | bool | Successful requests exist | | `event_vulnerable_url` | bool | URL matches suspicious patterns | #### Account attributes (ea_) Raw account data from User context: | Attribute | Type | Description | |-----------|------|-------------| | `ea_userid` | string | User identifier | | `ea_created` | string | Account creation timestamp | | `ea_lastseen` | string | Last activity timestamp | | `ea_total_visit` | int | Total visits | | `ea_total_country` | int | Total countries | | `ea_total_ip` | int | Total IP addresses | | `ea_total_device` | int | Total devices | | `ea_firstname` | string | First name | | `ea_lastname` | string | Last name | Derived account attributes: | Attribute | Type | Description | |-----------|------|-------------| | `ea_days_since_account_creation` | int | Days since account was created (-1 if unknown) | | `ea_days_since_last_visit` | int | Days since user's last activity (-1 if unknown) | | `ea_fullname_has_numbers` | bool | Full name contains digits | | `ea_fullname_has_spaces_hyphens` | bool | Full name contains spaces or hyphens | #### IP attributes (eip_) From Ip context: | Attribute | Type | Description | |-----------|------|-------------| | `eip_cidr_count` | array | Count of IPs per CIDR | | `eip_country_count` | array | Count of IPs per country | | `eip_country_id` | array | Country IDs | | `eip_data_center` | bool | IP belongs to datacenter | | `eip_tor` | bool | IP belongs to TOR network | | `eip_vpn` | bool | IP belongs to commercial VPN | | `eip_starlink` | bool | IP belongs to Starlink | | `eip_blocklist` | bool | IP appears in spam/blocklist | | `eip_has_fraud` | bool | Fraud detected for IP | | `eip_lan` | bool | IP belongs to LAN | | `eip_shared` | int | Number of users sharing this IP | | `eip_domains_count_len` | int | Number of domains on IP | | `eip_unique_cidrs` | int | Number of unique network ranges | | `eip_asn` | array | ASNs of the user's IP addresses | | `eip_only_residential` | bool | All IPs are residential (derived) | | `eip_suspicious_asn` | bool | An IP belongs to an ASN listed in `assets/lists/asn.php` (derived) | #### Device attributes (eup_) From Device context: | Attribute | Type | Description | |-----------|------|-------------| | `eup_device` | array | Device types (desktop, smartphone, tablet, etc.) | | `eup_browser_name` | array | Browser names | | `eup_browser_version` | array | Browser versions | | `eup_os_name` | array | Operating system names | | `eup_lang` | array | Browser languages | | `eup_ua` | array | Raw user agent strings | Derived device attributes: | Attribute | Type | Description | |-----------|------|-------------| | `eup_device_count` | int | Number of devices used | | `eup_has_rare_browser` | bool | User has uncommon browser | | `eup_has_rare_os` | bool | User has uncommon OS | | `eup_vulnerable_ua` | bool | User-Agent matches suspicious patterns | | `eup_empty_ua` | bool | A request was made with an empty User-Agent | | `eup_empty_lang` | bool | A request was made with an empty browser language | | `eup_ai_bot` | bool | Device matches an entry in `assets/lists/ai-bot.php` | #### Session attributes (event_session_) From Session context: | Attribute | Type | Description | |-----------|------|-------------| | `event_session_single_event` | bool | Session had only one event | | `event_session_multiple_country` | bool | Country changed within 30 min | | `event_session_multiple_ip` | bool | IP changed within 30 min | | `event_session_multiple_device` | bool | Device changed within 30 min | | `event_session_night_time` | bool | Activity between midnight and 5 AM | Derived last email attributes: | Attribute | Type | Description | |-----------|------|-------------| | `le_exists` | bool | Email address exists | | `le_is_invalid` | bool | Email format is invalid | | `le_has_suspicious_str` | bool | Email contains suspicious patterns | | `le_has_numeric_only_local_part` | bool | Email username is all numbers | | `le_email_has_consec_s_chars` | bool | Email has consecutive special characters | | `le_email_has_consec_nums` | bool | Email has consecutive digits | | `le_email_has_no_digits` | bool | Email has no digits | | `le_email_has_vowels` | bool | Email username contains vowels | | `le_email_has_consonants` | bool | Email username contains consonants | | `le_with_long_local_part_length` | bool | Email username exceeds max length | | `le_with_long_domain_length` | bool | Email domain exceeds max length | | `le_email_in_blockemails` | bool | Email is in blocklist | | `le_has_no_data_breaches` | bool | No known data breaches | | `le_appears_on_alert_list` | bool | Email on alert list | | `le_local_part_len` | int | Length of email username | #### Rule-local attributes Some core rules compute additional values in their own `prepareParams()` method, for example `event_many_failed_login_attempts` (A01), `event_new_device_and_new_country` (A03), `eup_old_browser` (D09) or `lp_country_code_in_eip_country_id` (P02). These values exist only inside the rule that defines them and are **not** available to custom rules. To reuse such logic, compute the value in your own rule's `prepareParams()` or in a custom `Context` class. ### Suspicious pattern lists tirreno maintains lists of suspicious patterns in `assets/lists/`: | File | Purpose | |------|---------| | `url.php` | URL attack patterns (SQL injection, path traversal, etc.) | | `user-agent.php` | Suspicious user agent strings | | `ai-bot.php` | AI agent, assistant and crawler user agent substrings (used by rule D13) | | `asn.php` | Suspicious ASN numbers (used by rule I13) | | `email.php` | Suspicious email patterns | | `file-extensions.php` | File extension categories (e.g. `Archive`, `Config`) | Each file in `assets/lists/` overrides the built-in default list in `app/Utils/Assets/Lists/`. If a file is missing or does not return an array, tirreno falls back to the built-in defaults. A file replaces the whole list, so it must contain every pattern you want to keep. Each file returns a PHP array (`asn.php` contains integers, `file-extensions.php` is grouped by category): ```php ', // ... ]; ``` To add patterns: 1. Open the appropriate file in `assets/lists/` 2. Add your pattern string to the array 3. Patterns are case-insensitive substring matches **Example patterns by type:** | List | Example Patterns | |------|------------------| | `url.php` | `'.env'`, `'../'`, `'/wp-admin'`, `'phpmyadmin'`, `'