Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions boilerplates/ssh-login-monitor/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules/
dist/
*.js.map
.env
21 changes: 21 additions & 0 deletions boilerplates/ssh-login-monitor/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 pxivory-max

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
42 changes: 42 additions & 0 deletions boilerplates/ssh-login-monitor/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# ThreatCrush Module — SSH Login Monitor

A ThreatCrush security module that monitors SSH authentication logs for
suspicious login activity and emits `ThreatEvent`s for brute-force detection.

## What it does

- Tails `/var/log/auth.log` (configurable) for SSH events
- Detects failed login attempts and successful logins
- Emits `high`/`critical` severity events when brute-force patterns are detected
(configurable threshold)
- Emits `info` events for successful SSH logins (useful for audit trails)
- Persists file offset via `ctx.setState` to avoid re-processing on restart

## Configuration

In `mod.toml`:

```toml
[module.config.defaults]
auth_log_path = "/var/log/auth.log"
failed_threshold = 5
poll_interval_seconds = 30
```

- `auth_log_path` — path to the sshd auth log
- `failed_threshold` — number of failed attempts from a single IP in one poll
cycle before escalating to `high` severity
- `poll_interval_seconds` — how often to check for new log entries

## Install

```bash
git clone https://github.com/pxivory-max/threatcrush-ssh-monitor
cd threatcrush-ssh-monitor
pnpm install
pnpm build
```

## License

MIT
24 changes: 24 additions & 0 deletions boilerplates/ssh-login-monitor/mod.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
[module]
name = "ssh-login-monitor"
version = "0.1.0"
description = "Monitors auth logs for SSH login attempts and emits ThreatEvents for failed/suspicious logins"
author = "pxivory-max"
license = "MIT"
homepage = "https://github.com/pxivory-max/threatcrush-ssh-monitor"

[module.pricing]
type = "free"

[module.requirements]
threatcrush = ">=0.1.0"
os = ["linux"]
capabilities = ["fs:read"]

[module.config.defaults]
enabled = true
# Path to auth log file
auth_log_path = "/var/log/auth.log"
# Number of failed attempts before escalating severity
failed_threshold = 5
# Poll interval in seconds
poll_interval_seconds = 30
20 changes: 20 additions & 0 deletions boilerplates/ssh-login-monitor/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "threatcrush-module-ssh-monitor",
"version": "0.1.0",
"private": true,
"description": "ThreatCrush module — monitors SSH login attempts and emits security events",
"type": "module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "tsc -p tsconfig.json",
"clean": "rm -rf dist"
},
"dependencies": {
"@threatcrush/sdk": "^0.1.0"
},
"devDependencies": {
"@types/node": "^22.0.0",
"typescript": "^5.9.3"
}
}
188 changes: 188 additions & 0 deletions boilerplates/ssh-login-monitor/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
/**
* SSH Login Monitor Module — ThreatCrush module.
*
* Tails /var/log/auth.log (configurable) for SSH login events, parses
* failed and successful attempts, and emits ThreatEvents when suspicious
* activity is detected (e.g., brute-force patterns, logins from new IPs).
*/

import { readFile, stat } from 'node:fs/promises';
import type {
ThreatCrushModule,
ModuleContext,
ThreatEvent,
EventSeverity,
} from '@threatcrush/sdk';

interface LoginAttempt {
timestamp: string;
user: string;
ip: string;
success: boolean;
method?: string;
}

