Adaugă codul complet al proiectului underchat-ircd

This commit is contained in:
mihaiitdata committed 2026-02-13 00:04:12 +02:00
1 parent caba5224bf
commit 5fdc1cc27c
462 files changed
+164488

No files matched your search

+504
View File
@@ -0,0 +1,504 @@
/*
* IRC - Internet Relay Chat, tools/Bounce/Bounce.cpp
* Copyright (C) 1990 Jarkko Oikarinen and
* University of Oulu, Computing Center
*
* See file AUTHORS in IRC package for additional names of
* the programmers.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 1, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Port Bouncer.
*
* This tool is designed to set up a number of local listening ports, and
* then forward any data recived on those ports, to another host/port combo.
* Each listening port can bounce to a different host/port defined in the
* config file. --Gte
*
* $Id: Bounce.cpp,v 1.3 2002-03-07 22:52:57 ghostwolf Exp $
*
*/
#include "Bounce.h"
int main() {
Bounce* application = new Bounce();
/*
* Ignore SIGPIPE.
*/
struct sigaction act;
act.sa_handler = SIG_IGN;
act.sa_flags = 0;
sigemptyset(&act.sa_mask);
sigaction(SIGPIPE, &act, 0);
#ifndef DEBUG
/*
* If we aren't debugging, we might as well
* detach from the console.
*/
pid_t forkResult = fork() ;
if(forkResult < 0)
{
printf("Unable to fork new process.\n");
return -1 ;
}
else if(forkResult != 0)
{
printf("Successfully Forked, New process ID is %i.\n", forkResult);
return 0;
}
#endif
/*
* Create new application object, bind listeners and begin
* polling them.
*/
application->bindListeners();
while (1) {
application->checkSockets();
}
}
/*
****************************************
* *
* Bounce class implementation. *
* *
****************************************
*/
void Bounce::bindListeners() {
/*
* bindListeners.
* Inputs: Nothing.
* Outputs: Nothing.
* Process: 1. Reads the config file, and..
* 2. Creates a new listener for each 'P' line found.
*
*/
FILE* configFd;
char tempBuf[256];
int localPort = 0;
int remotePort = 0;
char* remoteServer;
char* vHost;
/*
* Open config File.
*/
if(!(configFd = fopen("bounce.conf", "r")))
{
printf("Error, unable to open config file!\n");
exit(0);
}
while (fgets(tempBuf, 256, configFd) != NULL) {
if((tempBuf[0] != '#') && (tempBuf[0] != '\r')) {
switch(tempBuf[0])
{
case 'P': { /* Add new port listener */
strtok(tempBuf, ":");
vHost = strtok(NULL, ":");
localPort = atoi(strtok(NULL, ":"));
remoteServer = strtok(NULL, ":");
remotePort = atoi(strtok(NULL, ":"));
Listener* newListener = new Listener();
strcpy(newListener->myVhost, vHost);
strcpy(newListener->remoteServer, remoteServer);
newListener->remotePort = remotePort;
newListener->localPort = localPort;
#ifdef DEBUG
printf("Adding new Listener: Local: %s:%i, Remote: %s:%i\n", vHost, localPort, remoteServer, remotePort);
#endif
newListener->beginListening();
listenerList.insert(listenerList.begin(), newListener);
break;
}
}
}
}
}
void Bounce::checkSockets() {
/*
* checkSockets.
* Inputs: Nothing.
* Outputs: Nothing.
* Process: 1. Builds up a FD_SET of all sockets we wish to check.
* (Including all listeners & all open connections).
* 2. SELECT(2) the set, and forward/accept as needed.
*
*/
typedef std::list<Listener*> listenerContainer;
typedef listenerContainer::iterator listIter;
typedef std::list<Connection*> connectionContainer;
typedef connectionContainer::iterator connIter;
struct timeval tv;
fd_set readfds;
tv.tv_sec = 0;
tv.tv_usec = 1000;
int tempFd = 0;
int tempFd2 = 0;
int highestFd = 0;
int delCheck = 0;
char* tempBuf;
FD_ZERO(&readfds);
/*
* Add all Listeners to the set.
*/
listIter a = listenerList.begin();
while(a != listenerList.end())
{
tempFd = (*a)->fd;
FD_SET(tempFd, &readfds);
if (highestFd < tempFd) highestFd = tempFd;
a++;
}
/*
* Add Local & Remote connections from each
* connection object to the set.
*/
connIter b = connectionsList.begin();
while(b != connectionsList.end())
{
tempFd = (*b)->localSocket->fd;
tempFd2 = (*b)->remoteSocket->fd;
FD_SET(tempFd, &readfds);
if (highestFd < tempFd) highestFd = tempFd;
FD_SET(tempFd2, &readfds);
if (highestFd < tempFd2) highestFd = tempFd2;
b++;
}
select(highestFd+1, &readfds, NULL, NULL, &tv);
/*
* Check all connections for readability.
* First check Local FD's.
* If the connection is closed on either side,
* shutdown both sockets, and clean up.
* Otherwise, send the data from local->remote, or
* remote->local.
*/
b = connectionsList.begin();
while(b != connectionsList.end())
{
tempFd = (*b)->localSocket->fd;
if (FD_ISSET(tempFd, &readfds))
{
tempBuf = (*b)->localSocket->read();
if ((tempBuf[0] == 0)) // Connection closed.
{
close((*b)->localSocket->fd);
close((*b)->remoteSocket->fd);
#ifdef DEBUG
printf("Closing FD: %i\n", (*b)->localSocket->fd);
printf("Closing FD: %i\n", (*b)->remoteSocket->fd);
#endif
delete(*b);
delCheck = 1;
b = connectionsList.erase(b);
} else {
(*b)->remoteSocket->write(tempBuf, (*b)->localSocket->lastReadSize);
}
}
if (!delCheck) b++;
delCheck = 0;
}
/*
* Now check Remote FD's..
*/
b = connectionsList.begin();
while(b != connectionsList.end())
{
tempFd = (*b)->remoteSocket->fd;
if (FD_ISSET(tempFd, &readfds))
{
tempBuf = (*b)->remoteSocket->read();
if ((tempBuf[0] == 0)) // Connection closed.
{
close((*b)->localSocket->fd);
close((*b)->remoteSocket->fd);
#ifdef DEBUG
printf("Closing FD: %i\n", (*b)->localSocket->fd);
printf("Closing FD: %i\n", (*b)->remoteSocket->fd);
#endif
delete(*b);
delCheck = 1;
b = connectionsList.erase(b);
} else {
(*b)->localSocket->write(tempBuf, (*b)->remoteSocket->lastReadSize);
}
}
if (!delCheck) b++;
delCheck = 0;
}
/*
* Check all listeners for new connections.
*/
a = listenerList.begin();
while(a != listenerList.end())
{
tempFd = (*a)->fd;
if (FD_ISSET(tempFd, &readfds))
{
recieveNewConnection(*a);
}
a++;
}
}
void Bounce::recieveNewConnection(Listener* listener) {
/*
* recieveNewConnection.
* Inputs: A Listener Object.
* Outputs: Nothing.
* Process: 1. Recieves a new connection on a local port,
* and creates a connection object for it.
* 2. Accepts the incomming connection.
* 3. Creates a new Socket object for the remote
* end of the connection.
* 4. Connects up the remote Socket.
* 5. Adds the new Connection object to the
* connections list.
*
*/
Connection* newConnection = new Connection();
newConnection->localSocket = listener->handleAccept();
Socket* remoteSocket = new Socket();
newConnection->remoteSocket = remoteSocket;
if(remoteSocket->connectTo(listener->remoteServer, listener->remotePort)) {
connectionsList.insert(connectionsList.begin(), newConnection);
} else {
#ifdef DEBUG
newConnection->localSocket->write("Unable to connect to remote host.\n");
#endif
close(newConnection->localSocket->fd);
delete(newConnection);
delete(remoteSocket);
}
}
/*
****************************************
* *
* Listener class implementation. *
* *
****************************************
*/
Socket* Listener::handleAccept() {
/*
* handleAccept.
* Inputs: Nothing.
* Outputs: A Socket Object.
* Process: 1. Accept's an incomming connection,
* and returns a new socket object.
*/
int new_fd = 0;
int sin_size = sizeof(struct sockaddr_in);
Socket* newSocket = new Socket();
new_fd = accept(fd, (struct sockaddr*)&newSocket->address, (socklen_t*)&sin_size);
newSocket->fd = new_fd;
return newSocket;
}
void Listener::beginListening() {
/*
* beginListening.
* Inputs: Nothing.
* Outputs: Nothing.
* Process: 1. Binds the local ports for all the
* Listener objects.
*
*/
struct sockaddr_in my_addr;
int bindRes;
int optval;
optval = 1;
fd = socket(AF_INET, SOCK_STREAM, 0); /* Check for no FD's left?! */
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(localPort);
my_addr.sin_addr.s_addr = inet_addr(myVhost);
bzero(&(my_addr.sin_zero), 8);
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
bindRes = bind(fd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr));
if(bindRes == 0)
{
listen(fd, 10);
} else {
/*
* If we can't bind a listening port, we might aswell drop out.
*/
printf("Unable to bind to %s:%i!\n", myVhost, localPort);
exit(0);
}
}
/*
****************************************
* *
* Socket class implementation. *
* *
****************************************
*/
Socket::Socket() {
/*
* Socket Constructor.
* Inputs: Nothing.
* Outputs: Nothing.
* Process: Initialises member variables.
*
*/
fd = -1;
lastReadSize = 0;
}
int Socket::write(char *message, int len) {
/*
* write.
* Inputs: Message string, and lenght.
* Outputs: Amount written, or 0 on error.
* Process: 1. Writes out 'len' amount of 'message'.
* to this socket.
*
*/
if (fd == -1) return 0;
int amount = ::write(fd, message, len);
#ifdef DEBUG
printf("Wrote %i Bytes.\n", amount);
#endif
return amount;
}
int Socket::write(char *message) {
/*
* write(2).
* Inputs: Message string.
* Outputs: Amount writte, or 0 on error.
* Process: Writes out the whole of 'message'.
*
*/
if (fd == -1) return 0;
int amount = ::write(fd, message, strlen(message));
#ifdef DEBUG
printf("Wrote %i Bytes.\n", amount);
#endif
return amount;
}
int Socket::connectTo(char *hostname, unsigned short portnum) {
/*
* connectTo.
* Inputs: Hostname and port.
* Outputs: +ve on success, 0 on failure.
* Process: 1. Connects this socket to remote 'hostname' on
* port 'port'.
*
*/
struct hostent *hp;
if ((hp = gethostbyname(hostname)) == NULL) {
return 0;
}
memset(&address,0,sizeof(address));
memcpy((char *)&address.sin_addr,hp->h_addr,hp->h_length);
address.sin_family= hp->h_addrtype;
address.sin_port= htons((u_short)portnum);
if ((fd = socket(hp->h_addrtype,SOCK_STREAM,0)) < 0)
return 0;
if (connect(fd, (struct sockaddr*)&address, sizeof(address)) < 0) {
close(fd);
fd = -1;
return 0;
}
return(1);
}
char* Socket::read() {
/*
* read.
* Inputs: Nothing.
* Outputs: char* to static buffer containing data.
* Process: 1. Reads as much as possible from this socket, up to
* 4k.
*
*/
int amountRead = 0;
static char buffer[4096];
amountRead = ::read(fd, &buffer, 4096);
if ((amountRead == -1)) buffer[0] = '\0';
buffer[amountRead] = '\0';
#ifdef DEBUG
printf("Read %i Bytes.\n", amountRead);
#endif
/*
* Record this just incase we're dealing with binary data with 0's in it.
*/
lastReadSize = amountRead;
return (char *)&buffer;
}
+117
View File
@@ -0,0 +1,117 @@
/*
* IRC - Internet Relay Chat, tools/Bounce/Bounce.h
* Copyright (C) 1990 Jarkko Oikarinen and
* University of Oulu, Computing Center
*
* See file AUTHORS in IRC package for additional names of
* the programmers.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 1, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* $Id: Bounce.h 667 2002-03-07 22:52:57Z ghostwolf $
*
*/
#include <sys/types.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>
#include <ctype.h>
#include <time.h>
#include <stdio.h>
#include <unistd.h>
#include <stdarg.h>
#include <signal.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <ctype.h>
#include <time.h>
#include <list>
using std::list;
#define DEBUG
/*
* "Bounce" Class.
*/
class Listener;
class Connection;
class Bounce
{
public:
list<Listener*> listenerList; // List of 'Listeners'.
list<Connection*> connectionsList; // List of 'Connections'.
void bindListeners(); // Binds Listening Ports.
void checkSockets(); // Polls all sockets.
void recieveNewConnection(Listener*); // Accepts connections.
};
/*
* "Socket" Class.
*/
class Socket
{
public:
int fd; // File descriptor.
int lastReadSize; // Size of last read buffer.
struct sockaddr_in address; // Socket addr_in struct.
int connectTo(char*, unsigned short); // Connects the socket.
int write(char*, int); // Writes 'int' bytes from message.
int write(char*); // Writes strlen(message).
char* read(); // Reads as much as possible into a 4k buffer.
Socket(); // Constructor.
};
/*
* "Listener" Class.
*/
class Bounce;
class Listener
{
public:
int fd; // File descriptor.
int remotePort; // Remote port from config.
int localPort; // Local port for binding.
char myVhost[15]; // Vhost to bind locally.
char remoteServer[15]; // Remote server to connect to.
void beginListening(); // Bind listening ports.
Socket* handleAccept(); // Accept a new connection.
};
/*
* "Connection" Class.
* Simply a container for a local/remote Socket pair.
*/
class Connection
{
public:
Socket* localSocket;
Socket* remoteSocket;
};
+7
View File
@@ -0,0 +1,7 @@
# Format: P:<Local vhost>:<Local Port>:<Remote Address>:<Remote Port>
# IP's only for now :)
# $Id: bounce.conf,v 1.2 2002-03-07 22:52:57 ghostwolf Exp $
P:192.168.10.5:2000:192.168.10.1:80
P:192.168.10.5:3000:4.33.94.3:80
P:192.168.10.5:4000:209.207.224.42:80
+1
View File
@@ -0,0 +1 @@
g++ -O3 -ggdb -Wall -Wmissing-declarations -o Bounce Bounce.cpp
+70
View File
@@ -0,0 +1,70 @@
#
# Structure AutoDocumentator for ircu.
# 26/02/2000 --Gte
#
# Creates a 'structs.html', containing HTML Table definitions
# for all structures encountered in *.h in the current directory.
#
# $Id: autodoc.py,v 1.1 2000-03-18 05:20:30 bleep Exp $
import string, fnmatch, os
def parse(filename):
OutFile = open('structs.html', 'a')
OutFile.write("<B><H2>"+filename+"</H2>")
stage = 1
try:
IncFile = open(filename, 'r')
line = IncFile.readline()
while line != "":
line = string.replace(line,"\n","") # Stript out LF's.
splitline = string.split(line, " ")
try:
if ((stage == 2) & (splitline[0] == "};")):
OutFile.write("</TABLE><P>"+"\n")
stage = 1
if (stage == 2):
# Begin reading member information.
declr = string.split(string.strip(line), ";", 1)
comment = string.replace(declr[1], "*", "")
comment = string.replace(comment, "/", "")
OutFile.write("<tr>\n")
OutFile.write("<td WIDTH=\"22%\">"+string.strip(declr[0])+"</td>\n")
if (declr[1][-1] == "/"):
OutFile.write("<td WIDTH=\"78%\">"+string.strip(comment)+"</td>\n")
else:
# Loop until end of comment string.
while (declr[-1] != "/"):
line = IncFile.readline()
line = string.replace(line,"\n","") # Stript out LF's.
declr = string.strip(line)
comment = comment + line
comment = string.replace(comment, "*", "")
comment = string.replace(comment, "/", "")
OutFile.write("<td WIDTH=\"78%\">"+string.strip(comment)+"</td>\n")
OutFile.write("</tr>\n")
if ((splitline[0] == "struct") & (splitline[2] == "{") & (stage == 1)):
# We've found a "Standard" structure definition.
OutFile.write("Structure table for: \"<B>"+splitline[1]+"</B>\"<P>\n")
OutFile.write("<table BORDER CELLSPACING=0 CELLPADDING=2 WIDTH=\"100%\" ><tr><td VALIGN=TOP WIDTH=\"22%\"><b>Variable</b></td><td VALIGN=TOP WIDTH=\"78%\"><b>Description</b></td></tr>")
# Now, carry on until we encounter a "};".
stage = 2
except IndexError:
pass
line = IncFile.readline()
IncFile.close
OutFile.write("<HR>")
except IOError:
print("** Error, File does not exist.")
OutFile.close
files = os.listdir(".")
files.sort()
for file in files:
if (fnmatch.fnmatch(file, "*.h")):
parse(file)
+116
View File
@@ -0,0 +1,116 @@
General {
name = "%IRCD_GENERAL_NAME%";
description = "%IRCD_GENERAL_DESCRIPTION%";
numeric = %IRCD_GENERAL_NUMERIC%;
};
Features {
"LOG" = "SYSTEM" "FILE" "ircd.log";
"LOG" = "SYSTEM" "LEVEL" "CRIT";
};
Admin {
Location = "%IRCD_ADMIN_LOCATION%";
Contact = "%IRCD_ADMIN_CONTACT%";
};
Class {
name = "Server";
pingfreq = 1 minutes 30 seconds;
connectfreq = 5 minutes;
maxlinks = 1;
sendq = 9000000;
};
Class {
name = "LeafServer";
pingfreq = 1 minutes 30 seconds;
connectfreq = 5 minutes;
maxlinks = 0;
sendq = 9000000;
};
Class {
name = "Local";
pingfreq = 1 minutes 30 seconds;
maxlinks = 100;
sendq = 160000;
};
Class {
name = "Opers";
pingfreq = 90;
connectfreq = 0;
maxlinks = 100;
sendq = 160000;
whois_notice = no;
remove = no;
freeform = no;
hide_channels = no;
local_opmode = no;
force_local_opmode = no;
walk_lchan = no;
deop_lchan = no;
mode_lchan = no;
shun = no;
local_shun = no;
gline = no;
local_gline = no;
zline = no;
local_zline = no;
hide_idle = no;
xtraop = no;
snomask = 5645;
remote = yes;
};
Class {
name = "Users";
pingfreq = 1 minutes 30 seconds;
maxlinks = 4000;
sendq = 160000;
usermode = "x";
};
# This is an "I line" block. This one lets everyone in.
Client {
ip = "*";
host = "*";
# username = "*";
class = "Users";
};
Port {
port = 4497;
server = yes;
ssl = yes;
};
Port {
port = 16667;
};
Port {
port = 6667;
};
Port {
port = 7000;
};
Port {
port = 6697;
ssl = yes;
};
Port {
port = 9998;
ssl = yes;
};
# Do NOT remove the following lines; linesync.sh depends on them!
# BEGIN LINESYNC
# You need to get linesync running so the rest of the net's config will be appended after this.
# END LINESYNC
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
set -e
docker build -t rubinlinux/nefarious2:`git describe --long --always` -t rubinlinux/nefarious2:latest .
docker push rubinlinux/nefarious2:`git describe --long --always`
docker push rubinlinux/nefarious2:latest
+58
View File
@@ -0,0 +1,58 @@
#!/bin/bash
# Nefarious IRCd Docker Entrypoint
# Reads base.conf-dist, replaces all %VARIABLE% placeholders with environment
# variable values, and writes out base.conf
BASECONFDIST=/home/nefarious/ircd/base.conf-dist
BASECONF=/home/nefarious/ircd/base.conf
IRCDPEM=/home/nefarious/ircd/ircd.pem
# Set defaults for required variables (can be overridden by environment)
: "${IRCD_GENERAL_NAME:=localhost.localdomain}"
: "${IRCD_GENERAL_DESCRIPTION:=localhost.localdomain}"
: "${IRCD_ADMIN_LOCATION:=Somewhere}"
: "${IRCD_ADMIN_CONTACT:=root@localhost}"
: "${IRCD_GENERAL_NUMERIC:=1}"
# Copy the template to base.conf location
cp "$BASECONFDIST" "$BASECONF"
# Find all %VARIABLE% placeholders in the config and substitute them
# with corresponding environment variable values
grep -oE '%[A-Za-z_][A-Za-z0-9_]*%' "$BASECONF" | sort -u | while read -r placeholder; do
# Extract variable name (remove the % signs)
varname="${placeholder:1:-1}"
# Get the value from environment (indirect expansion)
value="${!varname}"
# Only substitute if the variable is set
if [ -n "$value" ]; then
# Escape special characters for sed (/, &, \)
escaped_value=$(printf '%s\n' "$value" | sed -e 's/[\/&]/\\&/g')
sed -i "s|${placeholder}|${escaped_value}|g" "$BASECONF"
else
echo "Warning: No value set for ${varname}, leaving ${placeholder} unchanged"
fi
done
echo "Generated $BASECONF from template"
#If cmd is the ircd...
if [ "$1" == "/home/nefarious/bin/ircd" ]; then
# Generate a pem file if there isnt one...
if [ ! -f /home/nefarious/ircd/ircd.pem ]; then
echo "Generating self signed ssl key for ircd.pem"
openssl req -new --x509 -days 365 -nodes -out ircd.pem -newkey rsa:4096 -keyout ircd.pem -subj "/CN=$IRCD_GENERAL_NAME/"
test 1 -eq 1 || test ! -f /dev/urandom || openssl gendh -rand $1/ircd.rand 512 >> $1/ircd.pem
test 1 -eq 1 || test -f /dev/urandom || openssl gendh 512 >> $1/ircd.pem
openssl x509 -subject -dates -fingerprint -noout -in $IRCDPEM
fi
fi
#Now run CMD from Dockerfile...
exec "$@"
+5
View File
@@ -0,0 +1,5 @@
include "base.conf";
include "ircd.conf";
include "linesync.conf";
View File
Whitespace-only changes.
+4
View File
@@ -0,0 +1,4 @@
# Do NOT remove the following lines; linesync.sh depends on them!
# BEGIN LINESYNC
# You need to get linesync running so the rest of the net's config will be appended after this.
# END LINESYNC
+92
View File
@@ -0,0 +1,92 @@
#!/usr/bin/perl
#
# hashtoy: a little script to read an ircu burst IP dump and try
# different hash formulae
# usage: hashtoy <filename> <tablesize> '<expression>'
# use x for the key and n for the table size
# example: hashtoy undernet-burst.txt 8192 '((x >> 14) + (x >> 7) + x) & 8191'
# notes: the input file is expected to contain one encoded IP address per
# line. see base64toint() and inttobase64() in ircd/s_user.c for
# details of the encoding.
#
# --Liandrin
#
# $Id: hashtoy,v 1.2 2002-03-07 22:52:57 ghostwolf Exp $
@convert2n = (
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0,
0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 62, 0, 63, 0, 0, 0, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
49, 50, 51
);
sub base64toint {
my $i = 0;
my $str = shift;
my @strc = ($str =~ /(.)/g);
$i = $convert2n[ord($strc[5])];
$i += $convert2n[ord($strc[4])] << 6;
$i += $convert2n[ord($strc[3])] << 12;
$i += $convert2n[ord($strc[2])] << 18;
$i += $convert2n[ord($strc[1])] << 24;
$i += $convert2n[ord($strc[0])] << 30;
}
sub ntohl {
my $i = shift;
my $j;
return (($i & 0xFF000000) >> 24) |
(($i & 0x00FF0000) >> 8) |
(($i & 0x0000FF00) << 8) |
(($i & 0x000000FF) << 24);
}
($file, $tablesize, $expression) = @ARGV;
while ($#ARGV > -1) { shift @ARGV; }
if (!defined($file) || !defined($tablesize) || !defined($expression)) {
print STDERR "usage: $0 filename tablesize expression\n";
print STDERR "sample expression: x % n\n";
exit 1;
}
$expression =~ s/\bx\b/\$ip/gi;
$expression =~ s/\bn\b/\$tablesize/gi;
$expression =~ s/^(.*)$/sub dohash { return ($1); }/;
$minkey = 2**32;
$maxkey = 0;
eval $expression;
open IPS, $file || die "Can't open $file at";
while (<IPS>) {
chomp;
$ip = base64toint($_);
$key = dohash($ip);
$minkey = $key if ($key < $minkey);
$maxkey = $key if ($key > $maxkey);
$testing{$key}++;
}
$max = 0;
$min = $tablesize + 1;
$nEntries = 0;
$total = 0;
for (values %testing) {
$max = $_ if ($_ > $max);
$min = $_ if ($_ < $min);
$nEntries++;
$total += $_;
}
print "Table size: $tablesize\n";
printf "Min/average/max chain length: $min/%.2f/$max\n", ($total / $nEntries);
print "Minimum key: $minkey\n";
print "Maximum key: $maxkey\n";
+254
View File
@@ -0,0 +1,254 @@
#! /usr/bin/perl
# iauth-test: test script for IRC authorization (iauth) protocol
# Copyright 2006 Michael Poole
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
require 5.008; # We assume deferred signal handlers, new in 5.008.
use strict;
use warnings;
use vars qw(%pending);
use Config; # for $Config{sig_name} and $Config{sig_num}
use FileHandle; # for autoflush method on file handles
# This script is intended to help test an implementation of the iauth
# protocol by exercising every command in the protocol and by
# exercising most distinct combinations of commands. It assumes IPv4
# support in the server and POSIX real-time signal support in the OS
# (recognized and supported by Perl).
# Certain behavior is triggered by receipt of real-time signals.
# SIGRTMIN + 0 -> Send server notice ('>').
# SIGRTMIN + 1 -> Toggle debug level ('G').
# SIGRTMIN + 2 -> Set policy options ('O').
# SIGRTMIN + 3 -> Simulate config change ('a', 'A').
# SIGRTMIN + 4 -> Simulate statistics change ('s', 'S').
# Note that Perl's value for SIGRTMIN may be different than your OS's.
# The easiest check is by running "perl -V:sig_num -V:sig_name".
# In the following discussion, sX means message X from the server, and
# iX means message X from iauth. The hard part is the ordering of
# various events during client registration. This includes sC, sP,
# sU, su, sn, sN/d, sH and sT; and o/U/u, iN, iI, iC and iD/R/k/K.
# sC is first, sD/sT/iD/R/k/K is last. If sH is sent, no more sU, su,
# sn, sN, sd or sH messages may be sent. If iI is sent, iN should
# also be sent (either before or after iI). Multiple sP, sU and iC
# messages may be sent. Otherwse, the ordering of unrelated messages
# from either source are not constrained, but only one message from
# each set of alternatives may be sent.
# This means the sets of commands with interesting orderings are:
# sU, su, io/U/u
# sN/d, iN, iI
# sH, sT or iD/R/k/K
# 127.x.y.z IP addresses are used to exercise these orderings; see the
# %handlers variable below.
sub dolog ($) {
print LOG "$_[0]\n";
}
sub reply ($;$$) {
my ($msg, $client, $extra) = @_;
if (not defined $msg) {
# Accept this for easier handling of client reply messages.
return;
} elsif (ref $msg eq '') {
$msg =~ s/^(.) ?/$1 $client->{id} $client->{ip} $client->{port} / if $client;
dolog "< $msg";
print "$msg\n";
} elsif (ref $msg eq 'ARRAY') {
grep { reply($_, $client, $extra); } @$msg;
} elsif (ref $msg eq 'CODE') {
&$msg($client, $extra);
} else {
die "Unknown reply message type.";
}
}
# Find the names of signals with values SIGRTMIN+1, +2, etc.
BEGIN {
my @sig_name;
my %sig_num;
sub populate_signals () {
die "No sigs?"
unless $Config{sig_name} and $Config{sig_num};
my @names = split ' ', $Config{sig_name};
@sig_num{@names} = split ' ', $Config{sig_num};
foreach (@names) { $sig_name[$sig_num{$_}] ||= $_; }
}
sub assign_signal_handlers() {
my $sigrtmin = $sig_num{RTMIN};
die "No realtime signals?"
unless $sigrtmin;
$SIG{$sig_name[$sigrtmin+0]} = \&send_server_notice;
$SIG{$sig_name[$sigrtmin+1]} = \&toggle_debug_level;
$SIG{$sig_name[$sigrtmin+2]} = \&set_policy_options;
$SIG{$sig_name[$sigrtmin+3]} = \&sim_config_changed;
$SIG{$sig_name[$sigrtmin+4]} = \&sim_stats_change;
}
}
BEGIN {
my $debug_level = 0;
my $max_debug_level = 2;
sub toggle_debug_level () {
if (++$debug_level > $max_debug_level) {
$debug_level = 0;
}
reply "G $debug_level";
}
}
BEGIN {
my %rotation = (
'' => 'AU',
'AU' => 'AURTW',
'AURTW' => '',
);
my $policy = '';
sub set_policy_options () {
$policy = $rotation{$policy};
reply "O $policy";
}
}
BEGIN {
my $generation = 0;
sub sim_config_changed () {
reply "a";
reply "A config $generation";
$generation++;
}
}
BEGIN {
my $generation = 0;
sub sim_stats_change () {
reply "s";
reply "S stats $generation";
$generation++;
}
}
sub send_server_notice () {
reply "> :Hello the server!";
}
my %handlers = (
# Default handliner: immediately report done.
'default' => { C_reply => 'D' },
# 127.0.0.x: various timings for iD/iR/ik/iK.
'127.0.0.1' => { C_reply => 'D' },
'127.0.0.2' => { C_reply => 'R account-1' },
'127.0.0.3' => { C_reply => 'k' },
'127.0.0.4' => { C_reply => 'K' },
'127.0.0.5' => { C_reply => 'D Specials' },
'127.0.0.6' => { C_reply => 'R account-1 Specials' },
'127.0.0.15' => { },
'127.0.0.16' => { H_reply => 'D' },
'127.0.0.17' => { H_reply => 'R account-2' },
'127.0.0.18' => { H_reply => 'k' },
'127.0.0.19' => { H_reply => 'K' },
'127.0.0.32' => { T_reply => 'D' },
'127.0.0.33' => { T_reply => 'R account-3' },
'127.0.0.34' => { T_reply => 'k' },
'127.0.0.35' => { T_reply => 'K' },
# 127.0.1.x: io/iU/iu/iM functionality.
'127.0.1.0' => { C_reply => 'o forced',
H_reply => 'D' },
'127.0.1.1' => { C_reply => 'U trusted',
H_reply => 'D' },
'127.0.1.2' => { C_reply => 'u untrusted',
H_reply => 'D' },
'127.0.1.3' => { C_reply => 'M +i',
H_reply => 'D' },
# 127.0.2.x: iI/iN functionality.
'127.0.2.0' => { C_reply => 'N iauth.assigned.host',
H_reply => 'D' },
'127.0.2.1' => { C_reply => \&ip_change },
'127.0.2.2' => { H_reply => \&host_change_and_done },
# 127.0.3.x: iC/sP functionality.
'127.0.3.0' => { C_reply => 'C :Please enter the password.',
P_reply => \&passwd_check },
);
sub handle_new_client ($$$$) {
my ($id, $ip, $port, $extra) = @_;
my $handler = $handlers{$ip} || $handlers{default};
my $client = { id => $id, ip => $ip, port => $port, handler => $handler };
# If we have any deferred reply handlers, we must save the client.
$pending{$id} = $client if grep /^[^C]_reply$/, keys %$handler;
reply $client->{handler}->{C_reply}, $client, $extra;
}
sub ip_change ($$) {
my ($client, $extra) = @_;
reply 'I 127.255.255.254', $client;
$client->{ip} = '127.255.255.254';
reply 'N other.assigned.host', $client;
reply 'D', $client;
}
# Note to potential debuggers: You will have to change the iauth
# policy before this (or any other H_reply hooks) will have any
# effect. Do this by sending two signals of $SIG{RTMIN+2} to the
# iauth-test process, as noted near the beginning of this script.
sub host_change_and_done ($$) {
my ($client, $extra) = @_;
reply 'N iauth.assigned.host', $client;
reply 'D', $client;
}
sub passwd_check ($$) {
my ($client, $extra) = @_;
if ($extra eq 'secret') {
reply 'D', $client;
} else {
reply 'C :Bad password', $client;
}
}
open LOG, ">> iauth.log";
populate_signals();
assign_signal_handlers();
autoflush LOG 1;
autoflush STDOUT 1;
autoflush STDERR 1;
dolog "IAuth starting " . scalar(localtime(time));
while (<>) {
my ($id, $client);
# Chomp newline and log incoming message.
s/\r?\n?\r?$//;
dolog "> $_";
# If there's an ID at the start of the line, parse it out.
if (s/^(\d+) //) { $id = $1; $client = $pending{$id}; }
# Figure out how to handle the command.
if (/^C (\S+) (\S+) (.+)$/) {
handle_new_client($id, $1, $2, $3);
} elsif (/^([DT])/ and $client) {
reply $client->{handler}->{"${1}_reply"}, $client;
delete $pending{$id};
} elsif (/^([d])/ and $client) {
reply $client->{handler}->{"${1}_reply"}, $client;
} elsif (/^([HNPUu]) (.+)/ and $client) {
reply $client->{handler}->{"${1}_reply"}, $client, $2;
}
}
+258
View File
@@ -0,0 +1,258 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
iauthd-ts is a TypeScript IAuth daemon for Nefarious IRCd. It performs real-time DNS blacklist (DNSBL) lookups on connecting IRC clients and can block, mark, whitelist, or assign connection classes based on results. It also handles SASL PLAIN authentication directly (without routing to services).
This is a port of the original Perl `iauthd.pl`. The only runtime dependency is `ldapts` for LDAP authentication support.
## Build & Development Commands
```bash
npm install # Install dependencies
npm run build # Compile TypeScript to dist/
npm run dev -- -c /path/to/config # Run directly from TypeScript (no compile)
npm test # Run all tests
npm run test:watch # Watch mode
npm run test:coverage # Coverage report
npm run stress # Memory stress test (5000 clients)
npm run stress -- --clients=10000 # Custom client count
```
## Running
```bash
node dist/index.js -c <configfile> [-v] [-d]
# -c, --config Config file to read (required)
# -v, --verbose Debug output in iauthd
# -d, --debug Debug output in IRCd
```
## Architecture
### Core Components
- **`src/index.ts`** - CLI entry point, parses args and starts daemon
- **`src/iauth.ts`** - Main `IAuthDaemon` class, handles IRCd communication via stdin/stdout using the IAuth protocol
- **`src/config.ts`** - Parses `#IAUTH` directives from config files
- **`src/dnsbl.ts`** - DNSBL lookup with caching, IP reversal utilities
- **`src/sasl.ts`** - SASL PLAIN decoding, password hashing utilities (SHA-256/512, MD5, bcrypt)
- **`src/types.ts`** - TypeScript interfaces for all data structures
### Authentication Module (`src/auth/`)
The auth module provides a modular, provider-based authentication system:
- **`src/auth/types.ts`** - AuthProvider interface and config types
- **`src/auth/manager.ts`** - AuthManager coordinates multiple providers with fallback chain
- **`src/auth/config.ts`** - Parses AUTH directive configuration
- **`src/auth/providers/file.ts`** - Static file-based authentication (wraps sasl.ts)
- **`src/auth/providers/ldap.ts`** - LDAP authentication with direct bind and search modes
- **`src/auth/providers/keycloak.ts`** - Keycloak authentication using ROPC grant
### IAuth Protocol Flow
The daemon communicates with Nefarious via stdin/stdout:
1. **Client connects** → IRCd sends `C <id> <ip> <port> <serverip> <serverport>`
2. **DNSBL lookups** → Started concurrently for all configured DNSBLs
3. **Results processed** → Check index/bitmask matches, apply marks/blocks/whitelist
4. **Hurry received** → IRCd sends `H <id> <class>` when registration timeout approaches
5. **Decision made** → Send `D` (accept), `k` (reject), or `m` (mark) back to IRCd
Key message handlers in `IAuthDaemon.handleLine()`:
- `C` - Client introduction, triggers DNSBL lookups
- `H` - Hurry, forces immediate decision
- `R` - Client authenticated via SASL/LOC (exempts from `block=anonymous`)
- `A`/`a` - SASL authentication start/continue
- `w` - Trusted WEBIRC, re-checks real IP
### DNSBL Matching
DNSBLs return `127.0.0.X` addresses where X indicates the listing reason:
- `index=2,3,4` - Match if X equals any listed value
- `bitmask=8` - Match if X AND bitmask is non-zero
- Neither specified - Any response is a match
### Caching
DNS results are cached globally in `dnsbl.ts`. Cache entries store:
- Query string (reversed IP + server)
- Result IPs or null (pending)
- Timestamp for expiration
### SASL Authentication
iauthd-ts handles SASL PLAIN authentication directly using a modular provider system:
1. IRCd sends `A <id> S :PLAIN`
2. iauthd responds with challenge `c <id> :+`
3. Client sends base64 credentials via `a <id> :<data>`
4. iauthd verifies against configured auth providers (file, LDAP, etc.)
5. Sends `L` (success) or `f` (fail) to IRCd
**Auth Provider Fallback**: When multiple providers are configured, they are tried in priority order (lower = first). First successful authentication wins.
Password formats for file provider: `$5$salt$hash` (SHA-256), `$6$salt$hash` (SHA-512), `$1$salt$hash` (MD5), `$2a$` or `$2b$` (bcrypt)
## Testing
Tests use Vitest with mocked DNS resolution:
- **`tests/config.test.ts`** - Configuration parsing
- **`tests/dnsbl.test.ts`** - IP functions, caching, matching
- **`tests/dnsbl-integration.test.ts`** - Full DNSBL pipeline with mock DNS
- **`tests/iauth.test.ts`** - Protocol integration tests
- **`tests/sasl.test.ts`** - SASL authentication utilities
- **`tests/auth/config.test.ts`** - AUTH directive parsing
- **`tests/auth/file.test.ts`** - FileAuthProvider tests
- **`tests/auth/manager.test.ts`** - AuthManager fallback behavior
- **`tests/auth/keycloak.test.ts`** - KeycloakAuthProvider tests
- **`tests/stress.ts`** - Memory stress test (not a vitest file)
Run a single test file:
```bash
npx vitest run tests/dnsbl.test.ts
npx vitest run tests/config.test.ts -t "parses DNSBL" # Run matching tests
```
## Configuration
Configuration uses `#IAUTH` directives embedded in ircd.conf (IRCd ignores lines starting with `#`):
```
#IAUTH POLICY RTAWUwFrS
#IAUTH DNSTIMEOUT 5
#IAUTH CACHETIME 86400
#IAUTH BLOCKMSG Your connection has been rejected
#IAUTH DNSBL server=dnsbl.dronebl.org index=2,3,5 mark=dronebl block=anonymous
#IAUTH DNSBL server=whitelist.example.com whitelist
```
### Authentication Providers
Use `#IAUTH AUTH` to configure authentication backends. Multiple providers can be configured; they are tried in priority order (lower = first).
#### Static File Provider
```
#IAUTH SASLDB /path/to/users # Legacy format (still supported)
#IAUTH AUTH provider=file path=/path/to/users # Explicit format
#IAUTH AUTH provider=file path=/path/to/users priority=50
```
#### LDAP Direct Bind Mode
> **Note**: LDAP support has not yet been tested against real LDAP servers. Use with caution and please report any issues.
User binds directly with their credentials using a DN template:
```
#IAUTH AUTH provider=ldap uri=ldap://ldap.example.com:389 mode=direct userdn=uid=%s,ou=users,dc=example,dc=com
```
#### LDAP Search Mode (Admin Bind + Search)
Binds as admin, searches for user, optionally checks group membership, then binds as user:
```
#IAUTH AUTH provider=ldap uri=ldaps://ldap.example.com:636 mode=search basedn=ou=users,dc=example,dc=com binddn=cn=admin,dc=example,dc=com bindpass=secret userfilter=(uid=%s)
# With group membership check:
#IAUTH AUTH provider=ldap uri=ldaps://ldap.example.com:636 mode=search basedn=ou=users,dc=example,dc=com binddn=cn=admin,dc=example,dc=com bindpass=secret userfilter=(uid=%s) groupdn=cn=ircusers,ou=groups,dc=example,dc=com
```
#### LDAP Configuration Options
| Option | Required | Mode | Description |
|--------|----------|------|-------------|
| `uri` | Yes | Both | LDAP server URI (`ldap://` or `ldaps://`) |
| `mode` | Yes | Both | `direct` or `search` |
| `userdn` | Yes | direct | DN template with `%s` for username |
| `basedn` | Yes | search | Base DN for user search |
| `binddn` | Yes | search | Admin bind DN |
| `bindpass` | Yes | search | Admin bind password |
| `userfilter` | Yes | search | Search filter with `%s` for username |
| `groupdn` | No | search | Group DN for membership check |
| `accountattr` | No | Both | Attribute to use as account name (default: uid/sAMAccountName) |
| `timeout` | No | Both | Connection timeout in ms (default: 5000) |
| `priority` | No | Both | Provider priority (default: 100, lower = first) |
#### Keycloak Provider
Uses Resource Owner Password Credentials (ROPC) grant to authenticate users against Keycloak. The client must have "Direct Access Grants" enabled in Keycloak.
```
#IAUTH AUTH provider=keycloak url=https://keycloak.example.com realm=myrealm clientid=irc-client
# With client secret (for confidential clients):
#IAUTH AUTH provider=keycloak url=https://keycloak.example.com realm=myrealm clientid=irc-client clientsecret=your-secret
# With custom account attribute:
#IAUTH AUTH provider=keycloak url=https://keycloak.example.com realm=myrealm clientid=irc-client accountattr=irc_nick
```
#### Keycloak Configuration Options
| Option | Required | Description |
|--------|----------|-------------|
| `url` | Yes | Keycloak server URL (e.g., `https://keycloak.example.com`) |
| `realm` | Yes | Keycloak realm name |
| `clientid` | Yes | OAuth2 client ID (must have Direct Access Grants enabled) |
| `clientsecret` | No | Client secret (for confidential clients) |
| `accountattr` | No | JWT claim to use as account name (default: `preferred_username`) |
| `timeout` | No | Request timeout in ms (default: 5000) |
| `priority` | No | Provider priority (default: 100, lower = first) |
#### Keycloak Server Setup
To configure Keycloak for IRC SASL authentication:
**1. Create a Realm**
- Go to Keycloak Admin Console
- Create a new realm (e.g., `irc` or `testnet`)
**2. Create a Client**
- Go to **Clients** → **Create client**
- **Client ID**: `irc-client` (or your preferred name)
- **Client Protocol**: `OpenID Connect` (not SAML)
- Click **Next**
- **Client authentication**: `OFF` (for public client) or `ON` if using `clientsecret`
- **Direct access grants**: `ON` ← **Critical for ROPC authentication**
- Click **Save**
**3. Configure User Profile (Optional but Recommended)**
- Go to **Realm Settings** → **User profile**
- Click on `firstName` → set "Required field" to `OFF` → Save
- Click on `lastName` → set "Required field" to `OFF` → Save
- This prevents "Account is not fully set up" errors for users without names
**4. Configure Authentication Flows (Optional)**
- Go to **Authentication** → **Flows** → select **direct grant**
- Ensure no required actions block password auth (e.g., set Conditional OTP to `DISABLED` if not using 2FA)
**5. Create Users**
- Go to **Users** → **Add user**
- Set username, email (if required)
- Go to **Credentials** tab → **Set password**
- **Important**: Set **Temporary** to `OFF` to avoid forced password change
- Ensure **Required user actions** is empty (no "Update Password", "Configure OTP", etc.)
**Common Issues**
- `"Account is not fully set up"` - User has pending required actions (check user's Required Actions field, or realm-level User Profile requirements)
- `"Wrong client protocol"` - Client is configured as SAML instead of OpenID Connect
- `"unauthorized_client"` - Direct Access Grants is not enabled on the client
- Connection errors - Use `http://` for dev mode (`start-dev`), `https://` for production
**Testing Authentication**
```bash
curl -s -X POST "http://localhost:8080/realms/REALM/protocol/openid-connect/token" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=password&client_id=CLIENT_ID&username=USER&password=PASS"
```
A successful response returns an `access_token`. Error responses include `error` and `error_description` fields.
### Password Hashes
Generate password hashes for the file provider:
```bash
npx tsx src/genhash.ts mypassword sha256
```
+477
View File
@@ -0,0 +1,477 @@
# iauthd-ts
A TypeScript implementation of an IAuth daemon for Nefarious IRCd. This daemon performs real-time DNS-based blacklist (DNSBL) lookups on connecting clients and can block, mark, or whitelist users based on the results.
This is a port of the original Perl `iauthd.pl` to TypeScript/Node.js.
## Features
- **DNSBL Lookups**: Check connecting clients against multiple DNS blacklists
- **Flexible Matching**: Match by index value or bitmask
- **Caching**: DNS results are cached to reduce lookup overhead
- **SASL Authentication**: Handle SASL PLAIN authentication directly in IAuth (no services required)
- **SASL/LOC Support**: Exempt authenticated users from blocks
- **WEBIRC Support**: Re-check real IP for trusted proxy connections
- **Marking**: Tag users with marks visible to operators
- **Class Assignment**: Assign users to connection classes based on DNSBL results
- **Whitelisting**: Exempt users matching certain DNSBLs from all blocks
## How It Works
```
┌─────────────┐ stdin/stdout ┌─────────────┐
│ Nefarious │ ◄──────────────────► │ iauthd-ts │
│ IRCd │ IAuth Protocol │ │
└─────────────┘ └──────┬──────┘
│
│ DNS queries
▼
┌─────────────┐
│ DNSBL │
│ Servers │
└─────────────┘
```
1. **Client Connects**: IRCd sends client info to iauthd-ts via the IAuth protocol
2. **DNSBL Lookup**: iauthd-ts reverses the client IP and queries configured DNSBLs
3. **Result Processing**: Responses are checked against configured index/bitmask rules
4. **Decision**: Client is accepted (with optional marks/class) or rejected
5. **Response**: iauthd-ts sends the decision back to IRCd
### IAuth Protocol
iauthd-ts communicates with Nefarious via stdin/stdout using the IAuth protocol:
| Direction | Message | Description |
|-----------|---------|-------------|
| IRCd → iauthd | `C <id> <ip> <port> <serverip> <serverport>` | Client introduction |
| IRCd → iauthd | `H <id> <class>` | Hurry up (registration timeout approaching) |
| IRCd → iauthd | `R <id> <account>` | Client authenticated via SASL/LOC |
| IRCd → iauthd | `D <id>` | Client disconnected |
| iauthd → IRCd | `D <id> <ip> <port> [class]` | Accept client |
| iauthd → IRCd | `k <id> <ip> <port> :<reason>` | Reject client |
| iauthd → IRCd | `m <id> <ip> <port> MARK <data>` | Mark client |
| IRCd → iauthd | `A <id> <ip> <port> S <mechanism> [:<certfp>]` | SASL auth start |
| IRCd → iauthd | `A <id> <ip> <port> H :<user@host:ip>` | SASL host info |
| IRCd → iauthd | `a <id> <ip> <port> :<data>` | SASL auth data |
| iauthd → IRCd | `c <id> <ip> <port> :<challenge>` | SASL challenge |
| iauthd → IRCd | `L <id> <ip> <port> <account>` | SASL login success |
| iauthd → IRCd | `f <id> <ip> <port>` | SASL auth failed |
| iauthd → IRCd | `l <id> <ip> <port> :<mechanisms>` | SASL mechanism list |
| iauthd → IRCd | `Z <id> <ip> <port>` | SASL auth complete |
## Requirements
- Node.js 18 or later
- npm
## Installation
### From Source
```bash
cd tools/iauthd-ts
npm install
npm run build
```
### Docker
iauthd-ts is automatically built as part of the Nefarious Docker image. The compiled files are located at `/home/nefarious/ircd/iauthd-ts/`.
## Configuration
iauthd-ts reads configuration from `#IAUTH` directives in the config file. These can be embedded in your `ircd.conf` since IRCd ignores lines starting with `#`.
### Directives
#### POLICY
```
#IAUTH POLICY RTAWUwFr
```
Sets the IAuth policy flags. See `doc/readme.iauth` for details.
#### DNSTIMEOUT
```
#IAUTH DNSTIMEOUT 5
```
Seconds to wait for DNSBL lookups. Default: 5
#### CACHETIME
```
#IAUTH CACHETIME 86400
```
Seconds to cache DNSBL results. Default: 86400 (24 hours)
#### BLOCKMSG
```
#IAUTH BLOCKMSG Sorry! Your connection has been rejected due to poor reputation.
```
Message shown to blocked users.
#### DEBUG
```
#IAUTH DEBUG
```
Enable debug output.
#### SASLDB
```
#IAUTH SASLDB /path/to/users
```
Path to the SASL users file. When set, iauthd-ts will handle SASL PLAIN authentication directly instead of routing to services. The policy must include 'S' for this to work.
#### SASLFAILMSG
```
#IAUTH SASLFAILMSG Authentication failed
```
Message shown when SASL authentication fails.
#### DNSBL
```
#IAUTH DNSBL server=<server> [options...]
```
Options:
| Option | Description |
|--------|-------------|
| `server=<host>` | DNSBL server hostname (required) |
| `index=<n,n,...>` | Match if response equals any of these values |
| `bitmask=<n>` | Match if response AND bitmask is non-zero |
| `mark=<tag>` | Apply this mark to matching clients |
| `block=all` | Block all matching clients |
| `block=anonymous` | Block matching clients unless SASL authenticated |
| `class=<name>` | Assign matching clients to this connection class |
| `whitelist` | Matching clients are exempt from all blocks |
| `cachetime=<n>` | Override cache time for this DNSBL |
### Example Configuration
```
# IAuth Configuration
#IAUTH POLICY RTAWUwFr
#IAUTH CACHETIME 86400
#IAUTH DNSTIMEOUT 5
#IAUTH BLOCKMSG Sorry! Your connection has been rejected due to poor reputation.
# Block open proxies and drones (unless authenticated)
#IAUTH DNSBL server=dnsbl.dronebl.org index=2,3,5,6,7,8,9,10,13,14,15 mark=dronebl block=anonymous
# Mark Tor exit nodes but don't block
#IAUTH DNSBL server=rbl.efnetrbl.org index=4 mark=tor
# Block other bad actors
#IAUTH DNSBL server=rbl.efnetrbl.org index=1,2,3,5 mark=efnetrbl block=anonymous
# Whitelist from a private DNSBL
#IAUTH DNSBL server=whitelist.example.com whitelist cachetime=3600
```
### SASL Authentication Configuration
To enable SASL authentication handling in iauthd-ts (instead of routing to services):
1. **Create a users file** (`users` or any path you prefer):
```
# Format: username:passwordhash
# Use genhash.ts to create hashes
admin:$5$salt$hashedpassword
user1:$6$salt$hashedpassword
```
2. **Generate password hashes**:
```bash
npx tsx src/genhash.ts mypassword sha256
# Output: $5$randomsalt$hashedpasswordvalue
```
3. **Configure iauthd-ts**:
```
#IAUTH POLICY RTAWUwFrS
#IAUTH SASLDB /path/to/users
#IAUTH SASLFAILMSG Invalid username or password
```
The `S` in the policy enables SASL handling.
4. **Supported hash formats**:
- `$5$salt$hash` - SHA-256 (recommended)
- `$6$salt$hash` - SHA-512
- `$1$salt$hash` - MD5 (legacy)
- Plain text (for testing only)
The users file is automatically reloaded when modified (checked on each SASL attempt).
### Modular Authentication Providers
iauthd-ts supports a modular authentication system with multiple backends. Providers are tried in priority order (lower number = tried first) until one succeeds.
#### AUTH Directive
```
#IAUTH AUTH provider=<type> [options...]
```
#### File Provider
Uses a static users file (same as SASLDB but with explicit provider syntax):
```
#IAUTH AUTH provider=file path=/path/to/users priority=50
```
#### LDAP Provider
> **Note**: LDAP support has not yet been tested with real LDAP servers. Please report any issues.
Two modes are supported:
**Direct Bind Mode** - Binds directly as the user:
```
#IAUTH AUTH provider=ldap uri=ldap://ldap.example.com:389 mode=direct userdn=uid=%s,ou=users,dc=example,dc=com
```
**Search Mode** - Admin bind, search for user, then bind as user:
```
#IAUTH AUTH provider=ldap uri=ldaps://ldap.example.com:636 mode=search basedn=ou=users,dc=example,dc=com binddn=cn=admin,dc=example,dc=com bindpass=secret userfilter=(uid=%s) groupdn=cn=ircusers,ou=groups,dc=example,dc=com
```
LDAP Options:
| Option | Required | Mode | Description |
|--------|----------|------|-------------|
| `uri` | Yes | Both | LDAP server URI (ldap:// or ldaps://) |
| `mode` | Yes | Both | `direct` or `search` |
| `userdn` | Yes | direct | DN template with `%s` for username |
| `basedn` | Yes | search | Base DN for user search |
| `binddn` | Yes | search | Admin bind DN |
| `bindpass` | Yes | search | Admin bind password |
| `userfilter` | Yes | search | Search filter with `%s` for username |
| `groupdn` | No | search | Group DN for membership check |
| `accountattr` | No | Both | Attribute to use as account name |
| `timeout` | No | Both | Connection timeout in ms (default: 5000) |
| `priority` | No | Both | Provider priority (default: 100) |
#### Keycloak Provider
Authenticates via Keycloak using Resource Owner Password Credentials (ROPC) grant:
```
#IAUTH AUTH provider=keycloak url=https://keycloak.example.com realm=myrealm clientid=irc-client
```
With client secret (for confidential clients):
```
#IAUTH AUTH provider=keycloak url=https://keycloak.example.com realm=myrealm clientid=irc-client clientsecret=mysecret
```
Keycloak Options:
| Option | Required | Description |
|--------|----------|-------------|
| `url` | Yes | Keycloak server URL |
| `realm` | Yes | Realm name |
| `clientid` | Yes | Client ID |
| `clientsecret` | No | Client secret (for confidential clients) |
| `accountattr` | No | JWT claim to use as account name (default: preferred_username) |
| `timeout` | No | Request timeout in ms (default: 5000) |
| `priority` | No | Provider priority (default: 100) |
#### Multiple Providers (Fallback Chain)
Configure multiple providers with different priorities. Lower priority = tried first:
```
#IAUTH AUTH provider=ldap uri=ldaps://ldap.example.com mode=direct userdn=uid=%s,ou=users,dc=example,dc=com priority=10
#IAUTH AUTH provider=keycloak url=https://keycloak.example.com realm=irc clientid=irc-client priority=20
#IAUTH AUTH provider=file path=/path/to/local-users priority=100
```
## Usage
### Command Line
```bash
node dist/index.js -c <configfile> [-v] [-d]
Options:
-c, --config Config file to read (required)
-v, --verbose Enable verbose output in iauthd
-d, --debug Enable debug output in IRCd
-h, --help Show help
```
### IRCd Configuration
Add to your `ircd.conf`:
```
IAuth {
program = "node" "/path/to/iauthd-ts/dist/index.js" "-v" "-c" "/path/to/ircd.conf";
};
```
For Docker deployments:
```
IAuth {
program = "node" "/home/nefarious/ircd/iauthd-ts/index.js" "-v" "-c" "/home/nefarious/ircd/ircd.conf";
};
```
### Monitoring
To see IAuth debug messages as an operator:
```
/quote mode YourNick +s 262144
```
### Statistics
IAuth statistics are available via `/stats iauth` and include:
- Uptime
- Cache size
- Total passed/rejected clients
- Per-DNSBL hit counts
## Development
### Project Structure
```
iauthd-ts/
├── src/
│ ├── index.ts # CLI entry point
│ ├── iauth.ts # Main IAuth daemon class
│ ├── config.ts # Configuration parser
│ ├── dnsbl.ts # DNSBL lookup and caching
│ ├── sasl.ts # SASL authentication handling
│ ├── genhash.ts # Password hash generator utility
│ └── types.ts # TypeScript interfaces
├── users.example # Example SASL users file
├── tests/
│ ├── config.test.ts # Config parser tests
│ ├── dnsbl.test.ts # DNSBL function tests
│ ├── iauth.test.ts # Integration tests
│ └── stress.ts # Memory stress test
├── dist/ # Compiled JavaScript (after build)
├── package.json
├── tsconfig.json
└── vitest.config.ts
```
### Building
```bash
npm install # Install dependencies
npm run build # Compile TypeScript to dist/
```
### Running Tests
```bash
npm test # Run all tests
npm run test:watch # Watch mode (re-run on changes)
npm run test:coverage # Generate coverage report
```
### Test Coverage
The test suite includes:
- **Unit tests** (45 tests): Config parsing, IP handling, DNSBL matching, caching
- **Protocol integration tests** (17 tests): IAuth protocol simulation
- **DNSBL integration tests** (32 tests): Full pipeline with mocked DNS responses
#### DNSBL Integration Tests
The DNSBL integration tests (`tests/dnsbl-integration.test.ts`) use a mock DNS resolver to test realistic scenarios:
| Category | Tests |
|----------|-------|
| Index matching | Exact match, multiple indices, no match, NXDOMAIN |
| Bitmask matching | Single bit, multiple bits, no bits match |
| block=all | Blocks both anonymous and authenticated |
| block=anonymous | Blocks anonymous, allows SASL-authenticated |
| Mark only | Accepts client but applies mark |
| Whitelist | Overrides subsequent blocking DNSBLs |
| Multiple DNSBLs | Accumulates marks, any block triggers rejection |
| Same server/different indices | AfterNET pattern (whitelist=2, rbl=250, cloud=251) |
| Class assignment | Assigns connection class from matching DNSBL |
| Real-world simulation | Full AfterNET production config scenarios |
### Stress Testing
The stress test simulates thousands of concurrent connections to verify:
- Memory stability (no leaks in client tracking)
- Cache behavior
- Performance under load
```bash
npm run stress # Default: 5000 clients, 120s max
npm run stress -- --clients=10000 # More clients
npm run stress -- --duration=60 # Shorter duration
npm run stress -- -v # Verbose output
```
Example output:
```
============================================================
iauthd-ts Memory Stress Test
============================================================
Clients to simulate: 5000
Max concurrent: 100
Max duration: 120s
============================================================
Sent: 5000 | Accepted: 4994 | Rejected: 6 | Active: 0 | Cache: 5000 | Rate: 520.3/s
============================================================
STRESS TEST RESULTS
============================================================
Total clients sent: 5000
Total clients accepted: 4994
Total clients rejected: 6
Unprocessed clients: 0
Total time: 9.61s
Average rate: 520.29 clients/s
MEMORY ANALYSIS
------------------------------------------------------------
✅ Memory usage appears stable.
✅ All clients were processed correctly.
============================================================
```
### Development Mode
Run directly from TypeScript without compiling:
```bash
npm run dev -- -c /path/to/config
```
## Comparison with iauthd.pl
| Feature | iauthd.pl (Perl) | iauthd-ts (TypeScript) |
|---------|------------------|------------------------|
| Runtime | Perl + POE | Node.js |
| Async Model | POE event loop | Native async/await |
| Type Safety | None | Full TypeScript types |
| Testing | None | 62 tests + stress test |
| Dependencies | 5 CPAN modules | 0 runtime deps |
## Troubleshooting
### iauthd-ts not starting
- Check that Node.js 18+ is installed: `node --version`
- Verify config file path is correct and readable
- Check for syntax errors in `#IAUTH` directives
### Clients timing out
- Increase `DNSTIMEOUT` if DNSBL servers are slow
- Check network connectivity to DNSBL servers
- Verify DNS resolution is working: `host 2.0.0.127.dnsbl.example.com`
### High memory usage
- Reduce `CACHETIME` to expire entries sooner
- Monitor with stress test: `npm run stress`
- Check for many unique IPs (each gets cached)
### Debug output
Run with `-v` flag and set operator snomask:
```
/quote mode YourNick +s 262144
```
## License
GPL-2.0 - Same as Nefarious IRCd
+2062
View File
File diff suppressed because it is too large. Load diff
+35
View File
@@ -0,0 +1,35 @@
{
"name": "iauthd-ts",
"version": "1.0.0",
"description": "IAuth daemon for Nefarious IRCd - TypeScript port",
"main": "dist/index.js",
"type": "module",
"scripts": {
"build": "tsc",
"start": "node dist/index.js",
"dev": "tsx src/index.ts",
"test": "vitest run",
"test:watch": "vitest",
"test:coverage": "vitest run --coverage",
"stress": "tsx tests/stress.ts"
},
"keywords": [
"irc",
"iauth",
"dnsbl",
"nefarious"
],
"license": "GPL-2.0",
"devDependencies": {
"@types/node": "^20.10.0",
"tsx": "^4.6.0",
"typescript": "^5.3.0",
"vitest": "^2.1.0"
},
"engines": {
"node": ">=18.0.0"
},
"dependencies": {
"ldapts": "^7.2.1"
}
}
+185
View File
@@ -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
};
}
+25
View File
@@ -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';
+173
View File
@@ -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;
}
}
+363
View File
@@ -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;
}
}
+144
View File
@@ -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';
}
+145
View File
@@ -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 };
}
+147
View File
@@ -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],
};
}
+40
View File
@@ -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);
+834
View File
@@ -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(',')}`);
}
}
}
+130
View File
@@ -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();
+264
View File
@@ -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'];
}
+132
View File
@@ -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;
}
+204
View File
@@ -0,0 +1,204 @@
/**
* Tests for auth configuration parsing
*/
import { describe, it, expect } from 'vitest';
import { parseAuthConfig, convertSASLDB } from '../../src/auth/config.js';
describe('Auth Config Parsing', () => {
describe('parseAuthConfig', () => {
it('should return null if provider is missing', () => {
const result = parseAuthConfig('path=/etc/users');
expect(result).toBeNull();
});
it('should parse file provider config', () => {
const result = parseAuthConfig('provider=file path=/etc/iauth/users');
expect(result).toEqual({
provider: 'file',
path: '/etc/iauth/users',
priority: undefined,
});
});
it('should parse file provider with priority', () => {
const result = parseAuthConfig('provider=file path=/etc/users priority=50');
expect(result).toEqual({
provider: 'file',
path: '/etc/users',
priority: 50,
});
});
it('should return null for file provider without path', () => {
const result = parseAuthConfig('provider=file');
expect(result).toBeNull();
});
it('should parse LDAP direct bind config', () => {
const result = parseAuthConfig(
'provider=ldap uri=ldap://ldap.example.com:389 mode=direct userdn=uid=%s,ou=users,dc=example,dc=com'
);
expect(result).toEqual({
provider: 'ldap',
uri: 'ldap://ldap.example.com:389',
mode: 'direct',
userdn: 'uid=%s,ou=users,dc=example,dc=com',
priority: undefined,
timeout: undefined,
accountattr: undefined,
});
});
it('should parse LDAP search mode config', () => {
const result = parseAuthConfig(
'provider=ldap uri=ldaps://ldap.example.com:636 mode=search ' +
'basedn=ou=users,dc=example,dc=com ' +
'binddn=cn=admin,dc=example,dc=com ' +
'bindpass=secret ' +
'userfilter=(uid=%s)'
);
expect(result).toEqual({
provider: 'ldap',
uri: 'ldaps://ldap.example.com:636',
mode: 'search',
basedn: 'ou=users,dc=example,dc=com',
binddn: 'cn=admin,dc=example,dc=com',
bindpass: 'secret',
userfilter: '(uid=%s)',
groupdn: undefined,
priority: undefined,
timeout: undefined,
accountattr: undefined,
});
});
it('should parse LDAP config with groupdn', () => {
const result = parseAuthConfig(
'provider=ldap uri=ldaps://ldap.example.com mode=search ' +
'basedn=ou=users,dc=example,dc=com ' +
'binddn=cn=admin,dc=example,dc=com ' +
'bindpass=secret ' +
'userfilter=(uid=%s) ' +
'groupdn=cn=ircusers,ou=groups,dc=example,dc=com'
);
expect(result?.provider).toBe('ldap');
if (result?.provider === 'ldap') {
expect(result.groupdn).toBe('cn=ircusers,ou=groups,dc=example,dc=com');
}
});
it('should parse LDAP config with timeout and priority', () => {
const result = parseAuthConfig(
'provider=ldap uri=ldap://server mode=direct userdn=uid=%s,dc=test timeout=10000 priority=25'
);
expect(result?.provider).toBe('ldap');
if (result?.provider === 'ldap') {
expect(result.timeout).toBe(10000);
expect(result.priority).toBe(25);
}
});
it('should return null for LDAP without uri', () => {
const result = parseAuthConfig('provider=ldap mode=direct');
expect(result).toBeNull();
});
it('should return null for LDAP without mode', () => {
const result = parseAuthConfig('provider=ldap uri=ldap://server');
expect(result).toBeNull();
});
it('should return null for unknown provider', () => {
const result = parseAuthConfig('provider=unknown');
expect(result).toBeNull();
});
it('should handle quoted values with spaces', () => {
const result = parseAuthConfig('provider=file path="/path/with spaces/users"');
expect(result).toEqual({
provider: 'file',
path: '/path/with spaces/users',
priority: undefined,
});
});
it('should handle single-quoted values', () => {
const result = parseAuthConfig("provider=file path='/path/with spaces/users'");
expect(result).toEqual({
provider: 'file',
path: '/path/with spaces/users',
priority: undefined,
});
});
it('should parse Keycloak config', () => {
const result = parseAuthConfig(
'provider=keycloak url=https://keycloak.example.com realm=myrealm clientid=irc-client'
);
expect(result).toEqual({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'myrealm',
clientid: 'irc-client',
clientsecret: undefined,
accountattr: undefined,
timeout: undefined,
priority: undefined,
});
});
it('should parse Keycloak config with clientsecret', () => {
const result = parseAuthConfig(
'provider=keycloak url=https://keycloak.example.com realm=myrealm clientid=irc-client clientsecret=mysecret'
);
expect(result?.provider).toBe('keycloak');
if (result?.provider === 'keycloak') {
expect(result.clientsecret).toBe('mysecret');
}
});
it('should parse Keycloak config with all options', () => {
const result = parseAuthConfig(
'provider=keycloak url=https://keycloak.example.com realm=myrealm clientid=irc-client ' +
'clientsecret=mysecret accountattr=irc_nick timeout=10000 priority=25'
);
expect(result?.provider).toBe('keycloak');
if (result?.provider === 'keycloak') {
expect(result.url).toBe('https://keycloak.example.com');
expect(result.realm).toBe('myrealm');
expect(result.clientid).toBe('irc-client');
expect(result.clientsecret).toBe('mysecret');
expect(result.accountattr).toBe('irc_nick');
expect(result.timeout).toBe(10000);
expect(result.priority).toBe(25);
}
});
it('should return null for Keycloak without url', () => {
const result = parseAuthConfig('provider=keycloak realm=test clientid=test');
expect(result).toBeNull();
});
it('should return null for Keycloak without realm', () => {
const result = parseAuthConfig('provider=keycloak url=https://kc.example.com clientid=test');
expect(result).toBeNull();
});
it('should return null for Keycloak without clientid', () => {
const result = parseAuthConfig('provider=keycloak url=https://kc.example.com realm=test');
expect(result).toBeNull();
});
});
describe('convertSASLDB', () => {
it('should convert SASLDB path to file provider config', () => {
const result = convertSASLDB('/etc/iauth/users');
expect(result).toEqual({
provider: 'file',
path: '/etc/iauth/users',
priority: 100,
});
});
});
});
+184
View File
@@ -0,0 +1,184 @@
/**
* Tests for FileAuthProvider
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { writeFileSync, unlinkSync, mkdtempSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { FileAuthProvider } from '../../src/auth/providers/file.js';
import { generateHash } from '../../src/sasl.js';
describe('FileAuthProvider', () => {
let tempDir: string;
let usersFile: string;
beforeEach(() => {
tempDir = mkdtempSync(join(tmpdir(), 'iauthd-test-'));
usersFile = join(tempDir, 'users');
});
afterEach(() => {
try {
unlinkSync(usersFile);
} catch {
// Ignore if file doesn't exist
}
});
describe('initialization', () => {
it('should initialize with empty users file', async () => {
writeFileSync(usersFile, '');
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
await provider.initialize();
expect(provider.isHealthy()).toBe(true);
expect(provider.getUserCount()).toBe(0);
});
it('should initialize with non-existent file', async () => {
const provider = new FileAuthProvider({
provider: 'file',
path: '/nonexistent/path/users',
});
await provider.initialize();
expect(provider.isHealthy()).toBe(true);
expect(provider.getUserCount()).toBe(0);
});
it('should load users from file', async () => {
writeFileSync(usersFile, 'testuser:plainpassword\nadmin:adminpass\n');
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
await provider.initialize();
expect(provider.isHealthy()).toBe(true);
expect(provider.getUserCount()).toBe(2);
});
it('should use default priority of 100', async () => {
writeFileSync(usersFile, '');
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
expect(provider.priority).toBe(100);
});
it('should use custom priority', async () => {
writeFileSync(usersFile, '');
const provider = new FileAuthProvider({
provider: 'file',
path: usersFile,
priority: 50,
});
expect(provider.priority).toBe(50);
});
});
describe('authentication', () => {
it('should authenticate valid user with plain password', async () => {
writeFileSync(usersFile, 'testuser:testpass\n');
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
await provider.initialize();
const result = await provider.authenticate('testuser', 'testpass');
expect(result.success).toBe(true);
expect(result.account).toBe('testuser');
});
it('should authenticate with SHA-256 hash', async () => {
const hash = generateHash('secretpass', 'sha256');
writeFileSync(usersFile, `testuser:${hash}\n`);
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
await provider.initialize();
const result = await provider.authenticate('testuser', 'secretpass');
expect(result.success).toBe(true);
expect(result.account).toBe('testuser');
});
it('should authenticate with SHA-512 hash', async () => {
const hash = generateHash('secretpass', 'sha512');
writeFileSync(usersFile, `testuser:${hash}\n`);
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
await provider.initialize();
const result = await provider.authenticate('testuser', 'secretpass');
expect(result.success).toBe(true);
expect(result.account).toBe('testuser');
});
it('should reject invalid password', async () => {
writeFileSync(usersFile, 'testuser:correctpass\n');
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
await provider.initialize();
const result = await provider.authenticate('testuser', 'wrongpass');
expect(result.success).toBe(false);
expect(result.error).toBe('Invalid credentials');
});
it('should reject unknown user', async () => {
writeFileSync(usersFile, 'testuser:testpass\n');
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
await provider.initialize();
const result = await provider.authenticate('unknownuser', 'testpass');
expect(result.success).toBe(false);
});
it('should be case-insensitive for usernames', async () => {
writeFileSync(usersFile, 'TestUser:testpass\n');
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
await provider.initialize();
const result = await provider.authenticate('TESTUSER', 'testpass');
expect(result.success).toBe(true);
});
it('should return error if not initialized', async () => {
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
// Don't call initialize
const result = await provider.authenticate('testuser', 'testpass');
expect(result.success).toBe(false);
expect(result.error).toBe('Users database not loaded');
});
});
describe('reload', () => {
it('should reload users file', async () => {
writeFileSync(usersFile, 'user1:pass1\n');
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
await provider.initialize();
expect(provider.getUserCount()).toBe(1);
// Modify file
writeFileSync(usersFile, 'user1:pass1\nuser2:pass2\n');
await provider.reload();
expect(provider.getUserCount()).toBe(2);
});
it('should detect file modifications during auth', async () => {
writeFileSync(usersFile, 'user1:pass1\n');
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
await provider.initialize();
// File is automatically reloaded if modified
// Wait a bit to ensure mtime changes
await new Promise((r) => setTimeout(r, 100));
writeFileSync(usersFile, 'user1:newpass\n');
// Auth should use new password after auto-reload
const result = await provider.authenticate('user1', 'newpass');
expect(result.success).toBe(true);
});
});
describe('shutdown', () => {
it('should mark provider as unhealthy after shutdown', async () => {
writeFileSync(usersFile, 'testuser:testpass\n');
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
await provider.initialize();
expect(provider.isHealthy()).toBe(true);
await provider.shutdown();
expect(provider.isHealthy()).toBe(false);
});
});
});
+415
View File
@@ -0,0 +1,415 @@
/**
* Tests for KeycloakAuthProvider
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { KeycloakAuthProvider } from '../../src/auth/providers/keycloak.js';
// Mock fetch globally
const mockFetch = vi.fn();
vi.stubGlobal('fetch', mockFetch);
describe('KeycloakAuthProvider', () => {
beforeEach(() => {
mockFetch.mockReset();
});
afterEach(() => {
vi.clearAllMocks();
});
/**
* Create a mock JWT access token
*/
function createMockToken(payload: Record<string, unknown>): string {
const header = Buffer.from(JSON.stringify({ alg: 'RS256', typ: 'JWT' })).toString('base64url');
const body = Buffer.from(JSON.stringify(payload)).toString('base64url');
const signature = 'mock-signature';
return `${header}.${body}.${signature}`;
}
describe('initialization', () => {
it('should throw if url is missing', async () => {
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: '',
realm: 'test',
clientid: 'myclient',
});
await expect(provider.initialize()).rejects.toThrow('requires url');
});
it('should throw if realm is missing', async () => {
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: '',
clientid: 'myclient',
});
await expect(provider.initialize()).rejects.toThrow('requires realm');
});
it('should throw if clientid is missing', async () => {
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: '',
});
await expect(provider.initialize()).rejects.toThrow('requires clientid');
});
it('should initialize successfully with valid config', async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => ({ issuer: 'https://keycloak.example.com/realms/test' }),
});
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
});
await provider.initialize();
expect(provider.isHealthy()).toBe(true);
});
it('should use default priority of 100', () => {
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
});
expect(provider.priority).toBe(100);
});
it('should use custom priority', () => {
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
priority: 50,
});
expect(provider.priority).toBe(50);
});
});
describe('authentication', () => {
it('should authenticate valid user', async () => {
const accessToken = createMockToken({
sub: 'user-uuid',
preferred_username: 'testuser',
email: 'test@example.com',
});
// Mock well-known endpoint
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => ({}),
});
// Mock token endpoint
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () =>
JSON.stringify({
access_token: accessToken,
token_type: 'Bearer',
expires_in: 300,
scope: 'openid profile email',
}),
});
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
});
await provider.initialize();
const result = await provider.authenticate('testuser', 'password123');
expect(result.success).toBe(true);
expect(result.account).toBe('testuser');
});
it('should use clientsecret for confidential clients', async () => {
const accessToken = createMockToken({ preferred_username: 'testuser' });
mockFetch.mockResolvedValueOnce({ ok: true, json: async () => ({}) });
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => JSON.stringify({ access_token: accessToken }),
});
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
clientsecret: 'secret123',
});
await provider.initialize();
await provider.authenticate('testuser', 'password123');
// Check that client_secret was included in the request
const tokenCall = mockFetch.mock.calls[1];
expect(tokenCall[1].body).toContain('client_secret=secret123');
});
it('should reject invalid credentials', async () => {
mockFetch.mockResolvedValueOnce({ ok: true, json: async () => ({}) });
mockFetch.mockResolvedValueOnce({
ok: false,
status: 401,
text: async () =>
JSON.stringify({
error: 'invalid_grant',
error_description: 'Invalid user credentials',
}),
});
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
});
await provider.initialize();
const result = await provider.authenticate('testuser', 'wrongpass');
expect(result.success).toBe(false);
expect(result.error).toBe('Invalid credentials');
});
it('should handle disabled account', async () => {
mockFetch.mockResolvedValueOnce({ ok: true, json: async () => ({}) });
mockFetch.mockResolvedValueOnce({
ok: false,
status: 400,
text: async () =>
JSON.stringify({
error: 'invalid_grant',
error_description: 'Account disabled',
}),
});
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
});
await provider.initialize();
const result = await provider.authenticate('disableduser', 'password');
expect(result.success).toBe(false);
expect(result.error).toBe('Account disabled');
});
it('should handle client misconfiguration', async () => {
mockFetch.mockResolvedValueOnce({ ok: true, json: async () => ({}) });
mockFetch.mockResolvedValueOnce({
ok: false,
status: 401,
text: async () =>
JSON.stringify({
error: 'unauthorized_client',
error_description: 'Client not allowed for direct access grants',
}),
});
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'misconfigured-client',
});
await provider.initialize();
const result = await provider.authenticate('testuser', 'password');
expect(result.success).toBe(false);
expect(result.error).toContain('Client error');
});
it('should extract account from custom attribute', async () => {
const accessToken = createMockToken({
sub: 'user-uuid',
preferred_username: 'testuser',
irc_account: 'CustomNick',
});
mockFetch.mockResolvedValueOnce({ ok: true, json: async () => ({}) });
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => JSON.stringify({ access_token: accessToken }),
});
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
accountattr: 'irc_account',
});
await provider.initialize();
const result = await provider.authenticate('testuser', 'password');
expect(result.success).toBe(true);
expect(result.account).toBe('CustomNick');
});
it('should fall back to sub if preferred_username not available', async () => {
const accessToken = createMockToken({
sub: 'user-uuid-12345',
});
mockFetch.mockResolvedValueOnce({ ok: true, json: async () => ({}) });
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => JSON.stringify({ access_token: accessToken }),
});
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
});
await provider.initialize();
const result = await provider.authenticate('testuser', 'password');
expect(result.success).toBe(true);
expect(result.account).toBe('user-uuid-12345');
});
});
describe('token endpoint URL', () => {
it('should build correct token endpoint URL', async () => {
const accessToken = createMockToken({ preferred_username: 'testuser' });
mockFetch.mockResolvedValueOnce({ ok: true, json: async () => ({}) });
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => JSON.stringify({ access_token: accessToken }),
});
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'myrealm',
clientid: 'myclient',
});
await provider.initialize();
await provider.authenticate('testuser', 'password');
// Check the token endpoint URL
const tokenCall = mockFetch.mock.calls[1];
expect(tokenCall[0]).toBe(
'https://keycloak.example.com/realms/myrealm/protocol/openid-connect/token'
);
});
it('should handle trailing slash in URL', async () => {
const accessToken = createMockToken({ preferred_username: 'testuser' });
mockFetch.mockResolvedValueOnce({ ok: true, json: async () => ({}) });
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => JSON.stringify({ access_token: accessToken }),
});
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com/', // Trailing slash
realm: 'myrealm',
clientid: 'myclient',
});
await provider.initialize();
await provider.authenticate('testuser', 'password');
const tokenCall = mockFetch.mock.calls[1];
expect(tokenCall[0]).toBe(
'https://keycloak.example.com/realms/myrealm/protocol/openid-connect/token'
);
});
});
describe('health status', () => {
it('should mark as unhealthy on connection failure', async () => {
mockFetch.mockRejectedValueOnce(new Error('Connection refused'));
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
});
await provider.initialize();
expect(provider.isHealthy()).toBe(false);
});
it('should mark as healthy after successful auth', async () => {
const accessToken = createMockToken({ preferred_username: 'testuser' });
// Initialize fails
mockFetch.mockRejectedValueOnce(new Error('Connection refused'));
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
});
await provider.initialize();
expect(provider.isHealthy()).toBe(false);
// Auth succeeds
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => JSON.stringify({ access_token: accessToken }),
});
const result = await provider.authenticate('testuser', 'password');
expect(result.success).toBe(true);
expect(provider.isHealthy()).toBe(true);
});
});
describe('shutdown', () => {
it('should mark provider as unhealthy after shutdown', async () => {
mockFetch.mockResolvedValueOnce({ ok: true, json: async () => ({}) });
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
});
await provider.initialize();
expect(provider.isHealthy()).toBe(true);
await provider.shutdown();
expect(provider.isHealthy()).toBe(false);
});
});
});
+191
View File
@@ -0,0 +1,191 @@
/**
* Tests for AuthManager
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { writeFileSync, unlinkSync, mkdtempSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { AuthManager } from '../../src/auth/manager.js';
import type { AuthProviderConfig } from '../../src/auth/types.js';
describe('AuthManager', () => {
let tempDir: string;
let usersFile1: string;
let usersFile2: string;
beforeEach(() => {
tempDir = mkdtempSync(join(tmpdir(), 'iauthd-test-'));
usersFile1 = join(tempDir, 'users1');
usersFile2 = join(tempDir, 'users2');
});
afterEach(() => {
try {
unlinkSync(usersFile1);
unlinkSync(usersFile2);
} catch {
// Ignore if files don't exist
}
});
describe('initialization', () => {
it('should initialize with no providers', async () => {
const manager = new AuthManager([]);
await manager.initialize();
expect(manager.hasProviders()).toBe(false);
expect(manager.getProviderCount()).toBe(0);
});
it('should initialize single file provider', async () => {
writeFileSync(usersFile1, 'testuser:testpass\n');
const configs: AuthProviderConfig[] = [
{ provider: 'file', path: usersFile1 },
];
const manager = new AuthManager(configs);
await manager.initialize();
expect(manager.hasProviders()).toBe(true);
expect(manager.getProviderCount()).toBe(1);
});
it('should initialize multiple providers', async () => {
writeFileSync(usersFile1, 'user1:pass1\n');
writeFileSync(usersFile2, 'user2:pass2\n');
const configs: AuthProviderConfig[] = [
{ provider: 'file', path: usersFile1, priority: 50 },
{ provider: 'file', path: usersFile2, priority: 100 },
];
const manager = new AuthManager(configs);
await manager.initialize();
expect(manager.getProviderCount()).toBe(2);
});
it('should sort providers by priority', async () => {
writeFileSync(usersFile1, 'user1:pass1\n');
writeFileSync(usersFile2, 'user2:pass2\n');
const configs: AuthProviderConfig[] = [
{ provider: 'file', path: usersFile1, priority: 100 },
{ provider: 'file', path: usersFile2, priority: 50 },
];
const manager = new AuthManager(configs);
await manager.initialize();
const info = manager.getProviderInfo();
expect(info[0].priority).toBe(50);
expect(info[1].priority).toBe(100);
});
});
describe('authentication with fallback chain', () => {
it('should authenticate against first matching provider', async () => {
writeFileSync(usersFile1, 'user1:pass1\n');
writeFileSync(usersFile2, 'user2:pass2\n');
const configs: AuthProviderConfig[] = [
{ provider: 'file', path: usersFile1, priority: 50 },
{ provider: 'file', path: usersFile2, priority: 100 },
];
const manager = new AuthManager(configs);
await manager.initialize();
const result = await manager.authenticate('user1', 'pass1');
expect(result.success).toBe(true);
expect(result.account).toBe('user1');
});
it('should fallback to second provider if first fails', async () => {
writeFileSync(usersFile1, 'user1:pass1\n');
writeFileSync(usersFile2, 'user2:pass2\n');
const configs: AuthProviderConfig[] = [
{ provider: 'file', path: usersFile1, priority: 50 },
{ provider: 'file', path: usersFile2, priority: 100 },
];
const manager = new AuthManager(configs);
await manager.initialize();
// user2 is only in the second file
const result = await manager.authenticate('user2', 'pass2');
expect(result.success).toBe(true);
expect(result.account).toBe('user2');
});
it('should fail if no provider matches', async () => {
writeFileSync(usersFile1, 'user1:pass1\n');
writeFileSync(usersFile2, 'user2:pass2\n');
const configs: AuthProviderConfig[] = [
{ provider: 'file', path: usersFile1 },
{ provider: 'file', path: usersFile2 },
];
const manager = new AuthManager(configs);
await manager.initialize();
const result = await manager.authenticate('unknownuser', 'anypass');
expect(result.success).toBe(false);
});
it('should return error if not initialized', async () => {
const manager = new AuthManager([]);
// Don't call initialize
const result = await manager.authenticate('user', 'pass');
expect(result.success).toBe(false);
expect(result.error).toBe('AuthManager not initialized');
});
it('should return error if no providers configured', async () => {
const manager = new AuthManager([]);
await manager.initialize();
const result = await manager.authenticate('user', 'pass');
expect(result.success).toBe(false);
expect(result.error).toBe('No auth providers configured');
});
});
describe('provider health', () => {
it('should report healthy providers', async () => {
writeFileSync(usersFile1, 'user1:pass1\n');
const configs: AuthProviderConfig[] = [
{ provider: 'file', path: usersFile1 },
];
const manager = new AuthManager(configs);
await manager.initialize();
expect(manager.hasHealthyProviders()).toBe(true);
const info = manager.getProviderInfo();
expect(info[0].healthy).toBe(true);
});
});
describe('reload', () => {
it('should reload all providers', async () => {
writeFileSync(usersFile1, 'user1:pass1\n');
const configs: AuthProviderConfig[] = [
{ provider: 'file', path: usersFile1 },
];
const manager = new AuthManager(configs);
await manager.initialize();
// Modify file
writeFileSync(usersFile1, 'user1:newpass\n');
await manager.reload();
// Should now use new password
const result = await manager.authenticate('user1', 'newpass');
expect(result.success).toBe(true);
});
});
describe('shutdown', () => {
it('should shutdown all providers', async () => {
writeFileSync(usersFile1, 'user1:pass1\n');
const configs: AuthProviderConfig[] = [
{ provider: 'file', path: usersFile1 },
];
const manager = new AuthManager(configs);
await manager.initialize();
await manager.shutdown();
expect(manager.hasProviders()).toBe(false);
});
});
});
+184
View File
@@ -0,0 +1,184 @@
/**
* Unit tests for configuration parser
*/
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { writeFileSync, unlinkSync, mkdtempSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { readConfigFile } from '../src/config.js';
describe('Config Parser', () => {
let tempDir: string;
let configPath: string;
beforeAll(() => {
tempDir = mkdtempSync(join(tmpdir(), 'iauthd-test-'));
configPath = join(tempDir, 'test.conf');
});
afterAll(() => {
try {
unlinkSync(configPath);
} catch {}
});
it('should parse POLICY directive', () => {
writeFileSync(configPath, '#IAUTH POLICY RTAWUwFr\n');
const { config } = readConfigFile(configPath);
expect(config.policy).toBe('RTAWUwFr');
});
it('should parse CACHETIME directive', () => {
writeFileSync(configPath, '#IAUTH CACHETIME 3600\n');
const { config } = readConfigFile(configPath);
expect(config.cacheTime).toBe(3600);
});
it('should parse DNSTIMEOUT directive', () => {
writeFileSync(configPath, '#IAUTH DNSTIMEOUT 10\n');
const { config } = readConfigFile(configPath);
expect(config.dnsTimeout).toBe(10);
});
it('should parse BLOCKMSG directive', () => {
writeFileSync(configPath, '#IAUTH BLOCKMSG Your connection has been rejected.\n');
const { config } = readConfigFile(configPath);
expect(config.blockMsg).toBe('Your connection has been rejected.');
});
it('should parse DEBUG directive', () => {
writeFileSync(configPath, '#IAUTH DEBUG\n');
const { config } = readConfigFile(configPath);
expect(config.debug).toBe(true);
});
it('should parse simple DNSBL directive', () => {
writeFileSync(configPath, '#IAUTH DNSBL server=dnsbl.example.com\n');
const { config } = readConfigFile(configPath);
expect(config.dnsbls).toHaveLength(1);
expect(config.dnsbls[0].server).toBe('dnsbl.example.com');
});
it('should parse DNSBL with index', () => {
writeFileSync(configPath, '#IAUTH DNSBL server=dnsbl.example.com index=2,3,4\n');
const { config } = readConfigFile(configPath);
expect(config.dnsbls[0].index).toBe('2,3,4');
});
it('should parse DNSBL with bitmask', () => {
writeFileSync(configPath, '#IAUTH DNSBL server=dnsbl.example.com bitmask=128\n');
const { config } = readConfigFile(configPath);
expect(config.dnsbls[0].bitmask).toBe('128');
});
it('should parse DNSBL with mark', () => {
writeFileSync(configPath, '#IAUTH DNSBL server=dnsbl.example.com mark=baduser\n');
const { config } = readConfigFile(configPath);
expect(config.dnsbls[0].mark).toBe('baduser');
});
it('should parse DNSBL with block=all', () => {
writeFileSync(configPath, '#IAUTH DNSBL server=dnsbl.example.com block=all\n');
const { config } = readConfigFile(configPath);
expect(config.dnsbls[0].block).toBe('all');
});
it('should parse DNSBL with block=anonymous', () => {
writeFileSync(configPath, '#IAUTH DNSBL server=dnsbl.example.com block=anonymous\n');
const { config } = readConfigFile(configPath);
expect(config.dnsbls[0].block).toBe('anonymous');
});
it('should parse DNSBL with whitelist', () => {
writeFileSync(configPath, '#IAUTH DNSBL server=whitelist.example.com whitelist\n');
const { config } = readConfigFile(configPath);
expect(config.dnsbls[0].whitelist).toBe(true);
});
it('should parse DNSBL with class', () => {
writeFileSync(configPath, '#IAUTH DNSBL server=dnsbl.example.com class=Trusted\n');
const { config } = readConfigFile(configPath);
expect(config.dnsbls[0].class).toBe('Trusted');
});
it('should parse DNSBL with cachetime override', () => {
writeFileSync(configPath, '#IAUTH DNSBL server=dnsbl.example.com cachetime=7200\n');
const { config } = readConfigFile(configPath);
expect(config.dnsbls[0].cacheTime).toBe(7200);
});
it('should parse multiple DNSBL directives', () => {
writeFileSync(configPath, `
#IAUTH DNSBL server=dnsbl1.example.com index=2,3 mark=bl1
#IAUTH DNSBL server=dnsbl2.example.com index=4,5 mark=bl2 block=anonymous
#IAUTH DNSBL server=whitelist.example.com whitelist
`);
const { config } = readConfigFile(configPath);
expect(config.dnsbls).toHaveLength(3);
expect(config.dnsbls[0].server).toBe('dnsbl1.example.com');
expect(config.dnsbls[1].server).toBe('dnsbl2.example.com');
expect(config.dnsbls[1].block).toBe('anonymous');
expect(config.dnsbls[2].whitelist).toBe(true);
});
it('should parse full config with all directives', () => {
writeFileSync(configPath, `
# This is a comment
#IAUTH POLICY RTAWUwFr
#IAUTH CACHETIME 86400
#IAUTH DNSTIMEOUT 5
#IAUTH BLOCKMSG Sorry! Your connection has been rejected.
#IAUTH DNSBL server=dnsbl.sorbs.net index=2,3,4,5 mark=sorbs block=anonymous
#IAUTH DNSBL server=rbl.efnetrbl.org index=4 mark=tor
# Some other config lines that should be ignored
General {
name = "test.server";
};
`);
const { config, configLines } = readConfigFile(configPath);
expect(config.policy).toBe('RTAWUwFr');
expect(config.cacheTime).toBe(86400);
expect(config.dnsTimeout).toBe(5);
expect(config.blockMsg).toBe('Sorry! Your connection has been rejected.');
expect(config.dnsbls).toHaveLength(2);
expect(configLines).toHaveLength(6);
});
it('should use defaults when directives are missing', () => {
writeFileSync(configPath, '# Empty config\n');
const { config } = readConfigFile(configPath);
expect(config.policy).toBe('RTAWUwFr');
expect(config.cacheTime).toBe(86400);
expect(config.dnsTimeout).toBe(5);
expect(config.debug).toBe(false);
expect(config.dnsbls).toHaveLength(0);
});
it('should ignore non-IAUTH lines', () => {
writeFileSync(configPath, `
# Regular comment
General { name = "test"; };
#IAUTH POLICY RTAW
#NOTIAUTHPOLICY test
`);
const { config } = readConfigFile(configPath);
expect(config.policy).toBe('RTAW');
});
it('should assign incrementing cfgNum to DNSBLs', () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH DNSBL server=first.example.com
#IAUTH DNSBL server=second.example.com
#IAUTH DNSBL server=third.example.com
`);
const { config } = readConfigFile(configPath);
expect(config.dnsbls[0].cfgNum).toBe(2);
expect(config.dnsbls[1].cfgNum).toBe(3);
expect(config.dnsbls[2].cfgNum).toBe(4);
});
});
@@ -0,0 +1,641 @@
/**
* DNSBL Integration Tests with Mocked DNS
*
* Tests the full pipeline: client connect → DNSBL lookup → decision
* Uses mock DNS responses to test all matching modes and edge cases.
*
* Based on real-world AfterNET production config.
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { spawn, ChildProcess } from 'node:child_process';
import { writeFileSync, unlinkSync, mkdtempSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { createInterface } from 'node:readline';
/**
* Mock DNS responses for testing
* Maps reversed-IP.dnsbl-server to response IP(s)
*/
const mockDnsResponses: Map<string, string[]> = new Map();
/**
* Set up a mock DNS response
*/
function mockDns(clientIp: string, dnsblServer: string, responses: string[]): void {
const reversed = clientIp.split('.').reverse().join('.');
const query = `${reversed}.${dnsblServer}`;
mockDnsResponses.set(query, responses);
}
/**
* Clear all mock DNS responses
*/
function clearMockDns(): void {
mockDnsResponses.clear();
}
interface TestHarness {
proc: ChildProcess;
output: string[];
send: (line: string) => void;
waitFor: (pattern: RegExp, timeout?: number) => Promise<string>;
getMarks: (clientId: number) => string[];
wasAccepted: (clientId: number) => boolean;
wasRejected: (clientId: number) => boolean;
close: () => Promise<void>;
}
/**
* Create a test harness with mock DNS injection
*/
async function createHarness(configPath: string): Promise<TestHarness> {
const output: string[] = [];
// Create a wrapper script that injects our mock DNS module
const wrapperPath = join(tmpdir(), `dns-mock-${Date.now()}.mjs`);
const mockResponses = JSON.stringify(Array.from(mockDnsResponses.entries()));
writeFileSync(wrapperPath, `
import { promises as dns } from 'node:dns';
// Mock DNS responses
const mockResponses = new Map(${mockResponses});
// Override dns.resolve4
const originalResolve4 = dns.resolve4.bind(dns);
dns.resolve4 = async (hostname) => {
const mock = mockResponses.get(hostname);
if (mock !== undefined) {
if (mock.length === 0) {
const err = new Error('NXDOMAIN');
err.code = 'ENOTFOUND';
throw err;
}
return mock;
}
// For non-mocked queries, return NXDOMAIN (not listed)
const err = new Error('NXDOMAIN');
err.code = 'ENOTFOUND';
throw err;
};
// Now import and run the actual daemon
import('${join(import.meta.dirname, '..', 'src', 'index.ts').replace(/\\/g, '/')}');
`);
const proc = spawn('npx', ['tsx', wrapperPath, '-v', '-c', configPath], {
cwd: join(import.meta.dirname, '..'),
stdio: ['pipe', 'pipe', 'pipe'],
env: { ...process.env },
});
const rl = createInterface({ input: proc.stdout! });
rl.on('line', (line) => output.push(line));
proc.stderr?.on('data', (data) => {
// Uncomment for debugging:
// console.error('stderr:', data.toString());
});
const send = (line: string) => {
proc.stdin!.write(line + '\n');
};
const waitFor = (pattern: RegExp, timeout = 5000): Promise<string> => {
return new Promise((resolve, reject) => {
// Check existing output
for (const line of output) {
if (pattern.test(line)) {
resolve(line);
return;
}
}
const startLen = output.length;
const interval = setInterval(() => {
for (let i = startLen; i < output.length; i++) {
if (pattern.test(output[i])) {
clearInterval(interval);
clearTimeout(timer);
resolve(output[i]);
return;
}
}
}, 10);
const timer = setTimeout(() => {
clearInterval(interval);
reject(new Error(`Timeout waiting for: ${pattern}\nOutput was:\n${output.join('\n')}`));
}, timeout);
});
};
const getMarks = (clientId: number): string[] => {
const marks: string[] = [];
const pattern = new RegExp(`^m ${clientId} .* MARK (\\S+)`);
for (const line of output) {
const match = line.match(pattern);
if (match) {
marks.push(match[1]);
}
}
return marks;
};
const wasAccepted = (clientId: number): boolean => {
return output.some(line => line.startsWith(`D ${clientId} `));
};
const wasRejected = (clientId: number): boolean => {
return output.some(line => line.startsWith(`k ${clientId} `));
};
const close = async (): Promise<void> => {
try { unlinkSync(wrapperPath); } catch {}
return new Promise((resolve) => {
proc.on('close', () => resolve());
proc.stdin!.end();
setTimeout(() => {
proc.kill('SIGTERM');
resolve();
}, 1000);
});
};
// Wait for startup
await waitFor(/^S iauthd-ts/);
await new Promise(r => setTimeout(r, 100));
return { proc, output, send, waitFor, getMarks, wasAccepted, wasRejected, close };
}
/**
* Simulate a full client connection flow
*/
async function connectClient(
harness: TestHarness,
clientId: number,
ip: string,
options: { authenticated?: string } = {}
): Promise<void> {
harness.send(`${clientId} C ${ip} ${10000 + clientId} 10.0.0.1 6667`);
if (options.authenticated) {
harness.send(`${clientId} R ${options.authenticated}`);
}
// Small delay to let lookups start
await new Promise(r => setTimeout(r, 50));
harness.send(`${clientId} H Users`);
// Wait for decision
await harness.waitFor(new RegExp(`^[Dk] ${clientId} `), 3000);
}
describe('DNSBL Integration Tests', () => {
let tempDir: string;
let configPath: string;
let harness: TestHarness;
beforeEach(() => {
tempDir = mkdtempSync(join(tmpdir(), 'iauthd-dnsbl-test-'));
configPath = join(tempDir, 'test.conf');
clearMockDns();
});
afterEach(async () => {
await harness?.close();
try { unlinkSync(configPath); } catch {}
});
describe('Index Matching', () => {
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH DNSBL server=test.dnsbl index=2,3,4 mark=testbl block=all
`);
});
it('should block when index matches exactly', async () => {
mockDns('192.168.1.100', 'test.dnsbl', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100');
expect(harness.wasRejected(0)).toBe(true);
expect(harness.wasAccepted(0)).toBe(false);
});
it('should block when any configured index matches', async () => {
mockDns('192.168.1.101', 'test.dnsbl', ['127.0.0.4']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.101');
expect(harness.wasRejected(0)).toBe(true);
});
it('should pass when index does not match', async () => {
mockDns('192.168.1.102', 'test.dnsbl', ['127.0.0.5']); // index=5 not in 2,3,4
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.102');
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.wasRejected(0)).toBe(false);
});
it('should pass when not listed (NXDOMAIN)', async () => {
// No mock = NXDOMAIN
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.103');
expect(harness.wasAccepted(0)).toBe(true);
});
});
describe('Bitmask Matching', () => {
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH DNSBL server=test.dnsbl bitmask=2,4 mark=testbl block=all
`);
});
it('should block when bitmask matches (bit 1 set)', async () => {
mockDns('192.168.1.100', 'test.dnsbl', ['127.0.0.2']); // 2 = 0010
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100');
expect(harness.wasRejected(0)).toBe(true);
});
it('should block when bitmask matches (bit 2 set)', async () => {
mockDns('192.168.1.101', 'test.dnsbl', ['127.0.0.4']); // 4 = 0100
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.101');
expect(harness.wasRejected(0)).toBe(true);
});
it('should block when multiple bits match', async () => {
mockDns('192.168.1.102', 'test.dnsbl', ['127.0.0.6']); // 6 = 0110 (bits 1 and 2)
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.102');
expect(harness.wasRejected(0)).toBe(true);
});
it('should pass when no bitmask bits match', async () => {
mockDns('192.168.1.103', 'test.dnsbl', ['127.0.0.1']); // 1 = 0001 (bit 0 only)
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.103');
expect(harness.wasAccepted(0)).toBe(true);
});
});
describe('Block Modes', () => {
describe('block=all', () => {
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH DNSBL server=test.dnsbl index=2 mark=testbl block=all
`);
});
it('should block unauthenticated users', async () => {
mockDns('192.168.1.100', 'test.dnsbl', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100');
expect(harness.wasRejected(0)).toBe(true);
});
it('should block authenticated users too', async () => {
mockDns('192.168.1.100', 'test.dnsbl', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100', { authenticated: 'testuser' });
expect(harness.wasRejected(0)).toBe(true);
});
});
describe('block=anonymous', () => {
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH BLOCKMSG You must authenticate to connect.
#IAUTH DNSBL server=test.dnsbl index=2 mark=testbl block=anonymous
`);
});
it('should block unauthenticated users', async () => {
mockDns('192.168.1.100', 'test.dnsbl', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100');
expect(harness.wasRejected(0)).toBe(true);
});
it('should allow SASL-authenticated users', async () => {
mockDns('192.168.1.100', 'test.dnsbl', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100', { authenticated: 'gooduser' });
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.wasRejected(0)).toBe(false);
});
it('should mark authenticated users even though not blocked', async () => {
mockDns('192.168.1.100', 'test.dnsbl', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100', { authenticated: 'gooduser' });
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.getMarks(0)).toContain('testbl');
});
});
describe('mark only (no block)', () => {
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH DNSBL server=test.dnsbl index=2 mark=infomark
`);
});
it('should accept client but apply mark', async () => {
mockDns('192.168.1.100', 'test.dnsbl', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100');
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.getMarks(0)).toContain('infomark');
});
});
});
describe('Whitelist', () => {
beforeEach(async () => {
// Whitelist first, then blocking DNSBLs - mimics AfterNET config
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH DNSBL server=whitelist.dnsbl index=2 mark=whitelist whitelist
#IAUTH DNSBL server=blocklist.dnsbl index=2 mark=blocked block=all
`);
});
it('should not block whitelisted clients even if they match blocking DNSBL', async () => {
mockDns('192.168.1.100', 'whitelist.dnsbl', ['127.0.0.2']); // Whitelisted
mockDns('192.168.1.100', 'blocklist.dnsbl', ['127.0.0.2']); // Also on blocklist
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100');
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.wasRejected(0)).toBe(false);
});
it('should block non-whitelisted clients that match blocking DNSBL', async () => {
// Not on whitelist, but on blocklist
mockDns('192.168.1.101', 'blocklist.dnsbl', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.101');
expect(harness.wasRejected(0)).toBe(true);
});
it('should apply whitelist mark', async () => {
mockDns('192.168.1.100', 'whitelist.dnsbl', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100');
expect(harness.getMarks(0)).toContain('whitelist');
});
});
describe('Multiple DNSBLs', () => {
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH DNSBL server=dnsbl1.test index=2 mark=list1
#IAUTH DNSBL server=dnsbl2.test index=2 mark=list2
#IAUTH DNSBL server=dnsbl3.test index=2 mark=list3 block=anonymous
`);
});
it('should accumulate marks from multiple DNSBLs', async () => {
mockDns('192.168.1.100', 'dnsbl1.test', ['127.0.0.2']);
mockDns('192.168.1.100', 'dnsbl2.test', ['127.0.0.2']);
// Not on dnsbl3
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100');
expect(harness.wasAccepted(0)).toBe(true);
const marks = harness.getMarks(0);
expect(marks).toContain('list1');
expect(marks).toContain('list2');
expect(marks).not.toContain('list3');
});
it('should block if any blocking DNSBL matches', async () => {
mockDns('192.168.1.100', 'dnsbl3.test', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100');
expect(harness.wasRejected(0)).toBe(true);
});
});
describe('Same Server, Different Indices (AfterNET pattern)', () => {
beforeEach(async () => {
// Mimics AfterNET's dnsbl.afternet.org with different indices
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH DNSBL server=dnsbl.example.org index=2 mark=whitelist whitelist
#IAUTH DNSBL server=dnsbl.example.org index=250 mark=rbl block=anonymous
#IAUTH DNSBL server=dnsbl.example.org index=251 mark=cloud block=anonymous
`);
});
it('should whitelist on index=2', async () => {
mockDns('192.168.1.100', 'dnsbl.example.org', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100');
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.getMarks(0)).toContain('whitelist');
});
it('should block anonymous on index=250', async () => {
mockDns('192.168.1.101', 'dnsbl.example.org', ['127.0.0.250']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.101');
expect(harness.wasRejected(0)).toBe(true);
});
it('should block anonymous on index=251', async () => {
mockDns('192.168.1.102', 'dnsbl.example.org', ['127.0.0.251']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.102');
expect(harness.wasRejected(0)).toBe(true);
});
it('should allow authenticated on index=250', async () => {
mockDns('192.168.1.101', 'dnsbl.example.org', ['127.0.0.250']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.101', { authenticated: 'user' });
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.getMarks(0)).toContain('rbl');
});
});
describe('Real-world AfterNET Config Simulation', () => {
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH CACHETIMEOUT 21600
#IAUTH DNSTIMEOUT 5
#IAUTH BLOCKMSG Sorry! Your connection has been rejected due to poor reputation.
#IAUTH DNSBL server=dnsbl.afternet.org index=2 mark=whitelist whitelist
#IAUTH DNSBL server=dnsbl.afternet.org index=250 mark=afternetrbl block=anonymous
#IAUTH DNSBL server=dnsbl.afternet.org index=251 mark=cloud block=anonymous
#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 block=anonymous
#IAUTH DNSBL server=rbl.efnetrbl.org index=1,2,3,5 mark=efnetrbl block=anonymous
#IAUTH DNSBL server=dnsbl-2.uceprotect.net index=2 mark=uce-2
#IAUTH DNSBL server=cbl.abuseat.org index=2 mark=cbl
`);
});
it('should accept clean clients', async () => {
harness = await createHarness(configPath);
await connectClient(harness, 0, '8.8.8.8');
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.getMarks(0)).toHaveLength(0);
});
it('should whitelist AfterNET trusted IPs', async () => {
mockDns('10.0.0.50', 'dnsbl.afternet.org', ['127.0.0.2']);
mockDns('10.0.0.50', 'dnsbl.dronebl.org', ['127.0.0.5']); // Also on dronebl!
harness = await createHarness(configPath);
await connectClient(harness, 0, '10.0.0.50');
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.getMarks(0)).toContain('whitelist');
});
it('should block drones unless authenticated', async () => {
mockDns('10.0.0.60', 'dnsbl.dronebl.org', ['127.0.0.5']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '10.0.0.60');
expect(harness.wasRejected(0)).toBe(true);
});
it('should allow authenticated drones', async () => {
mockDns('10.0.0.60', 'dnsbl.dronebl.org', ['127.0.0.5']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '10.0.0.60', { authenticated: 'droneuser' });
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.getMarks(0)).toContain('dronebl');
});
it('should block Tor exit nodes unless authenticated', async () => {
mockDns('10.0.0.70', 'rbl.efnetrbl.org', ['127.0.0.4']); // index=4 = tor
harness = await createHarness(configPath);
await connectClient(harness, 0, '10.0.0.70');
expect(harness.wasRejected(0)).toBe(true);
});
it('should mark UCE-2 but not block', async () => {
mockDns('10.0.0.80', 'dnsbl-2.uceprotect.net', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '10.0.0.80');
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.getMarks(0)).toContain('uce-2');
});
it('should mark CBL but not block', async () => {
mockDns('10.0.0.90', 'cbl.abuseat.org', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '10.0.0.90');
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.getMarks(0)).toContain('cbl');
});
it('should accumulate multiple marks', async () => {
mockDns('10.0.0.95', 'dnsbl-2.uceprotect.net', ['127.0.0.2']);
mockDns('10.0.0.95', 'cbl.abuseat.org', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '10.0.0.95');
expect(harness.wasAccepted(0)).toBe(true);
const marks = harness.getMarks(0);
expect(marks).toContain('uce-2');
expect(marks).toContain('cbl');
});
});
describe('Class Assignment', () => {
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH DNSBL server=trusted.dnsbl index=2 class=Trusted mark=trusted
#IAUTH DNSBL server=limited.dnsbl index=2 class=Limited mark=limited
`);
});
it('should assign class from matching DNSBL', async () => {
mockDns('192.168.1.100', 'trusted.dnsbl', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100');
expect(harness.wasAccepted(0)).toBe(true);
// Check the D message includes the class
const acceptLine = harness.output.find(l => l.startsWith('D 0 '));
expect(acceptLine).toContain('Trusted');
});
});
});
+228
View File
@@ -0,0 +1,228 @@
/**
* Unit tests for DNSBL functions
*/
import { describe, it, expect, beforeEach } from 'vitest';
import {
reverseIPv4,
isIPv4,
getCacheEntry,
setCacheEntry,
getCacheSize,
matchesDNSBL,
parseQuery,
} from '../src/dnsbl.js';
import type { DNSBLConfig } from '../src/types.js';
describe('DNSBL Functions', () => {
describe('reverseIPv4', () => {
it('should reverse a valid IPv4 address', () => {
expect(reverseIPv4('192.168.1.10')).toBe('10.1.168.192');
});
it('should handle 127.0.0.1', () => {
expect(reverseIPv4('127.0.0.1')).toBe('1.0.0.127');
});
it('should handle 0.0.0.0', () => {
expect(reverseIPv4('0.0.0.0')).toBe('0.0.0.0');
});
it('should handle 255.255.255.255', () => {
expect(reverseIPv4('255.255.255.255')).toBe('255.255.255.255');
});
it('should return null for invalid IPv4', () => {
expect(reverseIPv4('not-an-ip')).toBeNull();
});
it('should return null for IPv6 addresses', () => {
expect(reverseIPv4('::1')).toBeNull();
expect(reverseIPv4('2001:db8::1')).toBeNull();
});
it('should return null for partial IPs', () => {
expect(reverseIPv4('192.168.1')).toBeNull();
expect(reverseIPv4('192.168')).toBeNull();
});
it('should return null for IPs with invalid octets', () => {
expect(reverseIPv4('192.168.1.256')).toBeNull();
expect(reverseIPv4('192.168.1.1000')).toBeNull();
});
});
describe('isIPv4', () => {
it('should return true for valid IPv4 addresses', () => {
expect(isIPv4('192.168.1.1')).toBe(true);
expect(isIPv4('127.0.0.1')).toBe(true);
expect(isIPv4('0.0.0.0')).toBe(true);
expect(isIPv4('255.255.255.255')).toBe(true);
});
it('should return false for IPv6 addresses', () => {
expect(isIPv4('::1')).toBe(false);
expect(isIPv4('2001:db8::1')).toBe(false);
});
it('should return false for invalid strings', () => {
expect(isIPv4('not-an-ip')).toBe(false);
expect(isIPv4('')).toBe(false);
expect(isIPv4('192.168.1')).toBe(false);
});
});
describe('Cache functions', () => {
beforeEach(() => {
// Clear cache by setting entries and letting them expire
// Note: In a real implementation, we'd want a clearCache() function
});
it('should store and retrieve cache entries', () => {
const query = 'test-cache-1.dnsbl.example.com';
setCacheEntry(query, ['127.0.0.2']);
const entry = getCacheEntry(query, 3600);
expect(entry).not.toBeNull();
expect(entry?.result).toEqual(['127.0.0.2']);
});
it('should return null for non-existent entries', () => {
const entry = getCacheEntry('nonexistent.query.com', 3600);
expect(entry).toBeNull();
});
it('should expire old entries', () => {
const query = 'test-cache-expire.dnsbl.example.com';
setCacheEntry(query, ['127.0.0.2']);
// With cacheTime of 0, entry should be expired
const entry = getCacheEntry(query, 0);
expect(entry).toBeNull();
});
it('should track cache size', () => {
const initialSize = getCacheSize();
const query = `test-cache-size-${Date.now()}.dnsbl.example.com`;
setCacheEntry(query, ['127.0.0.2']);
expect(getCacheSize()).toBeGreaterThanOrEqual(initialSize);
});
it('should handle null results (pending lookups)', () => {
const query = 'test-cache-null.dnsbl.example.com';
setCacheEntry(query, null);
const entry = getCacheEntry(query, 3600);
expect(entry).not.toBeNull();
expect(entry?.result).toBeNull();
});
});
describe('matchesDNSBL', () => {
it('should match by index', () => {
const config: DNSBLConfig = {
cfgNum: 1,
server: 'dnsbl.example.com',
index: '2,3,4',
};
expect(matchesDNSBL(['127.0.0.2'], config)).toBe(true);
expect(matchesDNSBL(['127.0.0.3'], config)).toBe(true);
expect(matchesDNSBL(['127.0.0.4'], config)).toBe(true);
expect(matchesDNSBL(['127.0.0.5'], config)).toBe(false);
expect(matchesDNSBL(['127.0.0.1'], config)).toBe(false);
});
it('should match by bitmask', () => {
const config: DNSBLConfig = {
cfgNum: 1,
server: 'dnsbl.example.com',
bitmask: '2', // Binary: 010
};
expect(matchesDNSBL(['127.0.0.2'], config)).toBe(true); // 010 & 010 = 010
expect(matchesDNSBL(['127.0.0.3'], config)).toBe(true); // 011 & 010 = 010
expect(matchesDNSBL(['127.0.0.6'], config)).toBe(true); // 110 & 010 = 010
expect(matchesDNSBL(['127.0.0.1'], config)).toBe(false); // 001 & 010 = 000
expect(matchesDNSBL(['127.0.0.4'], config)).toBe(false); // 100 & 010 = 000
});
it('should match multiple bitmasks', () => {
const config: DNSBLConfig = {
cfgNum: 1,
server: 'dnsbl.example.com',
bitmask: '2,4', // Match if bit 1 or bit 2 set
};
expect(matchesDNSBL(['127.0.0.2'], config)).toBe(true);
expect(matchesDNSBL(['127.0.0.4'], config)).toBe(true);
expect(matchesDNSBL(['127.0.0.6'], config)).toBe(true);
expect(matchesDNSBL(['127.0.0.1'], config)).toBe(false);
});
it('should match any result if no index or bitmask', () => {
const config: DNSBLConfig = {
cfgNum: 1,
server: 'dnsbl.example.com',
};
expect(matchesDNSBL(['127.0.0.1'], config)).toBe(true);
expect(matchesDNSBL(['127.0.0.255'], config)).toBe(true);
});
it('should not match empty results', () => {
const config: DNSBLConfig = {
cfgNum: 1,
server: 'dnsbl.example.com',
index: '2',
};
expect(matchesDNSBL([], config)).toBe(false);
});
it('should match if any result matches (multiple results)', () => {
const config: DNSBLConfig = {
cfgNum: 1,
server: 'dnsbl.example.com',
index: '4',
};
expect(matchesDNSBL(['127.0.0.2', '127.0.0.4'], config)).toBe(true);
expect(matchesDNSBL(['127.0.0.1', '127.0.0.2'], config)).toBe(false);
});
it('should handle invalid result IPs gracefully', () => {
const config: DNSBLConfig = {
cfgNum: 1,
server: 'dnsbl.example.com',
index: '2',
};
expect(matchesDNSBL(['invalid', '127.0.0.2'], config)).toBe(true);
expect(matchesDNSBL(['invalid'], config)).toBe(false);
});
});
describe('parseQuery', () => {
it('should parse a valid DNSBL query', () => {
const result = parseQuery('10.1.168.192.dnsbl.example.com');
expect(result).not.toBeNull();
expect(result?.ip).toBe('192.168.1.10');
expect(result?.server).toBe('dnsbl.example.com');
});
it('should handle multi-part server names', () => {
const result = parseQuery('1.0.0.127.zen.spamhaus.org');
expect(result).not.toBeNull();
expect(result?.ip).toBe('127.0.0.1');
expect(result?.server).toBe('zen.spamhaus.org');
});
it('should return null for invalid queries', () => {
expect(parseQuery('invalid')).toBeNull();
expect(parseQuery('dnsbl.example.com')).toBeNull();
expect(parseQuery('')).toBeNull();
});
});
});
+474
View File
@@ -0,0 +1,474 @@
/**
* Integration tests for IAuth protocol
* Tests the full protocol communication by spawning the daemon
*/
import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach } from 'vitest';
import { spawn, ChildProcess } from 'node:child_process';
import { writeFileSync, unlinkSync, mkdtempSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { createInterface } from 'node:readline';
interface IAuthTestHarness {
process: ChildProcess;
output: string[];
send: (line: string) => void;
waitForOutput: (pattern: RegExp, timeout?: number) => Promise<string>;
waitForLines: (count: number, timeout?: number) => Promise<string[]>;
close: () => Promise<void>;
}
async function createTestHarness(configPath: string): Promise<IAuthTestHarness> {
const output: string[] = [];
const proc = spawn('npx', ['tsx', 'src/index.ts', '-v', '-c', configPath], {
cwd: join(import.meta.dirname, '..'),
stdio: ['pipe', 'pipe', 'pipe'],
});
const rl = createInterface({ input: proc.stdout! });
rl.on('line', (line) => {
output.push(line);
});
// Also capture stderr for debugging
proc.stderr?.on('data', (data) => {
console.error('stderr:', data.toString());
});
const send = (line: string) => {
proc.stdin!.write(line + '\n');
};
const waitForOutput = (pattern: RegExp, timeout = 5000): Promise<string> => {
return new Promise((resolve, reject) => {
// First check existing output
for (const line of output) {
if (pattern.test(line)) {
resolve(line);
return;
}
}
const startLen = output.length;
const checkInterval = setInterval(() => {
for (let i = startLen; i < output.length; i++) {
if (pattern.test(output[i])) {
clearInterval(checkInterval);
clearTimeout(timeoutId);
resolve(output[i]);
return;
}
}
}, 10);
const timeoutId = setTimeout(() => {
clearInterval(checkInterval);
reject(new Error(`Timeout waiting for pattern: ${pattern}`));
}, timeout);
});
};
const waitForLines = (count: number, timeout = 5000): Promise<string[]> => {
return new Promise((resolve, reject) => {
const startLen = output.length;
const checkInterval = setInterval(() => {
if (output.length >= startLen + count) {
clearInterval(checkInterval);
clearTimeout(timeoutId);
resolve(output.slice(startLen, startLen + count));
}
}, 10);
const timeoutId = setTimeout(() => {
clearInterval(checkInterval);
resolve(output.slice(startLen)); // Return what we have
}, timeout);
});
};
const close = (): Promise<void> => {
return new Promise((resolve) => {
proc.on('close', () => resolve());
proc.stdin!.end();
setTimeout(() => {
proc.kill('SIGTERM');
resolve();
}, 1000);
});
};
// Wait for startup - wait for stats output which comes last
await waitForOutput(/^S iauthd-ts/);
// Small delay to ensure all startup output is captured
await new Promise(r => setTimeout(r, 100));
return { process: proc, output, send, waitForOutput, waitForLines, close };
}
describe('IAuth Protocol Integration', () => {
let tempDir: string;
let configPath: string;
beforeAll(() => {
tempDir = mkdtempSync(join(tmpdir(), 'iauthd-test-'));
configPath = join(tempDir, 'test.conf');
});
afterAll(() => {
try {
unlinkSync(configPath);
} catch {}
});
describe('Startup Messages', () => {
let harness: IAuthTestHarness;
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH CACHETIME 3600
#IAUTH BLOCKMSG Test rejection message
`);
harness = await createTestHarness(configPath);
});
afterEach(async () => {
await harness?.close();
});
it('should send G (protocol version request) on startup', () => {
expect(harness.output).toContain('G 1');
});
it('should send V (version) on startup', () => {
const versionLine = harness.output.find(l => l.startsWith('V :'));
expect(versionLine).toBeDefined();
expect(versionLine).toContain('iauthd-ts');
});
it('should send O (policy) on startup', () => {
expect(harness.output).toContain('O RTAWUwFr');
});
it('should send a (new config) on startup', () => {
expect(harness.output).toContain('a');
});
it('should send A (config info) lines on startup', () => {
const configLines = harness.output.filter(l => l.startsWith('A *'));
expect(configLines.length).toBeGreaterThan(0);
});
it('should send s (stats start) on startup', () => {
expect(harness.output).toContain('s');
});
it('should send S (stats) lines on startup', () => {
const statsLines = harness.output.filter(l => l.startsWith('S '));
expect(statsLines.length).toBeGreaterThan(0);
});
});
describe('Client Handling', () => {
let harness: IAuthTestHarness;
beforeEach(async () => {
// Config with no DNSBLs - clients should pass immediately
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
`);
harness = await createTestHarness(configPath);
});
afterEach(async () => {
await harness?.close();
});
it('should accept a client with no DNSBLs configured', async () => {
harness.send('0 C 192.168.1.10 12345 10.0.0.1 6667');
harness.send('0 H Users');
const doneLine = await harness.waitForOutput(/^D 0 192\.168\.1\.10 12345/);
expect(doneLine).toBeDefined();
});
it('should handle client disconnect', async () => {
harness.send('0 C 192.168.1.10 12345 10.0.0.1 6667');
harness.send('0 D');
// Should see debug message about disconnect
await harness.waitForOutput(/disconnected/i, 1000).catch(() => {});
// No error should occur
});
it('should handle multiple concurrent clients', async () => {
harness.send('0 C 192.168.1.10 12345 10.0.0.1 6667');
harness.send('1 C 192.168.1.11 12346 10.0.0.1 6667');
harness.send('2 C 192.168.1.12 12347 10.0.0.1 6667');
harness.send('0 H Users');
harness.send('1 H Users');
harness.send('2 H Users');
// All three should be accepted (longer timeout for concurrent processing)
await harness.waitForOutput(/^D 0/, 10000);
await harness.waitForOutput(/^D 1/, 10000);
await harness.waitForOutput(/^D 2/, 10000);
}, 15000);
});
describe('SASL/LOC Authentication', () => {
let harness: IAuthTestHarness;
beforeEach(async () => {
// Config that blocks anonymous but allows authenticated
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH BLOCKMSG Blocked for testing
`);
harness = await createTestHarness(configPath);
});
afterEach(async () => {
await harness?.close();
});
it('should track authenticated account', async () => {
harness.send('0 C 192.168.1.10 12345 10.0.0.1 6667');
harness.send('0 R testuser');
harness.send('0 H Users');
// Should see debug about auth
const authLine = await harness.waitForOutput(/authed as testuser/i);
expect(authLine).toBeDefined();
});
});
describe('SASL PLAIN Authentication', () => {
let harness: IAuthTestHarness;
let usersPath: string;
beforeEach(async () => {
// Create users file with test user (password: testpass)
usersPath = join(tempDir, 'users');
// Plain text password for testing
writeFileSync(usersPath, 'testuser:testpass\n');
// Config with SASL enabled (S in policy) and users file
writeFileSync(configPath, `
#IAUTH POLICY SRTAWUwFr
#IAUTH SASLDB ${usersPath}
#IAUTH SASLFAILMSG Authentication failed
`);
harness = await createTestHarness(configPath);
});
afterEach(async () => {
await harness?.close();
try {
unlinkSync(usersPath);
} catch {}
});
it('should respond with challenge when SASL PLAIN is requested', async () => {
// IRCd introduces a client
harness.send('0 C 192.168.1.10 12345 10.0.0.1 6667');
// IRCd sends SASL start with mechanism
// Format: <id> A S :<mechanism>
harness.send('0 A S :PLAIN');
// iauthd should respond with empty challenge ('+' means ready)
// Format: c <id> <ip> <port> :<challenge>
const challengeLine = await harness.waitForOutput(/^c 0 192\.168\.1\.10 12345 :\+$/);
expect(challengeLine).toBeDefined();
});
it('should send L and Z messages on successful authentication', async () => {
harness.send('0 C 192.168.1.10 12345 10.0.0.1 6667');
harness.send('0 A S :PLAIN');
await harness.waitForOutput(/^c 0/);
// Send SASL continuation with credentials
// Format: <id> a :<base64_data>
// Base64 of "\0testuser\0testpass" (SASL PLAIN format)
const credentials = Buffer.from('\0testuser\0testpass').toString('base64');
harness.send(`0 a :${credentials}`);
// iauthd should respond with L (login success) then Z (SASL complete)
// Format: L <id> <ip> <port> <account>
const loginLine = await harness.waitForOutput(/^L 0 192\.168\.1\.10 12345 testuser$/);
expect(loginLine).toBeDefined();
// Format: Z <id> <ip> <port>
const completeLine = await harness.waitForOutput(/^Z 0 192\.168\.1\.10 12345$/);
expect(completeLine).toBeDefined();
});
it('should send f message on failed authentication', async () => {
harness.send('0 C 192.168.1.10 12345 10.0.0.1 6667');
harness.send('0 A S :PLAIN');
await harness.waitForOutput(/^c 0/);
// Send wrong credentials
const credentials = Buffer.from('\0testuser\0wrongpass').toString('base64');
harness.send(`0 a :${credentials}`);
// iauthd should respond with f (auth failed)
// Format: f <id> <ip> <port>
const failLine = await harness.waitForOutput(/^f 0 192\.168\.1\.10 12345$/);
expect(failLine).toBeDefined();
});
it('should handle SASL host info message', async () => {
harness.send('0 C 192.168.1.10 12345 10.0.0.1 6667');
// IRCd sends host info with SASL start
// Format: <id> A H :<user@host:ip>
harness.send('0 A H :user@testhost.example.com:192.168.1.10');
// Should see debug about host info
const hostLine = await harness.waitForOutput(/SASL host info.*testhost/i);
expect(hostLine).toBeDefined();
});
it('should handle mechanism with certfp', async () => {
harness.send('0 C 192.168.1.10 12345 10.0.0.1 6667');
// Format with certfp: <id> A S <mechanism> :<certfp>
harness.send('0 A S PLAIN :abc123fingerprint');
// Should respond with challenge
const challengeLine = await harness.waitForOutput(/^c 0/);
expect(challengeLine).toBeDefined();
});
it('should send mechanism list for unsupported mechanism', async () => {
harness.send('0 C 192.168.1.10 12345 10.0.0.1 6667');
// Request unsupported mechanism
harness.send('0 A S :EXTERNAL');
// Should respond with mechanism list
// Format: l <id> <ip> <port> :<mechanisms>
const mechLine = await harness.waitForOutput(/^l 0 192\.168\.1\.10 12345 :PLAIN$/);
expect(mechLine).toBeDefined();
});
it('should complete full SASL flow then accept client', async () => {
harness.send('0 C 192.168.1.10 12345 10.0.0.1 6667');
harness.send('0 A S :PLAIN');
await harness.waitForOutput(/^c 0/);
const credentials = Buffer.from('\0testuser\0testpass').toString('base64');
harness.send(`0 a :${credentials}`);
await harness.waitForOutput(/^L 0/);
await harness.waitForOutput(/^Z 0/);
// Now hurry up to finish connection
harness.send('0 H Users');
// Should accept the client with D message
const doneLine = await harness.waitForOutput(/^D 0 192\.168\.1\.10 12345/);
expect(doneLine).toBeDefined();
});
});
describe('WEBIRC Handling', () => {
let harness: IAuthTestHarness;
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
`);
harness = await createTestHarness(configPath);
});
afterEach(async () => {
await harness?.close();
});
it('should ignore untrusted WEBIRC (capital W)', async () => {
harness.send('0 C 10.0.0.100 12345 10.0.0.1 6667');
harness.send('0 W password user host.example.com 192.168.1.10');
await harness.waitForOutput(/untrusted WEBIRC/i);
});
it('should process trusted WEBIRC (lowercase w)', async () => {
harness.send('0 C 10.0.0.100 12345 10.0.0.1 6667');
harness.send('0 w password user host.example.com 192.168.1.10');
harness.send('0 H Users');
// Should accept with new IP
const doneLine = await harness.waitForOutput(/^D 0 192\.168\.1\.10/);
expect(doneLine).toBeDefined();
});
});
describe('Error Handling', () => {
let harness: IAuthTestHarness;
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
`);
harness = await createTestHarness(configPath);
});
afterEach(async () => {
await harness?.close();
});
it('should handle malformed client intro gracefully', async () => {
harness.send('0 C'); // Missing IP and ports
// Should not crash, might log an error
await new Promise(r => setTimeout(r, 100));
expect(harness.process.exitCode).toBeNull(); // Still running
});
it('should handle unknown message types gracefully', async () => {
harness.send('0 Z some unknown message');
await harness.waitForOutput(/unknown message/i, 1000).catch(() => {});
expect(harness.process.exitCode).toBeNull(); // Still running
});
it('should handle Hurry for unknown client gracefully', async () => {
harness.send('99 H Users'); // Client 99 was never introduced
await harness.waitForOutput(/ERROR.*hurry/i, 1000).catch(() => {});
expect(harness.process.exitCode).toBeNull(); // Still running
});
});
describe('IPv6 Handling', () => {
let harness: IAuthTestHarness;
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH DNSBL server=dnsbl.example.com index=2
`);
harness = await createTestHarness(configPath);
});
afterEach(async () => {
await harness?.close();
});
it('should skip DNSBL lookups for IPv6 and accept client', async () => {
harness.send('0 C 2001:db8::1 12345 ::1 6667');
harness.send('0 H Users');
// Should accept (IPv6 skips DNSBL lookups)
const doneLine = await harness.waitForOutput(/^D 0/);
expect(doneLine).toBeDefined();
});
});
});
+273
View File
@@ -0,0 +1,273 @@
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { writeFileSync, unlinkSync, mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import {
parseUsersFile,
verifyPassword,
generateHash,
decodeSASLPlain,
authenticatePlain,
} from '../src/sasl.js';
describe('SASL Module', () => {
describe('generateHash', () => {
it('should generate SHA-256 hash with $5$ prefix', () => {
const hash = generateHash('password', 'sha256');
expect(hash).toMatch(/^\$5\$[A-Za-z0-9]+\$[A-Za-z0-9+/]+$/);
});
it('should generate SHA-512 hash with $6$ prefix', () => {
const hash = generateHash('password', 'sha512');
expect(hash).toMatch(/^\$6\$[A-Za-z0-9]+\$[A-Za-z0-9+/]+$/);
});
it('should generate MD5 hash with $1$ prefix', () => {
const hash = generateHash('password', 'md5');
expect(hash).toMatch(/^\$1\$[A-Za-z0-9]+\$[A-Za-z0-9+/]+$/);
});
it('should generate different hashes for different passwords', () => {
const hash1 = generateHash('password1', 'sha256');
const hash2 = generateHash('password2', 'sha256');
expect(hash1).not.toBe(hash2);
});
it('should generate different hashes for same password (different salt)', () => {
const hash1 = generateHash('password', 'sha256');
const hash2 = generateHash('password', 'sha256');
// Salts are random, so hashes should be different
expect(hash1).not.toBe(hash2);
});
});
describe('verifyPassword', () => {
it('should verify SHA-256 hashed password', () => {
const hash = generateHash('testpass', 'sha256');
expect(verifyPassword('testpass', hash)).toBe(true);
expect(verifyPassword('wrongpass', hash)).toBe(false);
});
it('should verify SHA-512 hashed password', () => {
const hash = generateHash('testpass', 'sha512');
expect(verifyPassword('testpass', hash)).toBe(true);
expect(verifyPassword('wrongpass', hash)).toBe(false);
});
it('should verify MD5 hashed password', () => {
const hash = generateHash('testpass', 'md5');
expect(verifyPassword('testpass', hash)).toBe(true);
expect(verifyPassword('wrongpass', hash)).toBe(false);
});
it('should verify plain text password', () => {
expect(verifyPassword('plainpass', 'plainpass')).toBe(true);
expect(verifyPassword('wrongpass', 'plainpass')).toBe(false);
});
it('should reject invalid hash format', () => {
expect(verifyPassword('pass', '$invalid$format')).toBe(false);
expect(verifyPassword('pass', '$99$salt$hash')).toBe(false);
});
it('should handle empty password', () => {
const hash = generateHash('', 'sha256');
expect(verifyPassword('', hash)).toBe(true);
expect(verifyPassword('notempty', hash)).toBe(false);
});
});
describe('decodeSASLPlain', () => {
it('should decode valid SASL PLAIN data', () => {
// Format: base64(authzid \0 authcid \0 password)
const data = Buffer.from('\0testuser\0testpass').toString('base64');
const result = decodeSASLPlain(data);
expect(result).not.toBeNull();
expect(result?.authzid).toBe('');
expect(result?.authcid).toBe('testuser');
expect(result?.password).toBe('testpass');
});
it('should decode with authzid', () => {
const data = Buffer.from('authzid\0authcid\0password').toString('base64');
const result = decodeSASLPlain(data);
expect(result).not.toBeNull();
expect(result?.authzid).toBe('authzid');
expect(result?.authcid).toBe('authcid');
expect(result?.password).toBe('password');
});
it('should return null for invalid base64', () => {
const result = decodeSASLPlain('not-valid-base64!!!');
// Actually base64 decode may not fail, it will just produce garbage
// Let's test with wrong number of parts
});
it('should return null for wrong number of parts', () => {
// Only 2 parts instead of 3
const data = Buffer.from('user\0pass').toString('base64');
const result = decodeSASLPlain(data);
expect(result).toBeNull();
});
it('should handle empty fields', () => {
const data = Buffer.from('\0\0').toString('base64');
const result = decodeSASLPlain(data);
expect(result).not.toBeNull();
expect(result?.authzid).toBe('');
expect(result?.authcid).toBe('');
expect(result?.password).toBe('');
});
it('should handle special characters', () => {
const data = Buffer.from('\0user@example.com\0p@ss:word!').toString('base64');
const result = decodeSASLPlain(data);
expect(result).not.toBeNull();
expect(result?.authcid).toBe('user@example.com');
expect(result?.password).toBe('p@ss:word!');
});
});
describe('parseUsersFile', () => {
let tmpDir: string;
let usersFile: string;
beforeAll(() => {
tmpDir = mkdtempSync(join(tmpdir(), 'iauthd-test-'));
usersFile = join(tmpDir, 'users');
});
afterAll(() => {
try {
unlinkSync(usersFile);
} catch {}
});
it('should parse simple users file', () => {
writeFileSync(usersFile, 'testuser:testpass\nadmin:adminpass\n');
const db = parseUsersFile(usersFile);
expect(db.users.size).toBe(2);
expect(db.users.get('testuser')?.passwordHash).toBe('testpass');
expect(db.users.get('admin')?.passwordHash).toBe('adminpass');
});
it('should skip comments and empty lines', () => {
writeFileSync(usersFile, '# Comment\n\nuser:pass\n \n# Another comment\n');
const db = parseUsersFile(usersFile);
expect(db.users.size).toBe(1);
expect(db.users.get('user')?.passwordHash).toBe('pass');
});
it('should lowercase usernames', () => {
writeFileSync(usersFile, 'TestUser:pass\nADMIN:pass2\n');
const db = parseUsersFile(usersFile);
expect(db.users.has('testuser')).toBe(true);
expect(db.users.has('admin')).toBe(true);
expect(db.users.has('TestUser')).toBe(false);
});
it('should handle passwords with colons', () => {
writeFileSync(usersFile, 'user:pass:with:colons\n');
const db = parseUsersFile(usersFile);
expect(db.users.get('user')?.passwordHash).toBe('pass:with:colons');
});
it('should handle crypt-style hashes', () => {
const hash = '$5$salt$hashvalue';
writeFileSync(usersFile, `user:${hash}\n`);
const db = parseUsersFile(usersFile);
expect(db.users.get('user')?.passwordHash).toBe(hash);
});
it('should return empty db for non-existent file', () => {
const db = parseUsersFile('/nonexistent/file');
expect(db.users.size).toBe(0);
});
it('should skip lines without colon', () => {
writeFileSync(usersFile, 'validuser:pass\ninvalidline\nanotheruser:anotherpass\n');
const db = parseUsersFile(usersFile);
expect(db.users.size).toBe(2);
expect(db.users.has('validuser')).toBe(true);
expect(db.users.has('anotheruser')).toBe(true);
});
});
describe('authenticatePlain', () => {
let tmpDir: string;
let usersFile: string;
beforeAll(() => {
tmpDir = mkdtempSync(join(tmpdir(), 'iauthd-test-'));
usersFile = join(tmpDir, 'users');
// Create users file with various hash types
const sha256Hash = generateHash('sha256pass', 'sha256');
const sha512Hash = generateHash('sha512pass', 'sha512');
writeFileSync(usersFile, [
`plainuser:plainpass`,
`sha256user:${sha256Hash}`,
`sha512user:${sha512Hash}`,
].join('\n'));
});
afterAll(() => {
try {
unlinkSync(usersFile);
} catch {}
});
it('should authenticate with plain text password', () => {
const db = parseUsersFile(usersFile);
const result = authenticatePlain(db, 'plainuser', 'plainpass');
expect(result).toBe('plainuser');
});
it('should authenticate with SHA-256 hashed password', () => {
const db = parseUsersFile(usersFile);
const result = authenticatePlain(db, 'sha256user', 'sha256pass');
expect(result).toBe('sha256user');
});
it('should authenticate with SHA-512 hashed password', () => {
const db = parseUsersFile(usersFile);
const result = authenticatePlain(db, 'sha512user', 'sha512pass');
expect(result).toBe('sha512user');
});
it('should reject wrong password', () => {
const db = parseUsersFile(usersFile);
const result = authenticatePlain(db, 'plainuser', 'wrongpass');
expect(result).toBeNull();
});
it('should reject non-existent user', () => {
const db = parseUsersFile(usersFile);
const result = authenticatePlain(db, 'nouser', 'anypass');
expect(result).toBeNull();
});
it('should be case-insensitive for username', () => {
const db = parseUsersFile(usersFile);
const result = authenticatePlain(db, 'PlainUser', 'plainpass');
expect(result).toBe('plainuser');
});
});
});
+313
View File
@@ -0,0 +1,313 @@
#!/usr/bin/env npx tsx
/**
* Memory stress test for iauthd-ts
*
* Simulates thousands of client connections to verify:
* 1. Memory doesn't leak (client map cleanup)
* 2. DNS cache doesn't grow unbounded
* 3. Performance remains stable under load
*
* Usage:
* npm run stress
* npm run stress -- --clients=10000 --duration=60
*/
import { spawn, ChildProcess } from 'node:child_process';
import { writeFileSync, mkdtempSync, rmSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { createInterface } from 'node:readline';
import { parseArgs } from 'node:util';
interface StressOptions {
clients: number; // Total clients to simulate
concurrent: number; // Max concurrent connections
duration: number; // Max duration in seconds
verbose: boolean; // Verbose output
}
interface Stats {
clientsSent: number;
clientsAccepted: number;
clientsRejected: number;
startTime: number;
lastHeapUsed: number;
maxHeapUsed: number;
samples: Array<{ time: number; heap: number; clients: number; cache: number }>;
}
function parseOptions(): StressOptions {
const { values } = parseArgs({
options: {
clients: { type: 'string', short: 'n', default: '5000' },
concurrent: { type: 'string', short: 'c', default: '100' },
duration: { type: 'string', short: 'd', default: '120' },
verbose: { type: 'boolean', short: 'v', default: false },
},
strict: true,
});
return {
clients: parseInt(values.clients!, 10),
concurrent: parseInt(values.concurrent!, 10),
duration: parseInt(values.duration!, 10),
verbose: values.verbose!,
};
}
function generateRandomIP(): string {
const a = Math.floor(Math.random() * 223) + 1; // 1-223 (avoid 0 and 224+)
const b = Math.floor(Math.random() * 256);
const c = Math.floor(Math.random() * 256);
const d = Math.floor(Math.random() * 256);
return `${a}.${b}.${c}.${d}`;
}
async function runStressTest(options: StressOptions): Promise<void> {
console.log('='.repeat(60));
console.log('iauthd-ts Memory Stress Test');
console.log('='.repeat(60));
console.log(`Clients to simulate: ${options.clients}`);
console.log(`Max concurrent: ${options.concurrent}`);
console.log(`Max duration: ${options.duration}s`);
console.log('='.repeat(60));
console.log();
// Create temp config
const tempDir = mkdtempSync(join(tmpdir(), 'iauthd-stress-'));
const configPath = join(tempDir, 'stress.conf');
// Use a DNSBL that will respond quickly (or use a fake one)
// For stress testing, we want quick responses so we use short timeout
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH DNSTIMEOUT 1
#IAUTH CACHETIME 60
#IAUTH BLOCKMSG Stress test rejection
#IAUTH DNSBL server=zen.spamhaus.org index=2,3,4,5,6,7 mark=spamhaus block=anonymous
`);
const stats: Stats = {
clientsSent: 0,
clientsAccepted: 0,
clientsRejected: 0,
startTime: Date.now(),
lastHeapUsed: 0,
maxHeapUsed: 0,
samples: [],
};
// Spawn the daemon with memory tracking
const proc = spawn('node', [
'--expose-gc',
'--max-old-space-size=256', // Limit heap to catch leaks faster
'dist/index.js',
'-c', configPath,
], {
cwd: join(import.meta.dirname, '..'),
stdio: ['pipe', 'pipe', 'pipe'],
env: {
...process.env,
NODE_OPTIONS: '--expose-gc',
},
});
let cacheSize = 0;
let activeClients = 0;
const rl = createInterface({ input: proc.stdout! });
rl.on('line', (line) => {
if (options.verbose) {
console.log('< ' + line);
}
if (line.startsWith('D ')) {
stats.clientsAccepted++;
activeClients--;
} else if (line.startsWith('k ')) {
stats.clientsRejected++;
activeClients--;
} else if (line.includes('Cache size:')) {
const match = line.match(/Cache size: (\d+)/);
if (match) {
cacheSize = parseInt(match[1], 10);
}
}
});
proc.stderr?.on('data', (data) => {
if (options.verbose) {
console.error('stderr:', data.toString());
}
});
const send = (line: string) => {
if (options.verbose) {
console.log('> ' + line);
}
proc.stdin!.write(line + '\n');
};
// Wait for startup
await new Promise<void>((resolve) => {
const checkStartup = setInterval(() => {
// Check if we've seen the startup messages
if (stats.clientsSent === 0) {
clearInterval(checkStartup);
resolve();
}
}, 100);
setTimeout(() => {
clearInterval(checkStartup);
resolve();
}, 2000);
});
console.log('Daemon started. Beginning stress test...\n');
// Send server info
send('-1 M stress.test.server 65535');
const startTime = Date.now();
const endTime = startTime + (options.duration * 1000);
let clientId = 0;
// Progress reporting
const progressInterval = setInterval(() => {
const elapsed = (Date.now() - startTime) / 1000;
const rate = stats.clientsSent / elapsed;
const heapUsed = process.memoryUsage().heapUsed / 1024 / 1024;
stats.samples.push({
time: elapsed,
heap: heapUsed,
clients: activeClients,
cache: cacheSize,
});
if (heapUsed > stats.maxHeapUsed) {
stats.maxHeapUsed = heapUsed;
}
stats.lastHeapUsed = heapUsed;
process.stdout.write(
`\rSent: ${stats.clientsSent} | Accepted: ${stats.clientsAccepted} | ` +
`Rejected: ${stats.clientsRejected} | Active: ${activeClients} | ` +
`Cache: ${cacheSize} | Rate: ${rate.toFixed(1)}/s | ` +
`Elapsed: ${elapsed.toFixed(1)}s `
);
}, 1000);
// Main send loop
const sendBatch = () => {
const now = Date.now();
if (now >= endTime || stats.clientsSent >= options.clients) {
return false;
}
// Send up to concurrent limit
while (activeClients < options.concurrent && stats.clientsSent < options.clients) {
const ip = generateRandomIP();
const port = 10000 + (clientId % 55535);
send(`${clientId} C ${ip} ${port} 10.0.0.1 6667`);
send(`${clientId} H Users`);
stats.clientsSent++;
activeClients++;
clientId++;
}
return true;
};
// Run the send loop
while (sendBatch()) {
await new Promise(r => setTimeout(r, 10));
}
// Wait for remaining clients to be processed
console.log('\n\nWaiting for remaining clients to be processed...');
const drainStart = Date.now();
while (activeClients > 0 && (Date.now() - drainStart) < 30000) {
await new Promise(r => setTimeout(r, 100));
}
clearInterval(progressInterval);
// Cleanup
proc.stdin!.end();
await new Promise<void>((resolve) => {
proc.on('close', () => resolve());
setTimeout(() => {
proc.kill('SIGTERM');
resolve();
}, 2000);
});
try {
rmSync(tempDir, { recursive: true });
} catch {}
// Print results
const totalTime = (Date.now() - startTime) / 1000;
console.log('\n');
console.log('='.repeat(60));
console.log('STRESS TEST RESULTS');
console.log('='.repeat(60));
console.log(`Total clients sent: ${stats.clientsSent}`);
console.log(`Total clients accepted: ${stats.clientsAccepted}`);
console.log(`Total clients rejected: ${stats.clientsRejected}`);
console.log(`Unprocessed clients: ${stats.clientsSent - stats.clientsAccepted - stats.clientsRejected}`);
console.log(`Total time: ${totalTime.toFixed(2)}s`);
console.log(`Average rate: ${(stats.clientsSent / totalTime).toFixed(2)} clients/s`);
console.log(`Final cache size: ${cacheSize}`);
console.log('');
// Memory analysis
console.log('MEMORY ANALYSIS');
console.log('-'.repeat(60));
if (stats.samples.length > 1) {
const firstSample = stats.samples[0];
const lastSample = stats.samples[stats.samples.length - 1];
const heapGrowth = lastSample.heap - firstSample.heap;
const heapGrowthPercent = (heapGrowth / firstSample.heap) * 100;
console.log(`Initial heap: ${firstSample.heap.toFixed(2)} MB`);
console.log(`Final heap: ${lastSample.heap.toFixed(2)} MB`);
console.log(`Max heap: ${stats.maxHeapUsed.toFixed(2)} MB`);
console.log(`Heap growth: ${heapGrowth.toFixed(2)} MB (${heapGrowthPercent.toFixed(1)}%)`);
// Check for memory leak indicators
console.log('');
if (heapGrowthPercent > 100) {
console.log('⚠️ WARNING: Significant heap growth detected. Possible memory leak.');
} else if (heapGrowthPercent > 50) {
console.log('⚠️ NOTICE: Moderate heap growth. Monitor in production.');
} else {
console.log('✅ Memory usage appears stable.');
}
// Check if all clients were processed
const unprocessed = stats.clientsSent - stats.clientsAccepted - stats.clientsRejected;
if (unprocessed > 0) {
console.log(`⚠️ WARNING: ${unprocessed} clients were not processed. Possible state leak.`);
} else {
console.log('✅ All clients were processed correctly.');
}
// Check cache growth
const clientsPerCacheEntry = stats.clientsSent / Math.max(cacheSize, 1);
console.log(`Cache efficiency: ${clientsPerCacheEntry.toFixed(1)} clients per cache entry`);
}
console.log('='.repeat(60));
}
// Run the test
const options = parseOptions();
runStressTest(options).catch(console.error);
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": ["ES2022"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
+24
View File
@@ -0,0 +1,24 @@
# SASL Users File for iauthd-ts
# Format: username:passwordhash
#
# Supported hash formats:
# $5$salt$hash - SHA-256 crypt
# $6$salt$hash - SHA-512 crypt
# $1$salt$hash - MD5 crypt
# plaintext - Plain text (for testing only, not recommended)
#
# Use the genhash.ts utility to generate hashes:
# npx tsx src/genhash.ts <password> [sha256|sha512|md5]
#
# Example entries:
# Test user with plain text password (for testing only!)
testuser:testpass
# User with SHA-256 hashed password
# To generate: npx tsx src/genhash.ts mypassword sha256
#admin:$5$randomsalt$hashedpasswordhere
# User with SHA-512 hashed password (most secure)
# To generate: npx tsx src/genhash.ts mypassword sha512
#secureuser:$6$randomsalt$hashedpasswordhere
+15
View File
@@ -0,0 +1,15 @@
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
globals: true,
environment: 'node',
include: ['tests/**/*.test.ts'],
coverage: {
provider: 'v8',
reporter: ['text', 'html'],
include: ['src/**/*.ts'],
exclude: ['src/index.ts'],
},
},
});
+11
View File
@@ -0,0 +1,11 @@
#IAUTH POLICY RTAWUwFr
#IAUTH DNSTIMEOUT 5
#IAUTH BLOCKMSG Sorry! Your connection to AfterNET has been rejected because of your internet address's poor reputation. You may try an authenticated login using Login-On-Connect (LOC) instead. See http://afternet.org/rbl for more information.
#IAUTH DNSBL server=dnsbl.sorbs.net index=2,3,4,5,6,7,9 mark=sorbs block=anonymous
#IAUTH DNSBL server=dnsbl.ahbl.org index=3,14,15,16,17,18,19,20 mark=ahbl 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
#IAUTH DNSBL server=dnsbltest.afternet.org index=2 mark=dnsbltest2 block=anonymous
#IAUTH DNSBL server=dnsbltest.afternet.org index=1 mark=dnsbltest1
+746
View File
@@ -0,0 +1,746 @@
#!/usr/bin/perl
##############################################
# iauthd for doing DNSBL lookups, implimented in perl. Can be extended easily to also handle LOC/SASL
#
# Requirements:
# You need to install some perl dependancies for this to run.
#
# Debian/ubuntu/mint:
# apt-get install libpoe-perl libpoe-component-client-dns-perl libterm-readkey-perl libfile-slurp-perl libtime-duration-perl
#
# fedora/redhat/centos:
# yum install perl-POE perl-POE-Component-Client-DNS perl-TermReadKey perl-slurp perl-Time-Duration
#
# freebsd:
# ports dns/p5-POE-Component-Client-DNS devel/p5-Time-Duration devel/p5-File-Slurp devel/p5-Term-ReadKey
#
# or via cpan:
# cpan install Term::ReadKey POE::Component::Client::DNS File::Slurp Time::Duration
#
# Installation:
# Copy somewhere convenient
#
# Usage:
# iauth.pl -f /path/to/config
#
# Configuration:
#
# * Config directives begin with #IAUTHD and are one per line
# * Because configuration begins with a #, it can piggy back on existing
# ircd.conf file. ircd will ignore it. Handy for those using linesync.
# * Syntax is: #IAUTHD <directive> <arguments>
#
#
# Description of config 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 seperated 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 LOC/SASL
# whitelist- listed users wont be blocked by any rbl
# cachetime - Override default cache timeout. Useful for whitelists you run yourself
#
# DEBUG: - values greater than 0 turn iauth debugging on in the ircd
#
# Example:
#IAUTH POLICY RTAWUwFr
#IAUTH CACHETIME 86400
#IAUTH BLOCKMSG Sorry! Your connection has been rejected because of your internet address's 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 = "/usr/bin/perl" "iauthd.pl" "-v" "-d" "-c" "ircd.conf";
# };
#
# Debugging:
# * oper up first
# * set snomask /quote mode yournick +s 262144
#
########################3
=head1 NAME
iauthd.pl - a perl based iauthd daemon supporting DNSBL lookups
=head1 SYNOPSIS
iauthd.pl [options] --config=configfile.conf
Options: (short)
--help (-h) Print this message
--config (-c) Config file to read
--debug (-d) Turn on debugging in the ircd
--verbose (-v) Turn on debugging in iauthd
=cut
use strict;
use warnings;
use Getopt::Long;
use Pod::Usage;
use POE qw ( Wheel::SocketFactory Wheel::ReadWrite Filter::Line Driver::SysRW );
use POE::Driver::SysRW;
use POE::Filter::Line;
use POE::Wheel::ReadWrite;
use POE::Component::Client::DNS;
use Term::ReadKey;
use POSIX;
use File::Slurp;
use Data::Dumper;
use Time::Duration;
my $DEFAULT_CACHETIME = 60 * 60 * 24;
my $STARTTIME = time();
my $VERSION = "7";
my %clients;
my %dnsbl_cache;
my $count_pass = 0;
my $count_reject = 0;
my %dnsbl_counters;
my $poe_heap;
my %options;
GetOptions( \%options, 'help', 'config:s', 'debug', 'verbose') or confess("Error");
pod2usage(1) if ($options{'help'} or !$options{'config'});
my %config = read_configfile($options{'config'});
my $named = POE::Component::Client::DNS->spawn(
Alias => "named",
Timeout => ($config{'dnstimeout'} ? $config{'dnstimeout'} : 5)
);
# Create the POE object with callbacks
POE::Session->create (
inline_states => {
_start => \&poe_start,
#_stop => \&poe_stop,
myinput_event => \&myinput_event,
myerror_event => \&myerror_event,
myint_event => \&myint_event,
myresponse_event => \&myresponse_event,
}
);
# Start the event loop
POE::Kernel->run();
exit 0;
#####
#
# Subs
#
#####
sub poe_print {
my $str = join(' ', @_);
if($poe_heap) {
$poe_heap->{stdio}->put($str);
}
else {
print "$str\n";
}
}
sub debug {
my $str = join(' ', @_);
if($options{'debug'}) {
poe_print("> :$str");
}
}
sub poe_start {
my ( $kernel, $heap ) = @_[ KERNEL, HEAP ];
handle_startup();
# Start the terminal reader/writer.
$heap->{stdio} = POE::Wheel::ReadWrite->new (
InputHandle => \*STDIN,
OutputHandle => \*STDOUT,
InputEvent => "myinput_event",
Filter => POE::Filter::Line->new(),
ErrorEvent => "myerror_event",
);
$kernel->sig(INT => "myint_event");
$poe_heap = $heap;
}
sub poe_stop {
my ( $kernel, $heap ) = @_[ KERNEL, HEAP ];
poe_print "Doing poe_stop";
#$kernel->alias_remove($fileio_uuid);
}
sub myinput_event {
my ( $kernel, $heap, $line ) = @_[ KERNEL, HEAP, ARG0 ];
#debug("read a line...... '$line'");
return unless($line);
my @line = split / /, $line;
my $source = shift @line;
my $message = shift @line;
my $args = join(' ', @line);
return unless(defined $message);
# warning, this one can contain passwords...
#debug("<-- $line");
#print "Parsed source=$source, message=$message\n";
if($message eq 'C') { #client introduction: <remoteip> <remoteport> <localip> <localport>
my ($ip, $port, $serverip, $serverport) = split( / /, $args);
if(!defined $ip) {
debug("Got a C without a valid IP. Ignoring");
return;
}
handle_client($kernel, $heap, $source, $ip, $port, $serverip, $serverport);
}
elsif($message eq 'D') { #Client disconnect
debug("Client $source disconnected.");
if(exists $clients{$source}) {
client_delete($clients{$source});
}
}
elsif($message eq 'F') { #Client has ssl cert: <fingerprint>
}
elsif($message eq 'R') { #Client authed with sasl or loc: <account>
my $account = $args;
handle_auth($kernel, $heap, $source, $account);
}
elsif($message eq 'N') { #hostname received: <hostname>
}
elsif($message eq 'd') { #hostname timed out
}
elsif($message eq 'P') { #Client Password: :<password>
}
elsif($message eq 'U') { #client username: <username> <hostname> <servername> :<user info ...>
}
elsif($message eq 'u') { #client username: <username>
}
elsif($message eq 'n') { #client nickname: <nickname>
}
elsif($message eq 'H') { #Hurry up: <class>
handle_hurry($source, $args);
}
elsif($message eq 'T') { #Client Registered
}
elsif($message eq 'E') { #Error: :<aditional text>
debug("ircd complaining of error: $args");
}
elsif($message eq 'e') { #Error: :<aditional text>
if($args eq 'rehash') {
debug("Got a rehash. Rereading config file");
%config = read_configfile($options{'config'});
}
}
elsif($message eq 'M') { #Server name an dcapacity: <servername> <capacity>
}
elsif($message eq 'X') { #extension query reply: <servername> <routing> :<reply>
}
elsif($message eq 'x') { #extension query reply not linked: <servername> <routing> :Server not online
}
elsif($message eq 'W' || $message eq 'w') { #webirc received from client (or W trusted client): <pass> <user> <host> <ip>
my ($pass, $user, $host, $ip) = split(/ /, $args);
debug("Got a W line: $source - pass=<notshown>, user=$user, host=$host, ip=$ip");
if($message eq 'W') { #untrusted ones are ignored TODO: send a kill? (k)
debug("Got an untrusted WEBIRC attempt. Ignoring.");
}
else {
handle_webirc($kernel, $heap, $source, $pass, $user, $host, $ip);
}
}
else {
debug("Got unknown message '$message' from server");
}
}
sub myerror_event {
my ( $kernel, $heap ) = @_[ KERNEL, HEAP ];
debug("Everything either went to hell or we got to the end. Shutting down...");
exit 0;
#delete $heap->{wheels}->{$fileio_uuid};
$kernel->yield("_stop");
}
sub myresponse_event {
my ( $kernel, $heap, $response ) = @_[ KERNEL, HEAP, ARG0 ];
#debug("Got a response ... ");
my @result;
if(!defined $response->{response}) {
debug("got an empty response.. probably a timeout");
}
else {
foreach my $answer ($response->{response}->answer()) {
debug(
"$response->{host} = ",
$answer->type(), " ",
$answer->rdatastr(),
);
push @result, $answer->rdatastr();
}
}
handle_dnsbl_response($kernel, $heap, $response->{'host'}, \@result, 0);
}
sub read_configfile {
my $file = shift;
my %config;
my @dnsbls;
my $cfgnum = 0;
$config{'dnsbls'} = \@dnsbls;
$config{'blockmsg'} = "Your internet address has been rejected due to reputation (DNSBL).";
$config{'cachetime'} = $DEFAULT_CACHETIME;
debug("Reading $file...");
send_newconfig();
poe_print "A * version :Nefarious iauthd.pl $VERSION";
foreach my $line (read_file($file)) {
chomp $line;
if($line =~ /^\#IAUTH\s(\w+)(\s+(.+))?/) {
my $directive = $1;
my $args = $3;
$cfgnum++;
send_config("$cfgnum: $directive $args");
#debug("Got a config line: $line");
#debug(" directive is $directive");
#debug(" arg is $args");
if($directive eq 'POLICY') {
$config{'policy'} = $args;
}
elsif($directive eq 'DNSBL') {
my %dnsblconfig;
foreach my $arg (split /\s+/, $args) {
if($arg =~ /(\w+)\=(.+)/) { #key=val pair
my $k = $1;
my $v = $2;
$dnsblconfig{$k} = $v;
}
else {
$dnsblconfig{$arg} = 1;
}
}
$dnsblconfig{'cfgnum'} = $cfgnum;
push @dnsbls, \%dnsblconfig;
$dnsbl_counters{$dnsblconfig{'cfgnum'}} = 0;
}
elsif($directive eq 'DEBUG') {
$config{'debug'} = 1;
}
elsif($directive eq 'DNSTIMEOUT') {
$config{'dnstimeout'} = $args;
}
elsif($directive eq 'BLOCKMSG') {
$config{'blockmsg'} = $args;
}
elsif($directive eq 'CACHETIME') {
$config{'cachetime'} = $args;
}
else {
debug("Unknown IAUTH directive '$directive'");
}
}
}
#print Dumper(\%config);
return %config;
}
sub handle_startup {
poe_print "G 1";
poe_print "V :Nefarious2 iauthd.pl version $VERSION";
#TODO: send the config version of this..
poe_print "O RTAWUwFr";
#print "a\n";
#print "s\n";
debug("Starting up");
send_stats();
}
sub handle_client {
my ($kernel, $heap, $source, $ip, $port, $serverip, $serverport) = @_;
debug("Handling client connect: $source from $ip");
if(exists $clients{$source}){ #existing entry.
debug("ERROR: Found existing entry for client $source (ip=$ip). Something got left hanging? Exiting..");
exit 1;
}
#add client to list
debug("Adding new entry for client $source (ip=$ip)");
my $client = { id=>$source,
ip=>$ip,
port=>$port,
serverip=>$serverip,
serverport=>$serverport,
whitelist=>0,
block=>0,
marks=>{},
class=>undef,
hurry=>0,
lookups=>{},
};
$clients{$source} = $client;
if($ip =~ /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/) {
my $pi = join('.', reverse(split(/\./,$ip)));
foreach my $dnsbl (@{$config{'dnsbls'}}) {
my $server = $dnsbl->{'server'};
#Mark the lookup as pending.. (1)
$client->{'lookups'}->{$dnsbl->{'cfgnum'}} = 1;
debug("Looking up client $source: $pi.$server");
#Use global or specific cachetime setting
my $cachetime = $config{'cachetime'};
if(exists $dnsbl->{'cachetime'}) {
$cachetime = $dnsbl->{'cachetime'};
}
#purge from the cache if it matches...
if( exists $dnsbl_cache{"$pi.$server"}
&& exists $dnsbl_cache{"$pi.$server"}->{'ts'}
&& $dnsbl_cache{"$pi.$server"}->{'ts'} < ( time() - $cachetime) ) {
debug("Deleting stale cache entry for $pi.$server");
delete $dnsbl_cache{"$pi.$server"};
}
#Look up in the cache
if(exists $dnsbl_cache{"$pi.$server"}) { #Found a cache entry
my $cache_entry = $dnsbl_cache{"$pi.$server"};
debug("Found dnsbl cache entry for $pi.$server");
if(defined $cache_entry->{'result'}) { #got a completed lookup in the cache
handle_dnsbl_response($kernel, $heap, "$pi.$server", $cache_entry->{'result'}, 1);
}
else { #we started looking it up but no reply yet
debug("Cache pending... on $pi.$server");
}
}
else { #This lookup is not in the cache yet
#Adding pending cache entry
debug("Adding cache entry for pending lookup $pi.$server");
$dnsbl_cache{"$pi.$server"} = { result=>undef, ts=>time()};
#Begin a POE lookup on the dnsbl
my $response = $named->resolve(
event => "myresponse_event",
host => "$pi.$server",
context => { },
);
if($response) {
$kernel->yield(response => $response);
}
}
} #each dnsbl
}
else {
debug("Unknown IP format: $ip, probably ipv6 or something... ignoring");
}
}
sub handle_webirc {
my ($kernel, $heap, $source, $pass, $user, $newhost, $newip) = @_;
if(exists $clients{$source}) {
my $client = $clients{$source};
#Save some values to recreate the client
my $port = $client->{'port'};
my $serverip = $client->{'serverip'};
my $serverport = $client->{'serverport'};
my $washurry = $client->{'hurry'};
#Delete the client record, we need to start over
client_delete($clients{$source});
#Create a new client and start fresh
handle_client($kernel, $heap, $source, $newip, $port, $serverip, $serverport);
if($washurry) {
$clients{$source}->{'hurry'} = 1;
}
}
else {
debug("Got a webirc for a client we don't know about? Ignored.");
}
}
sub handle_auth {
my ( $kernel, $heap, $source, $account ) = @_;
my $client = $clients{$source};
debug("Client authed as $account");
$client->{'account'} = $account;
handle_client_update($client);
}
#Got a DNS reply, or found a cached one.
sub handle_dnsbl_response {
my ( $kernel, $heap, $host, $results, $iscached ) = @_;
my $lookup_string;
#Save the answer in the cache.
$dnsbl_cache{$host} = { result=>$results, ts=>time()} unless($iscached);
$host =~ /^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.(.+)$/;
my $host_ip = "$4.$3.$2.$1";
my $dnsbl_server = "$5";
debug("Got a ". ($iscached?"cache hit":"DNS reply") . " for $host_ip from $dnsbl_server..." . @$results . " replies...");
#If this result is a hit for any dnsbls, find related clients and mark/block/whitelist etc
foreach my $ip (@$results) {
if($ip =~ /^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/) {
my $value = $4;
#debug("Looking at response value $value from $host");
foreach my $config_dnsbl (@{$config{'dnsbls'}}) {
next unless($config_dnsbl->{'server'} eq $dnsbl_server);
my $flag;
if(exists $config_dnsbl->{'index'}) {
foreach my $index (split(/,/, $config_dnsbl->{'index'})) {
if($value eq $index) {
$flag++;
}
}
}
if(exists $config_dnsbl->{'bitmask'}) {
foreach my $bitmask (split(/,/, $config_dnsbl->{'bitmask'})) {
if($bitmask & $value) {
$flag++;
}
}
}
if($flag) {
#Go through all the client records. Check if this positive dnsbl hit affects them
foreach my $client_id (keys %clients) {
my $client = $clients{$client_id};
if($client->{'ip'} eq $host_ip) {
#We found a client in the queue which matches this
#dnsbl. Mark them and flag them etc
debug("client $client->{id} matches $config_dnsbl->{server} result $value");
#$dnsbl_counters{$config_dnsbl->{'cfgnum'}}++;
foreach my $field (qw( whitelist block class )) {
if($config_dnsbl->{$field}) {
$client->{$field} = $config_dnsbl->{$field};
}
}
if($config_dnsbl->{'mark'}) {
$client->{'marks'}->{$config_dnsbl->{'mark'}} = $config_dnsbl;
}
$client->{'hits'}->{$config_dnsbl->{'cfgnum'}} = 1;
} #client matches reply
} #each client
}
# #each index
} #each dnsbl
}
else {
debug("Unable to parse dnsbl result: $ip");
}
} #foreach @results
foreach my $client (values %clients) {
if($client->{'hits'}) {
foreach my $cfgnum (keys %{$client->{'hits'}}) {
$dnsbl_counters{$cfgnum}++;
delete $client->{'hits'};
}
}
}
#Clear all pending states on all clients with matching ips waiting on any related dnsbls.
foreach my $dnsbl (@{$config{'dnsbls'}}) {
if($dnsbl_server eq $dnsbl->{'server'}) {
foreach my $client (values %clients) {
if($client->{'ip'} eq $host_ip) {
if($client->{'lookups'}->{$dnsbl->{'cfgnum'}}) {
$client->{'lookups'}->{$dnsbl->{'cfgnum'}} = 0;
handle_client_update($client);
}
}
}
}
}
}
#The client has been updated. Check if its done
sub handle_client_update {
my $client = shift;
my $pending = 0;
foreach my $v (values %{$client->{'lookups'}}) {
$pending += $v;
}
if($client->{'hurry'}) {
debug("Client $client->{id} has Hurry set and $pending pending requests");
if($pending < 1) {
if($client->{'whitelist'}) {
client_pass($client);
}
elsif( ($client->{'block'} eq 'all')
|| ($client->{'block'} eq 'anonymous' && !$client->{'account'})) {
client_reject($client, $config{'blockmsg'});
}
else {
client_pass($client);
}
}
}
else {
debug("Client $client->{id} has $pending pending requests");
}
}
sub handle_hurry {
my $source = shift;
my $class = shift;
my $client = $clients{$source};
if(!$client) {
debug("ERROR: Got a hurry for a client we arent even holding on to!");
return;
}
debug("Handling a hurry on $source");
$client->{'hurry'} = 1;
handle_client_update($client);
}
sub client_pass {
my $client = shift;
debug("Passing client ". $client->{'id'} . ' ('. $client->{'ip'} . ')');
#print Dumper($client);
foreach my $mark (keys %{$client->{'marks'}}) {
send_mark($client->{'id'}, $client->{'ip'}, $client->{'port'}, 'MARK', $mark);
}
send_done($client->{'id'}, $client->{'ip'}, $client->{'port'}, $client->{'class'}?$client->{'class'}:undef);
$count_pass++;
client_delete($client);
send_stats();
}
sub client_reject {
my $client = shift;
my $reason = shift;
debug("Rejecting client " . $client->{'id'} . ' ('. $client->{'ip'} . "): $reason");
send_kill($client->{'id'}, $client->{'ip'}, $client->{'port'}, $reason);
$count_reject++;
client_delete($client);
send_stats();
}
sub client_delete {
my $client = shift;
debug("Deleting client from hash tables");
delete($clients{$client->{'id'}});
}
sub send_mark {
my $id = shift;
my $remoteip = shift;
my $remoteport = shift;
my $marktype = shift;
my $markdata = shift;
return unless($markdata);
poe_print "m $id $remoteip $remoteport $marktype $markdata";
}
sub send_done {
my $id = shift;
my $remoteip = shift;
my $remoteport = shift;
my $class = shift;
if($class) {
poe_print "D $id $remoteip $remoteport $class";
}
else {
poe_print "D $id $remoteip $remoteport";
}
}
sub send_kill {
my $id = shift;
my $remoteip = shift;
my $remoteport = shift;
my $reason = shift;
poe_print "k $id $remoteip $remoteport :$reason";
}
sub send_newconfig {
poe_print "a";
}
sub send_config {
my $config = shift;
poe_print "A * iauthd.pl :$config";
}
sub send_stats {
my $up = POSIX::strftime "%a %b %e %H:%M:%S %Y", localtime($STARTTIME);
my $uptime = duration(time() - $STARTTIME);
poe_print "s";
poe_print "S iauthd.pl :Up since $up ($uptime)";
poe_print "S iauthd.pl :Cache size: ". %dnsbl_cache . "";
poe_print "S iauthd.pl :Total Passed: $count_pass";
poe_print "S iauthd.pl :Total Rejected: $count_reject";
foreach my $config_dnsbl (@{$config{'dnsbls'}}) {
my $d = $config_dnsbl->{'server'};
if(exists $config_dnsbl->{'index'}) {
$d .= " (" . $config_dnsbl->{'index'}. ")";
}
if(exists $config_dnsbl->{'bitmask'}) {
$d .= " (" . $config_dnsbl->{'bitmask'}. ")";
}
my $c = 0;
if( exists $dnsbl_counters{$config_dnsbl->{'cfgnum'}}) {
$c = $dnsbl_counters{$config_dnsbl->{'cfgnum'}};
}
poe_print "S iauthd.pl :$d: $c";
}
}
+44
View File
@@ -0,0 +1,44 @@
#!/bin/bash
# If you put comments n your ircd.conf like this:
#
# SERVER foo.afternet.org
#
# then this script can parse those out and look up their IPs and add
# them to an icinga config file.
#
SRVLIST=/tmp/servers.txt
DATAFILE=/path/to/your/linesync/linesync.data
ICINGAFILE=/tmp/afternet_hosts.conf
# Run linesync
# Use linesync.data to get a server list
grep '# SERVER' "$DATAFILE" |awk '{print $3}' > "$SRVLIST"
while read servername; do
echo "I got $servername"
ip4=`host -t A "$servername"|awk '{print $4}'|grep -P '[0-9.]+'`
ip6=`host -t AAAA "$servername"|awk '{print $5}'|grep -P '[0-9:]+'`
echo "object Host \"$servername\" {" >> $ICINGAFILE
echo " import \"afternet-host\"" >> $ICINGAFILE
if [ x"${ip4}" != "x" ]; then
echo " address = \"$ip4\"" >> $ICINGAFILE
fi
if [ x"${ip6}" != "x" ]; then
echo " address6 = \"$ip6\"" >> $ICINGAFILE
fi
echo "}" >> $ICINGAFILE
done < "$SRVLIST"
echo "Saved icinga config to $ICINGAFILE"
+11
View File
@@ -0,0 +1,11 @@
CA="https://acme-v02.api.letsencrypt.org/directory"
OLDCA="https://acme-v01.api.letsencrypt.org/directory"
CHALLENGETYPE="dns-01"
BASEDIR=$SCRIPTDIR
DOMAINS_TXT="${BASEDIR}/domains.txt"
CERTDIR="${BASEDIR}/certs"
ACCOUNTDIR="${BASEDIR}/accounts"
HOOK="${BASEDIR}/hook.sh"
HOOK_CHAIN="yes"
PRIVATE_KEY_RENEW="no"
CONTACT_EMAIL="your-le-email@example.net"
+1
View File
@@ -0,0 +1 @@
yourmainserver.afternet.org irc.afternet.org
+58
View File
@@ -0,0 +1,58 @@
#!/usr/bin/env bash
NSUPDATE="nsupdate -k /home/alpha/dehydrated/nsupdate.key"
NSSERVER="127.0.0.1"
ZONE="le.example.net"
IRCDPEM="/home/alpha/ircd/lib/ircd.pem"
IRCDPID="/home/alpha/ircd/lib/ircd.pid"
deploy_challenge() {
local nsudttxt="server ${DNSSERVER}\nzone ${ZONE}.\n"
declare -a args=("$@")
for i in `seq 0 3 $(($#-1))`;
do
local DOMAIN="${args[$i]}" TOKEN_FILENAME="${args[$(($i+1))]}" TOKEN_VALUE="${args[$(($i+2))]}"
nsudttxt="${nsudttxt}update add _acme-challenge.${DOMAIN}.${ZONE}. 300 IN TXT \"${TOKEN_VALUE}\"\n"
printf "ADD: _acme-challenge.%s.%s. 300 IN TXT \"%s\"\n" "${DOMAIN}" "${ZONE}" "${TOKEN_VALUE}"
done
nsudttxt="${nsudttxt}send\n"
echo -e "${nsudttxt}" | $NSUPDATE
/bin/sleep 0.5
}
clean_challenge() {
local nsudttxt="server ${DNSSERVER}\nzone ${ZONE}.\n"
declare -a args=("$@")
for i in `seq 0 3 $(($#-1))`;
do
local DOMAIN="${args[$i]}" TOKEN_FILENAME="${args[$(($i+1))]}" TOKEN_VALUE="${args[$(($i+2))]}"
nsudttxt="${nsudttxt}update del _acme-challenge.${DOMAIN}.${ZONE}. 300 IN TXT \"${TOKEN_VALUE}\"\n"
printf "DEL: _acme-challenge.%s.%s. 300 IN TXT \"%s\"\n" "${DOMAIN}" "${ZONE}" "${TOKEN_VALUE}"
done
nsudttxt="${nsudttxt}send\n"
echo -e "${nsudttxt}" | $NSUPDATE
/bin/sleep 0.5
}
deploy_cert() {
local DOMAIN="${1}" KEYFILE="${2}" CERTFILE="${3}" FULLCHAINFILE="${4}" CHAINFILE="${5}" TIMESTAMP="${6}"
cat $KEYFILE > $IRCDPEM
cat $FULLCHAINFILE >> $IRCDPEM
kill -USR1 `cat $IRCDPID`
}
HANDLER="$1"; shift
if [[ "${HANDLER}" =~ ^(deploy_challenge|clean_challenge|deploy_cert)$ ]]; then
"$HANDLER" "$@"
fi
+9
View File
@@ -0,0 +1,9 @@
# This is used by nsupdate -k thisfile
# it is generated by:
#
# ddns-confgen -q -k some-key-name
#
key "some-key-name" {
algorithm hmac-sha256;
secret "CzSBCDAx5lvn+XuSr79bsB35v2JfAWPogK18mKhf1hw=";
};
+48
View File
@@ -0,0 +1,48 @@
==== Lets Encrypt ircd Certificates ====
This directory contains files and notes (in this file) about a proposed
way to use lets-encript ssl certificates. The trouble with LE certificates
that needs to be solved is thus:
* irc.network.org needs to point (via Route53 or similar) to any
particular server, and be valid
* servername.network.org needs to also point to that one server
and be valid
* Servers are run by different admins and those admins don't have
full trust to dns or website
Jobe has worked out a solution to this, and I am attempting to document
it for others to impliment easier.
The solution is to run an instance of the BIND dns server and
alias the acme lets-encript name to it from the primary domain.
Then in BIND, we setup access to each ircd server to add/remove TXT
entries to it. Each ircd server has its own key with privs that can
be revoked.
In our example we will use network.org as the primary network name
and lechallange.network.org as the subdomain used by BIND
First thing is to setup BIND somewhere. We make bind in charge of
the sub-domain le.network.org, specifically we are interested in adding
and removing TXT records as: _acme-challenge.le.network.org
Next setup the real network.org dns server. We add a CNAME from
_acme-challenge.network.org to _acme-challenge.le.network.org and an
NS record to le.network.org to our BIND server.
Finally, we set up dehydrated, and feed it in the required domain
consisting of: someserver.network.org with SAN of irc.network.org
dehydrated will add a TXT record called _acme-challenge.le.network.org
to BIND. Lets-encrypt will check _acme-challenge.network.org but will find
the CNAME to _acme-challenge.le.network.org and will follow it. When
complete, dehydrated will remove it again (And anyway, multiple TXT records
can exist and lets-encrypt will find the one it wants)
Finally, dehydrated will copy the files together as needed to create ircd.pem
and send a SIGUSR1 to ircd to reload.
This is a work in progress...
+60
View File
@@ -0,0 +1,60 @@
# Linesync Sidecar Container
# Provides git-based configuration synchronization for Nefarious IRCd
#
# Supports three modes:
# keygen - Generate SSH keypair for git authentication
# setup - Clone the linesync repository (initial setup)
# sync - Continuous sync loop (default)
#
# Automatically detects UID/GID from mounted directories for proper permissions.
FROM debian:12-slim
# Default UID/GID (will be overridden at runtime based on mounted directory ownership)
ENV LINESYNC_UID=1000
ENV LINESYNC_GID=1000
# Install required tools
RUN apt-get update && apt-get install -y --no-install-recommends \
bash \
git \
gawk \
openssh-client \
openssl \
ca-certificates \
curl \
gnupg \
gosu \
&& rm -rf /var/lib/apt/lists/*
# Install Docker CLI (for sending signals to nefarious container)
RUN install -m 0755 -d /etc/apt/keyrings \
&& curl -fsSL https://download.docker.com/linux/debian/gpg -o /etc/apt/keyrings/docker.asc \
&& chmod a+r /etc/apt/keyrings/docker.asc \
&& echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/debian bookworm stable" > /etc/apt/sources.list.d/docker.list \
&& apt-get update \
&& apt-get install -y --no-install-recommends docker-ce-cli \
&& rm -rf /var/lib/apt/lists/*
# Create user (UID/GID will be adjusted at runtime)
RUN groupadd -g ${LINESYNC_GID} linesync \
&& useradd -u ${LINESYNC_UID} -g ${LINESYNC_GID} -m linesync
# Create directories
RUN mkdir -p /home/linesync/.ssh \
&& mkdir -p /home/linesync/ircd \
&& chown -R linesync:linesync /home/linesync
# Copy scripts
COPY gitsync.sh /home/linesync/gitsync.sh
COPY linesync-entrypoint.sh /home/linesync/entrypoint.sh
RUN chmod +x /home/linesync/gitsync.sh /home/linesync/entrypoint.sh
# SSH config template (will be copied to user's .ssh at runtime)
RUN echo "Host *\n StrictHostKeyChecking accept-new\n UserKnownHostsFile /home/linesync/.ssh/known_hosts" > /etc/ssh/ssh_config.d/linesync.conf
WORKDIR /home/linesync
# Run as root initially; entrypoint will drop privileges after detecting UID/GID
ENTRYPOINT ["/home/linesync/entrypoint.sh"]
CMD ["sync"]
+166
View File
@@ -0,0 +1,166 @@
# Linesync
Git-based configuration sync for Nefarious IRCd. Pulls config updates from a git repository and sends SIGHUP to reload.
## Using Docker Compose
Add linesync to your `docker-compose.yml`:
```yaml
services:
nefarious:
image: ghcr.io/evilnet/nefarious2:latest
container_name: nefarious
volumes:
- ./local.conf:/home/nefarious/ircd/local.conf
ports:
- "6667:6667"
linesync:
image: ghcr.io/evilnet/nefarious2-linesync:latest
depends_on:
- nefarious
volumes:
- ./linesync-ssh:/home/linesync/.ssh
- ./local.conf:/home/linesync/ircd/local.conf
- ./linesync:/home/linesync/ircd/linesync
- /var/run/docker.sock:/var/run/docker.sock
environment:
NEFARIOUS_CONTAINER: nefarious
SYNC_INTERVAL: 300
IRCD_CONF: /home/linesync/ircd/local.conf
```
### Setup
```bash
# Create directories
mkdir -p ./linesync-ssh ./linesync
touch ./local.conf
# Generate SSH key
docker compose run --rm linesync keygen
# Add the printed public key to your git repo's deploy keys
# Clone the linesync repo
docker compose run --rm -e GIT_REPOSITORY=git@github.com:yourorg/linesync-data.git linesync setup
# Start services
docker compose up -d
```
### Manual sync
```bash
docker compose run --rm linesync once
```
---
## Using Standalone Docker
### Setup
```bash
# Build
cd tools/linesync
docker build -t linesync .
# Create directories
mkdir -p ./linesync-ssh ./linesync
touch ./local.conf
# Generate SSH key
docker run --rm -v ./linesync-ssh:/home/linesync/.ssh linesync keygen
# Add the printed public key to your git repo's deploy keys
# Clone the linesync repo
docker run --rm \
-v ./linesync-ssh:/home/linesync/.ssh \
-v ./local.conf:/home/linesync/ircd/local.conf \
-v ./linesync:/home/linesync/ircd/linesync \
-e GIT_REPOSITORY=git@github.com:yourorg/linesync-data.git \
linesync setup
```
### Run continuous sync
```bash
docker run -d \
--name linesync \
-v ./linesync-ssh:/home/linesync/.ssh \
-v ./local.conf:/home/linesync/ircd/local.conf \
-v ./linesync:/home/linesync/ircd/linesync \
-v /var/run/docker.sock:/var/run/docker.sock \
-e NEFARIOUS_CONTAINER=nefarious \
-e SYNC_INTERVAL=300 \
-e IRCD_CONF=/home/linesync/ircd/local.conf \
linesync sync
```
### Run once
```bash
docker run --rm \
-v ./linesync-ssh:/home/linesync/.ssh \
-v ./local.conf:/home/linesync/ircd/local.conf \
-v ./linesync:/home/linesync/ircd/linesync \
-v /var/run/docker.sock:/var/run/docker.sock \
-e IRCD_CONF=/home/linesync/ircd/local.conf \
linesync once
```
### Debug shell
```bash
docker run --rm -it \
-v ./linesync-ssh:/home/linesync/.ssh \
-v ./local.conf:/home/linesync/ircd/local.conf \
-v ./linesync:/home/linesync/ircd/linesync \
linesync shell
```
---
## Environment Variables
| Variable | Default | Description |
|----------|---------|-------------|
| `GIT_REPOSITORY` | — | Git repo URL (required for setup) |
| `NEFARIOUS_CONTAINER` | `nefarious` | Container to send SIGHUP |
| `SYNC_INTERVAL` | `300` | Seconds between syncs |
| `IRCD_CONF` | `/home/linesync/ircd/ircd.conf` | Config file path |
| `CERT_TAG` | — | Git tag for SSL cert sync |
| `CERT_FILE` | `fullchain.pem` | Output path for synced certificate |
## Config File Format
Your git repository needs a `linesync.data` file with IRC config blocks. These get inserted into your config between markers:
```
# BEGIN LINESYNC
... (managed by linesync) ...
# END LINESYNC
```
Markers are added automatically on first sync.
## SSL Certificate Sync
Store certs in git tags:
```bash
git tag -f myserver-cert $(cat fullchain.pem | git hash-object -w --stdin)
git push origin :refs/tags/myserver-cert
git push --tags
```
Then set `CERT_TAG=myserver-cert` in your environment. To write to a specific file (e.g., `ircd.pem`), also set `CERT_FILE=/home/linesync/ircd/ircd.pem`.
## Notes
- UID/GID is auto-detected from bind mounts — files will be owned by your host user
- Docker socket access grants container control privileges
- Use read-only deploy keys
+334
View File
@@ -0,0 +1,334 @@
#!/bin/bash
# gitysnc.sh, Copyright (c) 2015 Rubin
# based on linesync.sh (c) 2002 Arjen Wolfs
#
# The code contained is in this file is licenced under the terms
# and conditions as specified in the GNU General Public License.
#
# This program should be run from crontab, i.e something like:
# 0 0 * * * /home/irc/bin/gitsync.sh -s /home/irc/.ssh/id_rsa /home/irc/lib/ircd.conf /home/irc/lib/ircd.pid
#
usage() {
echo "Help: "
echo " $0 [-h|-i repository] <-p ircd.pem|-s id_rsa> <ircd.conf> <ircd.pid>"
echo ""
echo " -h - this help"
echo " -p ircd.pem - convert this ircd.pem certificate to an ssh key and use that instead of the default ~/.ssh/id_rsa"
echo " -s id_rsa - Full path to your ssh private key to use for git access (defaults to ~/.ssh/id_rsa)"
echo " -i repository-url - Perform initial setup, needed only once to set up. Provide git URL as argument"
echo " -c tagname - Load a certificate from this git tagged object (eg, servername-cert)"
echo " -C certfile - Write the certificate to this file (default: fullchain.pem in ircd.conf directory)"
echo " <ircd.conf> - Full path to your ircd.conf file"
echo " <ircd.pid> - Full path to your ircd.pid file"
echo ""
}
#Handle argument parsing
while getopts "hi:p:s:c:C:" opt; do
case $opt in
h)
usage
exit
;;
i)
dosetup="yes"
repository="$OPTARG"
;;
p)
ircdkey="yes"
kpath="$OPTARG"
;;
s)
skey="$OPTARG"
;;
c)
certtag="$OPTARG"
;;
C)
certfile="$OPTARG"
;;
\?)
echo "Unknown option: -$OPTARG" >&2
exit 1
;;
:)
echo "Option -$OPTARG requires an argument." >&2
exit 1
esac
done
shift $((OPTIND-1))
# This checks for the presence of an executable file in $PATH
locate_program() {
if [ ! -x "`which $1 2>&1`" ]; then
echo "You don't seem to have $1. Sorry."
exit 1
fi
}
# This checks for the presence of any file
check_file() {
if [ ! -f "$1" ]; then
echo "There doesn't appear to be a $1. Sorry."
exit 1
fi
}
# Try to find programs we will need
locate_program openssl
locate_program git
locate_program egrep
locate_program diff
locate_program chmod
locate_program readlink
# try to find GNU awk
awk_cmd=`which gawk`
if [ $? -ne 0 ]; then
awk_cmd=""
fi
if [ -z "$awk_cmd" ]; then
locate_program awk
is_gawk=`echo | awk --version | head -1 | egrep '^GNU.+$'`
if [ -z "$is_gawk" ]; then
echo "Your version of awk is not GNU awk. Sorry."
echo "Try: # sudo apt-get install gawk"
exit 1
fi
awk_cmd="awk"
fi
# Check for required command line parameters
if [ -z "$1" ] || [ -z "$2" ] ; then
echo "Error: No ircd.conf or ircd.pid specified"
usage
exit 1
fi
if [ -n "$skey" ] && [ -n "$ircdkey" ]; then
echo "Error: You cannot use -s and -p together. Pick one method to authenicate."
usage
exit;
fi
if [ -z "$skey" ] && [ -z "$ircdkey" ]; then
echo "Error: You must provide -s or -p. Pick one method to authenicate."
usage
exit;
fi
if [ -z "$skey" ]; then
skey="$HOME/.ssh/id_rsa"
fi
# check and set up stuff
diff_cmd="diff"
cpath="$1"
ppath="$2"
check_file "$cpath"
dpath=`dirname "$cpath"`
dpath=`readlink -f "$dpath"`
lpath="$dpath/linesync"
#check_file $lpath
save_dir="$PWD"; cd "$dpath"
tpath="$PWD"; cd "$save_dir"
tmp_path="$dpath/tmp"
ipath="$tmp_path/ssh.pem"
mkdir "$tmp_path" > /dev/null 2>&1
# Not all versions of date support %s, work around it
TS=`date +%Y%m%d%H%M%S`
TMPFILE="$tmp_path/linesync.$TS"
TMPCERT="$tmp_path/cert.$TS"
echo '#!/bin/bash' > "$tmp_path/git.sh"
#If they specified -p, we generate the git ssh key from ircd.pem
if [ -n "$ircdkey" ]; then
check_file "$kpath"
# first get the private key by just grabbing the lines that match...
awk '/BEGIN .*PRIVATE KEY/,/END .*PRIVATE KEY/' "$kpath" > "$ipath"
# Then we'll get the public key more properly..
if ! openssl x509 -in "$kpath" -pubkey -noout >> "$ipath"; then
echo "Error: I could not use $kpath as a key for some reason. Stopping!"
exit
fi
chmod 600 "$tmp_path/ssh.pem"
#Override git's ssh command so we can force our custom identity and no password
echo -e "ssh -oPasswordAuthentication=no -i \"$ipath\" \"\$1\" \"\$2\"\n" >> "$tmp_path/git.sh"
else
#Override git's ssh command so we can force our custom identity and no password
echo -e "ssh -oPasswordAuthentication=no -i \"$skey\" \"\$1\" \"\$2\"\n" >> "$tmp_path/git.sh"
fi
chmod a+x "$tmp_path/git.sh"
export GIT_SSH="$tmp_path/git.sh"
if [ "$dosetup" = "yes" ]; then
echo "Doing initial setup with repository $repository" >&2
# Check if destination already has a git repo
if [ -d "$lpath/.git" ]; then
echo "Doing setup.. but $lpath already contains a git repository."
echo "Remove it first if you want to re-clone: rm -rf $lpath/*"
exit 2
fi
# Check if directory exists and is not empty (allow empty dirs for bind mounts)
if [ -d "$lpath" ] && [ -n "$(ls -A "$lpath" 2>/dev/null)" ]; then
echo "Doing setup.. but destination directory $lpath already exists and is not empty."
echo "Move it out of the way and try again"
exit 2
fi
echo "Note: your public key (linesync admin will have added this to keydir):"
if [ -n "$ircdkey" ]; then
ssh-keygen -i -m PKCS8 -f "$tmp_path/ssh.pem"
#cat $ipath
else
cat "$skey".pub
fi
prevdir=`pwd`
cd "$dpath"
git clone "$repository" "$lpath"
if [ -d "$lpath"/.git ]; then
echo "Initial setup success"
exit 0
else
echo "Problem with initial setup. See above"
exit 5
fi
fi
#Check for the git repository
if [ ! -d "$lpath" ]; then
echo "Cannot find a git repository at $lpath."
echo "check ircd.conf path argument, or re-run with -i <repository> to perform initial setup"
usage
exit 6
fi
if [ ! -d "$lpath"/.git ]; then
echo "Error: $lpath is not a git repository. ?!"
usage
exit 10
fi
#update the repository from upstream
prevdir=`pwd`
cd "$lpath"
git reset -q --hard origin/master
git fetch --tags -f --quiet
git merge -q origin/master
if [ ! -z "$certtag" ]; then
#Store the cert in a temp file
git show "$certtag" > "$TMPCERT"
fi
cd "$prevdir"
#Copy the data to the temp file
cp "$lpath/linesync.data" "$TMPFILE"
if [ ! -s "$TMPFILE" ]; then
echo "Unable find retrieve $lpath/linesync.data, Sorry."
rm "$TMPFILE" > /dev/null 2>&1
exit 1
fi
# check our ircd.conf
ircd_setup=`egrep '^# (BEGIN|END) LINESYNC$' "$cpath"|wc -l`
if [ $ircd_setup != 2 ]; then
cp "$cpath" "$cpath.orig"
echo "Performing initial merge on $cpath, original file saved as $cpath.orig."
echo "# Do NOT remove the following line, linesync.sh depends on it!" >> $cpath
echo "# BEGIN LINESYNC" >> $cpath
echo "# END LINESYNC" >> $cpath
echo "# Do not remove the previous line, linesync.sh depends on it!" >> $cpath
# Do an initial merge to remove duplicates
inpath="$tmp_path/linesync.tmp.$TS"
$awk_cmd '
{
if (!loaded_template) {
command="cat " tempfile; tlines=0;
while ((command | getline avar) > 0) { template[tlines]=avar; tlines++ }
close(command)
loaded_template++
}
dup_line=0
for (i=0; i<tlines; i++) {
if (tolower($0)==tolower(template[i])) { dup_line++; break }
}
if (!dup_line) print $0
} ' "tempfile='$TMPFILE'" < "$cpath" > "$inpath"
else
inpath="$cpath"
fi
# Replace the marked block in ircd.conf with the new version
$awk_cmd '
$0=="# BEGIN LINESYNC" { chop++; print; next }
$0=="# END LINESYNC" {
command="cat " syncfile
while ((command | getline avar) > 0) { print avar }
close(command)
chop--
}
{ if (!chop) print $0 }
' "syncfile='$TMPFILE'" < "$inpath" > "$tmp_path/linesync.new.$TS"
# run a diff between current and new confs to see if we updated anything
# no point sending the ircd a -HUP if this is not needed, especially on a
# busy network, such as Undernet.
diff=`"$diff_cmd" "$cpath" "$tmp_path/linesync.new.$TS"`
if [ ! -z "$diff" ]; then
# Changes were detected
# Back up the current ircd.conf and replace it with the new one
cp "$cpath" "$dpath/ircd.conf.bk"
cp "$tmp_path/linesync.new.$TS" "$cpath"
# Rehash ircd (without caring wether or not it succeeds)
kill -HUP `cat "$ppath" 2>/dev/null` > /dev/null 2>&1
#todo: kill iauthd?
fi
if [ ! -z "$certtag" ]; then
# Use provided certfile path or default to fullchain.pem
: "${certfile:=$dpath/fullchain.pem}"
if [ ! -f "$certfile" ]; then
cdiff="yes"
else
cdiff=`"$diff_cmd" "$certfile" "$TMPCERT"`
fi
if [ ! -z "$cdiff" ]; then
#Changes detected
if [ -f "$certfile" ]; then
cp "$certfile" "${certfile}.backup"
fi
cp "$TMPCERT" "$certfile"
# Rehash pem files (without caring wether or not it succeeds)
kill -USR1 `cat "$ppath" 2>/dev/null` > /dev/null 2>&1
fi
fi
# (Try to) clean up
if [ -n "$tmp_path" ] && [ -d "$tmp_path" ]; then
rm -rf "$tmp_path" #> /dev/null 2>&1
fi
# That's it...
+33
View File
@@ -0,0 +1,33 @@
=== Some musings about a way to store lets-encrypt-generated ircd pem keys in git without flooding out the history ===
Save the certificate
git tag -f servername-cert $(command to generate cert | git hash-object -w --stdin)
Read the certificate
git show servername-cert
note about abusing remote tags:
https://stackoverflow.com/questions/19298600/tag-already-exists-in-the-remote-error-after-recreating-the-git-tag
Delete the tag on the server
git push origin :refs/tags/servername-cert
pushing and pulling include the tags
git pull --tags
git push --tags
So the sequence would be:
* Get new certificate from LE
* Put new certificate in git tag using the hash-object thing with -f to overwrite the old
* Delete the old tag on the server with the :refs/tags/ thing
* git push --tags to send the new tag(s) to the server
Then in gitsync.sh we need to do git pull --tags to get the latest (or just our needed tag?)
and save it to the ircd.pem file (key file will need to be seperated) and HUP the ircd if it changed.
+289
View File
@@ -0,0 +1,289 @@
#!/bin/bash
# Linesync Sidecar Entrypoint
# Supports multiple modes of operation for configuration synchronization
set -e
# =============================================================================
# UID/GID Auto-Detection and Privilege Dropping
# =============================================================================
# If running as root, detect the UID/GID from mounted directories and drop
# privileges to match. This allows bind mounts to work without manual -u flags.
if [ "$(id -u)" = "0" ]; then
# Detect UID/GID from mounted directories (in order of preference)
TARGET_UID=""
TARGET_GID=""
for detect_path in /home/linesync/ircd/ircd.conf ; do
if [ -d "$detect_path" ]; then
TARGET_UID=$(stat -c %u "$detect_path")
TARGET_GID=$(stat -c %g "$detect_path")
# Skip if owned by root (probably not a bind mount)
if [ "$TARGET_UID" != "0" ]; then
break
fi
fi
done
# Default to 1000:1000 if detection failed or got root
: "${TARGET_UID:=1000}"
: "${TARGET_GID:=1000}"
# Get current linesync UID/GID
CURRENT_UID=$(id -u linesync)
CURRENT_GID=$(id -g linesync)
# Modify user/group if needed
if [ "$TARGET_GID" != "$CURRENT_GID" ]; then
groupmod -g "$TARGET_GID" linesync 2>/dev/null || true
fi
if [ "$TARGET_UID" != "$CURRENT_UID" ]; then
usermod -u "$TARGET_UID" linesync 2>/dev/null || true
fi
# Fix ownership of home directory
chown -R linesync:linesync /home/linesync 2>/dev/null || true
# Ensure SSH config exists
if [ ! -f /home/linesync/.ssh/config ]; then
mkdir -p /home/linesync/.ssh
echo -e "Host *\n StrictHostKeyChecking accept-new\n UserKnownHostsFile /home/linesync/.ssh/known_hosts" > /home/linesync/.ssh/config
chmod 700 /home/linesync/.ssh
chmod 600 /home/linesync/.ssh/config
chown -R linesync:linesync /home/linesync/.ssh
fi
# Re-exec this script as linesync user
exec gosu linesync "$0" "$@"
fi
# =============================================================================
# Main Entrypoint (running as linesync user)
# =============================================================================
# Configuration with defaults
: "${SYNC_INTERVAL:=300}" # Sync interval in seconds (default: 5 minutes)
: "${IRCD_CONF:=/home/linesync/ircd/ircd.conf}"
: "${IRCD_PID:=/home/linesync/ircd/ircd.pid}"
: "${SSH_KEY:=/home/linesync/.ssh/id_ed25519}"
: "${NEFARIOUS_CONTAINER:=nefarious}"
: "${GIT_REPOSITORY:=}"
: "${CERT_TAG:=}"
: "${CERT_FILE:=}" # Output path for certificate (default: fullchain.pem in conf dir)
GITSYNC="/home/linesync/gitsync.sh"
show_help() {
echo "Linesync Sidecar Container"
echo ""
echo "Modes:"
echo " keygen Generate a new SSH keypair for git authentication"
echo " setup Clone the linesync git repository (initial setup)"
echo " sync Run continuous sync loop (default)"
echo " once Run sync once and exit"
echo " shell Start an interactive shell"
echo " help Show this help message"
echo ""
echo "Environment Variables:"
echo " SYNC_INTERVAL Seconds between sync attempts (default: 300)"
echo " IRCD_CONF Path to ircd.conf (default: /home/linesync/ircd/ircd.conf)"
echo " IRCD_PID Path to ircd.pid (default: /home/linesync/ircd/ircd.pid)"
echo " SSH_KEY Path to SSH private key (default: /home/linesync/.ssh/id_ed25519)"
echo " NEFARIOUS_CONTAINER Name of nefarious container to signal (default: nefarious)"
echo " GIT_REPOSITORY Git repository URL (required for setup mode)"
echo " CERT_TAG Git tag for SSL certificate (optional)"
echo " CERT_FILE Output path for certificate (default: fullchain.pem in conf dir)"
echo ""
echo "Volume Mounts:"
echo " /home/linesync/.ssh SSH keys directory"
echo " /home/linesync/ircd IRCd config directory (shared with nefarious)"
echo " /var/run/docker.sock Docker socket (for sending SIGHUP)"
echo ""
}
# Generate SSH keypair
do_keygen() {
local keytype="${1:-ed25519}"
local sshdir="/home/linesync/.ssh"
local keyfile="${sshdir}/id_${keytype}"
# Check if .ssh directory exists
if [ ! -d "$sshdir" ]; then
echo "Error: SSH directory $sshdir does not exist"
echo "Create the directory on the host first: mkdir -p ./linesync-ssh"
exit 1
fi
# Check if directory is writable
if [ ! -w "$sshdir" ]; then
echo "Error: SSH directory $sshdir is not writable"
echo "Check that the directory exists and has correct permissions"
exit 1
fi
# Ensure proper directory permissions
chmod 700 "$sshdir" 2>/dev/null || true
if [ -f "$keyfile" ]; then
echo "Key already exists at $keyfile"
echo "Public key:"
cat "${keyfile}.pub"
return 0
fi
echo "Generating ${keytype} keypair..."
ssh-keygen -t "$keytype" -f "$keyfile" -N "" -C "linesync@$(hostname)"
# Set proper permissions on the key files
chmod 600 "$keyfile"
chmod 644 "${keyfile}.pub"
echo ""
echo "Key generated successfully!"
echo ""
echo "Public key (add this to your git repository's deploy keys):"
echo "================================================================"
cat "${keyfile}.pub"
echo "================================================================"
}
# Initial repository setup
do_setup() {
if [ -z "$GIT_REPOSITORY" ]; then
echo "Error: GIT_REPOSITORY environment variable is required for setup"
exit 1
fi
if [ ! -f "$SSH_KEY" ]; then
echo "Error: SSH key not found at $SSH_KEY"
echo "Run 'keygen' mode first to create a keypair"
exit 1
fi
echo "Setting up linesync repository..."
echo "Repository: $GIT_REPOSITORY"
echo "SSH Key: $SSH_KEY"
echo "Config: $IRCD_CONF"
# Run gitsync.sh in setup mode
"$GITSYNC" -s "$SSH_KEY" -i "$GIT_REPOSITORY" "$IRCD_CONF" "$IRCD_PID"
}
# Signal nefarious container to reload config
signal_reload() {
if [ -S /var/run/docker.sock ]; then
echo "Sending SIGHUP to container: $NEFARIOUS_CONTAINER"
docker kill --signal=SIGHUP "$NEFARIOUS_CONTAINER" 2>/dev/null || \
echo "Warning: Could not signal container (may not be running)"
else
echo "Warning: Docker socket not available, cannot signal container"
echo "Config changes will take effect on next ircd restart"
fi
}
# Run a single sync
do_sync_once() {
local sync_args="-s $SSH_KEY"
if [ -n "$CERT_TAG" ]; then
sync_args="$sync_args -c $CERT_TAG"
if [ -n "$CERT_FILE" ]; then
sync_args="$sync_args -C $CERT_FILE"
fi
fi
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Running sync..."
# Create a wrapper that signals via docker instead of using PID file
# We'll run gitsync.sh but handle the signaling ourselves
local tmp_pid="/tmp/fake.pid"
echo "99999" > "$tmp_pid"
# Capture gitsync output to check if changes were made
local before_md5=""
local after_md5=""
if [ -f "$IRCD_CONF" ]; then
before_md5=$(md5sum "$IRCD_CONF" 2>/dev/null | cut -d' ' -f1)
fi
# Run gitsync (it will try to HUP pid 99999 which will fail silently)
"$GITSYNC" $sync_args "$IRCD_CONF" "$tmp_pid" 2>&1 || true
if [ -f "$IRCD_CONF" ]; then
after_md5=$(md5sum "$IRCD_CONF" 2>/dev/null | cut -d' ' -f1)
fi
# If config changed, signal the container
if [ "$before_md5" != "$after_md5" ] && [ -n "$after_md5" ]; then
echo "Configuration changed, signaling reload..."
signal_reload
fi
rm -f "$tmp_pid"
}
# Continuous sync loop
do_sync_loop() {
# Handle shutdown signals gracefully
trap 'echo "[$(date "+%Y-%m-%d %H:%M:%S")] Shutting down..."; exit 0' SIGTERM SIGINT
echo "Starting linesync daemon"
echo "Sync interval: ${SYNC_INTERVAL}s"
echo "Config: $IRCD_CONF"
echo "Container: $NEFARIOUS_CONTAINER"
echo ""
# Check prerequisites
if [ ! -f "$SSH_KEY" ]; then
echo "Error: SSH key not found at $SSH_KEY"
echo "Run 'keygen' mode first, or mount your key"
exit 1
fi
local linesync_dir
linesync_dir=$(dirname "$IRCD_CONF")/linesync
if [ ! -d "$linesync_dir" ]; then
echo "Error: Linesync repository not found at $linesync_dir"
echo "Run 'setup' mode first to clone the repository"
exit 1
fi
# Main loop
while true; do
do_sync_once
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Sleeping ${SYNC_INTERVAL}s..."
# Sleep in background so trap can interrupt
sleep "$SYNC_INTERVAL" &
wait $!
done
}
# Main entrypoint
case "${1:-sync}" in
keygen)
do_keygen "${2:-ed25519}"
;;
setup)
do_setup
;;
sync)
do_sync_loop
;;
once)
do_sync_once
;;
shell|bash|sh)
exec /bin/bash
;;
help|--help|-h)
show_help
;;
*)
echo "Unknown command: $1"
show_help
exit 1
;;
esac
+17
View File
@@ -0,0 +1,17 @@
# Configuration for linesync.sh
#
# - This file must be placed in the same directory as ircd.conf
# - Note that all URL's *MUST* have a trailing /
# - Since we are using wget, you could use ftp:// URL's as well if you want to
# Where do we get our ircd.conf update?
LINE_SERVER="http://some.domain/"
# Check servers, as many as you like, seperated by spaces
LINE_CHECK="http://host1.other.domain/lsync/ http://host-19.domain-x.net/ http://www.domain.what"
# What .conf lines are allowed in the downloaded updates?
# Pipe seperated - for Undernet use "Uworld|Jupe|Quarantine|Kill" (kKQU in .11 terms)
ALLOWED_LINES="Uworld|Jupe|Quarantine|Kill"
+241
View File
@@ -0,0 +1,241 @@
#!/bin/sh
# linesync.sh, Copyright (c) 2002 Arjen Wolfs
# 20020604, sengaia@undernet.org
# 20050417, daniel@undernet.org - modified for u2.10.12
# $Id: linesync.sh 1368 2005-04-17 16:59:49Z entrope $
#
# The code contained is in this file is licenced under the terms
# and conditions as specified in the GNU General Public License.
#
# linesync.sh - centralized ircd.conf updates.
# The purpose of this little shell script is to allow a section of an ircd.conf to be
# updated from a central location. Hence it is intended to facilitate the automated
# distribution of Kill, Jupe, Quarantine and Uworld lines; or any other .conf lines you
# may wish to keep synchronized accross all servers on a network.
#
# This script will download a file called linesync from a specified web server (see
# below for configuration), and calculate an md5sum from it. It will then download
# a file called linesync.sum from a configurable number of other web servers and
# compare the contents of these files against the checksum calculated. If any of the
# downloaded checksums mismatch, the program will abort. This provides security to
# the centralized update mechanism - in order for it to be compromised, multiple
# web servers would have to compromised.
#
# If all checksums match, the script inspects the .conf lines contained within the
# downloaded file. If any .conf lines are found that are not specifically allowed,
# the program will abort. This will prevent malicious/dangerous .conf lines (such as
# Operator or Connect lines) from being inserted into ircd.conf.
#
# If all the checks mentioned above are passed, the script checks ircd.conf for a section
# that begins with "# BEGIN LINESYNC", and ends with "# END LINESYNC". The section contained
# between these two comments is the section maintained by this program. If these lines are not
# found in the ircd.conf, they will be appended to it.
# Next, the script will build a new ircd.conf by removing all lines present between the two
# commented lines mentioned above, and replace them with the contents of the file downloaded.
#
# Once this has been completed, ircd.conf is backed up and replaced with the newly built version,
# and ircd will be rehashed.
#
# Configuration: This script requires two parameters - the full path to your ircd.conf, and the
# full path to your ircd.pid. It will look for a configuration file called linesync.conf in the
# same directory as ircd.conf. See the included sample linesync.conf for information on how to
# set it up. Obviously, you will need to have web server(s) to use for the distribution of your
# .conf update and checksums. This script requires the presence of wget and md5sum, and various
# other programs that should be present by default on any Unix system.
#
# This program should be run from crontab, i.e something like:
# 0 0 * * * /home/irc/bin/linesync.sh /home/irc/lib/ircd.conf /home/irc/lib/ircd.pid
#
# This program has been tested on and works on FreeBSD, Solaris, and Linux.
# md5sum is included in GNU textutils.
#
# Good Luck!
# Arjen Wolfs (sengaia@undernet.org), June 9 2002.
#
# This checks for the presence of an executable file in $PATH
locate_program() {
if [ ! -x "`which $1 2>&1`" ]; then
echo "You don't seem to have $1. Sorry."
exit 1
fi
}
# This checks for the presence of any file
check_file() {
if [ ! -f "$1" ]; then
echo "There doesn't appear to be a $1. Sorry."
exit 1
fi
}
# Try to find programs we will need
locate_program wget && locate_program egrep && locate_program diff
# try to find GNU awk
awk_cmd=`which gawk`
if [ $? -ne 0 ]; then
awk_cmd=""
fi
# try to find an appropriate md5 program
# BSD md5 capability courtesy of spale
md5_cmd=`which md5sum`
if [ -z "$md5_cmd" ]; then
md5_cmd=`which md5`
if [ -z "$md5_cmd" ]; then
echo "No MD5 capable programs found (I looked for md5sum and md5)."
exit
else
md5_cmd="$md5_cmd -q"
fi
fi
if [ -z "$awk_cmd" ]; then
locate_program awk
is_gawk=`echo | awk --version | head -1 | egrep '^GNU.+$'`
if [ -z "$is_gawk" ]; then
echo "Your version of awk is not GNU awk. Sorry."
exit 1
fi
awk_cmd="awk"
fi
# Check for required command line parameters
if [ -z "$1" -o -z "$2" ]; then
echo "Usage: $0 <conf_path> <pid_path>"
echo " <conf_path> Full path to ircd.conf (/home/irc/lib/ircd.conf)"
echo " <pid_path> Full path to ircd.pid (/home/irc/lib/ircd.pid)"
exit 1
fi
# check and set up stuff
diff_cmd="diff"
cpath=$1
ppath=$2
check_file $cpath
dpath=`dirname $cpath`
lpath="$dpath/linesync.conf"
check_file $lpath
save_dir=$PWD; cd $dpath
tpath=$PWD; cd $save_dir
tmp_path="$dpath/tmp"
mkdir $tmp_path > /dev/null 2>&1
# load and check configuration
. $lpath
if [ -z "$LINE_SERVER" -o -z "$LINE_CHECK" -o -z "$ALLOWED_LINES" ]; then
echo "Please setup $lpath correctly."
exit 1
fi
# Not all versions of date support %s, work around it
TS=`date +%Y%m%d%H%M%S`
TMPFILE="$tmp_path/linesync.$TS"
LSFILE="$LINE_SERVER""linesync"
# Attempt to download our .conf update
wget --cache=off --quiet --output-document=$TMPFILE $LSFILE > /dev/null 2>&1
if [ ! -s "$TMPFILE" ]; then
echo "Unable to retrieve $LSFILE. Sorry."
rm $TMPFILE > /dev/null 2>&1
exit 1
fi
# Check whether the file contains any disallowed .conf lines
bad_lines=`egrep '^[^'$ALLOWED_LINES'|#]+' $TMPFILE`
if [ ! -z "$bad_lines" ]; then
echo "The file downloaded in $TMPFILE contains the following disallowed line(s):"
echo $bad_lines
exit 1
fi
# Check whether somebody tried to sneak a second block onto some line
bad_lines=`egrep -i '}[ ]*;[ ]*[a-z]+[ ]*{' $TMPFILE`
if [ ! -z "$bad_lines" ] ; then
echo "The file downloaded in $TMPFILE contains the following multi-block line(s):"
echo $bad_lines
exit 1
fi
# check our ircd.conf
ircd_setup=`egrep '^# (BEGIN|END) LINESYNC$' $cpath|wc -l`
if [ $ircd_setup != 2 ]; then
cp $cpath $cpath.orig
echo "Performing initial merge on $cpath, original file saved as $cpath.orig."
echo "# Do NOT remove the following line, linesync.sh depends on it!" >> $cpath
echo "# BEGIN LINESYNC" >> $cpath
echo "# END LINESYNC" >> $cpath
echo "# Do not remove the previous line, linesync.sh depends on it!" >> $cpath
# Do an initial merge to remove duplicates
inpath="$tmp_path/linesync.tmp.$TS"
$awk_cmd '
{
if (!loaded_template) {
command="cat " tempfile; tlines=0;
while ((command | getline avar) > 0) { template[tlines]=avar; tlines++ }
close(command)
loaded_template++
}
dup_line=0
for (i=0; i<tlines; i++) {
if (tolower($0)==tolower(template[i])) { dup_line++; break }
}
if (!dup_line) print $0
} ' tempfile=$TMPFILE < $cpath > $inpath
else
inpath=$cpath
fi
# Get the checksum
CKSUM=`$md5_cmd $TMPFILE|cut -d' ' -f1`
check_file="$tmp_path/linesync.sum.$TS"
for ck_server in $LINE_CHECK; do
sumfile="$ck_server""linesync.sum"
wget --cache=off --quiet --output-document=$check_file $sumfile > /dev/null 2>&1
if [ ! -s "$check_file" ]; then
echo "Unable to retrieve checksum from $sumfile"
exit 1
fi
if [ "$CKSUM" != "`cat $check_file`" ]; then
echo "Checksum retrieved from $sumfile does not match!"
exit 1
fi
rm -f $check_file
done
# It all checks out, proceed...
# Replace the marked block in ircd.conf with the new version
$awk_cmd '
$0=="# BEGIN LINESYNC" { chop++; print; next }
$0=="# END LINESYNC" {
command="cat " syncfile
while ((command | getline avar) > 0) { print avar }
close(command)
chop--
}
{ if (!chop) print $0 }
' syncfile=$TMPFILE < $inpath > $tmp_path/linesync.new.$TS
# run a diff between current and new confs to see if we updated anything
# no point sending the ircd a -HUP if this is not needed, especially on a
# busy network, such as Undernet.
diff=`$diff_cmd $cpath $tmp_path/linesync.new.$TS`
if [ ! -z "$diff" ]; then
# Changes were detected
# Back up the current ircd.conf and replace it with the new one
cp $cpath $dpath/ircd.conf.bk
cp $tmp_path/linesync.new.$TS $cpath
# Rehash ircd (without caring wether or not it succeeds)
kill -HUP `cat $ppath 2>/dev/null` > /dev/null 2>&1
fi
# (Try to) clean up
rm -rf $tmp_path > /dev/null 2>&1
# That's it...
+54
View File
@@ -0,0 +1,54 @@
#! /bin/sh
#* $Id$
case $# in
0|1) echo 'Usage: makepem /dpath /top_srcdir' 1>&2; exit 2
esac
if test -f $2/config.h
then
grep USE_SSL $2/config.h | awk '{
if ($1 != "#define") {
printf "SSL Disabled, Skipping makepem Generation\n"
system("touch /tmp/ssltempdata")
}
}'
fi
if test -f /tmp/ssltempdata
then
rm -f /tmp/ssltempdata
else
echo 'Generating ircd.pem...'
if test -f $1/ircd.pem
then
echo 'ircd.pem already exists, exiting. Remove ircd.pem and run make install again to create a new one'
exit 0;
fi
echo Press Y if you want to use an SSL certificate that already exists; read sslans
if [ "$sslans" != "Y" ]; then
openssl req -new -x509 -days 365 -nodes -out $1/ircd.pem -newkey rsa:4096 -keyout $1/ircd.pem
test 1 -eq 1 || test ! -f /dev/urandom || openssl gendh -rand $1/ircd.rand 512 >> $1/ircd.pem
test 1 -eq 1 || test -f /dev/urandom || openssl gendh 512 >> $1/ircd.pem
openssl x509 -subject -dates -fingerprint -noout -in $1/ircd.pem
else
FileExist=FALSE
while [ "$FileExist" == "FALSE" ];
do
echo Please enter in the filname of the SSL certificate including the full path; read sslpath
if test -f $sslpath
then
FileExist=TRUE
else
echo File Does Not Exist
fi
done
cp $sslpath $1/ircd.pem
fi
fi
+99
View File
@@ -0,0 +1,99 @@
#!/bin/sh
#
# IRC - Internet Relay Chat, tools/mkchroot
# Copyright (C) 2001 Kevin L. Mitchell <klmitch@mit.edu>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 1, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
# $Id: mkchroot,v 1.1 2001-06-21 15:48:16 kev Exp $
if test $# -lt 2; then
echo "Usage: $0 <destdir> <executable> [<executable> [...]]" >&2
exit 2
fi
destdir=$1
shift
# Use ldd to formulate a newline-separated list of libraries
liblist=
for arg
do
# Interpret ldd output
libs=`ldd $arg | sed -e 's/ / /g' -e 's/ */ /g' -e 's/^ //g' | \
awk 'BEGIN { RS = " "; } { print; }' | grep '^/'`
# add it to the list so far
if test x"$liblist" = x; then
liblist=$libs
else
liblist="$liblist
$libs"
fi
done
# Sort the list and remove duplicates
liblist=`echo "$liblist" | sort -u`
# Now figure out all the subdirectories we're interested in
# Must create the top level, if need be
dirlist=/
# Break down the library list into directories and remove duplicates
dirs=`echo "$liblist" | sed -e 's@/[^/]*$@@' | sort -u`
# Go through each directory to break it down into its components
for headdir in $dirs; do
tIFS=$IFS
IFS=/$IFS
# Start at the top level
dir=
for subdir in $headdir; do
# update dir so we know where we are
if test x"$dir" = x; then
dir=$subdir
else
dir=$dir/$subdir
fi
# add (absolute) entry to directory list
dirlist="$dirlist
/$dir"
done
IFS=$tIFS
done
# Sort for ordering and remove duplicates
dirlist=`echo "$dirlist" | sort -u`
# Create the directories
echo "Creating directories:"
for dir in $dirlist; do
# add destination directory name, remove trailing /, if any, for test
dir=`echo "$destdir$dir" | sed -e 's@//*$@@'`
echo " $dir"
# sanity-check directory...
if test -f "$dir" -o -h "$dir"; then
echo "ERROR: A non-directory \"$dir\" already exists; bailing out" >&2
exit 2
elif test ! -d "$dir"; then
# Create the directory world-readable
mkdir -m 755 $dir
fi
done
# Now copy over the libraries
echo "Copying libraries:"
for lib in $liblist; do
echo " $lib -> $destdir$lib"
# Preserve permissions
cp -p $lib $destdir$lib
done
+341
View File
@@ -0,0 +1,341 @@
/*
** Copyright (C) 2002 by Kevin L. Mitchell <klmitch@mit.edu>
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
**
** @(#)$Id: ringlog.c 1084 2004-07-01 12:38:31Z entrope $
*/
/*
* This file contains two separate pieces, along with some common
* gunk. If RINGLOG_INSTRUMENT is defined, the two special functions
* __cyg_profile_func_enter() and __cyg_profile_func_exit() are
* defined; otherwise a main function is defined. The common gunk is
* init_log(), which opens and, if necessary, initializes a special
* binary log file that is treated as a ring buffer (to prevent the
* file from growing unboundedly).
*
* The object produced when compiled with RINGLOG_INSTRUMENT is
* designed to work with the special gcc option
* -finstrument-functions; this option causes the
* __cyg_profile_func_*() functions mentioned above to be called when
* a function is entered or exited. (Of course, ringlog.o should
* *not* be compiled with this option.) These functions will in turn
* call store_entry(), which will call init_log() as needed to open
* the log file, ensure that a start record is output, and then will
* store records for the function calls. The log file used is
* "call.ringlog" in the directory from which the program was
* started.
*
* When RINGLOG_INSTRUMENT is *not* defined while building, a main
* function is defined, and the result is an executable for
* interpretation of a ringlog. Usage is very simple: All arguments
* not beginning with '-' are treated as files to open, and all
* arguments beginning with '-' are treated as a specification for the
* number of entries new files should be created with. If this
* specification is 0 (which it is by default), files will not be
* created if they do not already exist.
*
* For every filename argument, at least one line will be printed
* out. If the file is not empty, the entries in the file will be
* printed out, one to a line. Each entry is numbered with a logical
* number. The entry numbers are followed by a two word description
* of the entry type ("Log start," "Function entry," "Function exit,"
* and "Invalid entry"), followed by a colon (":"), followed by the
* word "addr" and the address of the function, followed by the word
* "call" and the address from which the function was called. The
* ringlog program is not able to convert these addresses to symbols
* or file and line numbers--that can be done with a program like
* addr2line (part of the binutils package). The output has been
* carefully contrived to be parsable by a script.
*
* The file format is documented below. Note that data is stored in
* host byte order.
*
* 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Magic number |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | First entry | Last entry |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Records |
* \ \
* \ \
* | Records |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* Record format:
* 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Type code |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Function address |
* / /
* / /
* | Function address |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Calling location |
* / /
* / /
* | Calling location |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* Some systems may have pointers larger than 32 bits, which is why these
* fields are allowed to be variable width.
*/
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
/* /etc/magic rules:
*
* 0 belong 0x52e45fd4 RingLog call trace file, big endian
* >4 beshort x (First entry %u,
* >>6 beshort x last entry %u)
* 0 lelong 0x52e45fd4 RingLog call trace file, little endian
* >4 leshort x (First entry %u,
* >>6 leshort x last entry %u)
*/
#define RINGLOG_MAGIC 0x52e45fd4 /* verify file format */
#define RINGLOG_INIT 0x00000000 /* mark when a session was initiated */
#define RINGLOG_ENTER 0x01010101 /* record function entry */
#define RINGLOG_EXIT 0x02020202 /* record function exit */
#define RINGLOG_FNAME "call.ringlog" /* default file name */
#define RINGLOG_ILEN 2000 /* default number of entries */
/* length of the header and of individual entries */
#define HEAD_LEN (sizeof(u_int32_t) + 2 * sizeof(u_int16_t))
#define ENTRY_LEN (sizeof(u_int32_t) + 2 * sizeof(void *))
/* return an lvalue to the specified type stored at the specified location */
#define rl_ref(log, loc, type) (*((type *)((log) + (loc))))
/* access particular header fields */
#define rl_magic(log) rl_ref((log), 0, u_int32_t)
#define rl_first(log) rl_ref((log), 4, u_int16_t)
#define rl_last(log) rl_ref((log), 6, u_int16_t)
/* translate physical entry number to a file location */
#define rl_addr(loc) ((loc) * ENTRY_LEN + HEAD_LEN)
/* extract the type, function, and call fields of an entry */
#define rl_type(log, loc) rl_ref((log), rl_addr(loc), u_int32_t)
#define rl_func(log, loc) rl_ref((log), rl_addr(loc) + sizeof(u_int32_t), \
void *)
#define rl_call(log, loc) rl_ref((log), rl_addr(loc) + sizeof(u_int32_t) + \
sizeof(void *), void *)
static char *log = 0; /* the log has to be global data */
static size_t log_size = 0; /* remember the size of the log */
static int log_length = 0; /* remember how many entries it'll hold */
/* Open and initialize the log file */
static int
init_log(char *fname, size_t init_len)
{
char c = 0;
int fd, err = 0, size = -1;
struct stat buf;
/* open file */
if ((fd = open(fname, O_RDWR | (init_len > 0 ? O_CREAT : 0),
S_IRUSR | S_IWUSR)) < 0)
return errno; /* return error */
if (fstat(fd, &buf)) { /* get size */
err = errno; /* save errno... */
close(fd); /* close file descriptor */
return err; /* return error */
}
if (buf.st_size <= 8) /* too small */
size = HEAD_LEN + ENTRY_LEN * init_len;
else if ((buf.st_size - 8) % ENTRY_LEN) /* not a multiple of entry length */
size = ((buf.st_size - 8) / ENTRY_LEN + 1) * ENTRY_LEN + 8; /* round up */
if (size >= 0) { /* need to set the size */
if (lseek(fd, size - 1, SEEK_SET) < 0) { /* seek to the end of our file */
err = errno; /* save errno... */
close(fd); /* close file descriptor */
return err; /* return error */
}
if (write(fd, &c, 1) < 0) { /* write a zero to set the new size */
err = errno; /* save errno... */
close(fd); /* close file descriptor */
return err; /* return error */
}
log_size = size; /* record log size */
} else
log_size = buf.st_size; /* record log size */
/* map the file to memory */
if ((log = (char *)mmap(0, log_size, PROT_READ | PROT_WRITE,
MAP_SHARED, fd, 0)) == MAP_FAILED)
err = errno; /* save errno... */
close(fd); /* don't need the file descriptor anymore */
if (err) /* an error occurred while mapping the file; return it */
return err;
log_length = (log_size - HEAD_LEN) / ENTRY_LEN; /* store number of entries */
if (rl_magic(log) == 0) { /* initialize if necessary */
rl_magic(log) = RINGLOG_MAGIC;
rl_first(log) = -1;
rl_last(log) = -1;
}
if (rl_magic(log) != RINGLOG_MAGIC) { /* verify file format */
munmap(log, log_size); /* unmap file */
return -1; /* -1 indicates file format error */
}
return 0; /* return success */
}
#ifdef RINGLOG_INSTRUMENT
/* store an entry in the log file */
static void
store_entry(u_int32_t type, void *this_fn, void *call_site)
{
if (!log) { /* open the log file if necessary; die if unable */
assert(init_log(RINGLOG_FNAME, RINGLOG_ILEN) == 0);
store_entry(RINGLOG_INIT, 0, 0); /* mark start of logging */
}
if (++(rl_last(log)) >= log_length) /* select next entry to fill */
rl_last(log) = 0; /* wrap if needed */
if (rl_first(log) == rl_last(log)) { /* advance start pointer if collision */
if (++(rl_first(log)) >= log_length) /* wrap if necessary */
rl_first(log) = 0;
} else if (rl_first(log) == (u_int16_t)-1) /* no entries yet; enter one */
rl_first(log) = 0;
rl_type(log, rl_last(log)) = type; /* record the entry */
rl_func(log, rl_last(log)) = this_fn;
rl_call(log, rl_last(log)) = call_site;
}
/* called upon function entry */
void
__cyg_profile_func_enter(void *this_fn, void *call_site)
{
store_entry(RINGLOG_ENTER, this_fn, call_site);
}
/* called upon function exit */
void
__cyg_profile_func_exit(void *this_fn, void *call_site)
{
store_entry(RINGLOG_EXIT, this_fn, call_site);
}
#else /* !defined(RINGLOG_INSTRUMENT) */
/* converts a type to a printable string */
static char *
get_type(u_int32_t type)
{
switch (type) {
case RINGLOG_INIT:
return " Logging start";
break;
case RINGLOG_ENTER:
return "Function entry";
break;
case RINGLOG_EXIT:
return " Function exit";
break;
}
return " Invalid entry";
}
/* Print out entries from a starting point to an end point */
static void
extract(int *count, u_int16_t start, u_int16_t end)
{
for (; start <= end; start++)
printf("% 4d %s: addr %p call %p\n", (*count)++,
get_type(rl_type(log, start)), rl_func(log, start),
rl_call(log, start));
}
int
main(int argc, char **argv)
{
char *arg;
int i, err, size = 0;
while ((arg = *++argv)) {
if (arg[0] == '-') { /* -<number> turns into log file size */
size = atoi(arg + 1);
continue;
}
log = 0; /* initialize our data */
log_size = 0;
log_length = 0;
switch ((err = init_log(arg, size))) { /* initialize the log */
case -1: /* file is in an invalid format */
printf("File %s not a valid ringlog file\n", arg);
continue;
break;
case 0: /* file has opened and is ready to be read */
break;
default: /* some error occurred */
printf("Error %d opening file %s: %s\n", err, arg, strerror(err));
continue;
break;
}
if (rl_first(log) == (u_int16_t)-1) /* it's an empty file */
printf("File %s is empty\n", arg);
else { /* print out file contents */
printf("File %s contents:\n", arg);
i = 0; /* initialize counter */
if (rl_last(log) <= rl_first(log)) { /* print out log file */
extract(&i, rl_first(log), log_length - 1); /* end of buffer... */
extract(&i, 0, rl_last(log)); /* then beginning of buffer */
} else
extract(&i, rl_first(log), rl_last(log));
}
munmap(log, log_size); /* unmap the file */
}
return 0;
}
#endif /* !RINGLOG_INSTRUMENT */
+187
View File
@@ -0,0 +1,187 @@
#! /usr/bin/perl -w
#
# Copyright (C) 2002 by Kevin L. Mitchell <klmitch@mit.edu>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# @(#)$Id: ringlog.pl 1084 2004-07-01 12:38:31Z entrope $
#
# This program is intended to be used in conjunction with ringlog and
# the binutils program addr2line. The -r option specifies the path to
# the ringlog program; the -a option specifies the path to addr2line.
# (Both of these default to assuming that the programs are in your
# PATH.) All other options are passed to addr2line, and any other
# arguments are treated as filenames to pass to ringlog. If no
# filenames are given, the program operates in filter mode, expecting
# to get output from ringlog on its standard input. In this case,
# ringlog will not be directly executed, but addr2line still will.
use strict;
use Socket;
use IO::Handle;
sub start_addr2line {
my ($location, @args) = @_;
unshift(@args, '-f'); # always get functions
# Get a socket pair
socketpair(CHILD, PARENT, AF_UNIX, SOCK_STREAM, PF_UNSPEC)
or die "socketpair: $!";
CHILD->autoflush(1); # Make sure autoflush is turned on
PARENT->autoflush(1);
my $pid;
# Fork...
die "cannot fork: $!"
unless (defined($pid = fork));
if (!$pid) { # in child
close(CHILD);
open(STDIN, "<&PARENT");
open(STDOUT, ">&PARENT");
exec($location, @args); # exec!
}
# in parent
close(PARENT);
return \*CHILD; # Return a filehandle for it
}
sub xlate_addr {
my ($fh, $addr) = @_;
# Feed address into addr2line
print $fh "$addr\n";
# Get function name, file name, and line number
my $function = <$fh> || die "Couldn't get function name";
my $fileline = <$fh> || die "Couldn't get file name or line number";
# Remove newlines...
chomp($function, $fileline);
# If addr2line couldn't translate the address, just return it
return "[$addr]"
if ($function eq "??");
# return function(file:line)[address]
return "$function($fileline)[$addr]";
}
sub start_ringlog {
my ($location, @args) = @_;
# Build a pipe and fork, through the magic of open()
my $pid = open(RINGLOG, "-|");
# Make sure we forked!
die "couldn't fork: $!"
unless (defined($pid));
# Execute ringlog...
exec($location, @args)
unless ($pid);
return \*RINGLOG;
}
sub parse_ringlog {
my ($ringlog, $addr) = @_;
my $state = "reading";
while (<$ringlog>) {
chomp;
# Beginning of parsable data
if (/^File.*contents:$/) {
$state = "parsing";
# Here's actual parsable data, so parse it
} elsif ($state eq "parsing" && /^\s*\d+/) {
s/(0x[a-fA-F0-9]+)/&xlate_addr($addr, $1)/eg;
# Switch out of parsing mode
} else {
$state = "reading";
}
# Print the final result
print "$_\n";
}
}
# get an argument for an option that requires one
sub getarg (\$) {
my ($iref) = @_;
$ARGV[$$iref] =~ /^(-.)(.*)/;
die "Argument for $1 missing"
unless ((defined($2) && $2 ne "") || @ARGV > $$iref + 1);
return defined($2) && $2 ne "" ? $2 : $ARGV[++$$iref];
}
my ($ringlog_exe, $addr2line_exe) = ("ringlog", "addr2line");
my (@addr2line_args, @files);
# Deal with arguments; note that we have to deal with -b and -e for
# addr2line.
for (my $i = 0; $i < @ARGV; $i++) {
if ($ARGV[$i] =~ /^-r/) {
$ringlog_exe = getarg($i);
} elsif ($ARGV[$i] =~ /^-a/) {
$addr2line_exe = getarg($i);
} elsif ($ARGV[$i] =~ /^-([be])/) {
push(@addr2line_args, "-$1", getarg($i));
} elsif ($ARGV[$i] =~ /^-/) {
push(@addr2line_args, $ARGV[$i]);
} else {
push(@files, [ $ARGV[$i], @addr2line_args ]);
@addr2line_args = ();
}
}
# Verify that that left us with executable names, at least
die "No ringlog executable"
unless (defined($ringlog_exe) && $ringlog_exe ne "");
die "No addr2line executable"
unless (defined($addr2line_exe) && $addr2line_exe ne "");
# Ok, process each file we've been asked to process
foreach my $file (@files) {
my ($addr2line, $ringlog) =
(start_addr2line($addr2line_exe, @{$file}[1..$#{$file}]),
start_ringlog($ringlog_exe, $file->[0]));
parse_ringlog($ringlog, $addr2line);
close($addr2line);
close($ringlog);
}
# Now if there are still more unprocessed arguments, expect ringlog
# input on stdin...
if (@addr2line_args) {
my $addr2line = start_addr2line($addr2line_exe, @addr2line_args);
parse_ringlog(\*STDIN, $addr2line);
close($addr2line);
}
+6
View File
@@ -0,0 +1,6 @@
all:
gcc -Wall -Werror sid2num.c -o sid2num
gcc -Wall -Werror num2sid.c -o num2sid
clean:
rm -f *.core sid2num num2sid
+26
View File
@@ -0,0 +1,26 @@
#include <stdio.h>
#include <stdlib.h>
char b64map[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789[]";
int main(int argc, char *argv[])
{
int num = 0;
if (argc < 2)
{
printf("Syntax: %s <numeric>\n", argv[0]);
return -1;
}
num = atoi(argv[1]);
if ((num < 0) || (num > 4095)) {
printf("Numeric must be between 0 and 4095\n");
return -1;
}
printf("SID: %c%c\n", b64map[(int)(num >> 6)], b64map[(num & 0x3F)]);
return 0;
}
+40
View File
@@ -0,0 +1,40 @@
#include <string.h>
#include <stdio.h>
int b64map[] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 62, -1, 63, -1, -1,
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
};
int main(int argc, char *argv[])
{
if (argc < 2)
{
printf("Syntax: %s <sid>\n", argv[0]);
return -1;
}
if ((strlen(argv[1]) < 2) || (b64map[(int)argv[1][0]] < 0) || (b64map[(int)argv[1][1]] < 0))
{
printf("SID must be a 2 characters from A-Z, a-z, 0-9, [ or ]\n");
return -1;
}
printf("Numeric is: %d\n", ((b64map[(int)argv[1][0]] << 6) + b64map[(int)argv[1][1]]));
return 0;
}
+10
View File
@@ -0,0 +1,10 @@
#!/usr/bin/perl
#
# untabify - convert tabs to spaces
#
# $Id: untabify,v 1.2 2002-03-07 22:52:57 ghostwolf Exp $
use Text::Tabs;
$tabstop = 8;
while (<>) { print expand($_) }
+220
View File
@@ -0,0 +1,220 @@
/*
** Copyright (C) 2000 by Kevin L. Mitchell <klmitch@mit.edu>
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
**
** @(#)$Id: wrapper.c 1050 2004-05-15 14:50:09Z entrope $
*/
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <pwd.h>
#include <grp.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/resource.h>
#include <unistd.h>
/*
* Try and find the correct name to use with getrlimit() for setting the max.
* number of files allowed to be open by this process.
*
* Shamelessly stolen from ircu...
*/
#ifdef RLIMIT_FDMAX
#define RLIMIT_FD_MAX RLIMIT_FDMAX
#else
#ifdef RLIMIT_NOFILE
#define RLIMIT_FD_MAX RLIMIT_NOFILE
#else
#ifdef RLIMIT_OPEN_MAX
#define RLIMIT_FD_MAX RLIMIT_OPEN_MAX
#else
#error Unable to find a valid RLIMIT_FD_MAX
#endif
#endif
#endif
/*fix for change uid/gid with chroot #ubra 08/02/03*/
int uid, gid;
/*
* Set the hard and soft limits for maximum file descriptors.
*/
int
set_fdlimit(unsigned int max_descriptors)
{
struct rlimit limit;
limit.rlim_max = limit.rlim_cur = max_descriptors;
return setrlimit(RLIMIT_FD_MAX, &limit);
}
/*
* Change directories to the indicated root directory, then make it the
* root directory.
*/
int
change_root(char *root)
{
if (chdir(root))
return -1;
if (chroot(root))
return -1;
return 0;
}
/*
* Change the user and group ids--including supplementary groups!--as
* appropriate.
*
* fix for change uid/gid with chroot #ubra 08/02/03
* old change_user() got splited into get_user() and set_user()
*/
int
get_user(char *user, char *group)
{
struct passwd *pwd;
struct group *grp;
char *tmp;
/* Track down a struct passwd describing the desired user */
uid = strtol(user, &tmp, 10); /* was the user given as a number? */
if (*tmp) { /* strtol() failed to parse; look up as a user name */
if (!(pwd = getpwnam(user)))
return -1;
} else if (!(pwd = getpwuid(uid))) /* look up uid */
return -1;
uid = pwd->pw_uid; /* uid to change to */
gid = pwd->pw_gid; /* default gid for user */
if (group) { /* a group was specified; track down struct group */
gid = strtol(group, &tmp, 10); /* was the group given as a number? */
if (*tmp) { /* strtol() failed to parse; look up as a group name */
if (!(grp = getgrnam(group)))
return -1;
} else if (!(grp = getgrgid(gid))) /* look up gid */
return -1;
gid = grp->gr_gid; /* set the gid */
}
if (initgroups(pwd->pw_name, gid)) /* initialize supplementary groups */
return -1;
return 0; /* success! */
}
int
set_user(void) {
if (setgid(gid)) /* change our current group */
return -1;
if (setuid(uid)) /* change our current user */
return -1;
return 0; /* success! */
}
/*
* Explain how to use this program.
*/
void
usage(char *prog, int retval)
{
fprintf(stderr, "Usage: %s [-u <user>] [-g <group>] [-l <limit>] [-c <root>]"
" -- \\\n\t\t<cmd> [<cmdargs>]\n", prog);
fprintf(stderr, " %s -h\n", prog);
exit(retval);
}
int
main(int argc, char **argv)
{
int c, limit = -1;
char *prog, *user = 0, *group = 0, *root = 0;
/* determine program name for error reporting */
if ((prog = strrchr(argv[0], '/')))
prog++;
else
prog = argv[0];
/* process command line arguments */
while ((c = getopt(argc, argv, "hu:g:l:c:")) > 0)
switch (c) {
case 'h': /* requested help */
usage(prog, 0);
break;
case 'u': /* suggested a user */
user = optarg;
break;
case 'g': /* suggested a group */
group = optarg;
break;
case 'l': /* file descriptor limit */
limit = strtol(optarg, 0, 10);
break;
case 'c': /* select a root directory */
root = optarg;
break;
default: /* unknown command line argument */
usage(prog, 1);
break;
}
/* Not enough arguments; we must have a command to execute! */
if (optind >= argc)
usage(prog, 1);
if (limit > 0) /* set the requested fd limit */
if (set_fdlimit(limit) < 0) {
perror(prog);
return 1;
}
if(user) /* get the selected user account uid/gid*/
if (get_user(user, group)) {
perror(prog);
return 1;
}
if (root) /* change root directories */
if (change_root(root)) {
perror(prog);
return 1;
}
if (user) /* change to selected user account */
if (set_user()) {
perror(prog);
return 1;
}
/* execute the requested command */
execvp(argv[optind], argv + optind);
/* If we got here, execvp() failed; report the error */
perror(prog);
return 1;
}