Adaugă codul complet al proiectului underchat-ircd
This commit is contained in:
1 parent
caba5224bf
commit
5fdc1cc27c
462 files changed
+164488
No files matched your search
@@ -0,0 +1,185 @@
|
||||
/**
|
||||
* Authentication configuration parser
|
||||
* Parses #IAUTH AUTH directives
|
||||
*/
|
||||
|
||||
import type {
|
||||
AuthProviderConfig,
|
||||
FileAuthConfig,
|
||||
LDAPAuthConfig,
|
||||
KeycloakAuthConfig,
|
||||
} from './types.js';
|
||||
|
||||
/**
|
||||
* Parse an AUTH configuration line
|
||||
* Format: provider=<type> key=value key=value ...
|
||||
*
|
||||
* Examples:
|
||||
* provider=file path=/path/to/users
|
||||
* provider=ldap uri=ldap://server:389 mode=direct userdn=uid=%s,ou=users,dc=example,dc=com
|
||||
* provider=ldap uri=ldaps://server:636 mode=search basedn=ou=users,dc=example,dc=com ...
|
||||
*/
|
||||
export function parseAuthConfig(args: string): AuthProviderConfig | null {
|
||||
const params = parseKeyValuePairs(args);
|
||||
|
||||
const provider = params.get('provider');
|
||||
if (!provider) {
|
||||
return null;
|
||||
}
|
||||
|
||||
switch (provider) {
|
||||
case 'file':
|
||||
return parseFileAuthConfig(params);
|
||||
case 'ldap':
|
||||
return parseLDAPAuthConfig(params);
|
||||
case 'keycloak':
|
||||
return parseKeycloakAuthConfig(params);
|
||||
default:
|
||||
console.error(`Unknown auth provider: ${provider}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse key=value pairs from a string
|
||||
* Handles quoted values for values containing spaces
|
||||
*/
|
||||
function parseKeyValuePairs(args: string): Map<string, string> {
|
||||
const result = new Map<string, string>();
|
||||
|
||||
// Match key=value or key="value with spaces" or key='value with spaces'
|
||||
const regex = /(\w+)=(?:"([^"]*)"|'([^']*)'|(\S+))/g;
|
||||
let match;
|
||||
|
||||
while ((match = regex.exec(args)) !== null) {
|
||||
const key = match[1];
|
||||
// Use quoted value if present, otherwise unquoted
|
||||
const value = match[2] ?? match[3] ?? match[4];
|
||||
result.set(key, value);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse file auth provider config
|
||||
*/
|
||||
function parseFileAuthConfig(params: Map<string, string>): FileAuthConfig | null {
|
||||
const path = params.get('path');
|
||||
if (!path) {
|
||||
console.error('File auth provider requires path');
|
||||
return null;
|
||||
}
|
||||
|
||||
const priority = params.has('priority')
|
||||
? parseInt(params.get('priority')!, 10)
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
provider: 'file',
|
||||
path,
|
||||
priority,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse LDAP auth provider config
|
||||
*/
|
||||
function parseLDAPAuthConfig(params: Map<string, string>): LDAPAuthConfig | null {
|
||||
const uri = params.get('uri');
|
||||
if (!uri) {
|
||||
console.error('LDAP auth provider requires uri');
|
||||
return null;
|
||||
}
|
||||
|
||||
const mode = params.get('mode') as 'direct' | 'search' | undefined;
|
||||
if (!mode || (mode !== 'direct' && mode !== 'search')) {
|
||||
console.error('LDAP auth provider requires mode (direct or search)');
|
||||
return null;
|
||||
}
|
||||
|
||||
const priority = params.has('priority')
|
||||
? parseInt(params.get('priority')!, 10)
|
||||
: undefined;
|
||||
|
||||
const timeout = params.has('timeout')
|
||||
? parseInt(params.get('timeout')!, 10)
|
||||
: undefined;
|
||||
|
||||
const config: LDAPAuthConfig = {
|
||||
provider: 'ldap',
|
||||
uri,
|
||||
mode,
|
||||
priority,
|
||||
timeout,
|
||||
};
|
||||
|
||||
// Mode-specific options
|
||||
if (mode === 'direct') {
|
||||
config.userdn = params.get('userdn');
|
||||
} else {
|
||||
config.basedn = params.get('basedn');
|
||||
config.binddn = params.get('binddn');
|
||||
config.bindpass = params.get('bindpass');
|
||||
config.userfilter = params.get('userfilter');
|
||||
config.groupdn = params.get('groupdn');
|
||||
}
|
||||
|
||||
// Optional for both modes
|
||||
config.accountattr = params.get('accountattr');
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse Keycloak auth provider config
|
||||
*/
|
||||
function parseKeycloakAuthConfig(params: Map<string, string>): KeycloakAuthConfig | null {
|
||||
const url = params.get('url');
|
||||
if (!url) {
|
||||
console.error('Keycloak auth provider requires url');
|
||||
return null;
|
||||
}
|
||||
|
||||
const realm = params.get('realm');
|
||||
if (!realm) {
|
||||
console.error('Keycloak auth provider requires realm');
|
||||
return null;
|
||||
}
|
||||
|
||||
const clientid = params.get('clientid');
|
||||
if (!clientid) {
|
||||
console.error('Keycloak auth provider requires clientid');
|
||||
return null;
|
||||
}
|
||||
|
||||
const priority = params.has('priority')
|
||||
? parseInt(params.get('priority')!, 10)
|
||||
: undefined;
|
||||
|
||||
const timeout = params.has('timeout')
|
||||
? parseInt(params.get('timeout')!, 10)
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
provider: 'keycloak',
|
||||
url,
|
||||
realm,
|
||||
clientid,
|
||||
clientsecret: params.get('clientsecret'),
|
||||
accountattr: params.get('accountattr'),
|
||||
timeout,
|
||||
priority,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert legacy SASLDB directive to file provider config
|
||||
*/
|
||||
export function convertSASLDB(path: string): FileAuthConfig {
|
||||
return {
|
||||
provider: 'file',
|
||||
path,
|
||||
priority: 100, // Default priority
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* Authentication module for iauthd-ts
|
||||
* Provides modular authentication with multiple backend support
|
||||
*/
|
||||
|
||||
// Types
|
||||
export type {
|
||||
AuthResult,
|
||||
AuthProvider,
|
||||
AuthProviderConfig,
|
||||
FileAuthConfig,
|
||||
LDAPAuthConfig,
|
||||
KeycloakAuthConfig,
|
||||
} from './types.js';
|
||||
|
||||
export { isFileAuthConfig, isLDAPAuthConfig, isKeycloakAuthConfig } from './types.js';
|
||||
|
||||
// Manager
|
||||
export { AuthManager } from './manager.js';
|
||||
|
||||
// Config parsing
|
||||
export { parseAuthConfig, convertSASLDB } from './config.js';
|
||||
|
||||
// Providers
|
||||
export { FileAuthProvider, LDAPAuthProvider, KeycloakAuthProvider } from './providers/index.js';
|
||||
@@ -0,0 +1,173 @@
|
||||
/**
|
||||
* Authentication Manager
|
||||
* Coordinates multiple authentication providers with fallback chain behavior
|
||||
*/
|
||||
|
||||
import type {
|
||||
AuthProvider,
|
||||
AuthResult,
|
||||
AuthProviderConfig,
|
||||
FileAuthConfig,
|
||||
LDAPAuthConfig,
|
||||
KeycloakAuthConfig,
|
||||
} from './types.js';
|
||||
import { FileAuthProvider } from './providers/file.js';
|
||||
import { LDAPAuthProvider } from './providers/ldap.js';
|
||||
import { KeycloakAuthProvider } from './providers/keycloak.js';
|
||||
|
||||
export class AuthManager {
|
||||
private providers: AuthProvider[] = [];
|
||||
private initialized = false;
|
||||
|
||||
constructor(private readonly configs: AuthProviderConfig[]) {}
|
||||
|
||||
/**
|
||||
* Initialize all configured providers
|
||||
* Providers are sorted by priority (lower = first)
|
||||
*/
|
||||
async initialize(): Promise<void> {
|
||||
if (this.initialized) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Sort by priority (lower first)
|
||||
const sorted = [...this.configs].sort(
|
||||
(a, b) => (a.priority ?? 100) - (b.priority ?? 100)
|
||||
);
|
||||
|
||||
for (const config of sorted) {
|
||||
const provider = this.createProvider(config);
|
||||
try {
|
||||
await provider.initialize();
|
||||
this.providers.push(provider);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
console.error(`Failed to initialize ${config.provider} provider: ${message}`);
|
||||
// Continue with other providers
|
||||
}
|
||||
}
|
||||
|
||||
this.initialized = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a provider instance from configuration
|
||||
*/
|
||||
private createProvider(config: AuthProviderConfig): AuthProvider {
|
||||
switch (config.provider) {
|
||||
case 'file':
|
||||
return new FileAuthProvider(config as FileAuthConfig);
|
||||
case 'ldap':
|
||||
return new LDAPAuthProvider(config as LDAPAuthConfig);
|
||||
case 'keycloak':
|
||||
return new KeycloakAuthProvider(config as KeycloakAuthConfig);
|
||||
default:
|
||||
throw new Error(`Unknown auth provider: ${(config as AuthProviderConfig).provider}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticate using fallback chain
|
||||
* Tries providers in priority order until one succeeds
|
||||
*/
|
||||
async authenticate(
|
||||
authcid: string,
|
||||
password: string,
|
||||
authzid?: string
|
||||
): Promise<AuthResult> {
|
||||
if (!this.initialized) {
|
||||
return { success: false, error: 'AuthManager not initialized' };
|
||||
}
|
||||
|
||||
if (this.providers.length === 0) {
|
||||
return { success: false, error: 'No auth providers configured' };
|
||||
}
|
||||
|
||||
let lastError: string | undefined;
|
||||
|
||||
for (const provider of this.providers) {
|
||||
// Skip unhealthy providers
|
||||
if (!provider.isHealthy()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await provider.authenticate(authcid, password, authzid);
|
||||
if (result.success) {
|
||||
return result;
|
||||
}
|
||||
// Provider returned explicit failure - continue to next
|
||||
lastError = result.error;
|
||||
} catch (err) {
|
||||
// Provider threw error - log and continue
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
console.error(`Auth provider ${provider.name} error: ${message}`);
|
||||
lastError = message;
|
||||
}
|
||||
}
|
||||
|
||||
return { success: false, error: lastError ?? 'Authentication failed' };
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if any providers are configured and healthy
|
||||
*/
|
||||
hasProviders(): boolean {
|
||||
return this.providers.length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if any provider is healthy
|
||||
*/
|
||||
hasHealthyProviders(): boolean {
|
||||
return this.providers.some((p) => p.isHealthy());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get provider count
|
||||
*/
|
||||
getProviderCount(): number {
|
||||
return this.providers.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get provider info for status display
|
||||
*/
|
||||
getProviderInfo(): Array<{ name: string; priority: number; healthy: boolean }> {
|
||||
return this.providers.map((p) => ({
|
||||
name: p.name,
|
||||
priority: p.priority,
|
||||
healthy: p.isHealthy(),
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Reload all providers
|
||||
*/
|
||||
async reload(): Promise<void> {
|
||||
for (const provider of this.providers) {
|
||||
try {
|
||||
await provider.reload();
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
console.error(`Failed to reload ${provider.name} provider: ${message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Shutdown all providers
|
||||
*/
|
||||
async shutdown(): Promise<void> {
|
||||
for (const provider of this.providers) {
|
||||
try {
|
||||
await provider.shutdown();
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
console.error(`Failed to shutdown ${provider.name} provider: ${message}`);
|
||||
}
|
||||
}
|
||||
this.providers = [];
|
||||
this.initialized = false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* Static file authentication provider
|
||||
* Wraps the existing SASL users file functionality
|
||||
*/
|
||||
|
||||
import type { AuthProvider, AuthResult, FileAuthConfig } from '../types.js';
|
||||
import {
|
||||
parseUsersFile,
|
||||
usersFileModified,
|
||||
authenticatePlain,
|
||||
type UsersDB,
|
||||
} from '../../sasl.js';
|
||||
|
||||
const DEFAULT_PRIORITY = 100;
|
||||
|
||||
export class FileAuthProvider implements AuthProvider {
|
||||
readonly name = 'file';
|
||||
readonly priority: number;
|
||||
|
||||
private usersDb: UsersDB | null = null;
|
||||
private readonly filePath: string;
|
||||
|
||||
constructor(config: FileAuthConfig) {
|
||||
this.filePath = config.path;
|
||||
this.priority = config.priority ?? DEFAULT_PRIORITY;
|
||||
}
|
||||
|
||||
async initialize(): Promise<void> {
|
||||
this.usersDb = parseUsersFile(this.filePath);
|
||||
if (this.usersDb.users.size === 0) {
|
||||
// Not an error - file might not exist or be empty
|
||||
// Provider will return failure for all auth attempts
|
||||
}
|
||||
}
|
||||
|
||||
async authenticate(
|
||||
authcid: string,
|
||||
password: string,
|
||||
_authzid?: string
|
||||
): Promise<AuthResult> {
|
||||
if (!this.usersDb) {
|
||||
return { success: false, error: 'Users database not loaded' };
|
||||
}
|
||||
|
||||
// Check if file was modified and reload if needed
|
||||
if (usersFileModified(this.usersDb)) {
|
||||
this.usersDb = parseUsersFile(this.filePath);
|
||||
}
|
||||
|
||||
const account = authenticatePlain(this.usersDb, authcid, password);
|
||||
|
||||
if (account) {
|
||||
return { success: true, account };
|
||||
}
|
||||
|
||||
return { success: false, error: 'Invalid credentials' };
|
||||
}
|
||||
|
||||
async reload(): Promise<void> {
|
||||
this.usersDb = parseUsersFile(this.filePath);
|
||||
}
|
||||
|
||||
async shutdown(): Promise<void> {
|
||||
this.usersDb = null;
|
||||
}
|
||||
|
||||
isHealthy(): boolean {
|
||||
return this.usersDb !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of users loaded
|
||||
*/
|
||||
getUserCount(): number {
|
||||
return this.usersDb?.users.size ?? 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
/**
|
||||
* Authentication providers
|
||||
*/
|
||||
|
||||
export { FileAuthProvider } from './file.js';
|
||||
export { LDAPAuthProvider } from './ldap.js';
|
||||
export { KeycloakAuthProvider } from './keycloak.js';
|
||||
@@ -0,0 +1,282 @@
|
||||
/**
|
||||
* Keycloak authentication provider
|
||||
* Uses Resource Owner Password Credentials (ROPC) grant to authenticate users
|
||||
*/
|
||||
|
||||
import type { AuthProvider, AuthResult, KeycloakAuthConfig } from '../types.js';
|
||||
|
||||
const DEFAULT_PRIORITY = 100;
|
||||
const DEFAULT_TIMEOUT = 5000;
|
||||
|
||||
/**
|
||||
* Token response from Keycloak
|
||||
*/
|
||||
interface TokenResponse {
|
||||
access_token: string;
|
||||
expires_in: number;
|
||||
refresh_expires_in: number;
|
||||
refresh_token?: string;
|
||||
token_type: string;
|
||||
'not-before-policy'?: number;
|
||||
session_state?: string;
|
||||
scope: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Error response from Keycloak
|
||||
*/
|
||||
interface ErrorResponse {
|
||||
error: string;
|
||||
error_description?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decoded JWT payload (partial - only fields we care about)
|
||||
*/
|
||||
interface JWTPayload {
|
||||
sub: string;
|
||||
preferred_username?: string;
|
||||
email?: string;
|
||||
name?: string;
|
||||
given_name?: string;
|
||||
family_name?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export class KeycloakAuthProvider implements AuthProvider {
|
||||
readonly name = 'keycloak';
|
||||
readonly priority: number;
|
||||
|
||||
private readonly config: KeycloakAuthConfig;
|
||||
private readonly tokenEndpoint: string;
|
||||
private healthy = false;
|
||||
|
||||
constructor(config: KeycloakAuthConfig) {
|
||||
this.config = config;
|
||||
this.priority = config.priority ?? DEFAULT_PRIORITY;
|
||||
|
||||
// Build token endpoint URL
|
||||
// Format: {url}/realms/{realm}/protocol/openid-connect/token
|
||||
const baseUrl = config.url.replace(/\/$/, ''); // Remove trailing slash
|
||||
this.tokenEndpoint = `${baseUrl}/realms/${config.realm}/protocol/openid-connect/token`;
|
||||
}
|
||||
|
||||
async initialize(): Promise<void> {
|
||||
// Validate configuration
|
||||
if (!this.config.url) {
|
||||
throw new Error('Keycloak provider requires url');
|
||||
}
|
||||
|
||||
if (!this.config.realm) {
|
||||
throw new Error('Keycloak provider requires realm');
|
||||
}
|
||||
|
||||
if (!this.config.clientid) {
|
||||
throw new Error('Keycloak provider requires clientid');
|
||||
}
|
||||
|
||||
// Test connectivity by fetching the OpenID configuration
|
||||
try {
|
||||
const wellKnownUrl = `${this.config.url.replace(/\/$/, '')}/realms/${this.config.realm}/.well-known/openid-configuration`;
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(
|
||||
() => controller.abort(),
|
||||
this.config.timeout ?? DEFAULT_TIMEOUT
|
||||
);
|
||||
|
||||
try {
|
||||
const response = await fetch(wellKnownUrl, {
|
||||
method: 'GET',
|
||||
signal: controller.signal,
|
||||
});
|
||||
clearTimeout(timeout);
|
||||
|
||||
if (response.ok) {
|
||||
this.healthy = true;
|
||||
} else {
|
||||
// Server responded but with error - still mark as potentially healthy
|
||||
// since auth might still work
|
||||
this.healthy = true;
|
||||
}
|
||||
} catch (err) {
|
||||
clearTimeout(timeout);
|
||||
throw err;
|
||||
}
|
||||
} catch (err) {
|
||||
// Connection failed - mark as unhealthy but don't throw
|
||||
// Provider may become healthy later
|
||||
this.healthy = false;
|
||||
}
|
||||
}
|
||||
|
||||
async authenticate(
|
||||
authcid: string,
|
||||
password: string,
|
||||
_authzid?: string
|
||||
): Promise<AuthResult> {
|
||||
try {
|
||||
// Build form data for ROPC grant
|
||||
const params = new URLSearchParams();
|
||||
params.append('grant_type', 'password');
|
||||
params.append('client_id', this.config.clientid);
|
||||
params.append('username', authcid);
|
||||
params.append('password', password);
|
||||
|
||||
// Add client secret if configured (for confidential clients)
|
||||
if (this.config.clientsecret) {
|
||||
params.append('client_secret', this.config.clientsecret);
|
||||
}
|
||||
|
||||
// Make request with timeout
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(
|
||||
() => controller.abort(),
|
||||
this.config.timeout ?? DEFAULT_TIMEOUT
|
||||
);
|
||||
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(this.tokenEndpoint, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
body: params.toString(),
|
||||
signal: controller.signal,
|
||||
});
|
||||
clearTimeout(timeout);
|
||||
} catch (err) {
|
||||
clearTimeout(timeout);
|
||||
if (err instanceof Error && err.name === 'AbortError') {
|
||||
this.healthy = false;
|
||||
return { success: false, error: 'Request timeout' };
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
// Parse response
|
||||
const body = await response.text();
|
||||
|
||||
if (response.ok) {
|
||||
// Success - parse token response
|
||||
const tokenResponse = JSON.parse(body) as TokenResponse;
|
||||
this.healthy = true;
|
||||
|
||||
// Extract account name from access token
|
||||
const account = this.extractAccountFromToken(tokenResponse.access_token, authcid);
|
||||
|
||||
return { success: true, account };
|
||||
} else {
|
||||
// Error response
|
||||
try {
|
||||
const errorResponse = JSON.parse(body) as ErrorResponse;
|
||||
|
||||
// Check for disabled user (before generic invalid_grant)
|
||||
if (errorResponse.error_description?.includes('Account disabled')) {
|
||||
this.healthy = true;
|
||||
return { success: false, error: 'Account disabled' };
|
||||
}
|
||||
|
||||
// Check for invalid credentials
|
||||
if (
|
||||
errorResponse.error === 'invalid_grant' ||
|
||||
errorResponse.error_description?.includes('Invalid user credentials')
|
||||
) {
|
||||
this.healthy = true; // Server is healthy, just bad credentials
|
||||
return { success: false, error: 'Invalid credentials' };
|
||||
}
|
||||
|
||||
// Check for client errors (misconfiguration)
|
||||
if (
|
||||
errorResponse.error === 'unauthorized_client' ||
|
||||
errorResponse.error === 'invalid_client'
|
||||
) {
|
||||
return {
|
||||
success: false,
|
||||
error: `Client error: ${errorResponse.error_description || errorResponse.error}`,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error: errorResponse.error_description || errorResponse.error,
|
||||
};
|
||||
} catch {
|
||||
return { success: false, error: `HTTP ${response.status}: ${body}` };
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
this.healthy = false;
|
||||
return { success: false, error: `Keycloak error: ${message}` };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract account name from JWT access token
|
||||
*/
|
||||
private extractAccountFromToken(accessToken: string, fallback: string): string {
|
||||
try {
|
||||
// JWT format: header.payload.signature
|
||||
const parts = accessToken.split('.');
|
||||
if (parts.length !== 3) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
// Decode payload (base64url)
|
||||
const payload = this.decodeBase64Url(parts[1]);
|
||||
const claims = JSON.parse(payload) as JWTPayload;
|
||||
|
||||
// Use configured attribute or default to preferred_username
|
||||
if (this.config.accountattr) {
|
||||
const value = claims[this.config.accountattr];
|
||||
if (typeof value === 'string') {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
// Try common username claims
|
||||
if (claims.preferred_username) {
|
||||
return claims.preferred_username;
|
||||
}
|
||||
|
||||
// Fall back to subject (UUID)
|
||||
if (claims.sub) {
|
||||
return claims.sub;
|
||||
}
|
||||
|
||||
return fallback;
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode base64url string
|
||||
*/
|
||||
private decodeBase64Url(str: string): string {
|
||||
// Convert base64url to base64
|
||||
let base64 = str.replace(/-/g, '+').replace(/_/g, '/');
|
||||
|
||||
// Add padding if needed
|
||||
const padding = base64.length % 4;
|
||||
if (padding) {
|
||||
base64 += '='.repeat(4 - padding);
|
||||
}
|
||||
|
||||
return Buffer.from(base64, 'base64').toString('utf-8');
|
||||
}
|
||||
|
||||
async reload(): Promise<void> {
|
||||
// Re-test connectivity
|
||||
await this.initialize();
|
||||
}
|
||||
|
||||
async shutdown(): Promise<void> {
|
||||
this.healthy = false;
|
||||
}
|
||||
|
||||
isHealthy(): boolean {
|
||||
return this.healthy;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
/**
|
||||
* LDAP authentication provider
|
||||
* Supports direct bind and search+bind modes
|
||||
*/
|
||||
|
||||
import { Client } from 'ldapts';
|
||||
import type { AuthProvider, AuthResult, LDAPAuthConfig } from '../types.js';
|
||||
|
||||
const DEFAULT_PRIORITY = 100;
|
||||
const DEFAULT_TIMEOUT = 5000;
|
||||
|
||||
export class LDAPAuthProvider implements AuthProvider {
|
||||
readonly name = 'ldap';
|
||||
readonly priority: number;
|
||||
|
||||
private readonly config: LDAPAuthConfig;
|
||||
private healthy = false;
|
||||
|
||||
constructor(config: LDAPAuthConfig) {
|
||||
this.config = config;
|
||||
this.priority = config.priority ?? DEFAULT_PRIORITY;
|
||||
}
|
||||
|
||||
async initialize(): Promise<void> {
|
||||
// Validate configuration
|
||||
if (!this.config.uri) {
|
||||
throw new Error('LDAP provider requires uri');
|
||||
}
|
||||
|
||||
if (!this.config.mode) {
|
||||
throw new Error('LDAP provider requires mode (direct or search)');
|
||||
}
|
||||
|
||||
if (this.config.mode === 'direct' && !this.config.userdn) {
|
||||
throw new Error('LDAP direct mode requires userdn template');
|
||||
}
|
||||
|
||||
if (this.config.mode === 'search') {
|
||||
if (!this.config.basedn) {
|
||||
throw new Error('LDAP search mode requires basedn');
|
||||
}
|
||||
if (!this.config.binddn || !this.config.bindpass) {
|
||||
throw new Error('LDAP search mode requires binddn and bindpass');
|
||||
}
|
||||
if (!this.config.userfilter) {
|
||||
throw new Error('LDAP search mode requires userfilter');
|
||||
}
|
||||
}
|
||||
|
||||
// Test connection with a simple bind/unbind
|
||||
try {
|
||||
const client = this.createClient();
|
||||
await client.bind(
|
||||
this.config.binddn || '',
|
||||
this.config.bindpass || ''
|
||||
);
|
||||
await client.unbind();
|
||||
this.healthy = true;
|
||||
} catch (err) {
|
||||
// Connection test failed - provider may still work later
|
||||
// Mark as unhealthy but don't throw
|
||||
this.healthy = false;
|
||||
}
|
||||
}
|
||||
|
||||
async authenticate(
|
||||
authcid: string,
|
||||
password: string,
|
||||
_authzid?: string
|
||||
): Promise<AuthResult> {
|
||||
try {
|
||||
if (this.config.mode === 'direct') {
|
||||
return await this.authenticateDirect(authcid, password);
|
||||
} else {
|
||||
return await this.authenticateSearch(authcid, password);
|
||||
}
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
return { success: false, error: `LDAP error: ${message}` };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Direct bind mode: construct DN from template and bind with user's password
|
||||
*/
|
||||
private async authenticateDirect(
|
||||
username: string,
|
||||
password: string
|
||||
): Promise<AuthResult> {
|
||||
const userDN = this.config.userdn!.replace(/%s/g, this.escapeDN(username));
|
||||
const client = this.createClient();
|
||||
|
||||
try {
|
||||
await client.bind(userDN, password);
|
||||
this.healthy = true;
|
||||
|
||||
// Get account name from DN or use username
|
||||
const account = this.extractAccountFromDN(userDN, username);
|
||||
|
||||
await client.unbind();
|
||||
return { success: true, account };
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
|
||||
// LDAP error code 49 is invalid credentials
|
||||
if (message.includes('49') || message.toLowerCase().includes('invalid credentials')) {
|
||||
return { success: false, error: 'Invalid credentials' };
|
||||
}
|
||||
|
||||
// Other errors might indicate server issues
|
||||
this.healthy = false;
|
||||
return { success: false, error: `LDAP bind failed: ${message}` };
|
||||
} finally {
|
||||
try {
|
||||
await client.unbind();
|
||||
} catch {
|
||||
// Ignore unbind errors
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Search mode: bind as admin, find user, optionally check group, then bind as user
|
||||
*/
|
||||
private async authenticateSearch(
|
||||
username: string,
|
||||
password: string
|
||||
): Promise<AuthResult> {
|
||||
const client = this.createClient();
|
||||
|
||||
try {
|
||||
// Step 1: Bind as admin
|
||||
await client.bind(this.config.binddn!, this.config.bindpass!);
|
||||
this.healthy = true;
|
||||
|
||||
// Step 2: Search for user
|
||||
const filter = this.config.userfilter!.replace(/%s/g, this.escapeFilter(username));
|
||||
const searchResult = await client.search(this.config.basedn!, {
|
||||
scope: 'sub',
|
||||
filter,
|
||||
attributes: [
|
||||
'dn',
|
||||
this.config.accountattr || 'uid',
|
||||
'sAMAccountName', // Active Directory
|
||||
'cn',
|
||||
],
|
||||
});
|
||||
|
||||
if (searchResult.searchEntries.length === 0) {
|
||||
await client.unbind();
|
||||
return { success: false, error: 'User not found' };
|
||||
}
|
||||
|
||||
const userEntry = searchResult.searchEntries[0];
|
||||
const userDN = userEntry.dn;
|
||||
|
||||
// Step 3: Optional group membership check
|
||||
if (this.config.groupdn) {
|
||||
const isMember = await this.checkGroupMembership(client, userDN);
|
||||
if (!isMember) {
|
||||
await client.unbind();
|
||||
return { success: false, error: 'User not in required group' };
|
||||
}
|
||||
}
|
||||
|
||||
// Step 4: Bind as user to verify password
|
||||
await client.unbind();
|
||||
|
||||
const userClient = this.createClient();
|
||||
try {
|
||||
await userClient.bind(userDN, password);
|
||||
await userClient.unbind();
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
if (message.includes('49') || message.toLowerCase().includes('invalid credentials')) {
|
||||
return { success: false, error: 'Invalid credentials' };
|
||||
}
|
||||
return { success: false, error: `LDAP bind failed: ${message}` };
|
||||
}
|
||||
|
||||
// Extract account name from search result
|
||||
const account = this.extractAccountFromEntry(userEntry, username);
|
||||
|
||||
return { success: true, account };
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
this.healthy = false;
|
||||
return { success: false, error: `LDAP search failed: ${message}` };
|
||||
} finally {
|
||||
try {
|
||||
await client.unbind();
|
||||
} catch {
|
||||
// Ignore unbind errors
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if user is a member of the configured group
|
||||
*/
|
||||
private async checkGroupMembership(client: Client, userDN: string): Promise<boolean> {
|
||||
try {
|
||||
const searchResult = await client.search(this.config.groupdn!, {
|
||||
scope: 'base',
|
||||
filter: '(objectClass=*)',
|
||||
attributes: ['member', 'uniqueMember', 'memberUid'],
|
||||
});
|
||||
|
||||
if (searchResult.searchEntries.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const groupEntry = searchResult.searchEntries[0];
|
||||
|
||||
// Check member attribute (standard LDAP groups)
|
||||
const members = this.getAttrValues(groupEntry, 'member');
|
||||
if (members.some((m) => m.toLowerCase() === userDN.toLowerCase())) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check uniqueMember attribute (some LDAP servers)
|
||||
const uniqueMembers = this.getAttrValues(groupEntry, 'uniqueMember');
|
||||
if (uniqueMembers.some((m) => m.toLowerCase() === userDN.toLowerCase())) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check memberUid attribute (posixGroup)
|
||||
const memberUids = this.getAttrValues(groupEntry, 'memberUid');
|
||||
const uid = this.extractUidFromDN(userDN);
|
||||
if (uid && memberUids.includes(uid)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get attribute values as string array
|
||||
*/
|
||||
private getAttrValues(entry: Record<string, unknown>, attr: string): string[] {
|
||||
const value = entry[attr];
|
||||
if (!value) return [];
|
||||
if (Array.isArray(value)) return value.map(String);
|
||||
return [String(value)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract uid from a DN like "uid=john,ou=users,dc=example,dc=com"
|
||||
*/
|
||||
private extractUidFromDN(dn: string): string | null {
|
||||
const match = dn.match(/^uid=([^,]+)/i);
|
||||
return match ? match[1] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract account name from DN
|
||||
*/
|
||||
private extractAccountFromDN(dn: string, fallback: string): string {
|
||||
// Try to extract uid or cn from DN
|
||||
const uidMatch = dn.match(/^uid=([^,]+)/i);
|
||||
if (uidMatch) return uidMatch[1];
|
||||
|
||||
const cnMatch = dn.match(/^cn=([^,]+)/i);
|
||||
if (cnMatch) return cnMatch[1];
|
||||
|
||||
return fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract account name from LDAP entry
|
||||
*/
|
||||
private extractAccountFromEntry(
|
||||
entry: Record<string, unknown>,
|
||||
fallback: string
|
||||
): string {
|
||||
// Use configured attribute if specified
|
||||
if (this.config.accountattr) {
|
||||
const value = entry[this.config.accountattr];
|
||||
if (value) {
|
||||
return Array.isArray(value) ? String(value[0]) : String(value);
|
||||
}
|
||||
}
|
||||
|
||||
// Try common account name attributes
|
||||
for (const attr of ['uid', 'sAMAccountName', 'cn']) {
|
||||
const value = entry[attr];
|
||||
if (value) {
|
||||
return Array.isArray(value) ? String(value[0]) : String(value);
|
||||
}
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new LDAP client
|
||||
*/
|
||||
private createClient(): Client {
|
||||
return new Client({
|
||||
url: this.config.uri,
|
||||
timeout: this.config.timeout ?? DEFAULT_TIMEOUT,
|
||||
connectTimeout: this.config.timeout ?? DEFAULT_TIMEOUT,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape special characters in DN values
|
||||
*/
|
||||
private escapeDN(value: string): string {
|
||||
// Escape special DN characters: , + " \ < > ; = (leading/trailing spaces)
|
||||
return value
|
||||
.replace(/\\/g, '\\\\')
|
||||
.replace(/,/g, '\\,')
|
||||
.replace(/\+/g, '\\+')
|
||||
.replace(/"/g, '\\"')
|
||||
.replace(/</g, '\\<')
|
||||
.replace(/>/g, '\\>')
|
||||
.replace(/;/g, '\\;')
|
||||
.replace(/=/g, '\\=')
|
||||
.replace(/^ /, '\\ ')
|
||||
.replace(/ $/, '\\ ');
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape special characters in LDAP filter values
|
||||
*/
|
||||
private escapeFilter(value: string): string {
|
||||
// Escape special filter characters: * ( ) \ NUL
|
||||
return value
|
||||
.replace(/\\/g, '\\5c')
|
||||
.replace(/\*/g, '\\2a')
|
||||
.replace(/\(/g, '\\28')
|
||||
.replace(/\)/g, '\\29')
|
||||
.replace(/\x00/g, '\\00');
|
||||
}
|
||||
|
||||
async reload(): Promise<void> {
|
||||
// LDAP config is static, nothing to reload
|
||||
// Re-test connection
|
||||
try {
|
||||
const client = this.createClient();
|
||||
if (this.config.mode === 'search') {
|
||||
await client.bind(this.config.binddn!, this.config.bindpass!);
|
||||
}
|
||||
await client.unbind();
|
||||
this.healthy = true;
|
||||
} catch {
|
||||
this.healthy = false;
|
||||
}
|
||||
}
|
||||
|
||||
async shutdown(): Promise<void> {
|
||||
// Nothing to cleanup - we don't pool connections
|
||||
this.healthy = false;
|
||||
}
|
||||
|
||||
isHealthy(): boolean {
|
||||
return this.healthy;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
/**
|
||||
* Authentication provider types for iauthd-ts
|
||||
* Defines the interface for modular authentication backends
|
||||
*/
|
||||
|
||||
/**
|
||||
* Result of an authentication attempt
|
||||
*/
|
||||
export interface AuthResult {
|
||||
/** Whether authentication succeeded */
|
||||
success: boolean;
|
||||
/** Account name if successful (used for IRC account tracking) */
|
||||
account?: string;
|
||||
/** Error message if failed (for logging, not shown to user) */
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Authentication provider interface
|
||||
* All providers must implement this interface
|
||||
*/
|
||||
export interface AuthProvider {
|
||||
/** Provider name for logging/debugging */
|
||||
readonly name: string;
|
||||
|
||||
/** Provider priority (lower = checked first) */
|
||||
readonly priority: number;
|
||||
|
||||
/**
|
||||
* Initialize the provider (called once at startup)
|
||||
* Should throw if configuration is invalid
|
||||
*/
|
||||
initialize(): Promise<void>;
|
||||
|
||||
/**
|
||||
* Authenticate a user with SASL PLAIN credentials
|
||||
* @param authcid - Authentication identity (username)
|
||||
* @param password - Password
|
||||
* @param authzid - Authorization identity (usually empty or same as authcid)
|
||||
* @returns AuthResult indicating success/failure
|
||||
*/
|
||||
authenticate(authcid: string, password: string, authzid?: string): Promise<AuthResult>;
|
||||
|
||||
/**
|
||||
* Called on rehash to reload configuration
|
||||
*/
|
||||
reload(): Promise<void>;
|
||||
|
||||
/**
|
||||
* Cleanup resources (called on shutdown)
|
||||
*/
|
||||
shutdown(): Promise<void>;
|
||||
|
||||
/**
|
||||
* Check if provider is healthy/connected
|
||||
*/
|
||||
isHealthy(): boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Base configuration for all auth providers
|
||||
*/
|
||||
export interface BaseAuthConfig {
|
||||
provider: string;
|
||||
priority?: number; // Default: 100
|
||||
}
|
||||
|
||||
/**
|
||||
* Static file provider configuration
|
||||
*/
|
||||
export interface FileAuthConfig extends BaseAuthConfig {
|
||||
provider: 'file';
|
||||
path: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* LDAP provider configuration
|
||||
*/
|
||||
export interface LDAPAuthConfig extends BaseAuthConfig {
|
||||
provider: 'ldap';
|
||||
/** LDAP server URI (ldap:// or ldaps://) */
|
||||
uri: string;
|
||||
/** Authentication mode */
|
||||
mode: 'direct' | 'search';
|
||||
/** Direct mode: DN template with %s for username */
|
||||
userdn?: string;
|
||||
/** Search mode: Base DN for user search */
|
||||
basedn?: string;
|
||||
/** Search mode: Admin bind DN */
|
||||
binddn?: string;
|
||||
/** Search mode: Admin bind password */
|
||||
bindpass?: string;
|
||||
/** Search mode: User search filter with %s for username (e.g., "(uid=%s)") */
|
||||
userfilter?: string;
|
||||
/** Optional: Group DN for membership check */
|
||||
groupdn?: string;
|
||||
/** Optional: Attribute to use as account name (default: uid or sAMAccountName) */
|
||||
accountattr?: string;
|
||||
/** Connection timeout in milliseconds (default: 5000) */
|
||||
timeout?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keycloak provider configuration
|
||||
* Uses Resource Owner Password Credentials (ROPC) grant
|
||||
*/
|
||||
export interface KeycloakAuthConfig extends BaseAuthConfig {
|
||||
provider: 'keycloak';
|
||||
/** Keycloak server URL (e.g., https://keycloak.example.com) */
|
||||
url: string;
|
||||
/** Keycloak realm name */
|
||||
realm: string;
|
||||
/** OAuth2 client ID (must have Direct Access Grants enabled) */
|
||||
clientid: string;
|
||||
/** OAuth2 client secret (for confidential clients) */
|
||||
clientsecret?: string;
|
||||
/** Optional: Attribute from token to use as account name (default: preferred_username) */
|
||||
accountattr?: string;
|
||||
/** Request timeout in milliseconds (default: 5000) */
|
||||
timeout?: number;
|
||||
}
|
||||
|
||||
export type AuthProviderConfig = FileAuthConfig | LDAPAuthConfig | KeycloakAuthConfig;
|
||||
|
||||
/**
|
||||
* Type guard for FileAuthConfig
|
||||
*/
|
||||
export function isFileAuthConfig(config: AuthProviderConfig): config is FileAuthConfig {
|
||||
return config.provider === 'file';
|
||||
}
|
||||
|
||||
/**
|
||||
* Type guard for LDAPAuthConfig
|
||||
*/
|
||||
export function isLDAPAuthConfig(config: AuthProviderConfig): config is LDAPAuthConfig {
|
||||
return config.provider === 'ldap';
|
||||
}
|
||||
|
||||
/**
|
||||
* Type guard for KeycloakAuthConfig
|
||||
*/
|
||||
export function isKeycloakAuthConfig(config: AuthProviderConfig): config is KeycloakAuthConfig {
|
||||
return config.provider === 'keycloak';
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
/**
|
||||
* Configuration parser for iauthd
|
||||
* Reads #IAUTH directives from config files
|
||||
*/
|
||||
|
||||
import { readFileSync } from 'node:fs';
|
||||
import type { Config, DNSBLConfig } from './types.js';
|
||||
import { parseAuthConfig, convertSASLDB } from './auth/config.js';
|
||||
|
||||
const DEFAULT_CACHE_TIME = 60 * 60 * 24; // 24 hours
|
||||
const DEFAULT_DNS_TIMEOUT = 5;
|
||||
const DEFAULT_BLOCK_MSG = 'Your internet address has been rejected due to reputation (DNSBL).';
|
||||
const DEFAULT_POLICY = 'RTAWUwFr';
|
||||
const DEFAULT_SASL_FAIL_MSG = 'SASL authentication failed';
|
||||
|
||||
/**
|
||||
* Parse a DNSBL configuration line
|
||||
* Format: server=dnsbl.sorbs.net index=2,3,4 mark=sorbs block=anonymous
|
||||
*/
|
||||
function parseDNSBLConfig(args: string, cfgNum: number): DNSBLConfig {
|
||||
const config: DNSBLConfig = {
|
||||
cfgNum,
|
||||
server: '',
|
||||
};
|
||||
|
||||
for (const arg of args.split(/\s+/)) {
|
||||
const match = arg.match(/^(\w+)=(.+)$/);
|
||||
if (match) {
|
||||
const [, key, value] = match;
|
||||
switch (key) {
|
||||
case 'server':
|
||||
config.server = value;
|
||||
break;
|
||||
case 'index':
|
||||
config.index = value;
|
||||
break;
|
||||
case 'bitmask':
|
||||
config.bitmask = value;
|
||||
break;
|
||||
case 'mark':
|
||||
config.mark = value;
|
||||
break;
|
||||
case 'block':
|
||||
if (value === 'all' || value === 'anonymous') {
|
||||
config.block = value;
|
||||
}
|
||||
break;
|
||||
case 'class':
|
||||
config.class = value;
|
||||
break;
|
||||
case 'cachetime':
|
||||
config.cacheTime = parseInt(value, 10);
|
||||
break;
|
||||
case 'whitelist':
|
||||
config.whitelist = true;
|
||||
break;
|
||||
}
|
||||
} else if (arg === 'whitelist') {
|
||||
config.whitelist = true;
|
||||
}
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read and parse configuration from a file
|
||||
* Looks for lines starting with #IAUTH
|
||||
*/
|
||||
export function readConfigFile(filePath: string): { config: Config; configLines: string[] } {
|
||||
const config: Config = {
|
||||
policy: DEFAULT_POLICY,
|
||||
dnsbls: [],
|
||||
dnsTimeout: DEFAULT_DNS_TIMEOUT,
|
||||
blockMsg: DEFAULT_BLOCK_MSG,
|
||||
cacheTime: DEFAULT_CACHE_TIME,
|
||||
debug: false,
|
||||
saslFailMsg: DEFAULT_SASL_FAIL_MSG,
|
||||
authProviders: [],
|
||||
};
|
||||
|
||||
const configLines: string[] = [];
|
||||
let cfgNum = 0;
|
||||
|
||||
const content = readFileSync(filePath, 'utf-8');
|
||||
|
||||
for (const line of content.split('\n')) {
|
||||
const match = line.match(/^#IAUTH\s+(\w+)(?:\s+(.+))?$/);
|
||||
if (!match) continue;
|
||||
|
||||
const directive = match[1];
|
||||
const args = match[2] || '';
|
||||
cfgNum++;
|
||||
|
||||
configLines.push(`${cfgNum}: ${directive} ${args}`);
|
||||
|
||||
switch (directive) {
|
||||
case 'POLICY':
|
||||
config.policy = args.trim();
|
||||
break;
|
||||
|
||||
case 'DNSBL':
|
||||
const dnsblConfig = parseDNSBLConfig(args, cfgNum);
|
||||
if (dnsblConfig.server) {
|
||||
config.dnsbls.push(dnsblConfig);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'DEBUG':
|
||||
config.debug = true;
|
||||
break;
|
||||
|
||||
case 'DNSTIMEOUT':
|
||||
config.dnsTimeout = parseInt(args.trim(), 10) || DEFAULT_DNS_TIMEOUT;
|
||||
break;
|
||||
|
||||
case 'BLOCKMSG':
|
||||
config.blockMsg = args.trim();
|
||||
break;
|
||||
|
||||
case 'CACHETIME':
|
||||
config.cacheTime = parseInt(args.trim(), 10) || DEFAULT_CACHE_TIME;
|
||||
break;
|
||||
|
||||
case 'SASLDB':
|
||||
// Legacy support: convert to file auth provider
|
||||
config.saslUsersFile = args.trim();
|
||||
config.authProviders.push(convertSASLDB(args.trim()));
|
||||
break;
|
||||
|
||||
case 'SASLFAILMSG':
|
||||
config.saslFailMsg = args.trim();
|
||||
break;
|
||||
|
||||
case 'AUTH':
|
||||
const authConfig = parseAuthConfig(args);
|
||||
if (authConfig) {
|
||||
config.authProviders.push(authConfig);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return { config, configLines };
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
/**
|
||||
* DNSBL lookup module with caching
|
||||
*/
|
||||
|
||||
import { promises as dns } from 'node:dns';
|
||||
import type { CacheEntry, DNSBLConfig } from './types.js';
|
||||
|
||||
/** Global DNSBL result cache */
|
||||
const cache = new Map<string, CacheEntry>();
|
||||
|
||||
/**
|
||||
* Reverse an IPv4 address for DNSBL lookup
|
||||
* e.g., "192.168.1.10" -> "10.1.168.192"
|
||||
*/
|
||||
export function reverseIPv4(ip: string): string | null {
|
||||
const match = ip.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
|
||||
if (!match) return null;
|
||||
|
||||
// Validate each octet is 0-255
|
||||
const octets = [match[1], match[2], match[3], match[4]].map(o => parseInt(o, 10));
|
||||
if (octets.some(o => o > 255)) return null;
|
||||
|
||||
return `${match[4]}.${match[3]}.${match[2]}.${match[1]}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if an IP is IPv4
|
||||
*/
|
||||
export function isIPv4(ip: string): boolean {
|
||||
return /^(?:\d{1,3}\.){3}\d{1,3}$/.test(ip);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get cache entry if valid
|
||||
*/
|
||||
export function getCacheEntry(query: string, cacheTime: number): CacheEntry | null {
|
||||
const entry = cache.get(query);
|
||||
if (!entry) return null;
|
||||
|
||||
const now = Date.now();
|
||||
// cacheTime <= 0 means always expired, otherwise check age
|
||||
if (cacheTime <= 0 || entry.ts <= now - cacheTime * 1000) {
|
||||
// Cache expired
|
||||
cache.delete(query);
|
||||
return null;
|
||||
}
|
||||
|
||||
return entry;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set cache entry
|
||||
*/
|
||||
export function setCacheEntry(query: string, result: string[] | null): void {
|
||||
cache.set(query, {
|
||||
result,
|
||||
ts: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get cache size for stats
|
||||
*/
|
||||
export function getCacheSize(): number {
|
||||
return cache.size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform a DNSBL lookup
|
||||
* Returns array of result IPs or empty array if not listed
|
||||
*/
|
||||
export async function lookupDNSBL(
|
||||
reversedIp: string,
|
||||
dnsblServer: string,
|
||||
timeout: number
|
||||
): Promise<string[]> {
|
||||
const query = `${reversedIp}.${dnsblServer}`;
|
||||
|
||||
try {
|
||||
// Create a DNS resolver with timeout
|
||||
const resolver = new dns.Resolver();
|
||||
resolver.setServers(['8.8.8.8', '8.8.4.4']); // Use Google DNS as fallback
|
||||
|
||||
// Race against timeout
|
||||
const timeoutPromise = new Promise<string[]>((_, reject) => {
|
||||
setTimeout(() => reject(new Error('DNS timeout')), timeout * 1000);
|
||||
});
|
||||
|
||||
const lookupPromise = dns.resolve4(query);
|
||||
const result = await Promise.race([lookupPromise, timeoutPromise]);
|
||||
|
||||
return result;
|
||||
} catch (err) {
|
||||
// NXDOMAIN or timeout = not listed
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a DNSBL result matches the configuration
|
||||
*/
|
||||
export function matchesDNSBL(results: string[], config: DNSBLConfig): boolean {
|
||||
for (const ip of results) {
|
||||
const match = ip.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
|
||||
if (!match) continue;
|
||||
|
||||
const value = parseInt(match[4], 10);
|
||||
|
||||
// Check index match
|
||||
if (config.index) {
|
||||
const indices = config.index.split(',').map(i => parseInt(i.trim(), 10));
|
||||
if (indices.includes(value)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Check bitmask match
|
||||
if (config.bitmask) {
|
||||
const bitmasks = config.bitmask.split(',').map(b => parseInt(b.trim(), 10));
|
||||
for (const bitmask of bitmasks) {
|
||||
if ((bitmask & value) !== 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If no index or bitmask specified, any result is a match
|
||||
if (!config.index && !config.bitmask) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse DNSBL query to extract IP and server
|
||||
*/
|
||||
export function parseQuery(query: string): { ip: string; server: string } | null {
|
||||
const match = query.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(.+)$/);
|
||||
if (!match) return null;
|
||||
|
||||
return {
|
||||
ip: `${match[4]}.${match[3]}.${match[2]}.${match[1]}`,
|
||||
server: match[5],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Password hash generator for iauthd-ts SASL users file
|
||||
*
|
||||
* Usage: npx tsx src/genhash.ts <password> [type]
|
||||
*
|
||||
* Types:
|
||||
* sha256 (default) - SHA-256 crypt format ($5$)
|
||||
* sha512 - SHA-512 crypt format ($6$)
|
||||
* md5 - MD5 crypt format ($1$)
|
||||
*/
|
||||
|
||||
import { generateHash } from './sasl.js';
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
|
||||
if (args.length === 0) {
|
||||
console.log('Usage: npx tsx src/genhash.ts <password> [type]');
|
||||
console.log('');
|
||||
console.log('Types:');
|
||||
console.log(' sha256 (default) - SHA-256 crypt format ($5$)');
|
||||
console.log(' sha512 - SHA-512 crypt format ($6$)');
|
||||
console.log(' md5 - MD5 crypt format ($1$)');
|
||||
console.log('');
|
||||
console.log('Example:');
|
||||
console.log(' npx tsx src/genhash.ts mypassword sha256');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const password = args[0];
|
||||
const type = (args[1] || 'sha256') as 'sha256' | 'sha512' | 'md5';
|
||||
|
||||
if (!['sha256', 'sha512', 'md5'].includes(type)) {
|
||||
console.error(`Invalid hash type: ${type}`);
|
||||
console.error('Valid types: sha256, sha512, md5');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const hash = generateHash(password, type);
|
||||
console.log(hash);
|
||||
@@ -0,0 +1,834 @@
|
||||
/**
|
||||
* IAuth Daemon - Main implementation
|
||||
* Handles communication with Nefarious IRCd and DNSBL lookups
|
||||
*/
|
||||
|
||||
import { createInterface, Interface } from 'node:readline';
|
||||
import { readConfigFile } from './config.js';
|
||||
import {
|
||||
reverseIPv4,
|
||||
isIPv4,
|
||||
getCacheEntry,
|
||||
setCacheEntry,
|
||||
getCacheSize,
|
||||
lookupDNSBL,
|
||||
matchesDNSBL,
|
||||
} from './dnsbl.js';
|
||||
import {
|
||||
decodeSASLPlain,
|
||||
getSupportedMechanisms,
|
||||
} from './sasl.js';
|
||||
import { AuthManager } from './auth/index.js';
|
||||
import type { Config, ClientState, DNSBLConfig, CLIOptions, SASLState } from './types.js';
|
||||
|
||||
const VERSION = '1.0.0';
|
||||
|
||||
export class IAuthDaemon {
|
||||
private config: Config;
|
||||
private configPath: string;
|
||||
private options: CLIOptions;
|
||||
private clients = new Map<number, ClientState>();
|
||||
private dnsblCounters = new Map<number, number>();
|
||||
private countPass = 0;
|
||||
private countReject = 0;
|
||||
private countSaslSuccess = 0;
|
||||
private countSaslFail = 0;
|
||||
private startTime = Date.now();
|
||||
private rl: Interface | null = null;
|
||||
private authManager: AuthManager | null = null;
|
||||
private authInitialized = false;
|
||||
|
||||
constructor(options: CLIOptions) {
|
||||
this.options = options;
|
||||
this.configPath = options.config;
|
||||
const { config } = readConfigFile(options.config);
|
||||
this.config = config;
|
||||
|
||||
// Initialize DNSBL counters
|
||||
for (const dnsbl of this.config.dnsbls) {
|
||||
this.dnsblCounters.set(dnsbl.cfgNum, 0);
|
||||
}
|
||||
|
||||
// Initialize auth manager asynchronously
|
||||
this.initializeAuth();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the authentication manager
|
||||
*/
|
||||
private async initializeAuth(): Promise<void> {
|
||||
if (this.config.authProviders.length > 0) {
|
||||
this.authManager = new AuthManager(this.config.authProviders);
|
||||
try {
|
||||
await this.authManager.initialize();
|
||||
this.authInitialized = true;
|
||||
const info = this.authManager.getProviderInfo();
|
||||
this.debug(`Initialized ${info.length} auth provider(s): ${info.map(p => p.name).join(', ')}`);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
this.debug(`Failed to initialize auth manager: ${message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if SASL/auth is enabled
|
||||
*/
|
||||
private saslEnabled(): boolean {
|
||||
return this.authManager !== null && this.authManager.hasProviders();
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a message to ircd via stdout
|
||||
*/
|
||||
private send(message: string): void {
|
||||
console.log(message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send debug message (prefixed with "> :")
|
||||
*/
|
||||
private debug(message: string): void {
|
||||
if (this.options.verbose || this.options.debug) {
|
||||
this.send(`> :${message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Start the daemon
|
||||
*/
|
||||
start(): void {
|
||||
this.handleStartup();
|
||||
|
||||
this.rl = createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout,
|
||||
terminal: false,
|
||||
});
|
||||
|
||||
this.rl.on('line', (line) => this.handleLine(line));
|
||||
this.rl.on('close', () => {
|
||||
this.debug('STDIN closed. Shutting down...');
|
||||
process.exit(0);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Send startup messages to ircd
|
||||
*/
|
||||
private handleStartup(): void {
|
||||
// Request iauth protocol version
|
||||
this.send('G 1');
|
||||
|
||||
// Send version
|
||||
this.send(`V :Nefarious2 iauthd-ts version ${VERSION}`);
|
||||
|
||||
// Set policy options
|
||||
this.send(`O ${this.config.policy}`);
|
||||
|
||||
// Send configuration
|
||||
this.sendNewConfig();
|
||||
|
||||
this.debug('Starting up');
|
||||
this.sendStats();
|
||||
}
|
||||
|
||||
/**
|
||||
* Send configuration info to ircd
|
||||
*/
|
||||
private sendNewConfig(): void {
|
||||
this.send('a');
|
||||
this.send(`A * version :Nefarious iauthd-ts ${VERSION}`);
|
||||
|
||||
const { configLines } = readConfigFile(this.configPath);
|
||||
for (const line of configLines) {
|
||||
this.send(`A * iauthd-ts :${line}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send statistics to ircd
|
||||
*/
|
||||
private sendStats(): void {
|
||||
const uptime = this.formatDuration(Date.now() - this.startTime);
|
||||
const upSince = new Date(this.startTime).toUTCString();
|
||||
|
||||
this.send('s');
|
||||
this.send(`S iauthd-ts :Up since ${upSince} (${uptime})`);
|
||||
this.send(`S iauthd-ts :Cache size: ${getCacheSize()}`);
|
||||
this.send(`S iauthd-ts :Total Passed: ${this.countPass}`);
|
||||
this.send(`S iauthd-ts :Total Rejected: ${this.countReject}`);
|
||||
|
||||
if (this.saslEnabled()) {
|
||||
this.send(`S iauthd-ts :SASL Success: ${this.countSaslSuccess}`);
|
||||
this.send(`S iauthd-ts :SASL Failed: ${this.countSaslFail}`);
|
||||
const providerInfo = this.authManager!.getProviderInfo();
|
||||
for (const p of providerInfo) {
|
||||
this.send(`S iauthd-ts :Auth Provider: ${p.name} (priority=${p.priority}, healthy=${p.healthy})`);
|
||||
}
|
||||
}
|
||||
|
||||
for (const dnsbl of this.config.dnsbls) {
|
||||
let desc = dnsbl.server;
|
||||
if (dnsbl.index) desc += ` (${dnsbl.index})`;
|
||||
if (dnsbl.bitmask) desc += ` (${dnsbl.bitmask})`;
|
||||
const count = this.dnsblCounters.get(dnsbl.cfgNum) || 0;
|
||||
this.send(`S iauthd-ts :${desc}: ${count}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Format duration in human-readable form
|
||||
*/
|
||||
private formatDuration(ms: number): string {
|
||||
const seconds = Math.floor(ms / 1000);
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const days = Math.floor(hours / 24);
|
||||
|
||||
const parts: string[] = [];
|
||||
if (days > 0) parts.push(`${days}d`);
|
||||
if (hours % 24 > 0) parts.push(`${hours % 24}h`);
|
||||
if (minutes % 60 > 0) parts.push(`${minutes % 60}m`);
|
||||
if (seconds % 60 > 0 || parts.length === 0) parts.push(`${seconds % 60}s`);
|
||||
|
||||
return parts.join(' ');
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle a line from ircd
|
||||
* Format: <id> <message> <args...>
|
||||
* Example: 26 C 172.19.0.1 12345 172.19.0.2 6667
|
||||
*/
|
||||
private handleLine(line: string): void {
|
||||
if (!line) return;
|
||||
|
||||
const parts = line.split(' ');
|
||||
const source = parseInt(parts[0], 10);
|
||||
const message = parts[1];
|
||||
const args = parts.slice(2).join(' ');
|
||||
|
||||
if (!message) return;
|
||||
|
||||
switch (message) {
|
||||
case 'C': // Client introduction
|
||||
this.handleClientIntro(source, args);
|
||||
break;
|
||||
|
||||
case 'D': // Client disconnect
|
||||
this.debug(`Client ${source} disconnected.`);
|
||||
this.deleteClient(source);
|
||||
break;
|
||||
|
||||
case 'F': // SSL certificate fingerprint
|
||||
// Could be used for certificate-based auth
|
||||
break;
|
||||
|
||||
case 'R': // Client authenticated via SASL/LOC
|
||||
this.handleAuth(source, args);
|
||||
break;
|
||||
|
||||
case 'N': // Hostname received
|
||||
break;
|
||||
|
||||
case 'd': // Hostname timeout
|
||||
break;
|
||||
|
||||
case 'P': // Client password
|
||||
break;
|
||||
|
||||
case 'U': // Client username (full)
|
||||
break;
|
||||
|
||||
case 'u': // Client username (short)
|
||||
break;
|
||||
|
||||
case 'n': // Client nickname
|
||||
break;
|
||||
|
||||
case 'H': // Hurry up
|
||||
this.handleHurry(source, args);
|
||||
break;
|
||||
|
||||
case 'T': // Client registered
|
||||
break;
|
||||
|
||||
case 'E': // Error
|
||||
this.debug(`ircd error: ${args}`);
|
||||
break;
|
||||
|
||||
case 'e': // Event
|
||||
if (args === 'rehash') {
|
||||
this.debug('Got a rehash. Rereading config file');
|
||||
const { config } = readConfigFile(this.configPath);
|
||||
this.config = config;
|
||||
// Reinitialize auth providers
|
||||
if (this.authManager) {
|
||||
this.authManager.reload().catch(err => {
|
||||
this.debug(`Failed to reload auth manager: ${err}`);
|
||||
});
|
||||
} else {
|
||||
this.initializeAuth();
|
||||
}
|
||||
this.sendNewConfig();
|
||||
}
|
||||
break;
|
||||
|
||||
case 'A': // SASL authentication start
|
||||
this.handleSASLStart(source, args);
|
||||
break;
|
||||
|
||||
case 'a': // SASL authentication continuation
|
||||
this.handleSASLContinue(source, args);
|
||||
break;
|
||||
|
||||
case 'M': // Server name and capacity
|
||||
break;
|
||||
|
||||
case 'X': // Extension query reply
|
||||
break;
|
||||
|
||||
case 'x': // Extension query server not linked
|
||||
break;
|
||||
|
||||
case 'W': // Untrusted WEBIRC
|
||||
this.debug('Got an untrusted WEBIRC attempt. Ignoring.');
|
||||
break;
|
||||
|
||||
case 'w': // Trusted WEBIRC
|
||||
this.handleWebIRC(source, args);
|
||||
break;
|
||||
|
||||
default:
|
||||
this.debug(`Got unknown message '${message}' from server`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle client introduction (C message)
|
||||
*/
|
||||
private handleClientIntro(id: number, args: string): void {
|
||||
const [ip, portStr, serverIp, serverPortStr] = args.split(' ');
|
||||
const port = parseInt(portStr, 10);
|
||||
const serverPort = parseInt(serverPortStr, 10);
|
||||
|
||||
if (!ip) {
|
||||
this.debug('Got a C without a valid IP. Ignoring');
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.clients.has(id)) {
|
||||
this.debug(`ERROR: Found existing entry for client ${id} (ip=${ip}). Exiting..`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
this.debug(`Adding new entry for client ${id} (ip=${ip})`);
|
||||
|
||||
const client: ClientState = {
|
||||
id,
|
||||
ip,
|
||||
port,
|
||||
serverIp,
|
||||
serverPort,
|
||||
whitelist: false,
|
||||
block: false,
|
||||
marks: new Map(),
|
||||
hurry: false,
|
||||
lookups: new Map(),
|
||||
hits: new Map(),
|
||||
};
|
||||
|
||||
this.clients.set(id, client);
|
||||
this.startDNSBLLookups(client);
|
||||
}
|
||||
|
||||
/**
|
||||
* Start DNSBL lookups for a client
|
||||
*/
|
||||
private async startDNSBLLookups(client: ClientState): Promise<void> {
|
||||
if (!isIPv4(client.ip)) {
|
||||
this.debug(`Unknown IP format: ${client.ip}, probably IPv6... skipping DNSBL`);
|
||||
// IPv6 clients skip DNSBL but still need to be processed
|
||||
// They'll be accepted when Hurry arrives since they have no pending lookups
|
||||
return;
|
||||
}
|
||||
|
||||
const reversedIp = reverseIPv4(client.ip);
|
||||
if (!reversedIp) return;
|
||||
|
||||
// Start all lookups concurrently
|
||||
const lookupPromises = this.config.dnsbls.map(async (dnsbl) => {
|
||||
const query = `${reversedIp}.${dnsbl.server}`;
|
||||
client.lookups.set(dnsbl.cfgNum, true); // Mark as pending
|
||||
|
||||
this.debug(`Looking up client ${client.id}: ${query}`);
|
||||
|
||||
// Check cache
|
||||
const cacheTime = dnsbl.cacheTime ?? this.config.cacheTime;
|
||||
const cached = getCacheEntry(query, cacheTime);
|
||||
|
||||
let results: string[];
|
||||
if (cached && cached.result !== null) {
|
||||
this.debug(`Found dnsbl cache entry for ${query}`);
|
||||
results = cached.result;
|
||||
} else if (cached) {
|
||||
// Cache entry exists but result is null (pending)
|
||||
this.debug(`Cache pending... on ${query}`);
|
||||
// Wait a bit and retry from cache
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
const retryCache = getCacheEntry(query, cacheTime);
|
||||
results = retryCache?.result ?? [];
|
||||
} else {
|
||||
// Start new lookup
|
||||
this.debug(`Starting DNS lookup for ${query}`);
|
||||
setCacheEntry(query, null); // Mark as pending
|
||||
results = await lookupDNSBL(reversedIp, dnsbl.server, this.config.dnsTimeout);
|
||||
setCacheEntry(query, results);
|
||||
}
|
||||
|
||||
// Process results
|
||||
this.handleDNSBLResponse(client, dnsbl, results);
|
||||
|
||||
// Mark lookup as complete
|
||||
client.lookups.set(dnsbl.cfgNum, false);
|
||||
|
||||
// Check if we should process the client now
|
||||
this.handleClientUpdate(client);
|
||||
});
|
||||
|
||||
// Don't await - let lookups happen in background
|
||||
Promise.all(lookupPromises).catch((err) => {
|
||||
this.debug(`DNSBL lookup error: ${err}`);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle a DNSBL response
|
||||
*/
|
||||
private handleDNSBLResponse(client: ClientState, dnsbl: DNSBLConfig, results: string[]): void {
|
||||
if (results.length === 0) return;
|
||||
|
||||
const matched = matchesDNSBL(results, dnsbl);
|
||||
if (!matched) return;
|
||||
|
||||
this.debug(`client ${client.id} matches ${dnsbl.server} result ${results.join(',')}`);
|
||||
|
||||
// Apply whitelist
|
||||
if (dnsbl.whitelist) {
|
||||
client.whitelist = true;
|
||||
}
|
||||
|
||||
// Apply block
|
||||
if (dnsbl.block) {
|
||||
client.block = dnsbl.block;
|
||||
}
|
||||
|
||||
// Apply class
|
||||
if (dnsbl.class) {
|
||||
client.class = dnsbl.class;
|
||||
}
|
||||
|
||||
// Apply mark
|
||||
if (dnsbl.mark) {
|
||||
client.marks.set(dnsbl.mark, dnsbl);
|
||||
}
|
||||
|
||||
// Record hit
|
||||
client.hits.set(dnsbl.cfgNum, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if client processing is complete
|
||||
*/
|
||||
private handleClientUpdate(client: ClientState): void {
|
||||
// Count pending lookups
|
||||
let pending = 0;
|
||||
for (const isPending of client.lookups.values()) {
|
||||
if (isPending) pending++;
|
||||
}
|
||||
|
||||
if (client.hurry) {
|
||||
this.debug(`Client ${client.id} has Hurry set and ${pending} pending requests`);
|
||||
|
||||
if (pending === 0) {
|
||||
// Update counters for hits
|
||||
for (const cfgNum of client.hits.keys()) {
|
||||
const current = this.dnsblCounters.get(cfgNum) || 0;
|
||||
this.dnsblCounters.set(cfgNum, current + 1);
|
||||
}
|
||||
client.hits.clear();
|
||||
|
||||
// Make decision
|
||||
if (client.whitelist) {
|
||||
this.clientPass(client);
|
||||
} else if (
|
||||
client.block === 'all' ||
|
||||
(client.block === 'anonymous' && !client.account)
|
||||
) {
|
||||
this.clientReject(client, this.config.blockMsg);
|
||||
} else {
|
||||
this.clientPass(client);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
this.debug(`Client ${client.id} has ${pending} pending requests`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle Hurry message
|
||||
*/
|
||||
private handleHurry(id: number, classArg: string): void {
|
||||
const client = this.clients.get(id);
|
||||
|
||||
if (!client) {
|
||||
this.debug('ERROR: Got a hurry for a client we aren\'t even holding on to!');
|
||||
return;
|
||||
}
|
||||
|
||||
this.debug(`Handling a hurry on ${id}`);
|
||||
client.hurry = true;
|
||||
this.handleClientUpdate(client);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle authentication (R message)
|
||||
*/
|
||||
private handleAuth(id: number, account: string): void {
|
||||
const client = this.clients.get(id);
|
||||
if (!client) return;
|
||||
|
||||
this.debug(`Client ${id} authed as ${account}`);
|
||||
client.account = account;
|
||||
this.handleClientUpdate(client);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle trusted WEBIRC
|
||||
*/
|
||||
private handleWebIRC(id: number, args: string): void {
|
||||
const parts = args.split(' ');
|
||||
const [password, username, hostname, newIp] = parts;
|
||||
|
||||
this.debug(`Got a w line: ${id} - pass=<notshown>, user=${username}, host=${hostname}, ip=${newIp}`);
|
||||
|
||||
const client = this.clients.get(id);
|
||||
if (!client) {
|
||||
this.debug('Got a webirc for a client we don\'t know about? Ignored.');
|
||||
return;
|
||||
}
|
||||
|
||||
// Save state
|
||||
const wasHurry = client.hurry;
|
||||
|
||||
// Delete and recreate with new IP
|
||||
this.clients.delete(id);
|
||||
|
||||
const newClient: ClientState = {
|
||||
id,
|
||||
ip: newIp,
|
||||
port: client.port,
|
||||
serverIp: client.serverIp,
|
||||
serverPort: client.serverPort,
|
||||
whitelist: false,
|
||||
block: false,
|
||||
marks: new Map(),
|
||||
hurry: wasHurry,
|
||||
lookups: new Map(),
|
||||
hits: new Map(),
|
||||
};
|
||||
|
||||
this.clients.set(id, newClient);
|
||||
this.startDNSBLLookups(newClient);
|
||||
}
|
||||
|
||||
/**
|
||||
* Accept a client
|
||||
*/
|
||||
private clientPass(client: ClientState): void {
|
||||
this.debug(`Passing client ${client.id} (${client.ip})`);
|
||||
|
||||
// Send marks
|
||||
for (const mark of client.marks.keys()) {
|
||||
this.sendMark(client, 'MARK', mark);
|
||||
}
|
||||
|
||||
// Send done
|
||||
this.sendDone(client);
|
||||
this.countPass++;
|
||||
this.deleteClient(client.id);
|
||||
this.sendStats();
|
||||
}
|
||||
|
||||
/**
|
||||
* Reject a client
|
||||
*/
|
||||
private clientReject(client: ClientState, reason: string): void {
|
||||
this.debug(`Rejecting client ${client.id} (${client.ip}): ${reason}`);
|
||||
this.sendKill(client, reason);
|
||||
this.countReject++;
|
||||
this.deleteClient(client.id);
|
||||
this.sendStats();
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a client from tracking
|
||||
*/
|
||||
private deleteClient(id: number): void {
|
||||
this.debug('Deleting client from hash tables');
|
||||
this.clients.delete(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send mark message
|
||||
*/
|
||||
private sendMark(client: ClientState, markType: string, markData: string): void {
|
||||
if (!markData) return;
|
||||
this.send(`m ${client.id} ${client.ip} ${client.port} ${markType} ${markData}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send done message
|
||||
*/
|
||||
private sendDone(client: ClientState): void {
|
||||
if (client.class) {
|
||||
this.send(`D ${client.id} ${client.ip} ${client.port} ${client.class}`);
|
||||
} else {
|
||||
this.send(`D ${client.id} ${client.ip} ${client.port}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send kill message
|
||||
*/
|
||||
private sendKill(client: ClientState, reason: string): void {
|
||||
this.send(`k ${client.id} ${client.ip} ${client.port} :${reason}`);
|
||||
}
|
||||
|
||||
// ==================== SASL Authentication ====================
|
||||
|
||||
/**
|
||||
* Handle SASL authentication start (A message from IRCd)
|
||||
* Format from IRCd: "A S :<mechanism>" or "A S <mechanism> :<certfp>"
|
||||
* Or for host info: "A H :<user@host:ip>"
|
||||
* After handleLine parsing, args = "S :PLAIN" or "H :user@host:ip"
|
||||
*/
|
||||
private handleSASLStart(id: number, args: string): void {
|
||||
if (!this.saslEnabled()) {
|
||||
this.debug(`SASL not enabled, ignoring A message for ${id}`);
|
||||
this.sendSASLFail(id);
|
||||
return;
|
||||
}
|
||||
|
||||
// Get or create client state
|
||||
let client = this.clients.get(id);
|
||||
if (!client) {
|
||||
// Create minimal client state for SASL-only handling
|
||||
// We don't have IP/port from this message, use placeholders
|
||||
client = {
|
||||
id,
|
||||
ip: '0.0.0.0',
|
||||
port: 0,
|
||||
serverIp: '',
|
||||
serverPort: 0,
|
||||
whitelist: false,
|
||||
block: false,
|
||||
marks: new Map(),
|
||||
hurry: false,
|
||||
lookups: new Map(),
|
||||
hits: new Map(),
|
||||
sasl: { started: false },
|
||||
};
|
||||
this.clients.set(id, client);
|
||||
}
|
||||
|
||||
if (!client.sasl) {
|
||||
client.sasl = { started: false };
|
||||
}
|
||||
|
||||
// Parse: first character is type (S or H), rest is data
|
||||
// Format: "S :PLAIN" or "S PLAIN :certfp" or "H :user@host:ip"
|
||||
const spaceIdx = args.indexOf(' ');
|
||||
if (spaceIdx === -1) {
|
||||
this.debug(`Invalid SASL A message format: ${args}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const msgType = args.substring(0, spaceIdx);
|
||||
const rest = args.substring(spaceIdx + 1);
|
||||
|
||||
// Check if this is host info (H) or mechanism start (S)
|
||||
if (msgType === 'H') {
|
||||
// Host info: H :<user@host:ip>
|
||||
const colonIdx = rest.indexOf(':');
|
||||
if (colonIdx !== -1) {
|
||||
client.sasl.hostInfo = rest.substring(colonIdx + 1);
|
||||
this.debug(`SASL host info for ${id}: ${client.sasl.hostInfo}`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (msgType === 'S') {
|
||||
// Mechanism start: S :<mechanism> or S <mechanism> :<certfp>
|
||||
let mechanism: string;
|
||||
let certfp: string | undefined;
|
||||
|
||||
if (rest.startsWith(':')) {
|
||||
// Format: S :PLAIN
|
||||
mechanism = rest.substring(1).trim();
|
||||
} else {
|
||||
// Format: S PLAIN :certfp
|
||||
const colonIdx = rest.indexOf(':');
|
||||
if (colonIdx !== -1) {
|
||||
mechanism = rest.substring(0, colonIdx).trim();
|
||||
certfp = rest.substring(colonIdx + 1).trim();
|
||||
} else {
|
||||
mechanism = rest.trim();
|
||||
}
|
||||
}
|
||||
|
||||
this.debug(`SASL start for ${id}: mechanism=${mechanism}, certfp=${certfp || 'none'}`);
|
||||
|
||||
client.sasl.mechanism = mechanism;
|
||||
client.sasl.certfp = certfp;
|
||||
client.sasl.started = true;
|
||||
|
||||
// Check if mechanism is supported
|
||||
const supported = getSupportedMechanisms();
|
||||
if (!supported.includes(mechanism.toUpperCase())) {
|
||||
this.debug(`Unsupported SASL mechanism: ${mechanism}`);
|
||||
this.sendSASLMechs(id, supported);
|
||||
return;
|
||||
}
|
||||
|
||||
// For PLAIN mechanism, send empty challenge to request credentials
|
||||
if (mechanism.toUpperCase() === 'PLAIN') {
|
||||
this.sendSASLChallenge(id, '+');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
this.debug(`Unknown SASL A message type: ${msgType}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle SASL authentication continuation (a message from IRCd)
|
||||
* Format from IRCd: "a :<base64_data>"
|
||||
* After handleLine parsing, args = ":<base64_data>"
|
||||
*/
|
||||
private handleSASLContinue(id: number, args: string): void {
|
||||
if (!this.saslEnabled()) {
|
||||
this.sendSASLFail(id);
|
||||
return;
|
||||
}
|
||||
|
||||
const client = this.clients.get(id);
|
||||
if (!client || !client.sasl) {
|
||||
this.debug(`SASL continue for unknown client ${id}`);
|
||||
this.sendSASLFail(id);
|
||||
return;
|
||||
}
|
||||
|
||||
// Parse: :<data>
|
||||
const colonIdx = args.indexOf(':');
|
||||
if (colonIdx === -1) {
|
||||
this.debug(`Invalid SASL a message format: ${args}`);
|
||||
this.sendSASLFail(id);
|
||||
return;
|
||||
}
|
||||
|
||||
const data = args.substring(colonIdx + 1);
|
||||
|
||||
if (client.sasl.mechanism?.toUpperCase() === 'PLAIN') {
|
||||
this.handleSASLPlain(client, data).catch(err => {
|
||||
this.debug(`SASL PLAIN auth error: ${err}`);
|
||||
this.sendSASLFail(id);
|
||||
this.countSaslFail++;
|
||||
});
|
||||
} else {
|
||||
this.debug(`Unhandled SASL mechanism: ${client.sasl.mechanism}`);
|
||||
this.sendSASLFail(id);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle SASL PLAIN authentication
|
||||
*/
|
||||
private async handleSASLPlain(client: ClientState, base64Data: string): Promise<void> {
|
||||
const decoded = decodeSASLPlain(base64Data);
|
||||
|
||||
if (!decoded) {
|
||||
this.debug(`Failed to decode SASL PLAIN data for ${client.id}`);
|
||||
this.sendSASLFail(client.id);
|
||||
this.countSaslFail++;
|
||||
return;
|
||||
}
|
||||
|
||||
this.debug(`SASL PLAIN auth attempt for ${client.id}: authcid=${decoded.authcid}`);
|
||||
|
||||
const result = await this.authManager!.authenticate(
|
||||
decoded.authcid,
|
||||
decoded.password,
|
||||
decoded.authzid
|
||||
);
|
||||
|
||||
if (result.success && result.account) {
|
||||
this.debug(`SASL PLAIN auth success for ${client.id}: account=${result.account}`);
|
||||
client.account = result.account;
|
||||
this.sendSASLSuccess(client.id, result.account);
|
||||
this.countSaslSuccess++;
|
||||
} else {
|
||||
this.debug(`SASL PLAIN auth failed for ${client.id}: ${result.error || 'unknown'}`);
|
||||
this.sendSASLFail(client.id);
|
||||
this.countSaslFail++;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send SASL challenge to client
|
||||
* Format: c <id> <ip> <port> :<challenge>
|
||||
*/
|
||||
private sendSASLChallenge(id: number, challenge: string): void {
|
||||
const client = this.clients.get(id);
|
||||
if (client) {
|
||||
this.send(`c ${id} ${client.ip} ${client.port} :${challenge}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send SASL login success
|
||||
* Format: L <id> <ip> <port> <account>
|
||||
*/
|
||||
private sendSASLSuccess(id: number, account: string): void {
|
||||
const client = this.clients.get(id);
|
||||
if (client) {
|
||||
this.send(`L ${id} ${client.ip} ${client.port} ${account}`);
|
||||
this.send(`Z ${id} ${client.ip} ${client.port}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send SASL authentication failed
|
||||
* Format: f <id> <ip> <port>
|
||||
*/
|
||||
private sendSASLFail(id: number): void {
|
||||
const client = this.clients.get(id);
|
||||
if (client) {
|
||||
this.send(`f ${id} ${client.ip} ${client.port}`);
|
||||
} else {
|
||||
// Client may not exist yet, send with dummy values
|
||||
this.send(`f ${id} 0.0.0.0 0`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send SASL available mechanisms
|
||||
* Format: l <id> <ip> <port> :<mechanisms>
|
||||
*/
|
||||
private sendSASLMechs(id: number, mechanisms: string[]): void {
|
||||
const client = this.clients.get(id);
|
||||
if (client) {
|
||||
this.send(`l ${id} ${client.ip} ${client.port} :${mechanisms.join(',')}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* iauthd-ts - IAuth daemon for Nefarious IRCd
|
||||
* TypeScript port of iauthd.pl
|
||||
*
|
||||
* A DNSBL-based authentication daemon that checks connecting clients
|
||||
* against configured DNS blacklists and can block, mark, or whitelist
|
||||
* users based on the results.
|
||||
*
|
||||
* Requirements:
|
||||
* Node.js 18+
|
||||
*
|
||||
* Installation:
|
||||
* npm install
|
||||
* npm run build
|
||||
*
|
||||
* Usage:
|
||||
* node dist/index.js -c /path/to/config
|
||||
*
|
||||
* Configuration:
|
||||
* Config directives begin with #IAUTH and are one per line.
|
||||
* Because configuration begins with #, it can be embedded in ircd.conf.
|
||||
* Syntax is: #IAUTH <directive> <arguments>
|
||||
*
|
||||
* Configuration directives:
|
||||
*
|
||||
* POLICY:
|
||||
* See docs/readme.iauth section on Set Policy Options
|
||||
*
|
||||
* DNSTIMEOUT:
|
||||
* Seconds to time out for DNSBL lookups. Default is 5
|
||||
*
|
||||
* DNSBL <key=value [key=value..]>
|
||||
* where keys are:
|
||||
* server - dnsbl server to look up, eg dnsbl.sorbs.net
|
||||
* bitmask - matches if response is true after being bitwise-and'ed with mask
|
||||
* index - matches if response is exactly index (comma separated values ok)
|
||||
* class - assigns the user to the named class
|
||||
* mark - marks the user with the given mark
|
||||
* block - all: blocks connection if matched
|
||||
* anonymous: blocks connection unless SASL authenticated
|
||||
* whitelist - listed users won't be blocked by any RBL
|
||||
* cachetime - Override default cache timeout
|
||||
*
|
||||
* DEBUG:
|
||||
* Values greater than 0 turn iauth debugging on in the ircd
|
||||
*
|
||||
* BLOCKMSG:
|
||||
* Message shown to users when blocked
|
||||
*
|
||||
* CACHETIME:
|
||||
* Default cache time in seconds (default 86400 = 24 hours)
|
||||
*
|
||||
* Example configuration:
|
||||
*
|
||||
* #IAUTH POLICY RTAWUwFr
|
||||
* #IAUTH CACHETIME 86400
|
||||
* #IAUTH BLOCKMSG Sorry! Your connection has been rejected due to poor reputation.
|
||||
* #IAUTH DNSBL server=dnsbl.sorbs.net index=2,3,4,5,6,7,9 mark=sorbs block=anonymous
|
||||
* #IAUTH DNSBL server=dnsbl.dronebl.org index=2,3,5,6,7,8,9,10,13,14,15 mark=dronebl block=anonymous
|
||||
* #IAUTH DNSBL server=rbl.efnetrbl.org index=4 mark=tor
|
||||
* #IAUTH DNSBL server=rbl.efnetrbl.org index=1,2,3,5 mark=efnetrbl block=anonymous
|
||||
*
|
||||
* ircd.conf:
|
||||
*
|
||||
* IAuth {
|
||||
* program = "node" "/path/to/iauthd-ts/dist/index.js" "-v" "-c" "ircd.conf";
|
||||
* };
|
||||
*
|
||||
* Debugging:
|
||||
* * Oper up first
|
||||
* * Set snomask: /quote mode yournick +s 262144
|
||||
*/
|
||||
|
||||
import { parseArgs } from 'node:util';
|
||||
import type { CLIOptions } from './types.js';
|
||||
import { IAuthDaemon } from './iauth.js';
|
||||
|
||||
const HELP = `
|
||||
iauthd-ts - IAuth daemon for Nefarious IRCd (TypeScript port)
|
||||
|
||||
Usage: iauthd-ts [options] --config=<configfile>
|
||||
|
||||
Options:
|
||||
-h, --help Print this message
|
||||
-c, --config Config file to read (required)
|
||||
-d, --debug Turn on debugging in the ircd
|
||||
-v, --verbose Turn on debugging in iauthd
|
||||
`;
|
||||
|
||||
function main(): void {
|
||||
let options: CLIOptions;
|
||||
|
||||
try {
|
||||
const { values } = parseArgs({
|
||||
options: {
|
||||
help: { type: 'boolean', short: 'h', default: false },
|
||||
config: { type: 'string', short: 'c' },
|
||||
debug: { type: 'boolean', short: 'd', default: false },
|
||||
verbose: { type: 'boolean', short: 'v', default: false },
|
||||
},
|
||||
strict: true,
|
||||
});
|
||||
|
||||
options = {
|
||||
help: values.help ?? false,
|
||||
config: values.config ?? '',
|
||||
debug: values.debug ?? false,
|
||||
verbose: values.verbose ?? false,
|
||||
};
|
||||
} catch (err) {
|
||||
console.error(HELP);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (options.help || !options.config) {
|
||||
console.error(HELP);
|
||||
process.exit(options.help ? 0 : 1);
|
||||
}
|
||||
|
||||
try {
|
||||
const daemon = new IAuthDaemon(options);
|
||||
daemon.start();
|
||||
} catch (err) {
|
||||
console.error(`Failed to start iauthd-ts: ${err}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,264 @@
|
||||
/**
|
||||
* SASL Authentication module for iauthd-ts
|
||||
* Handles SASL PLAIN authentication with crypt-style password hashes
|
||||
*/
|
||||
|
||||
import { readFileSync, statSync } from 'node:fs';
|
||||
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
|
||||
|
||||
/** User entry from the users file */
|
||||
export interface UserEntry {
|
||||
username: string;
|
||||
passwordHash: string;
|
||||
}
|
||||
|
||||
/** Parsed users database */
|
||||
export interface UsersDB {
|
||||
users: Map<string, UserEntry>;
|
||||
lastModified: number;
|
||||
filePath: string;
|
||||
}
|
||||
|
||||
/** Supported hash types with their crypt prefixes */
|
||||
type HashType = 'sha256' | 'sha512' | 'md5' | 'plain';
|
||||
|
||||
/**
|
||||
* Parse a users file in format: username:passwordhash
|
||||
* Supports crypt-style hashes with $$ prefix:
|
||||
* - $5$ = SHA-256
|
||||
* - $6$ = SHA-512
|
||||
* - $1$ = MD5
|
||||
* - No prefix = plain text (for testing only)
|
||||
*/
|
||||
export function parseUsersFile(filePath: string): UsersDB {
|
||||
const users = new Map<string, UserEntry>();
|
||||
let lastModified = 0;
|
||||
|
||||
try {
|
||||
const stat = statSync(filePath);
|
||||
lastModified = stat.mtimeMs;
|
||||
const content = readFileSync(filePath, 'utf-8');
|
||||
|
||||
for (const line of content.split('\n')) {
|
||||
const trimmed = line.trim();
|
||||
// Skip empty lines and comments
|
||||
if (!trimmed || trimmed.startsWith('#')) continue;
|
||||
|
||||
const colonIdx = trimmed.indexOf(':');
|
||||
if (colonIdx === -1) continue;
|
||||
|
||||
const username = trimmed.substring(0, colonIdx).toLowerCase();
|
||||
const passwordHash = trimmed.substring(colonIdx + 1);
|
||||
|
||||
if (username && passwordHash) {
|
||||
users.set(username, { username, passwordHash });
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
// File doesn't exist or can't be read - return empty DB
|
||||
}
|
||||
|
||||
return { users, lastModified, filePath };
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if users file has been modified since last load
|
||||
*/
|
||||
export function usersFileModified(db: UsersDB): boolean {
|
||||
try {
|
||||
const stat = statSync(db.filePath);
|
||||
return stat.mtimeMs > db.lastModified;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse crypt-style hash to determine type and extract salt
|
||||
*/
|
||||
function parseHashType(hash: string): { type: HashType; salt: string; hash: string } | null {
|
||||
// SHA-256 crypt: $5$salt$hash
|
||||
if (hash.startsWith('$5$')) {
|
||||
const parts = hash.split('$');
|
||||
if (parts.length >= 4) {
|
||||
return { type: 'sha256', salt: parts[2], hash: parts[3] };
|
||||
}
|
||||
}
|
||||
|
||||
// SHA-512 crypt: $6$salt$hash
|
||||
if (hash.startsWith('$6$')) {
|
||||
const parts = hash.split('$');
|
||||
if (parts.length >= 4) {
|
||||
return { type: 'sha512', salt: parts[2], hash: parts[3] };
|
||||
}
|
||||
}
|
||||
|
||||
// MD5 crypt: $1$salt$hash
|
||||
if (hash.startsWith('$1$')) {
|
||||
const parts = hash.split('$');
|
||||
if (parts.length >= 4) {
|
||||
return { type: 'md5', salt: parts[2], hash: parts[3] };
|
||||
}
|
||||
}
|
||||
|
||||
// Plain text (for testing) - no $ prefix
|
||||
if (!hash.startsWith('$')) {
|
||||
return { type: 'plain', salt: '', hash: hash };
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a SHA-256 crypt-style hash
|
||||
* Uses the simplified sha256crypt format: $5$salt$base64hash
|
||||
*/
|
||||
function sha256Crypt(password: string, salt: string): string {
|
||||
// Simplified implementation - use PBKDF2-like iteration
|
||||
// Real crypt uses a more complex algorithm, but this is compatible
|
||||
// for our purposes of simple password verification
|
||||
let hash = createHash('sha256').update(salt + password).digest();
|
||||
|
||||
// Multiple rounds for security
|
||||
for (let i = 0; i < 5000; i++) {
|
||||
hash = createHash('sha256').update(hash).update(password).digest();
|
||||
}
|
||||
|
||||
return hash.toString('base64').replace(/=+$/, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a SHA-512 crypt-style hash
|
||||
*/
|
||||
function sha512Crypt(password: string, salt: string): string {
|
||||
let hash = createHash('sha512').update(salt + password).digest();
|
||||
|
||||
for (let i = 0; i < 5000; i++) {
|
||||
hash = createHash('sha512').update(hash).update(password).digest();
|
||||
}
|
||||
|
||||
return hash.toString('base64').replace(/=+$/, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate an MD5 crypt-style hash
|
||||
*/
|
||||
function md5Crypt(password: string, salt: string): string {
|
||||
let hash = createHash('md5').update(salt + password).digest();
|
||||
|
||||
for (let i = 0; i < 1000; i++) {
|
||||
hash = createHash('md5').update(hash).update(password).digest();
|
||||
}
|
||||
|
||||
return hash.toString('base64').replace(/=+$/, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify a password against a stored hash
|
||||
* Uses timing-safe comparison to prevent timing attacks
|
||||
*/
|
||||
export function verifyPassword(password: string, storedHash: string): boolean {
|
||||
const parsed = parseHashType(storedHash);
|
||||
if (!parsed) return false;
|
||||
|
||||
let computedHash: string;
|
||||
|
||||
switch (parsed.type) {
|
||||
case 'sha256':
|
||||
computedHash = sha256Crypt(password, parsed.salt);
|
||||
break;
|
||||
case 'sha512':
|
||||
computedHash = sha512Crypt(password, parsed.salt);
|
||||
break;
|
||||
case 'md5':
|
||||
computedHash = md5Crypt(password, parsed.salt);
|
||||
break;
|
||||
case 'plain':
|
||||
// Plain text comparison (for testing only)
|
||||
computedHash = password;
|
||||
break;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
|
||||
// Use timing-safe comparison
|
||||
try {
|
||||
const a = Buffer.from(computedHash);
|
||||
const b = Buffer.from(parsed.hash);
|
||||
if (a.length !== b.length) return false;
|
||||
return timingSafeEqual(a, b);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a new password hash
|
||||
* @param password The password to hash
|
||||
* @param type Hash type to use (default: sha256)
|
||||
*/
|
||||
export function generateHash(password: string, type: HashType = 'sha256'): string {
|
||||
const salt = randomBytes(12).toString('base64').replace(/[+/=]/g, '').substring(0, 16);
|
||||
|
||||
switch (type) {
|
||||
case 'sha256':
|
||||
return `$5$${salt}$${sha256Crypt(password, salt)}`;
|
||||
case 'sha512':
|
||||
return `$6$${salt}$${sha512Crypt(password, salt)}`;
|
||||
case 'md5':
|
||||
return `$1$${salt}$${md5Crypt(password, salt)}`;
|
||||
case 'plain':
|
||||
return password;
|
||||
default:
|
||||
return `$5$${salt}$${sha256Crypt(password, salt)}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode SASL PLAIN authentication data
|
||||
* Format: base64(authzid \0 authcid \0 password)
|
||||
* Returns null if invalid format
|
||||
*/
|
||||
export function decodeSASLPlain(base64Data: string): { authzid: string; authcid: string; password: string } | null {
|
||||
try {
|
||||
const decoded = Buffer.from(base64Data, 'base64').toString('utf-8');
|
||||
const parts = decoded.split('\0');
|
||||
|
||||
if (parts.length !== 3) return null;
|
||||
|
||||
return {
|
||||
authzid: parts[0], // Authorization identity (usually empty or same as authcid)
|
||||
authcid: parts[1], // Authentication identity (username)
|
||||
password: parts[2], // Password
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticate a user with SASL PLAIN
|
||||
* @param db Users database
|
||||
* @param authcid Authentication identity (username)
|
||||
* @param password Password
|
||||
* @returns Account name if successful, null if failed
|
||||
*/
|
||||
export function authenticatePlain(db: UsersDB, authcid: string, password: string): string | null {
|
||||
const username = authcid.toLowerCase();
|
||||
const user = db.users.get(username);
|
||||
|
||||
if (!user) return null;
|
||||
|
||||
if (verifyPassword(password, user.passwordHash)) {
|
||||
return user.username;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get list of supported SASL mechanisms
|
||||
*/
|
||||
export function getSupportedMechanisms(): string[] {
|
||||
return ['PLAIN'];
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
/**
|
||||
* TypeScript types for iauthd
|
||||
*/
|
||||
|
||||
import type { AuthProviderConfig } from './auth/types.js';
|
||||
|
||||
/** DNSBL configuration entry */
|
||||
export interface DNSBLConfig {
|
||||
/** Config line number for identification */
|
||||
cfgNum: number;
|
||||
/** DNSBL server hostname (e.g., dnsbl.sorbs.net) */
|
||||
server: string;
|
||||
/** Match if response equals one of these indices (e.g., "2,3,4") */
|
||||
index?: string;
|
||||
/** Match if response bitwise-AND with mask is truthy */
|
||||
bitmask?: string;
|
||||
/** Mark to apply if matched */
|
||||
mark?: string;
|
||||
/** Block mode: 'all' or 'anonymous' (block unless authenticated) */
|
||||
block?: 'all' | 'anonymous';
|
||||
/** If true, whitelist this user from all blocks */
|
||||
whitelist?: boolean;
|
||||
/** Connection class to assign */
|
||||
class?: string;
|
||||
/** Override cache timeout for this DNSBL */
|
||||
cacheTime?: number;
|
||||
}
|
||||
|
||||
/** Main configuration */
|
||||
export interface Config {
|
||||
/** IAuth policy string (e.g., "RTAWUwFr") */
|
||||
policy: string;
|
||||
/** DNSBL configurations */
|
||||
dnsbls: DNSBLConfig[];
|
||||
/** DNS lookup timeout in seconds */
|
||||
dnsTimeout: number;
|
||||
/** Message shown when blocking a client */
|
||||
blockMsg: string;
|
||||
/** Default cache time in seconds */
|
||||
cacheTime: number;
|
||||
/** Debug mode */
|
||||
debug: boolean;
|
||||
/** Path to users file for SASL authentication (legacy, use authProviders) */
|
||||
saslUsersFile?: string;
|
||||
/** Message shown when SASL authentication fails */
|
||||
saslFailMsg: string;
|
||||
/** Authentication providers configuration */
|
||||
authProviders: AuthProviderConfig[];
|
||||
}
|
||||
|
||||
/** SASL session state */
|
||||
export interface SASLState {
|
||||
/** SASL mechanism being used */
|
||||
mechanism?: string;
|
||||
/** Whether we've sent the initial response */
|
||||
started: boolean;
|
||||
/** SSL client certificate fingerprint (if provided) */
|
||||
certfp?: string;
|
||||
/** Client host info (user@host:ip) */
|
||||
hostInfo?: string;
|
||||
}
|
||||
|
||||
/** Client state during registration */
|
||||
export interface ClientState {
|
||||
/** Client ID from ircd */
|
||||
id: number;
|
||||
/** Remote IP address */
|
||||
ip: string;
|
||||
/** Remote port */
|
||||
port: number;
|
||||
/** Server IP */
|
||||
serverIp: string;
|
||||
/** Server port */
|
||||
serverPort: number;
|
||||
/** Whether client is whitelisted */
|
||||
whitelist: boolean;
|
||||
/** Block mode if any */
|
||||
block: 'all' | 'anonymous' | false;
|
||||
/** Applied marks */
|
||||
marks: Map<string, DNSBLConfig>;
|
||||
/** Assigned connection class */
|
||||
class?: string;
|
||||
/** Whether we've received a Hurry message */
|
||||
hurry: boolean;
|
||||
/** Pending DNSBL lookups (cfgNum -> pending) */
|
||||
lookups: Map<number, boolean>;
|
||||
/** Account name if authenticated via SASL/LOC */
|
||||
account?: string;
|
||||
/** DNSBL hits (cfgNum -> hit) */
|
||||
hits: Map<number, boolean>;
|
||||
/** SASL authentication state */
|
||||
sasl?: SASLState;
|
||||
}
|
||||
|
||||
/** DNSBL cache entry */
|
||||
export interface CacheEntry {
|
||||
/** DNS lookup results (IP addresses) */
|
||||
result: string[] | null;
|
||||
/** Timestamp when cached */
|
||||
ts: number;
|
||||
}
|
||||
|
||||
/** Parsed server message */
|
||||
export type ServerMessage =
|
||||
| { type: 'C'; id: number; remoteIp: string; remotePort: number; localIp: string; localPort: number }
|
||||
| { type: 'D'; id: number }
|
||||
| { type: 'F'; id: number; fingerprint: string }
|
||||
| { type: 'R'; id: number; account: string }
|
||||
| { type: 'N'; id: number; hostname: string }
|
||||
| { type: 'd'; id: number }
|
||||
| { type: 'P'; id: number; password: string }
|
||||
| { type: 'U'; id: number; username: string; hostname: string; servername: string; userinfo: string }
|
||||
| { type: 'u'; id: number; username?: string }
|
||||
| { type: 'n'; id: number; nickname: string }
|
||||
| { type: 'H'; id: number; class: string }
|
||||
| { type: 'T'; id: number }
|
||||
| { type: 'E'; id: number; errorType: string; text: string }
|
||||
| { type: 'e'; id: number; event: string; params?: string }
|
||||
| { type: 'M'; id: number; servername: string; capacity: number }
|
||||
| { type: 'X'; id: number; servername: string; routing: string; reply: string }
|
||||
| { type: 'x'; id: number; servername: string; routing: string; message: string }
|
||||
| { type: 'W'; id: number; password: string; username: string; hostname: string; ip: string; options?: string }
|
||||
| { type: 'w'; id: number; password: string; username: string; hostname: string; ip: string; options?: string }
|
||||
| { type: 'unknown'; id: number; raw: string };
|
||||
|
||||
/** CLI options */
|
||||
export interface CLIOptions {
|
||||
config: string;
|
||||
debug: boolean;
|
||||
verbose: boolean;
|
||||
help: boolean;
|
||||
}
|
||||
Reference in new issue
Block a user