Skip to content
Merged
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
13 changes: 13 additions & 0 deletions behavioral-auth/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Continuous Authentication Using Behavioral Biometrics

This tool implements continuous authentication by monitoring user behavior (keystrokes, mouse movements) and triggering re-authentication or session termination on anomalies.

## Modules
- behavioral-biometrics-engine.js: Monitors user behavior
- anomaly-detector.js: Detects anomalies
- continuous-auth.js: Integrates authentication workflow
- session-manager.js: Manages sessions
- behavioral-auth-ui.js: CLI demo

## Usage
Run behavioral-auth-ui.js to see a demo of continuous authentication and anomaly detection.
34 changes: 34 additions & 0 deletions behavioral-auth/anomaly-detector.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// anomaly-detector.js
// Detects anomalies in user behavior for continuous authentication

class AnomalyDetector {
constructor() {
this.keystrokeBaseline = [];
this.mouseBaseline = [];
}

setBaseline(keystrokePatterns, mousePatterns) {
this.keystrokeBaseline = keystrokePatterns;
this.mouseBaseline = mousePatterns;
}

detectKeystrokeAnomaly(currentPatterns) {
// Simple anomaly detection: compare length and timing
if (currentPatterns.length < this.keystrokeBaseline.length * 0.5) return true;
// Advanced: compare timing, sequence, etc.
return false;
}

detectMouseAnomaly(currentPatterns) {
// Simple anomaly detection: compare movement frequency
if (currentPatterns.length < this.mouseBaseline.length * 0.5) return true;
// Advanced: compare speed, direction, etc.
return false;
}

detectAnomaly(currentKeystrokes, currentMouse) {
return this.detectKeystrokeAnomaly(currentKeystrokes) || this.detectMouseAnomaly(currentMouse);
}
}

module.exports = AnomalyDetector;
36 changes: 36 additions & 0 deletions behavioral-auth/behavioral-auth-ui.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// behavioral-auth-ui.js
// CLI demo for Continuous Authentication Using Behavioral Biometrics

const ContinuousAuth = require('./continuous-auth');
const SessionManager = require('./session-manager');

function runBehavioralAuthDemo() {
const userId = 'user123';
const sessionManager = new SessionManager();
const sessionId = sessionManager.createSession(userId);

// Baseline patterns (simulate normal user behavior)
const baselineKeystrokes = Array(20).fill().map((_, i) => ({ key: 'a', timestamp: Date.now() + i * 100 }));
const baselineMouse = Array(20).fill().map((_, i) => ({ x: i * 10, y: i * 5, timestamp: Date.now() + i * 120 }));

const continuousAuth = new ContinuousAuth();
continuousAuth.startSession(sessionId, baselineKeystrokes, baselineMouse);

// Simulate normal user activity
baselineKeystrokes.forEach(event => continuousAuth.recordKeystroke(event));
baselineMouse.forEach(event => continuousAuth.recordMouseMovement(event));

// Simulate anomaly (sudden drop in activity)
const anomalyKeystrokes = Array(5).fill().map((_, i) => ({ key: 'b', timestamp: Date.now() + i * 200 }));
anomalyKeystrokes.forEach(event => continuousAuth.recordKeystroke(event));

// Session status
if (!continuousAuth.sessionActive) {
sessionManager.terminateSession(sessionId);
console.log('Session terminated due to anomaly.');
} else {
console.log('Session remains active.');
}
}

runBehavioralAuthDemo();
36 changes: 36 additions & 0 deletions behavioral-auth/behavioral-biometrics-engine.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// behavioral-biometrics-engine.js
// Monitors user keystrokes and mouse movements for continuous authentication

class BehavioralBiometricsEngine {
constructor() {
this.keystrokePatterns = [];
this.mousePatterns = [];
this.sessionId = null;
}

startSession(sessionId) {
this.sessionId = sessionId;
this.keystrokePatterns = [];
this.mousePatterns = [];
}

recordKeystroke(event) {
// event: { key, timestamp }
this.keystrokePatterns.push(event);
}

recordMouseMovement(event) {
// event: { x, y, timestamp }
this.mousePatterns.push(event);
}

getKeystrokePatterns() {
return this.keystrokePatterns;
}

getMousePatterns() {
return this.mousePatterns;
}
}