export default class SshLoginMonitorModule implements ThreatCrushModule {
name = 'ssh-login-monitor';
version = '0.1.0';
description = 'Monitors SSH auth logs for failed/suspicious login attempts';

private ctx!: ModuleContext;
private timer: NodeJS.Timeout | null = null;
private running = false;

async init(ctx: ModuleContext): Promise<void> {
this.ctx = ctx;
this.ctx.logger.info('[%s] initialized', this.name);
}

async start(): Promise<void> {
const intervalSec =
(this.ctx.config.poll_interval_seconds as number | undefined) ?? 30;
this.ctx.logger.info(
'[%s] starting auth log monitor (every %ds)',
this.name,
intervalSec,
);
this.running = true;
void this.tick();
this.timer = setInterval(() => void this.tick(), intervalSec * 1000);
}

async stop(): Promise<void> {
this.running = false;
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
this.ctx.logger.info('[%s] stopped', this.name);
}

private async tick(): Promise<void> {
if (!this.running) return;

const logPath =
(this.ctx.config.auth_log_path as string | undefined) ??
'/var/log/auth.log';

let fileSize: number;
try {
const s = await stat(logPath);
fileSize = s.size;
} catch (err) {
this.ctx.logger.error('[%s] cannot stat %s: %s', this.name, logPath, String(err));
return;
}

const lastOffset = (this.ctx.getState('last_offset') as number) ?? 0;

// If file was rotated (smaller than last offset), reset
const readFrom = fileSize < lastOffset ? 0 : lastOffset;

if (readFrom >= fileSize) return; // no new data

let content: string;
try {
const buf = await readFile(logPath, { encoding: 'utf8' });

Check failure

Code scanning / CodeQL

Potential file system race condition High

The file may have changed since it
was checked
.
content = buf.slice(readFrom);
} catch (err) {
this.ctx.logger.error('[%s] read error: %s', this.name, String(err));
return;
}

const attempts = this.parseAuthLog(content);
const failedByIp = new Map<string, number>();

const threshold =
(this.ctx.config.failed_threshold as number | undefined) ?? 5;

for (const attempt of attempts) {
if (!attempt.success) {
const count = (failedByIp.get(attempt.ip) ?? 0) + 1;
failedByIp.set(attempt.ip, count);
}

// Emit individual events for successful logins (potential compromise)
if (attempt.success) {
const event: ThreatEvent = {
timestamp: new Date(),
module: this.name,
category: 'auth',
severity: 'info',
message: `SSH login success: ${attempt.user}@${attempt.ip}`,
details: {
user: attempt.user,
ip: attempt.ip,
method: attempt.method,
},
};
this.ctx.emit(event);
}
}

// Emit high-severity events for brute-force patterns
for (const [ip, count] of failedByIp) {
if (count >= threshold) {
const severity: EventSeverity = count >= threshold * 2 ? 'critical' : 'high';
const event: ThreatEvent = {
timestamp: new Date(),
module: this.name,
category: 'auth',
severity,
message: `SSH brute-force detected: ${count} failed attempts from ${ip}`,
details: {
ip,
failed_count: count,
threshold,
},
};
this.ctx.emit(event);
}
}

this.ctx.setState('last_offset', fileSize);
this.ctx.logger.info(
'[%s] processed %d bytes, found %d attempts',
this.name,
fileSize - readFrom,
attempts.length,
);
}

private parseAuthLog(content: string): LoginAttempt[] {
const attempts: LoginAttempt[] = [];

for (const line of content.split('\n')) {
// Failed password
const failedMatch = line.match(
/^(\w+\s+\d+\s+[\d:]+)\s+\S+\s+sshd\[\d+\]:\s+Failed password for (?:invalid user )?(\S+) from ([\d.]+)/,
);
if (failedMatch) {
attempts.push({
timestamp: failedMatch[1],
user: failedMatch[2],
ip: failedMatch[3],
success: false,
});
continue;
}

// Accepted login
const acceptMatch = line.match(
/^(\w+\s+\d+\s+[\d:]+)\s+\S+\s+sshd\[\d+\]:\s+Accepted (\S+) for (\S+) from ([\d.]+)/,
);
if (acceptMatch) {
attempts.push({
timestamp: acceptMatch[1],
user: acceptMatch[3],
ip: acceptMatch[4],
success: true,
method: acceptMatch[2],
});
continue;
}
}

return attempts;
}
}
14 changes: 14 additions & 0 deletions boilerplates/ssh-login-monitor/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"outDir": "dist",
"rootDir": "src",
"declaration": true,
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
},
"include": ["src/**/*.ts"]
}
Loading