module.exports = BehavioralBiometricsEngine;
44 changes: 44 additions & 0 deletions behavioral-auth/continuous-auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// continuous-auth.js
// Integrates behavioral biometrics and anomaly detection for continuous authentication

const BehavioralBiometricsEngine = require('./behavioral-biometrics-engine');
const AnomalyDetector = require('./anomaly-detector');

class ContinuousAuth {
constructor() {
this.engine = new BehavioralBiometricsEngine();
this.detector = new AnomalyDetector();
this.sessionActive = false;
}

startSession(sessionId, baselineKeystrokes, baselineMouse) {
this.engine.startSession(sessionId);
this.detector.setBaseline(baselineKeystrokes, baselineMouse);
this.sessionActive = true;
}

recordKeystroke(event) {
this.engine.recordKeystroke(event);
this.checkForAnomaly();
}

recordMouseMovement(event) {
this.engine.recordMouseMovement(event);
this.checkForAnomaly();
}

checkForAnomaly() {
const keystrokes = this.engine.getKeystrokePatterns();
const mouse = this.engine.getMousePatterns();
if (this.detector.detectAnomaly(keystrokes, mouse)) {
this.triggerReauthentication();
}
}

triggerReauthentication() {
this.sessionActive = false;
console.log('Anomaly detected! Triggering re-authentication or session termination.');
}
}

module.exports = ContinuousAuth;
33 changes: 33 additions & 0 deletions behavioral-auth/session-manager.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// session-manager.js
// Manages user sessions and handles re-authentication

class SessionManager {
constructor() {
this.sessions = {};
}

createSession(userId) {
const sessionId = `${userId}-${Date.now()}`;
this.sessions[sessionId] = { userId, active: true };
return sessionId;
}

terminateSession(sessionId) {
if (this.sessions[sessionId]) {
this.sessions[sessionId].active = false;
}
}

isSessionActive(sessionId) {
return this.sessions[sessionId] && this.sessions[sessionId].active;
}

reauthenticate(sessionId) {
if (this.sessions[sessionId]) {
this.sessions[sessionId].active = true;
console.log(`Session ${sessionId} re-authenticated.`);
}
}
}

module.exports = SessionManager;
21 changes: 21 additions & 0 deletions dlp/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Real-Time Data Loss Prevention (DLP)

## Overview
This module provides real-time DLP for outgoing data in ExpenseFlow. It scans API responses and exports for sensitive information and enforces policies (block, alert, log).

## Components
- `dlp-engine.js`: Core detection and policy evaluation
- `dlp-middleware.js`: Express middleware for outgoing responses
- `dlp-config.js`: Patterns and policies configuration
- `dlp-logger.js`: Audit trail for DLP events
- `dlp-utils.js`: Helper functions (masking, etc.)
- `dlp-test.js`: Unit tests

## Usage
1. Add `dlp-middleware` to your Express routes.
2. Configure patterns and policies in `dlp-config.js`.
3. Check `dlp-audit.log` for DLP events.

## Extending
- Add new patterns/policies in `dlp-config.js`.
- Integrate with alerting systems as needed.
17 changes: 17 additions & 0 deletions dlp/dlp-config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// DLP Configuration: Patterns and policies
// ...existing code...

module.exports = {
patterns: [
{ type: 'email', regex: '[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+', severity: 'high' },
{ type: 'ssn', regex: '\b\d{3}-\d{2}-\d{4}\b', severity: 'high' },
{ type: 'credit_card', regex: '\b(?:\d[ -]*?){13,16}\b', severity: 'high' },
{ type: 'phone', regex: '\b\d{3}[-.\s]?\d{3}[-.\s]?\d{4}\b', severity: 'medium' },
// Add more patterns as needed
],
policies: [
{ types: ['email', 'ssn', 'credit_card'], action: 'block', message: 'Sensitive data detected. Action blocked.' },
{ types: ['phone'], action: 'alert', message: 'Phone number detected. Alert logged.' },
// Add more policies as needed
],
};
43 changes: 43 additions & 0 deletions dlp/dlp-engine.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// DLP Engine: Core detection and policy evaluation
// ...existing code...

class DLPEngine {
constructor(config) {
this.config = config;
this.patterns = config.patterns || [];
this.policies = config.policies || [];
}

scanData(data) {
let findings = [];
for (const pattern of this.patterns) {
const regex = new RegExp(pattern.regex, 'gi');
if (regex.test(data)) {
findings.push({
type: pattern.type,
match: data.match(regex),
severity: pattern.severity || 'medium',
});
}
}
return findings;
}

evaluatePolicies(findings) {
let actions = [];
for (const policy of this.policies) {
for (const finding of findings) {
if (policy.types.includes(finding.type)) {
actions.push({
action: policy.action,
finding,
message: policy.message || 'Policy violation detected',
});
}
}
}
return actions;
}
}

module.exports = DLPEngine;
15 changes: 15 additions & 0 deletions dlp/dlp-logger.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// DLP Logger: Audit trail for DLP events
// ...existing code...
const fs = require('fs');
const path = require('path');

const LOG_FILE = path.join(__dirname, 'dlp-audit.log');

function logDLPEvent(event) {
const entry = `${new Date().toISOString()} | ${event.action} | ${event.finding.type} | ${event.finding.match} | ${event.message}\n`;
fs.appendFile(LOG_FILE, entry, err => {
if (err) console.error('DLP Logger error:', err);
});
}

module.exports = logDLPEvent;
29 changes: 29 additions & 0 deletions dlp/dlp-middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// DLP Middleware: Intercepts outgoing responses
// ...existing code...

const DLPEngine = require('./dlp-engine');
const dlpConfig = require('./dlp-config');
const logDLPEvent = require('./dlp-logger');

const dlpEngine = new DLPEngine(dlpConfig);

function dlpMiddleware(req, res, next) {
const originalSend = res.send;
res.send = function (body) {
const findings = dlpEngine.scanData(typeof body === 'string' ? body : JSON.stringify(body));
const actions = dlpEngine.evaluatePolicies(findings);
actions.forEach(action => logDLPEvent(action));
if (actions.some(a => a.action === 'block')) {
res.status(403);
return originalSend.call(this, { error: 'DLP policy violation', details: actions });
}
if (actions.some(a => a.action === 'alert')) {
// Log or alert (implementation below)
console.log('DLP Alert:', actions);
}
return originalSend.call(this, body);
};
next();
}

module.exports = dlpMiddleware;
25 changes: 25 additions & 0 deletions dlp/dlp-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// DLP Test: Unit tests for DLP engine
// ...existing code...

const DLPEngine = require('./dlp-engine');
const dlpConfig = require('./dlp-config');

const engine = new DLPEngine(dlpConfig);

function testScanData() {
const testData = 'User email: test@example.com, SSN: 123-45-6789, Card: 4111 1111 1111 1111';
const findings = engine.scanData(testData);
console.log('Findings:', findings);
}

function testEvaluatePolicies() {
const findings = [
{ type: 'email', match: ['test@example.com'], severity: 'high' },
{ type: 'ssn', match: ['123-45-6789'], severity: 'high' },
];
const actions = engine.evaluatePolicies(findings);
console.log('Actions:', actions);
}

testScanData();
testEvaluatePolicies();
15 changes: 15 additions & 0 deletions dlp/dlp-utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// DLP Utilities: Helper functions for sensitive data detection
// ...existing code...

function maskSensitiveData(data, patterns) {
let masked = data;
for (const pattern of patterns) {
const regex = new RegExp(pattern.regex, 'gi');
masked = masked.replace(regex, '[MASKED]');
}
return masked;
}

module.exports = {
maskSensitiveData,
};
Loading