summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authortpearson <tpearson@283d02a7-25f6-0310-bc7c-ecb5cbfe19da>2010-03-01 18:47:14 +0000
committertpearson <tpearson@283d02a7-25f6-0310-bc7c-ecb5cbfe19da>2010-03-01 18:47:14 +0000
commit3eaf4237194e25804f221af93c269d3d97e2809d (patch)
treecdedf3fc954b0727b0b34aa9b0b211cc18f854eb
downloadsmartcardauth-3eaf4237.tar.gz
smartcardauth-3eaf4237.zip
Added my SmartCard login/session lock/unlock utility
git-svn-id: svn://anonsvn.kde.org/home/kde/branches/trinity/applications/smartcardauth@1097604 283d02a7-25f6-0310-bc7c-ecb5cbfe19da
-rwxr-xr-xMakefile21
-rwxr-xr-xbuild_ckpasswd5
-rwxr-xr-xdebian/changelog5
-rwxr-xr-xdebian/compat1
-rwxr-xr-xdebian/control23
-rwxr-xr-xdebian/dirs1
-rwxr-xr-xdebian/rules11
-rwxr-xr-xdebian/smartcardauth.postinst9
-rwxr-xr-xetc/init/smartauthlogin.conf14
-rw-r--r--etc/smartauth/smartauth.sh.in177
-rw-r--r--etc/smartauth/smartauthmon.sh.in608
-rw-r--r--gpl.txt674
-rw-r--r--include/inn/buffer.h48
-rw-r--r--include/inn/confparse.h78
-rw-r--r--include/inn/defines.h66
-rw-r--r--include/inn/hashtab.h60
-rw-r--r--include/inn/history.h110
-rw-r--r--include/inn/innconf.h211
-rw-r--r--include/inn/list.h51
-rw-r--r--include/inn/md5.h79
-rw-r--r--include/inn/messages.h99
-rw-r--r--include/inn/mmap.h33
-rw-r--r--include/inn/qio.h49
-rw-r--r--include/inn/sequence.h21
-rw-r--r--include/inn/timer.h38
-rw-r--r--include/inn/tst.h88
-rw-r--r--include/inn/vector.h87
-rw-r--r--include/inn/wire.h46
-rwxr-xr-xscriptor_standalone.pl171
-rw-r--r--src/Makefile16
-rw-r--r--src/ckpasswd.c366
-rw-r--r--src/messages.c493
-rw-r--r--src/xmalloc.c163
-rwxr-xr-xusr/bin/cryptosmartcard.sh88
-rwxr-xr-xusr/bin/setupcard.sh1010
-rwxr-xr-xusr/bin/setupslavecard.sh502
-rw-r--r--usr/bin/smartauth.sh74
-rw-r--r--usr/share/applications/smartcardauth.desktop10
-rw-r--r--usr/share/applications/smartcardrestrict.desktop10
-rw-r--r--usr/share/icons/hicolor/16x16/apps/smartcardauth.pngbin0 -> 595 bytes
-rw-r--r--usr/share/icons/hicolor/32x32/apps/smartcardauth.pngbin0 -> 1807 bytes
-rwxr-xr-xusr/share/initramfs-tools/hooks/cryptlukssc65
42 files changed, 5681 insertions, 0 deletions
diff --git a/Makefile b/Makefile
new file mode 100755
index 0000000..236a57a
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,21 @@
+FPACKAGE = smartcardauth
+VERSION = 1.0
+
+build:
+
+clean:
+
+install:
+ sed -i "s#scriptor#scriptor_standalone#g" scriptor_standalone.pl
+ /usr/bin/pp -a /usr/lib/perl5/Chipcard -a /usr/lib/perl5/Chipcard -o scriptor_standalone scriptor_standalone.pl
+ rm scriptor_standalone.pl
+ mv scriptor_standalone usr/bin/scriptor_standalone
+
+ ./build_ckpasswd
+
+ mkdir -p $(DESTDIR)/usr
+ cp -Rp src/ckpasswd usr/bin/smartauthckpasswd
+ cp -Rp usr/* $(DESTDIR)/usr/
+
+ mkdir -p $(DESTDIR)/etc
+ cp -Rp etc/* $(DESTDIR)/etc/
diff --git a/build_ckpasswd b/build_ckpasswd
new file mode 100755
index 0000000..b354c1f
--- /dev/null
+++ b/build_ckpasswd
@@ -0,0 +1,5 @@
+#!/bin/bash
+
+cd src/
+make
+cd ..
diff --git a/debian/changelog b/debian/changelog
new file mode 100755
index 0000000..e598f5f
--- /dev/null
+++ b/debian/changelog
@@ -0,0 +1,5 @@
+smartcardauth (1.0-3ubuntu5) karmic; urgency=low
+
+ * Karmic build
+
+ -- Timothy Pearson <kb9vqf@pearsoncomputing.net> Thu, 23 July 2009 10:42:00 -0600
diff --git a/debian/compat b/debian/compat
new file mode 100755
index 0000000..7ed6ff8
--- /dev/null
+++ b/debian/compat
@@ -0,0 +1 @@
+5
diff --git a/debian/control b/debian/control
new file mode 100755
index 0000000..fda6725
--- /dev/null
+++ b/debian/control
@@ -0,0 +1,23 @@
+Source: smartcardauth
+Section: kde
+Priority: extra
+Maintainer: Timothy Pearson <kb9vqf@pearsoncomputing.net>
+Uploaders: Timothy Pearson <kb9vqf@pearsoncomputing.net>
+Build-Depends: debhelper (>=5.0), cdbs, pcsc-tools, pcscd-nodbus, initramfs-tools, libpcsc-perl, libpcsclite1, libccid, opensc, libpar-packer-perl, libdb4.7-dev, libpam0g-dev, libssl-dev, libkrb5-dev
+Standards-Version: 3.8.2
+
+Package: smartcardauth
+Architecture: any
+Depends: pcsc-tools, pcscd-nodbus, initramfs-tools, libpcsc-perl, libpcsclite1, libccid, opensc, zenity, gksu
+Conflicts: openct
+Description: SmartCard Login and LUKS Decrypt, Setup Utility
+ This utility will allow you to set up your computer to accept a SmartCard as an authentication source for:
+ - Your encrypted LUKS partition
+ - KDE3.5, including automatic login, lock, and unlock features
+ It is designed to work with any ISO 7816-1,2,3,4 compliant smartcard
+ Examples of such cards are:
+ - The Schlumberger MultiFlex
+ - The ACS ACOS5 / ACOS6 series of cryptographic ISO 7816 cards
+ If a card is chosen that has PKSC support, such as the ACOS cards, this utility can run
+ simultaneously with the certificate reading program(s) to provide single sign on
+ in addition to the PKCS certificate functionality
diff --git a/debian/dirs b/debian/dirs
new file mode 100755
index 0000000..73752c9
--- /dev/null
+++ b/debian/dirs
@@ -0,0 +1 @@
+usr
diff --git a/debian/rules b/debian/rules
new file mode 100755
index 0000000..a9e7e66
--- /dev/null
+++ b/debian/rules
@@ -0,0 +1,11 @@
+#!/usr/bin/make -f
+include /usr/share/cdbs/1/class/makefile.mk
+include /usr/share/cdbs/1/rules/debhelper.mk
+
+DEB_BUILD_OPTIONS := nostrip
+export DEB_BUILD_OPTIONS = debug nostrip
+
+CFLAGS=-g -Wall -fPIC
+
+DEB_MAKE_INSTALL_TARGET := install DESTDIR="$(DEB_DESTDIR)"
+DEB_INSTALL_DOCS_ALL :=
diff --git a/debian/smartcardauth.postinst b/debian/smartcardauth.postinst
new file mode 100755
index 0000000..842e001
--- /dev/null
+++ b/debian/smartcardauth.postinst
@@ -0,0 +1,9 @@
+#!/bin/bash
+
+set -e
+
+if [[ $1 = "configure" ]]; then
+ /usr/bin/setupcard.sh upgrade
+fi
+
+
diff --git a/etc/init/smartauthlogin.conf b/etc/init/smartauthlogin.conf
new file mode 100755
index 0000000..89852d5
--- /dev/null
+++ b/etc/init/smartauthlogin.conf
@@ -0,0 +1,14 @@
+# smartauthlogin - smart card login manager
+#
+
+description "smart card login monitor"
+
+start on (filesystem
+ and started kdm-kde3)
+stop on stopping kdm-kde3
+
+script
+ if [ -e /usr/bin/smartauthmon.sh ]; then
+ /usr/bin/smartauthmon.sh
+ fi
+end script
diff --git a/etc/smartauth/smartauth.sh.in b/etc/smartauth/smartauth.sh.in
new file mode 100644
index 0000000..92a9c56
--- /dev/null
+++ b/etc/smartauth/smartauth.sh.in
@@ -0,0 +1,177 @@
+#!/bin/bash
+
+# Smart Card Authentication Helper (c) 2009 Timothy Pearson
+#
+# 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 3 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, see <http://www.gnu.org/licenses/>.
+
+get_file () {
+ if [[ $COMMAND_MODE == "acos" ]]; then
+ # Select EF $1 under DF 1000
+ echo "$SELECT_FILE $1" > query
+ scriptor_standalone query 1> response2
+ echo $(cat response2)
+
+ # Read binary
+ echo "$READ_BINARY" > query
+ scriptor_standalone query 1> response2
+ authokresponse="90 00 : Normal processing"
+ response1=$(cat response2 | grep "$authokresponse")
+ if [[ $response1 != "" ]]; then
+ cat response2 | tr -d '\n' > response4
+ stringtoreplace="Using T=0 protocol00 B0 00 00 FF> 00 B0 00 00 FF< "
+ newstring=""
+ sed -i "s#${stringtoreplace}#${newstring}#g" response4
+ stringtoreplace=" 90 00 : Normal processing."
+ newstring=""
+ sed -i "s#${stringtoreplace}#${newstring}#g" response4
+ if [[ $2 == "text" ]]; then
+ stringtoreplace=" 00"
+ newstring=""
+ sed -i "s#${stringtoreplace}#${newstring}#g" response4
+ fi
+ echo $(cat response4)
+ rm -f lukskey
+ xxd -r -p response4 lukskey
+ RESPONSE=lukskey
+ fi
+ fi
+
+ if [[ $COMMAND_MODE == "cryptoflex" ]]; then
+ echo "get $1" | opensc-explorer
+ RESPONSE="3F00_$1"
+ fi
+}
+
+# Initialize pcscd
+killall pcscd &
+sleep 1
+pcscd &
+sleep 1
+
+# Get card ATR
+echo "RESET" > query
+scriptor_standalone query 1> response2
+authokresponse="OK: "
+response1=$(cat response2 | grep "$authokresponse")
+if [[ $response1 != "" ]]; then
+ cat response2 | tr -d '\n' > response4
+ stringtoreplace="Using T=0 protocolRESET> RESET< OK: "
+ newstring=""
+ sed -i "s#${stringtoreplace}#${newstring}#g" response4
+ smartatr=$(cat response4)
+ echo "Got ATR: $smartatr"
+ if [[ $smartatr == "3B BE 18 00 00 41 05 10 00 00 00 00 00 00 00 00 00 90 00 " ]]; then
+ echo "Detected ACOS5 card"
+ COMMAND_MODE="acos"
+ fi
+ if [[ $smartatr == "3B 02 14 50 " ]]; then
+ echo "Detected Schlumberger CryptoFlex card"
+ COMMAND_MODE="cryptoflex"
+ fi
+else
+ echo "No card detected!"
+ exit 1
+fi
+
+if [[ $COMMAND_MODE == "cryptoflex" ]]; then
+ GET_CHALLENGE="C0 84 00 00 08"
+ EXTERNAL_AUTH="C0 82 00 00 07 01"
+ SELECT_FILE="C0 A4 00 00 02"
+ DELETE_FILE="F0 E4 00 00 02"
+fi
+
+if [[ $COMMAND_MODE == "acos" ]]; then
+ GET_CHALLENGE="00 84 00 00 08"
+ EXTERNAL_AUTH="00 82 00 83 08" # Key 3
+ SELECT_FILE="00 A4 00 00 02"
+ DELETE_FILE="00 E4 00 00 00"
+ READ_BINARY="00 B0 00 00 FF"
+ UPDATE_BINARY="00 D6 00 00 FF"
+ ACTIVATE_FILE="00 44 00 00 02"
+fi
+
+# Authenticate card
+if [[ $COMMAND_MODE == "acos" ]]; then
+ # Select MF
+ echo "00 A4 00 00 00" > query
+ scriptor_standalone query 1> response2
+ echo $(cat response2)
+
+ # Select DF 1000 under MF
+ echo "$SELECT_FILE 10 00" > query
+ scriptor_standalone query 1> response2
+ echo $(cat response2)
+fi
+
+echo $GET_CHALLENGE > authscript
+
+scriptor_standalone authscript | grep 'Normal processing' > challenge
+perl -pi -e 's/ //g' challenge
+perl -pi -e 's/:Normalprocessing.//g' challenge
+perl -pi -e 's/<//g' challenge
+xxd -r -p challenge challenge
+
+# Now DES encrypt the challenge
+# Later, change the initialization vector to random if possible
+openssl des-ecb -in challenge -out response -K <your key in hexidecimal> -iv 1
+
+if [[ $COMMAND_MODE == "acos" ]]; then
+ # Truncate to 8 bytes
+ dd if=response of=response2 bs=1 count=8
+
+ # Expand to standard hex listing format
+ xxd -g 1 response2 response
+ dd if=response of=response2 bs=1 count=23 skip=9
+fi
+
+if [[ $COMMAND_MODE == "cryptoflex" ]]; then
+ # Truncate to 6 bytes
+ dd if=response of=response2 bs=1 count=6
+
+ # Expand to standard hex listing format
+ xxd -g 1 response2 response
+ dd if=response of=response2 bs=1 count=17 skip=9
+fi
+
+# Assemble the response file
+response2=$(cat response2)
+response1="$EXTERNAL_AUTH ${response2}"
+echo $response1 > response
+
+# Send the response!
+scriptor_standalone response > response2
+
+# Get the result
+authokresponse="< 90 00 : Normal processing"
+response1=$(cat response2 | grep "$authokresponse")
+echo $response1
+if [[ $response1 != "" ]]; then
+ echo "Smart card validation successfull!"
+ # Get encryption key
+ if [[ $COMMAND_MODE == "acos" ]]; then
+ get_file "10 01"
+ fi
+
+ if [[ $COMMAND_MODE == "cryptoflex" ]]; then
+ get_file "1001"
+ fi
+ mv $RESPONSE smart.key
+else
+ echo "Authentication failed!"
+fi
+
+rm authscript &
+rm response &
+rm response2 &
+rm challenge &
diff --git a/etc/smartauth/smartauthmon.sh.in b/etc/smartauth/smartauthmon.sh.in
new file mode 100644
index 0000000..219e89e
--- /dev/null
+++ b/etc/smartauth/smartauthmon.sh.in
@@ -0,0 +1,608 @@
+#!/bin/bash
+
+# Smart Card KDE3.5 Authentication Script (c) 2009 Timothy Pearson
+#
+# 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 3 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, see <http://www.gnu.org/licenses/>.
+
+# Maximum number of virtual terminals on this system
+MAXIMUM_VTS=49
+
+# The [secure] temporary directory for authentication
+SECURE_DIRECTORY=/tmp/smartauth
+
+hexcvt ()
+{
+ echo ""$1" "16" o p" | dc
+}
+
+# Create the secure directory and lock it down
+rm -rf $SECURE_DIRECTORY
+mkdir -p $SECURE_DIRECTORY
+chown root $SECURE_DIRECTORY
+chgrp root $SECURE_DIRECTORY
+chmod 600 $SECURE_DIRECTORY
+SECURE_DIRECTORY=$(mktemp /tmp/smartauth/smartauthmon.XXXXXXXXXX)
+rm -rf $SECURE_DIRECTORY
+mkdir -p $SECURE_DIRECTORY
+chown root $SECURE_DIRECTORY
+chgrp root $SECURE_DIRECTORY
+chmod 600 $SECURE_DIRECTORY
+
+# Restart PCSCD and kill spurious processes
+killall -9 pcscd
+/etc/init.d/pcscd restart
+/etc/init.d/pcscd-nodbus restart
+
+# See if required programs are installed
+scriptor=$(whereis scriptor)
+if [[ $scriptor == "scriptor:" ]]; then
+ echo "ERROR: scriptor is not installed! This program cannot continue!"
+ exit
+fi
+opensc=$(whereis opensc-explorer)
+if [[ $opensc == "opensc-explorer:" ]]; then
+ echo "ERROR: opensc-explorer is not installed! This program cannot continue!"
+ exit
+fi
+
+get_file () {
+ if [[ $COMMAND_MODE == "acos" ]]; then
+ # Select EF $1 under DF 1000
+ echo "$SELECT_FILE $1" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+
+ # Read binary
+ echo "$READ_BINARY" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ authokresponse="90 00 : Normal processing"
+ response1=$(cat $SECURE_DIRECTORY/response2 | grep "$authokresponse")
+ if [[ $response1 != "" ]]; then
+ cat $SECURE_DIRECTORY/response2 | tr -d '\n' > $SECURE_DIRECTORY/response4
+ stringtoreplace="Using T=0 protocol00 B0 00 00 FF> 00 B0 00 00 FF< "
+ newstring=""
+ sed -i "s#${stringtoreplace}#${newstring}#g" $SECURE_DIRECTORY/response4
+ stringtoreplace=" 90 00 : Normal processing."
+ newstring=""
+ sed -i "s#${stringtoreplace}#${newstring}#g" $SECURE_DIRECTORY/response4
+ if [[ $2 == "text" ]]; then
+ stringtoreplace=" 00"
+ newstring=""
+ sed -i "s#${stringtoreplace}#${newstring}#g" $SECURE_DIRECTORY/response4
+ fi
+ echo $(cat $SECURE_DIRECTORY/response4)
+ rm -f $SECURE_DIRECTORY/lukskey
+ xxd -r -p $SECURE_DIRECTORY/response4 $SECURE_DIRECTORY/lukskey
+ RESPONSE=$SECURE_DIRECTORY/lukskey
+ fi
+ fi
+
+ if [[ $COMMAND_MODE == "cryptoflex" ]]; then
+ FILE=${1/ /}
+ echo "get $FILE" | opensc-explorer
+ RESPONSE="3F00_$FILE"
+ fi
+}
+
+update_file () {
+ if [[ $COMMAND_MODE == "acos" ]]; then
+ # Select EF $1 under DF 1000
+ echo "$SELECT_FILE $1" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+
+ # Update existing file
+ # Zero pad input file
+ dd if=/dev/zero of=$SECURE_DIRECTORY/response2 bs=1 count=255
+ dd if=$2 of=$SECURE_DIRECTORY/response2 bs=1 count=255 conv=notrunc
+
+ # Truncate to 255 bytes and expand to standard hex listing format
+ xxd -l 255 -ps -c 1 $SECURE_DIRECTORY/response2 > $SECURE_DIRECTORY/response
+ cat $SECURE_DIRECTORY/response | tr '\n' ' ' > $SECURE_DIRECTORY/hexready
+ echo "$UPDATE_BINARY $(cat $SECURE_DIRECTORY/hexready)" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2 2>/dev/null
+ echo $(cat $SECURE_DIRECTORY/response2)
+ fi
+
+ if [[ $COMMAND_MODE == "cryptoflex" ]]; then
+ # Delete old file
+ echo "$DELETE_FILE $1" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2 2>/dev/null
+ echo $(cat $SECURE_DIRECTORY/response2)
+
+ # Create new file
+ createfile "FF" $1
+ FILE=${1/ /}
+ echo "put $FILE $2" | opensc-explorer
+ fi
+}
+
+oldsmartcard_username=""
+echo "Ready..."
+while [[ 1 == 1 ]]; do
+ sleep 1
+ echo "exit" | scriptor 2>/dev/null 1>/dev/null
+ OUTPUT=$?
+ if [[ $OUTPUT -eq 0 ]]; then
+ echo "Card inserted!"
+
+ # Get card ATR
+ echo "RESET" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ authokresponse="OK: "
+ response1=$(cat $SECURE_DIRECTORY/response2 | grep "$authokresponse")
+ if [[ $response1 != "" ]]; then
+ cat $SECURE_DIRECTORY/response2 | tr -d '\n' > $SECURE_DIRECTORY/response4
+ stringtoreplace="Using T=0 protocolRESET> RESET< OK: "
+ newstring=""
+ sed -i "s#${stringtoreplace}#${newstring}#g" $SECURE_DIRECTORY/response4
+ smartatr=$(cat $SECURE_DIRECTORY/response4)
+ echo "Got ATR: $smartatr"
+ if [[ $smartatr == "3B BE 18 00 00 41 05 10 00 00 00 00 00 00 00 00 00 90 00 " ]]; then
+ echo "Detected ACOS5 card"
+ COMMAND_MODE="acos"
+ fi
+ if [[ $smartatr == "3B 02 14 50 " ]]; then
+ echo "Detected Schlumberger CryptoFlex card"
+ COMMAND_MODE="cryptoflex"
+ fi
+ else
+ echo "No card detected!"
+ fi
+
+ if [[ $COMMAND_MODE == "cryptoflex" ]]; then
+ GET_CHALLENGE="C0 84 00 00 08"
+ EXTERNAL_AUTH="C0 82 00 00 07 01"
+ SELECT_FILE="C0 A4 00 00 02"
+ DELETE_FILE="F0 E4 00 00 02"
+ fi
+
+ if [[ $COMMAND_MODE == "acos" ]]; then
+ GET_CHALLENGE="00 84 00 00 08"
+ EXTERNAL_AUTH="00 82 00 82 08" # Key 2
+ SELECT_FILE="00 A4 00 00 02"
+ DELETE_FILE="00 E4 00 00 00"
+ READ_BINARY="00 B0 00 00 FF"
+ UPDATE_BINARY="00 D6 00 00 FF"
+ ACTIVATE_FILE="00 44 00 00 02"
+ fi
+
+ # Authenticate card
+
+ if [[ $COMMAND_MODE == "acos" ]]; then
+ # Select MF
+ echo "00 A4 00 00 00" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+
+ # Select DF 1000 under MF
+ echo "$SELECT_FILE 10 00" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+ fi
+
+ echo $GET_CHALLENGE > $SECURE_DIRECTORY/authscript
+
+ scriptor $SECURE_DIRECTORY/authscript | grep 'Normal processing' > $SECURE_DIRECTORY/challenge
+ perl -pi -e 's/ //g' $SECURE_DIRECTORY/challenge
+ perl -pi -e 's/:Normalprocessing.//g' $SECURE_DIRECTORY/challenge
+ perl -pi -e 's/<//g' $SECURE_DIRECTORY/challenge
+ xxd -r -p $SECURE_DIRECTORY/challenge $SECURE_DIRECTORY/challenge
+
+ # Now DES encrypt the challenge
+ # Later, change the initialization vector to random if possible
+ openssl des-ecb -in $SECURE_DIRECTORY/challenge -out $SECURE_DIRECTORY/response -K <your key in hexadecimal> -iv 1
+
+ if [[ $COMMAND_MODE == "acos" ]]; then
+ # Truncate to 8 bytes
+ dd if=$SECURE_DIRECTORY/response of=$SECURE_DIRECTORY/response2 bs=1 count=8
+
+ # Expand to standard hex listing format
+ xxd -g 1 $SECURE_DIRECTORY/response2 $SECURE_DIRECTORY/response
+ dd if=$SECURE_DIRECTORY/response of=$SECURE_DIRECTORY/response2 bs=1 count=23 skip=9
+ fi
+
+ if [[ $COMMAND_MODE == "cryptoflex" ]]; then
+ # Truncate to 6 bytes
+ dd if=$SECURE_DIRECTORY/response of=$SECURE_DIRECTORY/response2 bs=1 count=6
+
+ # Expand to standard hex listing format
+ xxd -g 1 $SECURE_DIRECTORY/response2 $SECURE_DIRECTORY/response
+ dd if=$SECURE_DIRECTORY/response of=$SECURE_DIRECTORY/response2 bs=1 count=17 skip=9
+ fi
+
+ # Assemble the response file
+ response2=$(cat $SECURE_DIRECTORY/response2)
+ response1="$EXTERNAL_AUTH ${response2}"
+ echo $response1 > $SECURE_DIRECTORY/response
+
+ # Send the response!
+ scriptor $SECURE_DIRECTORY/response > $SECURE_DIRECTORY/response2
+
+ # Get the result
+ authokresponse="< 90 00 : Normal processing"
+ response1=$(cat $SECURE_DIRECTORY/response2 | grep "$authokresponse")
+ echo $response1
+ if [[ $response1 != "" ]]; then
+ echo "Smart card validation successfull!"
+ # Get username and password
+ get_file "10 02" "text"
+ smartcard_username=$(cat $RESPONSE)
+ get_file "10 03" "text"
+ mv $RESPONSE $SECURE_DIRECTORY/password
+ get_file "10 04" "text"
+ smartcard_slave=$(cat $RESPONSE)
+ if [[ $smartcard_slave == "SLAVE" ]]; then
+ get_file "10 05" "text"
+ smartcard_minutes=$(cat $RESPONSE)
+ get_file "10 06" "text"
+ internet_minutes=$(cat $RESPONSE)
+ fi
+ else
+ echo "This card does not recognize this system!"
+ sleep 1
+ smartcard_username=""
+ rm -f $SECURE_DIRECTORY/password
+ smartcard_slave=""
+ fi
+
+ if [[ $smartcard_slave == "SLAVE" ]]; then
+ if [[ $smartcard_minutes == "" ]]; then
+ smartcard_minutes=1
+ fi
+
+ # Decrement minutes on card
+ if [[ $smartcard_minutes -gt 0 ]]; then
+ let "smartcard_minutes=smartcard_minutes-1"
+ echo $smartcard_minutes > $SECURE_DIRECTORY/minutes
+ update_file "10 05" "$SECURE_DIRECTORY/minutes"
+ fi
+
+ if [[ $smartcard_minutes -eq 0 ]]; then
+ echo "Minutes have been used up!"
+ # Prohibit logon
+ smartcard_username=""
+ rm $SECURE_DIRECTORY/password
+ fi
+
+ mkdir -p /etc/smartmon
+ echo $smartcard_minutes > /etc/smartmon/minutesremaining
+ chmod 755 /etc/smartmon/minutesremaining
+ fi
+
+ # Initialize variables
+ loginok=1
+
+ # Try to do the authentication
+ result=""
+ timeout=0
+ errcode=0
+ waserror=0
+ noactivesessions=0
+
+ result_is_consistent=0
+ while [[ $result_is_consistent == 0 ]]; do
+ result_one=$(/opt/kde3/bin/kdmctl -g list)
+ sleep 0.1
+ result_two=$(/opt/kde3/bin/kdmctl -g list)
+ sleep 0.1
+ result_three=$(/opt/kde3/bin/kdmctl -g list)
+ sleep 0.1
+ result_four=$(/opt/kde3/bin/kdmctl -g list)
+ if [[ $result_one == $result_two ]]; then
+ if [[ $result_one == $result_three ]]; then
+ if [[ $result_one == $result_four ]]; then
+ result=$result_one
+ result_is_consistent=1
+ fi
+ fi
+ fi
+ done
+ if [[ $result == "ok" ]]; then
+ noactivesessions=1
+ result="okbutempty"
+ fi
+ echo $result
+ resultbkp=$result
+
+ if [[ $errcode -eq 0 ]]; then
+ # Allow KDM to finish starting
+ if [[ $waserror -eq 1 ]]; then
+ sleep 10
+ fi
+
+ # Zero the desktop array
+ index=0
+ while [[ $index != $MAXIMUM_VTS ]]; do
+ darray[index]=""
+ index=$((index+1))
+ done
+
+ if [[ result != "okbutempty" ]]; then
+ posone="0"
+ posone=$(expr index "$result" " :")
+ postwo="0"
+ postwo=$(expr index "$result" ",")
+ while [[ $posone != "0" ]]; do
+ length=$((postwo-posone-1))
+ terminals="${result:posone:length}"
+ echo $terminals
+
+ # Delete the terminal we just got from the list of terminals
+ result="${result:postwo}"
+ postwo=$(expr index "$result" ",")
+ result="${result:postwo}"
+ postwo=$(expr index "$result" ",")
+ length=$((postwo-1))
+ username="${result:0:length}"
+ darray[terminals]=$username # Save username of this terminal
+ echo $username
+ result="${result:postwo}"
+ postwo=$(expr index "$result" ",")
+ result="${result:postwo}"
+
+ # Now see if there might be ANOTHER terminal active or not
+ posone="0"
+ posone=$(expr index "$result" " :")
+ postwo="0"
+ postwo=$(expr index "$result" ",")
+ done
+ fi
+
+ # See if the desired user is already logged in
+ index=0
+ foundsession=0
+ while [[ $index != $MAXIMUM_VTS ]]; do
+ if [[ ${darray[index]} == $smartcard_username ]]; then
+ if [[ ${darray[index]} != "" ]]; then
+ echo "Found existing session on desktop: ${index}"
+ foundsession=1
+ # Check password
+ lverify=$(/usr/bin/smartauthckpasswd -u ${darray[index]} -p $(cat $SECURE_DIRECTORY/password))
+ cverify="User:${darray[index]}"
+ udisplay=":${index}"
+ if [[ $lverify == $cverify ]]; then
+ su $smartcard_username -c "export DISPLAY=$udisplay; /opt/kde3/bin/dcop kdesktop KScreensaverIface quit"
+ /opt/kde3/bin/kdmctl activate $udisplay
+ fi
+ else
+ echo "Username not specified"
+ foundsession=2
+ sleep 1
+ fi
+ fi
+ index=$((index+1))
+ done
+
+ if [[ $foundsession == "0" ]]; then
+ echo "Existing session not found, starting new..."
+
+ # Make sure that this is not display :0 (default login screen).
+ # If it is, execute login. If not, create new session, then execute login
+ usebasedisplay=0
+ if [[ $noactivesessions -eq 1 ]]; then
+ newdisplay=$(ls /var/run/xdmctl/ | grep 'xdmctl-:0')
+ echo $newdisplay
+ if [[ $newdisplay != "" ]]; then
+ usebasedisplay=1
+ fi
+ fi
+ vtsessions=$(echo "$resultbkp" | grep ',vt')
+ if [[ $vtsessions == "" ]]; then
+ newdisplay=$(ls /var/run/xdmctl/ | grep 'xdmctl-:0')
+ echo $newdisplay
+ if [[ $newdisplay != "" ]]; then
+ usebasedisplay=1
+ fi
+ fi
+
+ echo "Creating new session"
+ # Attempt login
+ ls /var/run/xdmctl > $SECURE_DIRECTORY/originalxdm
+
+ # Set loop separator to end of line
+ BAKIFS=$IFS
+ IFS=$(echo -en "\n\b")
+ exec 3<&0
+ exec 0<"$SECURE_DIRECTORY/originalxdm"
+ newdisplayfound=0
+ newdisplay=-1
+ while read -r line
+ do
+ # use $line variable to process lines
+ line=$(echo $line | grep 'xdmctl-:' | sed -e 's/xdmctl-://')
+ if [ "`expr $line - $line 2>/dev/null`" == "0" ]; then
+ echo "Found active display on $line"
+ if [[ $newdisplayfound -eq 0 ]]; then
+ tempnewdisplay=$((newdisplay + 1))
+ if [[ $line -eq $tempnewdisplay ]]; then
+ echo "Sequential display $line found after display $newdisplay..."
+ newdisplay=$line
+ fi
+ fi
+ fi
+ done
+ exec 0<&3
+ newdisplay=$(($newdisplay + 1))
+ newdisplay=":$newdisplay"
+ echo "The next display to start will be $newdisplay"
+ rm $SECURE_DIRECTORY/originalxdm
+
+ /opt/kde3/bin/kdmctl -g reserve
+ /opt/kde3/bin/kdmctl -g login $newdisplay now $smartcard_username $(cat $SECURE_DIRECTORY/password)
+ sleep 2
+ /opt/kde3/bin/kdmctl -g activate $newdisplay
+ udisplay=$newdisplay
+ fi
+
+ if [[ $smartcard_slave == "SLAVE" ]]; then
+ if [[ $smartcard_minutes -lt 5 ]]; then
+ su $smartcard_username -c "export DISPLAY=$udisplay; zenity --warning --text 'You have less than 5 minutes of computer time remaining' || exit 0" &
+ fi
+ fi
+
+ rm -f $SECURE_DIRECTORY/password
+
+ #if [[ loginok -eq 1 ]]; then
+ # Wait for SmartCard removal
+ TIMER=60
+ OUTPUT=0
+
+ while [[ $OUTPUT -eq 0 ]]; do
+ sleep 1
+ su $smartcard_username -c "export DISPLAY=$udisplay; /opt/kde3/bin/dcop kdesktop KScreensaverIface quit"
+ echo "exit" | scriptor 2>/dev/null 1>/dev/null
+ OUTPUT=$?
+ if [[ $smartcard_slave == "SLAVE" ]]; then
+ TIMER=$(( TIMER - 1 ))
+ if [[ $TIMER -eq 0 ]]; then
+ # 60 seconds have passed, decrement minutes on card
+ let "smartcard_minutes=smartcard_minutes-1"
+ echo $smartcard_minutes > /etc/smartmon/minutesremaining
+ chmod 755 /etc/smartmon/minutesremaining
+
+ TIMER=60
+
+ echo $smartcard_minutes > $SECURE_DIRECTORY/minutes
+ update_file "10 05" "$SECURE_DIRECTORY/minutes"
+
+ if [[ $smartcard_minutes -eq 0 ]]; then
+ echo "Minutes have been used up!"
+ # Prohibit logon
+ smartcard_username=""
+ rm $SECURE_DIRECTORY/password
+ fi
+
+ mkdir -p /etc/smartmon
+ echo $smartcard_minutes > /etc/smartmon/minutesremaining
+ chmod 755 /etc/smartmon/minutesremaining
+
+ if [[ $smartcard_minutes -eq 5 ]]; then
+ su $smartcard_username -c "export DISPLAY=$udisplay; zenity --warning --text 'You have less than 5 minutes of computer time remaining' || exit 0" &
+ fi
+
+ if [[ $smartcard_minutes -eq 0 ]]; then
+ echo "Minutes have been used up!"
+ echo "Beginning logoff process"
+ OUTPUT=254
+ fi
+ fi
+ fi
+ done
+
+ echo "Card removed!"
+
+ # Is the user still logged in?
+ result="ok"
+ timeout=0
+ errcode=0
+ result_is_consistent=0
+ while [[ $result_is_consistent == 0 ]]; do
+ result_one=$(/opt/kde3/bin/kdmctl -g list)
+ sleep 0.1
+ result_two=$(/opt/kde3/bin/kdmctl -g list)
+ sleep 0.1
+ result_three=$(/opt/kde3/bin/kdmctl -g list)
+ sleep 0.1
+ result_four=$(/opt/kde3/bin/kdmctl -g list)
+ if [[ $result_one == $result_two ]]; then
+ if [[ $result_one == $result_three ]]; then
+ if [[ $result_one == $result_four ]]; then
+ result=$result_one
+ result_is_consistent=1
+ fi
+ fi
+ fi
+ done
+ if [[ $result == "ok" ]]; then
+ noactivesessions=1
+ result="okbutempty"
+ fi
+ echo $result
+
+ # Zero the desktop array
+ index=0
+ while [[ $index != $MAXIMUM_VTS ]]; do
+ darray[index]=""
+ index=$((index+1))
+ done
+
+ posone="0"
+ posone=$(expr index "$result" " :")
+ postwo="0"
+ postwo=$(expr index "$result" ",")
+ while [[ $posone != "0" ]]; do
+ length=$((postwo-posone-1))
+ terminals="${result:posone:length}"
+ echo $terminals
+
+ # Delete the terminal we just got from the list of terminals
+ result="${result:postwo}"
+ postwo=$(expr index "$result" ",")
+ result="${result:postwo}"
+ postwo=$(expr index "$result" ",")
+ length=$((postwo-1))
+ username="${result:0:length}"
+ darray[terminals]=$username # Save username of this terminal
+ echo $username
+ result="${result:postwo}"
+ postwo=$(expr index "$result" ",")
+ result="${result:postwo}"
+
+ # Now see if there might be ANOTHER terminal active or not
+ posone="0"
+ posone=$(expr index "$result" " :")
+ postwo="0"
+ postwo=$(expr index "$result" ",")
+ done
+
+ # See if the desired user is still logged in
+ index=0
+ foundsession=0
+ while [[ $index != $MAXIMUM_VTS ]]; do
+ if [[ ${darray[index]} == $smartcard_username ]]; then
+ if [[ ${darray[index]} != "" ]]; then
+ echo "Found existing session on desktop: ${index}"
+ udisplay=":${index}"
+ foundsession=1
+ errcode=1
+ timeout=0
+ blankresult=""
+ while [[ $blankresult != "true" ]]; do
+ /opt/kde3/bin/kdmctl -g activate $udisplay
+ su $smartcard_username -c "export DISPLAY=$udisplay; /opt/kde3/bin/dcop kdesktop KScreensaverIface lock"
+ blankresult=$(su $smartcard_username -c "export DISPLAY=$udisplay; /opt/kde3/bin/dcop kdesktop KScreensaverIface isBlanked")
+ if [[ $? != 0 ]]; then
+ blankresult="true"
+ fi
+ logouttest=$(echo $blankresult | grep 'target display has no VT assigned')
+ if [[ "$logouttest" != "" ]]; then
+ echo "User has logged out"
+ blankresult="true"
+ fi
+ done
+ else
+ echo "Username not specified!"
+ sleep 1
+ fi
+ fi
+ index=$((index+1))
+ done
+ #fi
+ fi
+
+ smartcard_username=""
+ rm -rf /etc/smartmon/minutesremaining
+ fi
+done
diff --git a/gpl.txt b/gpl.txt
new file mode 100644
index 0000000..94a9ed0
--- /dev/null
+++ b/gpl.txt
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ 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 3 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, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/include/inn/buffer.h b/include/inn/buffer.h
new file mode 100644
index 0000000..e9deb2b
--- /dev/null
+++ b/include/inn/buffer.h
@@ -0,0 +1,48 @@
+/* $Id: buffer.h 6295 2003-04-16 05:46:38Z rra $
+**
+** Counted, reusable memory buffer.
+**
+** A buffer is an allocated bit of memory with a known size and a separate
+** data length. It's intended to store strings and can be reused repeatedly
+** to minimize the number of memory allocations. Buffers increase in
+** increments of 1K.
+**
+** A buffer contains a notion of the data that's been used and the data
+** that's been left, used when the buffer is an I/O buffer where lots of data
+** is buffered and then slowly processed out of the buffer. The total length
+** of the data is used + left. If a buffer is just used to store some data,
+** used can be set to 0 and left stores the length of the data.
+*/
+
+#ifndef INN_BUFFER_H
+#define INN_BUFFER_H 1
+
+#include <inn/defines.h>
+
+struct buffer {
+ size_t size; /* Total allocated length. */
+ size_t used; /* Data already used. */
+ size_t left; /* Remaining unused data. */
+ char *data; /* Pointer to allocated memory. */
+};
+
+BEGIN_DECLS
+
+/* Allocate a new buffer and initialize its contents. */
+struct buffer *buffer_new(void);
+
+/* Resize a buffer to be at least as large as the provided size. */
+void buffer_resize(struct buffer *, size_t);
+
+/* Set the buffer contents, ignoring anything currently there. */
+void buffer_set(struct buffer *, const char *data, size_t length);
+
+/* Append data to the buffer. */
+void buffer_append(struct buffer *, const char *data, size_t length);
+
+/* Swap the contents of two buffers. */
+void buffer_swap(struct buffer *, struct buffer *);
+
+END_DECLS
+
+#endif /* INN_BUFFER_H */
diff --git a/include/inn/confparse.h b/include/inn/confparse.h
new file mode 100644
index 0000000..5c2aa1c
--- /dev/null
+++ b/include/inn/confparse.h
@@ -0,0 +1,78 @@
+/* $Id: confparse.h 5114 2002-02-18 01:17:24Z rra $
+**
+** Configuration file parsing interface.
+*/
+
+#ifndef INN_CONFPARSE_H
+#define INN_CONFPARSE_H 1
+
+#include <inn/defines.h>
+
+/* Avoid including <inn/vector.h> unless the client needs it. */
+struct vector;
+
+/* The opaque data type representing a configuration tree. */
+struct config_group;
+
+BEGIN_DECLS
+
+/* Parse the given file and build a configuration tree. This does purely
+ syntactic parsing; no semantic checking is done. After the file name, a
+ NULL-terminated list of const char * pointers should be given, naming the
+ top-level group types that the caller is interested in. If none are given
+ (if the second argument is NULL), the entire file is parsed. (This is
+ purely for efficiency reasons; if one doesn't care about speed, everything
+ will work the same if no types are given.)
+
+ Returns a config_group for the top-level group representing the entire
+ file. Generally one never wants to query parameters in this group;
+ instead, the client should then call config_find_group for the group type
+ of interest. Returns NULL on failure to read the file or on a parse
+ failure; errors are reported via warn. */
+struct config_group *config_parse_file(const char *filename, /* types */ ...);
+
+/* config_find_group returns the first group of the given type found in the
+ tree rooted at its argument. config_next_group returns the next group in
+ the tree of the same type as the given group (or NULL if none is found).
+ This can be used to do such things as enumerate all "peer" groups in a
+ configuration file. */
+struct config_group *config_find_group(struct config_group *,
+ const char *type);
+struct config_group *config_next_group(struct config_group *);
+
+/* Accessor functions for group information. */
+const char *config_group_type(struct config_group *);
+const char *config_group_tag(struct config_group *);
+
+/* Look up a parameter in a given config tree. The second argument is the
+ name of the parameter, and the result will be stored in the third argument
+ if the function returns true. If it returns false, the third argument is
+ unchanged and that parameter wasn't set (or was set to an invalid value for
+ the expected type). */
+bool config_param_boolean(struct config_group *, const char *, bool *);
+bool config_param_integer(struct config_group *, const char *, long *);
+bool config_param_real(struct config_group *, const char *, double *);
+bool config_param_string(struct config_group *, const char *, const char **);
+bool config_param_list(struct config_group *, const char *, struct vector *);
+
+/* Used for checking a configuration file, returns a vector of all parameters
+ set for the given config_group, including inherited ones. */
+struct vector *config_params(struct config_group *);
+
+/* Used for reporting semantic errors, config_error_param reports the given
+ error at a particular parameter in a config_group and config_error_group
+ reports an error at the definition of that group. The error is reported
+ using warn. */
+void config_error_group(struct config_group *, const char *format, ...);
+void config_error_param(struct config_group *, const char *key,
+ const char *format, ...);
+
+/* Free all space allocated by the tree rooted at config_group. One normally
+ never wants to do this. WARNING: This includes the storage allocated for
+ all strings returned by config_param_string and config_param_list for any
+ configuration groups in this tree. */
+void config_free(struct config_group *);
+
+END_DECLS
+
+#endif /* INN_CONFPARSE_H */
diff --git a/include/inn/defines.h b/include/inn/defines.h
new file mode 100644
index 0000000..74f4969
--- /dev/null
+++ b/include/inn/defines.h
@@ -0,0 +1,66 @@
+/* $Id: defines.h 6124 2003-01-14 06:03:29Z rra $
+**
+** Portable defines used by other INN header files.
+**
+** In order to make the libraries built by INN usable by other software,
+** INN needs to install several header files. Installing autoconf-
+** generated header files, however, is a bad idea, since the defines will
+** conflict with other software that uses autoconf.
+**
+** This header contains common definitions, such as internal typedefs and
+** macros, common to INN's header files but not based on autoconf probes.
+** As such, it's limited in what it can do; if compiling software against
+** INN's header files on a system not supporting basic ANSI C features
+** (such as const) or standard types (like size_t), the software may need
+** to duplicate the tests that INN itself performs, generate a config.h,
+** and make sure that config.h is included before any INN header files.
+*/
+
+#ifndef INN_DEFINES_H
+#define INN_DEFINES_H 1
+
+#include <inn/system.h>
+
+/* BEGIN_DECLS is used at the beginning of declarations so that C++
+ compilers don't mangle their names. END_DECLS is used at the end. */
+#undef BEGIN_DECLS
+#undef END_DECLS
+#ifdef __cplusplus
+# define BEGIN_DECLS extern "C" {
+# define END_DECLS }
+#else
+# define BEGIN_DECLS /* empty */
+# define END_DECLS /* empty */
+#endif
+
+/* __attribute__ is available in gcc 2.5 and later, but only with gcc 2.7
+ could you use the __format__ form of the attributes, which is what we use
+ (to avoid confusion with other macros). */
+#ifndef __attribute__
+# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 7)
+# define __attribute__(spec) /* empty */
+# endif
+#endif
+
+/* Used for unused parameters to silence gcc warnings. */
+#define UNUSED __attribute__((__unused__))
+
+/* Make available the bool type. */
+#if INN_HAVE_STDBOOL_H
+# include <stdbool.h>
+#else
+# undef true
+# undef false
+# define true (1)
+# define false (0)
+# ifndef __cplusplus
+# define bool int
+# endif
+#endif /* INN_HAVE_STDBOOL_H */
+
+/* Tell Perl that we have a bool type. */
+#ifndef HAS_BOOL
+# define HAS_BOOL 1
+#endif
+
+#endif /* !INN_DEFINES_H */
diff --git a/include/inn/hashtab.h b/include/inn/hashtab.h
new file mode 100644
index 0000000..8d9f31e
--- /dev/null
+++ b/include/inn/hashtab.h
@@ -0,0 +1,60 @@
+/* $Id: hashtab.h 5944 2002-12-08 02:33:08Z rra $
+**
+** Generic hash table interface.
+**
+** Written by Russ Allbery <rra@stanford.edu>
+** This work is hereby placed in the public domain by its author.
+**
+** A hash table takes a hash function that acts on keys, a function to
+** extract the key from a data item stored in a hash, a function that takes
+** a key and a data item and returns true if the key matches, and a
+** function to be called on any data item being deleted from the hash.
+**
+** hash_create creates a hash and hash_free frees all the space allocated
+** by one. hash_insert, hash_replace, and hash_delete modify it, and
+** hash_lookup extracts values. hash_traverse can be used to walk the
+** hash, and hash_count returns the number of elements currently stored in
+** the hash. hash_searches, hash_collisions, and hash_expansions extract
+** performance and debugging statistics.
+*/
+
+#ifndef INN_HASHTAB_H
+#define INN_HASHTAB_H 1
+
+#include <inn/defines.h>
+
+BEGIN_DECLS
+
+/* The layout of this struct is entirely internal to the implementation. */
+struct hash;
+
+/* Data types for function pointers used by the hash table interface. */
+typedef unsigned long (*hash_func)(const void *);
+typedef const void * (*hash_key_func)(const void *);
+typedef bool (*hash_equal_func)(const void *, const void *);
+typedef void (*hash_delete_func)(void *);
+typedef void (*hash_traverse_func)(void *, void *);
+
+/* Generic hash table interface. */
+struct hash * hash_create(size_t, hash_func, hash_key_func,
+ hash_equal_func, hash_delete_func);
+void hash_free(struct hash *);
+void * hash_lookup(struct hash *, const void *key);
+bool hash_insert(struct hash *, const void *key, void *datum);
+bool hash_replace(struct hash *, const void *key, void *datum);
+bool hash_delete(struct hash *, const void *key);
+void hash_traverse(struct hash *, hash_traverse_func, void *);
+unsigned long hash_count(struct hash *);
+unsigned long hash_searches(struct hash *);
+unsigned long hash_collisions(struct hash *);
+unsigned long hash_expansions(struct hash *);
+
+/* Hash functions available for callers. */
+unsigned long hash_string(const void *);
+
+/* Functions useful for constructing new hashes. */
+unsigned long hash_lookup2(const char *, size_t, unsigned long partial);
+
+END_DECLS
+
+#endif /* INN_HASHTAB_H */
diff --git a/include/inn/history.h b/include/inn/history.h
new file mode 100644
index 0000000..48c6e25
--- /dev/null
+++ b/include/inn/history.h
@@ -0,0 +1,110 @@
+/* $Id: history.h 4916 2001-07-18 12:33:01Z alexk $
+**
+** Interface to history API
+*/
+
+#ifndef INN_HISTORY_H
+#define INN_HISTORY_H
+
+#include <inn/defines.h>
+
+BEGIN_DECLS
+
+/*
+** ensure appropriate scoping; we don't pull inn/storage.h as we
+** don't need; our caller then has the option
+*/
+struct history;
+struct token;
+
+/*
+** structure giving cache statistics returned from HISstats
+*/
+struct histstats {
+ /* number of positive hits */
+ int hitpos;
+ /* number of negative hits */
+ int hitneg;
+ /* number of misses (positive hit, but not in cache) */
+ int misses;
+ /* number of does not exists (negative hit, but not in cache) */
+ int dne;
+};
+
+
+/*
+** flags passed to HISopen
+*/
+
+/* open database read only */
+#define HIS_RDONLY (0)
+
+/* open database read/write */
+#define HIS_RDWR (1<<0)
+
+/* create on open */
+#define HIS_CREAT (1<<1)
+
+/* hint that the data should be kept on disk */
+#define HIS_ONDISK (1<<2)
+
+/* hint that the data should be kept in core */
+#define HIS_INCORE (1<<3)
+
+/* hint that the data should be kept mmap()ed */
+#define HIS_MMAP (1<<4)
+
+/*
+** values passed to HISctl
+*/
+enum {
+ /* (char **) get history path */
+ HISCTLG_PATH,
+
+ /* (char *) set history path */
+ HISCTLS_PATH,
+
+ /* (int) how many history writes may be outstanding */
+ HISCTLS_SYNCCOUNT,
+
+ /* (size_t) number of pairs for which the database should be sized */
+ HISCTLS_NPAIRS,
+
+ /* (bool) Ignore old database during expire */
+ HISCTLS_IGNOREOLD,
+
+ /* (time_t) interval, in s, between stats of the history database
+ * for * detecting a replacement, or 0 to disable (no checks);
+ * defaults {hisv6, taggedhash} */
+ HISCTLS_STATINTERVAL
+
+};
+
+struct history * HISopen(const char *, const char *, int);
+bool HISclose(struct history *);
+bool HISsync(struct history *);
+void HISsetcache(struct history *, size_t);
+bool HISlookup(struct history *, const char *, time_t *,
+ time_t *, time_t *, struct token *);
+bool HIScheck(struct history *, const char *);
+bool HISwrite(struct history *, const char *, time_t,
+ time_t, time_t, const struct token *);
+bool HISremember(struct history *, const char *, time_t);
+bool HISreplace(struct history *, const char *, time_t,
+ time_t, time_t, const struct token *);
+bool HISexpire(struct history *, const char *, const char *,
+ bool, void *, time_t,
+ bool (*)(void *, time_t, time_t, time_t,
+ struct token *));
+bool HISwalk(struct history *, const char *, void *,
+ bool (*)(void *, time_t, time_t, time_t,
+ const struct token *));
+struct histstats HISstats(struct history *);
+const char * HISerror(struct history *);
+bool HISctl(struct history *, int, void *);
+void HISlogclose(void);
+void HISlogto(const char *s);
+
+END_DECLS
+
+#endif
diff --git a/include/inn/innconf.h b/include/inn/innconf.h
new file mode 100644
index 0000000..8cd24d2
--- /dev/null
+++ b/include/inn/innconf.h
@@ -0,0 +1,211 @@
+/* $Id: innconf.h 7751 2008-04-06 14:35:40Z iulius $
+**
+** inn.conf parser interface.
+**
+** The interface to reading inn.conf configuration files and managing the
+** resulting innconf struct.
+*/
+
+#ifndef INN_INNCONF_H
+#define INN_INNCONF_H 1
+
+#include <inn/defines.h>
+#include <stdio.h>
+
+/*
+** This structure is organized in the same order as the variables contained
+** in it are mentioned in the inn.conf documentation, and broken down into
+** the same sections. Note that due to the implementation, only three types
+** of variables are permissible here: char *, bool, and long.
+*/
+struct innconf {
+ /* General Settings */
+ char *domain; /* Default domain of local host */
+ char *innflags; /* Flags to pass to innd on startup */
+ char *mailcmd; /* Command to send report/control type mail */
+ char *mta; /* MTA for mailing to moderators, innmail */
+ char *pathhost; /* Entry for the Path line */
+ char *server; /* Default server to connect to */
+
+ /* Feed Configuration */
+ long artcutoff; /* Max accepted article age */
+ char *bindaddress; /* Which interface IP to bind to */
+ char *bindaddress6; /* Which interface IPv6 to bind to */
+ bool dontrejectfiltered; /* Don't reject filtered article? */
+ long hiscachesize; /* Size of the history cache in kB */
+ bool ignorenewsgroups; /* Propagate cmsgs by affected group? */
+ bool immediatecancel; /* Immediately cancel timecaf messages? */
+ long linecountfuzz; /* Check linecount and reject if off by more */
+ long maxartsize; /* Reject articles bigger than this */
+ long maxconnections; /* Max number of incoming NNTP connections */
+ char *pathalias; /* Prepended Host for the Path line */
+ char *pathcluster; /* Appended Host for the Path line */
+ bool pgpverify; /* Verify control messages with pgpverify? */
+ long port; /* Which port innd should listen on */
+ bool refusecybercancels; /* Reject message IDs with "<cancel."? */
+ bool remembertrash; /* Put unwanted article IDs into history */
+ char *sourceaddress; /* Source IP for outgoing NNTP connections */
+ char *sourceaddress6; /* Source IPv6 for outgoing NNTP connections */
+ bool verifycancels; /* Verify cancels against article author */
+ bool wanttrash; /* Put unwanted articles in junk */
+ long wipcheck; /* How long to defer other copies of article */
+ long wipexpire; /* How long to keep pending article record */
+
+ /* History settings */
+ char *hismethod; /* Which history method to use */
+
+ /* Article Storage */
+ long cnfscheckfudgesize; /* Additional CNFS integrity checking */
+ bool enableoverview; /* Store overview info for articles? */
+ bool groupbaseexpiry; /* Do expiry by newsgroup? */
+ bool mergetogroups; /* Refile articles from to.* into to */
+ bool nfswriter; /* Use NFS writer functionality */
+ long overcachesize; /* fd size cache for tradindexed */
+ char *ovgrouppat; /* Newsgroups to store overview for */
+ char *ovmethod; /* Which overview method to use */
+ bool storeonxref; /* SMstore use Xref to detemine class? */
+ bool useoverchan; /* overchan write the overview, not innd? */
+ bool wireformat; /* Store tradspool artilces in wire format? */
+ bool xrefslave; /* Act as a slave of another server? */
+
+ /* Reading */
+ bool allownewnews; /* Allow use of the NEWNEWS command */
+ bool articlemmap; /* Use mmap to read articles? */
+ long clienttimeout; /* How long nnrpd can be inactive */
+ long initialtimeout; /* How long nnrpd waits for first command */
+ long msgidcachesize; /* Number of entries in the message ID cache */
+ bool nfsreader; /* Use NFS reader functionality */
+ long nfsreaderdelay; /* Delay applied to article arrival */
+ bool nnrpdcheckart; /* Check article existence before returning? */
+ char *nnrpdflags; /* Arguments to pass when spawning nnrpd */
+ long nnrpdloadlimit; /* Maximum getloadvg() we allow */
+ bool noreader; /* Refuse to fork nnrpd for readers? */
+ bool readerswhenstopped; /* Allow nnrpd when server is paused */
+ bool readertrack; /* Use the reader tracking system? */
+ bool tradindexedmmap; /* Whether to mmap for tradindexed */
+
+ /* Reading -- Keyword Support */
+ bool keywords; /* Generate keywords in overview? */
+ long keyartlimit; /* Max article size for keyword generation */
+ long keylimit; /* Max allocated space for keywords */
+ long keymaxwords; /* Max count of interesting works */
+
+ /* Posting */
+ bool addnntppostingdate; /* Add NNTP-Posting-Date: to posts */
+ bool addnntppostinghost; /* Add NNTP-Posting-Host: to posts */
+ bool checkincludedtext; /* Reject if too much included text */
+ char *complaints; /* Address for X-Complaints-To: */
+ char *fromhost; /* Host for the From: line */
+ long localmaxartsize; /* Max article size of local postings */
+ char *moderatormailer; /* Default host to mail moderated articles */
+ bool nnrpdauthsender; /* Add authenticated Sender: header? */
+ char *nnrpdposthost; /* Host postings should be forwarded to */
+ long nnrpdpostport; /* Port postings should be forwarded to */
+ char *organization; /* Data for the Organization: header */
+ bool spoolfirst; /* Spool all posted articles? */
+ bool strippostcc; /* Strip To:, Cc: and Bcc: from posts */
+
+ /* Posting -- Exponential Backoff */
+ bool backoffauth; /* Backoff by user, not IP address */
+ char *backoffdb; /* Directory for backoff databases */
+ long backoffk; /* Multiple for the sleep time */
+ long backoffpostfast; /* Upper time limit for fast posting */
+ long backoffpostslow; /* Lower time limit for slow posting */
+ long backofftrigger; /* Number of postings before triggered */
+
+ /* Monitoring */
+ bool doinnwatch; /* Start innwatch from rc.news? */
+ long innwatchbatchspace; /* Minimum free space in pathoutgoing */
+ long innwatchlibspace; /* Minimum free space in pathdb */
+ long innwatchloload; /* Load times 100 at which to restart */
+ long innwatchhiload; /* Load times 100 at which to throttle */
+ long innwatchpauseload; /* Load times 100 at which to pause */
+ long innwatchsleeptime; /* Seconds to wait between checks */
+ long innwatchspoolnodes; /* Minimum free inodes in patharticles */
+ long innwatchspoolspace; /* Minimum free space in patharticles */
+
+ /* Logging */
+ bool docnfsstat; /* Run cnfsstat in the background? */
+ bool logartsize; /* Log article sizes? */
+ bool logcancelcomm; /* Log ctlinnd cancel commands to syslog? */
+ long logcycles; /* How many old logs scanlogs should keep */
+ bool logipaddr; /* Log by host IP address? */
+ bool logsitename; /* Log outgoing site names? */
+ bool nnrpdoverstats; /* Log overview statistics? */
+ long nntpactsync; /* Checkpoint log after this many articles */
+ bool nntplinklog; /* Put storage token into the log? */
+ long status; /* Status file update interval */
+ long timer; /* Performance monitoring interval */
+ char *stathist; /* Filename for history profiler outputs */
+
+ /* System Tuning */
+ long badiocount; /* Failure count before dropping channel */
+ long blockbackoff; /* Multiplier for sleep in EAGAIN writes */
+ long chaninacttime; /* Wait before noticing inactive channels */
+ long chanretrytime; /* How long before channel restarts */
+ long icdsynccount; /* Articles between active & history updates */
+ long keepmmappedthreshold; /* Threshold for keeping mmap in buffindexed */
+ long maxforks; /* Give up after this many fork failure */
+ long nicekids; /* Child processes get niced to this */
+ long nicenewnews; /* If NEWNEWS command is used, nice to this */
+ long nicennrpd; /* nnrpd is niced to this */
+ long pauseretrytime; /* Seconds before seeing if pause is ended */
+ long peertimeout; /* How long peers can be inactive */
+ long rlimitnofile; /* File descriptor limit to set */
+ long maxcmdreadsize; /* max NNTP command read size used by innd */
+ long datamovethreshold; /* threshold no to extend buffer for ever */
+
+ /* Paths */
+ char *patharchive; /* Archived news. */
+ char *patharticles; /* Articles. */
+ char *pathbin; /* News binaries. */
+ char *pathcontrol; /* Path to control message handlers */
+ char *pathdb; /* News database files */
+ char *pathetc; /* News configuration files */
+ char *pathfilter; /* Filtering code */
+ char *pathhttp; /* HTML files */
+ char *pathincoming; /* Incoming spooled news */
+ char *pathlog; /* Log files */
+ char *pathnews; /* Home directory for news user */
+ char *pathoutgoing; /* Outgoing news batch files */
+ char *pathoverview; /* Overview infomation */
+ char *pathrun; /* Runtime state and sockets */
+ char *pathspool; /* Root of news spool hierarchy */
+ char *pathtmp; /* Temporary files for the news system */
+};
+
+/* The global innconf variable used in programs. */
+extern struct innconf *innconf;
+
+/* Used to request various types of quoting when printing out values. */
+enum innconf_quoting {
+ INNCONF_QUOTE_NONE,
+ INNCONF_QUOTE_SHELL,
+ INNCONF_QUOTE_PERL,
+ INNCONF_QUOTE_TCL
+};
+
+BEGIN_DECLS
+
+/* Parse the given file into innconf, using the default path if NULL. */
+bool innconf_read(const char *path);
+
+/* Free an innconf struct and all allocated memory for it. */
+void innconf_free(struct innconf *);
+
+/* Print a single value with appropriate quoting, return whether found. */
+bool innconf_print_value(FILE *, const char *key, enum innconf_quoting);
+
+/* Dump the entire configuration with appropriate quoting. */
+void innconf_dump(FILE *, enum innconf_quoting);
+
+/* Compare two instances of an innconf struct, for testing. */
+bool innconf_compare(struct innconf *, struct innconf *);
+
+/* Check the validity of an inn.conf file. Does innconf_read plus checking
+ for any unknown parameters that are set. */
+bool innconf_check(const char *path);
+
+END_DECLS
+
+#endif /* INN_INNCONF_H */
diff --git a/include/inn/list.h b/include/inn/list.h
new file mode 100644
index 0000000..99004e4
--- /dev/null
+++ b/include/inn/list.h
@@ -0,0 +1,51 @@
+/* $Id: list.h 6168 2003-01-21 06:27:32Z alexk $
+**
+*/
+
+#ifndef INN_LIST_H
+#define INN_LIST_H 1
+
+#include <inn/defines.h>
+
+struct node {
+ struct node *succ;
+ struct node *pred;
+};
+
+struct list {
+ struct node *head;
+ struct node *tail;
+ struct node *tailpred;
+};
+
+BEGIN_DECLS
+
+/* initialise a new list */
+void list_new(struct list *list);
+
+/* add a node to the head of the list */
+struct node *list_addhead(struct list *list, struct node *node);
+
+/* add a node to the tail of the list */
+struct node *list_addtail(struct list *list, struct node *node);
+
+/* return a pointer to the first node on the list */
+struct node *list_head(struct list *list);
+
+/* return a pointer to the last node on the list */
+struct node *list_tail(struct list *list);
+
+struct node *list_succ(struct node *node);
+struct node *list_pred(struct node *node);
+
+struct node *list_remhead(struct list *list);
+struct node *list_remove(struct node *node);
+struct node *list_remtail(struct list *list);
+struct node *list_insert(struct list *list, struct node *node,
+ struct node *pred);
+
+bool list_isempty(struct list *list);
+
+END_DECLS
+
+#endif /* INN_LIST_H */
diff --git a/include/inn/md5.h b/include/inn/md5.h
new file mode 100644
index 0000000..f0b1584
--- /dev/null
+++ b/include/inn/md5.h
@@ -0,0 +1,79 @@
+/* $Id: md5.h 4567 2001-02-24 08:10:16Z rra $
+**
+** RSA Data Security, Inc. MD5 Message-Digest Algorithm
+**
+** LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+** INCLUDING ALL IMPLIED WARRANTIES OF MER- CHANTABILITY AND FITNESS. IN
+** NO EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
+** CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
+** USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
+** OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+** PERFORMANCE OF THIS SOFTWARE.
+**
+** Copyright (C) 1990, RSA Data Security, Inc. All rights reserved.
+**
+** License to copy and use this software is granted provided that it is
+** identified as the "RSA Data Security, Inc. MD5 Message-Digest
+** Algorithm" in all material mentioning or referencing this software or
+** this function.
+**
+** License is also granted to make and use derivative works provided that
+** such works are identified as "derived from the RSA Data Security,
+** Inc. MD5 Message-Digest Algorithm" in all material mentioning or
+** referencing the derived work.
+**
+** RSA Data Security, Inc. makes no representations concerning either the
+** merchantability of this software or the suitability of this software for
+** any particular purpose. It is provided "as is" without express or
+** implied warranty of any kind.
+**
+** These notices must be retained in any copies of any part of this
+** documentation and/or software.
+*/
+
+#ifndef INN_MD5_H
+#define INN_MD5_H 1
+
+#include <inn/defines.h>
+
+/* Make sure we have uint32_t. */
+#include <sys/types.h>
+#if INN_HAVE_INTTYPES_H
+# include <inttypes.h>
+#endif
+
+/* SCO OpenServer gets int32_t from here. */
+#if INN_HAVE_SYS_BITYPES_H
+# include <sys/bitypes.h>
+#endif
+
+/* Bytes to process at once, defined by the algorithm. */
+#define MD5_CHUNKSIZE (1 << 6)
+#define MD5_CHUNKWORDS (MD5_CHUNKSIZE / sizeof(uint32_t))
+
+/* Length of the digest, defined by the algorithm. */
+#define MD5_DIGESTSIZE 16
+#define MD5_DIGESTWORDS (MD5_DIGESTSIZE / sizeof(uint32_t))
+
+BEGIN_DECLS
+
+/* Data structure for MD5 message-digest computation. */
+struct md5_context {
+ uint32_t count[2]; /* A 64-bit byte count. */
+ uint32_t buf[MD5_DIGESTWORDS]; /* Scratch buffer. */
+ union {
+ unsigned char byte[MD5_CHUNKSIZE]; /* Byte chunk buffer. */
+ uint32_t word[MD5_CHUNKWORDS]; /* Word chunk buffer. */
+ } in;
+ unsigned int datalen; /* Length of data in in. */
+ unsigned char digest[MD5_DIGESTSIZE]; /* Final digest. */
+};
+
+extern void md5_hash(const unsigned char *, size_t, unsigned char *);
+extern void md5_init(struct md5_context *);
+extern void md5_update(struct md5_context *, const unsigned char *, size_t);
+extern void md5_final(struct md5_context *);
+
+END_DECLS
+
+#endif /* !INN_MD5_H */
diff --git a/include/inn/messages.h b/include/inn/messages.h
new file mode 100644
index 0000000..22297fa
--- /dev/null
+++ b/include/inn/messages.h
@@ -0,0 +1,99 @@
+/* $Id: messages.h 5496 2002-06-07 13:59:06Z alexk $
+**
+** Logging, debugging, and error reporting functions.
+**
+** This collection of functions facilitate logging, debugging, and error
+** reporting in a flexible manner that can be used by libraries as well as by
+** programs. The functions are based around the idea of handlers, which take
+** a message and do something appropriate with it. The program can set the
+** appropriate handlers for all the message reporting functions, and then
+** library code can use them with impunity and know the right thing will
+** happen with the messages.
+*/
+
+#ifndef INN_MESSAGES_H
+#define INN_MESSAGES_H 1
+
+#include <inn/defines.h>
+#include <stdarg.h>
+
+BEGIN_DECLS
+
+/* These are the currently-supported types of traces. */
+enum message_trace {
+ TRACE_NETWORK, /* Network traffic. */
+ TRACE_PROGRAM, /* Stages of program execution. */
+ TRACE_ALL /* All traces; this must be last. */
+};
+
+/* The reporting functions. The ones prefaced by "sys" add a colon, a space,
+ and the results of strerror(errno) to the output and are intended for
+ reporting failures of system calls. */
+extern void trace(enum message_trace, const char *, ...)
+ __attribute__((__format__(printf, 2, 3)));
+extern void notice(const char *, ...)
+ __attribute__((__format__(printf, 1, 2)));
+extern void sysnotice(const char *, ...)
+ __attribute__((__format__(printf, 1, 2)));
+extern void warn(const char *, ...)
+ __attribute__((__format__(printf, 1, 2)));
+extern void syswarn(const char *, ...)
+ __attribute__((__format__(printf, 1, 2)));
+extern void die(const char *, ...)
+ __attribute__((__noreturn__, __format__(printf, 1, 2)));
+extern void sysdie(const char *, ...)
+ __attribute__((__noreturn__, __format__(printf, 1, 2)));
+
+/* Debug is handled specially, since we want to make the code disappear
+ completely unless we're built with -DDEBUG. We can only do that with
+ support for variadic macros, though; otherwise, the function just won't do
+ anything. */
+#if !defined(DEBUG) && (INN_HAVE_C99_VAMACROS || INN_HAVE_GNU_VAMACROS)
+# if INN_HAVE_C99_VAMACROS
+# define debug(format, ...) /* empty */
+# elif INN_HAVE_GNU_VAMACROS
+# define debug(format, args...) /* empty */
+# endif
+#else
+extern void debug(const char *, ...)
+ __attribute__((__format__(printf, 1, 2)));
+#endif
+
+/* Set the handlers for various message functions. All of these functions
+ take a count of the number of handlers and then function pointers for each
+ of those handlers. These functions are not thread-safe; they set global
+ variables. */
+extern void message_handlers_debug(int count, ...);
+extern void message_handlers_trace(int count, ...);
+extern void message_handlers_notice(int count, ...);
+extern void message_handlers_warn(int count, ...);
+extern void message_handlers_die(int count, ...);
+
+/* Enable or disable tracing for particular classes of messages. */
+extern void message_trace_enable(enum message_trace, bool);
+
+/* Some useful handlers, intended to be passed to message_handlers_*. All
+ handlers take the length of the formatted message, the format, a variadic
+ argument list, and the errno setting if any. */
+extern void message_log_stdout(int, const char *, va_list, int);
+extern void message_log_stderr(int, const char *, va_list, int);
+extern void message_log_syslog_debug(int, const char *, va_list, int);
+extern void message_log_syslog_info(int, const char *, va_list, int);
+extern void message_log_syslog_notice(int, const char *, va_list, int);
+extern void message_log_syslog_warning(int, const char *, va_list, int);
+extern void message_log_syslog_err(int, const char *, va_list, int);
+extern void message_log_syslog_crit(int, const char *, va_list, int);
+
+/* The type of a message handler. */
+typedef void (*message_handler_func)(int, const char *, va_list, int);
+
+/* If non-NULL, called before exit and its return value passed to exit. */
+extern int (*message_fatal_cleanup)(void);
+
+/* If non-NULL, prepended (followed by ": ") to all messages printed by either
+ message_log_stdout or message_log_stderr. */
+extern const char *message_program_name;
+
+END_DECLS
+
+#endif /* INN_MESSAGE_H */
diff --git a/include/inn/mmap.h b/include/inn/mmap.h
new file mode 100644
index 0000000..3769d51
--- /dev/null
+++ b/include/inn/mmap.h
@@ -0,0 +1,33 @@
+/* $Id: mmap.h 7598 2007-02-09 02:40:51Z eagle $
+**
+** MMap manipulation routines
+**
+** Written by Alex Kiernan (alex.kiernan@thus.net)
+**
+** These routines work with mmap()ed memory
+*/
+
+#ifndef INN_MMAP_H
+#define INN_MMAP_H 1
+
+#include <inn/defines.h>
+
+BEGIN_DECLS
+
+/* Figure out what page an address is in and flush those pages. This is the
+ internal function, which we wrap with a define below. */
+void inn__mapcntl(void *, size_t, int);
+
+/* Some platforms only support two arguments to msync. On those platforms,
+ make the third argument to mapcntl always be zero, getting rid of whatever
+ the caller tried to pass. This avoids undefined symbols for MS_ASYNC and
+ friends on platforms with two-argument msync functions. */
+#ifdef INN_HAVE_MSYNC_3_ARG
+# define inn_mapcntl inn__mapcntl
+#else
+# define inn_mapcntl(p, l, f) inn__mapcntl((p), (l), 0)
+#endif
+
+END_DECLS
+
+#endif /* INN_MMAP_H */
diff --git a/include/inn/qio.h b/include/inn/qio.h
new file mode 100644
index 0000000..132da6f
--- /dev/null
+++ b/include/inn/qio.h
@@ -0,0 +1,49 @@
+/* $Id: qio.h 3653 2000-07-29 02:57:50Z rra $
+**
+** Quick I/O package.
+**
+** The interface to the Quick I/O package, optimized for reading through
+** files line by line. This package uses internal buffering like stdio,
+** but is even more aggressive about its buffering.
+*/
+
+#ifndef INN_QIO_H
+#define INN_QIO_H 1
+
+#include <inn/defines.h>
+
+BEGIN_DECLS
+
+/*
+** State for a quick open file, equivalent to FILE for stdio. All callers
+** should treat this structure as opaque and instead use the functions and
+** macros defined below.
+*/
+enum QIOflag { QIO_ok, QIO_error, QIO_long };
+
+typedef struct {
+ int _fd;
+ size_t _length; /* Length of the current string. */
+ size_t _size; /* Size of the internal buffer. */
+ char * _buffer;
+ char * _start; /* Start of the unread data. */
+ char * _end; /* End of the available data. */
+ off_t _count; /* Number of bytes read so far. */
+ enum QIOflag _flag;
+} QIOSTATE;
+
+#define QIOerror(qp) ((qp)->_flag != QIO_ok)
+#define QIOtoolong(qp) ((qp)->_flag == QIO_long)
+#define QIOfileno(qp) ((qp)->_fd)
+#define QIOlength(qp) ((qp)->_length)
+#define QIOtell(qp) ((qp)->_count - ((qp)->_end - (qp)->_start))
+
+extern QIOSTATE * QIOopen(const char *name);
+extern QIOSTATE * QIOfdopen(int fd);
+extern char * QIOread(QIOSTATE *qp);
+extern void QIOclose(QIOSTATE *qp);
+extern int QIOrewind(QIOSTATE *qp);
+
+END_DECLS
+
+#endif /* !INN_QIO_H */
diff --git a/include/inn/sequence.h b/include/inn/sequence.h
new file mode 100644
index 0000000..d7bfa33
--- /dev/null
+++ b/include/inn/sequence.h
@@ -0,0 +1,21 @@
+/* $Id: sequence.h 4871 2001-07-09 08:09:58Z alexk $
+**
+** Sequence space arithmetic routines.
+**
+** This is a set of routines for implementing so called sequence
+** space arithmetic (typically used for DNS serial numbers). The
+** implementation here is taken from RFC 1982.
+*/
+
+#ifndef INN_SEQUENCE_H
+#define INN_SEQUENCE_H 1
+
+#include <inn/defines.h>
+
+BEGIN_DECLS
+
+int seq_lcompare(unsigned long, unsigned long);
+
+END_DECLS
+
+#endif /* INN_SEQUENCE_H */
diff --git a/include/inn/timer.h b/include/inn/timer.h
new file mode 100644
index 0000000..0cc611f
--- /dev/null
+++ b/include/inn/timer.h
@@ -0,0 +1,38 @@
+/* $Id: timer.h 6129 2003-01-19 00:39:49Z rra $
+**
+** Timer library interface.
+**
+** An interface to a simple profiling library. An application can declare
+** its intent to use n timers by calling TMRinit(n), and then start and
+** stop numbered timers with TMRstart and TMRstop. TMRsummary logs the
+** results to syslog given labels for each numbered timer.
+*/
+
+#ifndef INN_TIMER_H
+#define INN_TIMER_H
+
+#include <inn/defines.h>
+
+BEGIN_DECLS
+
+enum {
+ TMR_HISHAVE, /* Looking up ID in history (yes/no). */
+ TMR_HISGREP, /* Looking up ID in history (data). */
+ TMR_HISWRITE, /* Writing to history. */
+ TMR_HISSYNC, /* Syncing history to disk. */
+ TMR_APPLICATION /* Application numbering starts here. */
+};
+
+void TMRinit(unsigned int);
+void TMRstart(unsigned int);
+void TMRstop(unsigned int);
+void TMRsummary(const char *prefix, const char *const *labels);
+unsigned long TMRnow(void);
+void TMRfree(void);
+
+/* Return the current time as a double of seconds and fractional sections. */
+double TMRnow_double(void);
+
+END_DECLS
+
+#endif /* INN_TIMER_H */
diff --git a/include/inn/tst.h b/include/inn/tst.h
new file mode 100644
index 0000000..44bfff6
--- /dev/null
+++ b/include/inn/tst.h
@@ -0,0 +1,88 @@
+/* $Id: tst.h 6083 2002-12-27 07:24:36Z rra $
+**
+** Ternary search trie implementation.
+**
+** This implementation is based on the implementation by Peter A. Friend
+** (version 1.3), but has been assimilated into INN and modified to use INN
+** formatting conventions.
+**
+** Copyright (c) 2002, Peter A. Friend
+** All rights reserved.
+**
+** Redistribution and use in source and binary forms, with or without
+** modification, are permitted provided that the following conditions are
+** met:
+**
+** Redistributions of source code must retain the above copyright notice,
+** this list of conditions and the following disclaimer.
+**
+** Redistributions in binary form must reproduce the above copyright notice,
+** this list of conditions and the following disclaimer in the documentation
+** and/or other materials provided with the distribution.
+**
+** Neither the name of Peter A. Friend nor the names of its contributors may
+** be used to endorse or promote products derived from this software without
+** specific prior written permission.
+**
+** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+** IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+** THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+** PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+** CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+** EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#ifndef INN_TST_H
+#define INN_TST_H 1
+
+#include <inn/defines.h>
+
+BEGIN_DECLS
+
+/* Constants used for return values and options. */
+enum tst_constants {
+ TST_OK,
+ TST_NULL_KEY,
+ TST_NULL_DATA,
+ TST_DUPLICATE_KEY,
+ TST_REPLACE
+};
+
+/* Opaque data type returned by and used by ternary search trie functions. */
+struct tst;
+
+/* Allocate a new ternary search trie. width is the number of nodes allocated
+ at a time and should be chosen carefully. One node is required for every
+ character in the tree. If you choose a value that is too small, your
+ application will spend too much time calling malloc and your node space
+ will be too spread out. Too large a value is just a waste of space. */
+struct tst *tst_init(int width);
+
+/* Insert a value into the tree. If the key already exists in the tree,
+ option determiens the behavior. If set to TST_REPLACE, the data for that
+ key is replaced with the new data value and the old value is returned in
+ exist_ptr. Otherwise, TST_DUPLICATE_KEY is returned. If key is zero
+ length, TST_NULL_KEY is returned. If data is NULL, TST_NULL_DATA is
+ returned. On success, TST_OK is returned.
+
+ The data argument may not be NULL. For a simple existence tree, use the
+ struct tst pointer as the data. */
+int tst_insert(struct tst *, const unsigned char *key, void *data, int option,
+ void **exist_ptr);
+
+/* Search for a key and return the associated data, or NULL if not found. */
+void *tst_search(struct tst *, const unsigned char *key);
+
+/* Delete the given key out of the trie, returning the data that it pointed
+ to. If the key was not found, returns NULL. */
+void *tst_delete(struct tst *, const unsigned char *key);
+
+/* Free the given ternary search trie and all resources it uses. */
+void tst_cleanup(struct tst *);
+
+#endif /* !INN_TST_H */
diff --git a/include/inn/vector.h b/include/inn/vector.h
new file mode 100644
index 0000000..ed63e32
--- /dev/null
+++ b/include/inn/vector.h
@@ -0,0 +1,87 @@
+/* $Id: vector.h 5450 2002-04-23 06:06:10Z rra $
+**
+** Vector handling (counted lists of char *'s).
+**
+** Written by Russ Allbery <rra@stanford.edu>
+** This work is hereby placed in the public domain by its author.
+**
+** A vector is a simple array of char *'s combined with a count. It's a
+** convenient way of managing a list of strings, as well as a reasonable
+** output data structure for functions that split up a string. There are
+** two basic types of vectors, regular vectors (in which case strings are
+** copied when put into a vector and freed when the vector is freed) and
+** cvectors or const vectors (where each pointer is a const char * to some
+** external string that isn't freed when the vector is freed).
+**
+** There are two interfaces here, one for vectors and one for cvectors,
+** with the basic operations being the same between the two.
+*/
+
+#ifndef INN_VECTOR_H
+#define INN_VECTOR_H 1
+
+#include <inn/defines.h>
+
+struct vector {
+ size_t count;
+ size_t allocated;
+ char **strings;
+};
+
+struct cvector {
+ size_t count;
+ size_t allocated;
+ const char **strings;
+};
+
+BEGIN_DECLS
+
+/* Create a new, empty vector. */
+struct vector *vector_new(void);
+struct cvector *cvector_new(void);
+
+/* Add a string to a vector. Resizes the vector if necessary. */
+void vector_add(struct vector *, const char *string);
+void cvector_add(struct cvector *, const char *string);
+
+/* Resize the array of strings to hold size entries. Saves reallocation work
+ in vector_add if it's known in advance how many entries there will be. */
+void vector_resize(struct vector *, size_t size);
+void cvector_resize(struct cvector *, size_t size);
+
+/* Reset the number of elements to zero, freeing all of the strings for a
+ regular vector, but not freeing the strings array (to cut down on memory
+ allocations if the vector will be reused). */
+void vector_clear(struct vector *);
+void cvector_clear(struct cvector *);
+
+/* Free the vector and all resources allocated for it. */
+void vector_free(struct vector *);
+void cvector_free(struct cvector *);
+
+/* Split functions build a vector from a string. vector_split splits on a
+ specified character, while vector_split_space splits on any sequence of
+ spaces or tabs (not any sequence of whitespace, as just spaces or tabs is
+ more useful for INN). The cvector versions destructively modify the
+ provided string in-place to insert nul characters between the strings. If
+ the vector argument is NULL, a new vector is allocated; otherwise, the
+ provided one is reused.
+
+ Empty strings will yield zero-length vectors. Adjacent delimiters are
+ treated as a single delimiter by *_split_space, but *not* by *_split, so
+ callers of *_split should be prepared for zero-length strings in the
+ vector. */
+struct vector *vector_split(const char *string, char sep, struct vector *);
+struct vector *vector_split_space(const char *string, struct vector *);
+struct cvector *cvector_split(char *string, char sep, struct cvector *);
+struct cvector *cvector_split_space(char *string, struct cvector *);
+
+/* Build a string from a vector by joining its components together with the
+ specified string as separator. Returns a newly allocated string; caller is
+ responsible for freeing. */
+char *vector_join(const struct vector *, const char *seperator);
+char *cvector_join(const struct cvector *, const char *separator);
+
+END_DECLS
+
+#endif /* INN_VECTOR_H */
diff --git a/include/inn/wire.h b/include/inn/wire.h
new file mode 100644
index 0000000..bafae0b
--- /dev/null
+++ b/include/inn/wire.h
@@ -0,0 +1,46 @@
+/* $Id: wire.h 6028 2002-12-24 05:10:39Z rra $
+**
+** Wire format article utilities.
+**
+** Originally written by Alex Kiernan (alex.kiernan@thus.net)
+**
+** These routines manipulate wire format articles; in particular, they should
+** be safe in the presence of embedded NULs and UTF-8 characters.
+*/
+
+#ifndef INN_WIRE_H
+#define INN_WIRE_H 1
+
+#include <inn/defines.h>
+
+BEGIN_DECLS
+
+/* Given a pointer to the start of an article, locate the first octet
+ of the body (which may be the octet beyond the end of the buffer if
+ your article is bodyless). */
+char *wire_findbody(const char *, size_t);
+
+/* Given a pointer into an article and a pointer to the end of the article,
+ find the start of the next line or return NULL if there are no more lines
+ remaining in the article. */
+char *wire_nextline(const char *, const char *end);
+
+/* Given a pointer to the start of an article and the name of a header, find
+ the beginning of the value of the given header (the returned pointer will
+ be after the name of the header and any initial whitespace). Headers whose
+ only content is whitespace are ignored. If the header isn't found, returns
+ NULL.
+
+ WARNING: This function does not comply with RFC 2822's idea of header
+ content, particularly in its skipping of initial whitespace. */
+char *wire_findheader(const char *article, size_t, const char *header);
+
+/* Given a pointer inside a header's value and a pointer to the end of the
+ article, returns a pointer to the end of the header value (the \n at the
+ end of the terminating \r\n with folding taken into account), or NULL if no
+ such terminator was found before the end of the article. */
+char *wire_endheader(const char *header, const char *end);
+
+END_DECLS
+
+#endif /* INN_WIRE_H */
diff --git a/scriptor_standalone.pl b/scriptor_standalone.pl
new file mode 100755
index 0000000..b3dad8c
--- /dev/null
+++ b/scriptor_standalone.pl
@@ -0,0 +1,171 @@
+#!/usr/bin/env perl
+
+# scriptor.pl: text interface to send APDU commands to a smart card
+# Copyright (C) 2001 Lionel Victor
+# 2002-2008 Ludovic Rousseau
+#
+# 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: scriptor,v 1.22 2008-05-11 13:28:44 rousseau Exp $
+
+use Getopt::Std;
+use Chipcard::PCSC;
+use Chipcard::PCSC::Card;
+
+use strict;
+use warnings;
+
+my %options;
+
+my $hContext = new Chipcard::PCSC();
+my $hCard;
+my @out_buffer;
+my $in_buffer;
+my $echo;
+
+die ("Could not create Chipcard::PCSC object: $Chipcard::PCSC::errno\n") unless defined $hContext;
+
+getopt ("r:p:" , \%options);
+
+if ($options{h}) {
+ print "Usage: $0 [-h] [-r reader] [-p protocol] [file]\n";
+ print " -h: this help\n";
+ print " -r reader: specify to use the PCSC smart card reader named reader\n";
+ print " By defaults the first one found is used so you\n";
+ print " don't have to specify anything if you just have\n";
+ print " one reader\n";
+ print " -p protocol: protocol to use among T=0 and T=1.\n";
+ print " Default is to let pcsc-lite choose the protocol\n";
+ print " file: file containing APDUs\n";
+ exit (0);
+}
+
+# protocol option
+if ($options{p}) {
+ if ($options{p} =~ m/T=0/) {
+ print STDERR "Trying T=0 protocol\n";
+ $options{p} = $Chipcard::PCSC::SCARD_PROTOCOL_T0;
+ } else {
+ if ($options{p} =~ m/T=1/) {
+ print STDERR "Trying T=1 protocol\n";
+ $options{p} = $Chipcard::PCSC::SCARD_PROTOCOL_T1;
+ } else {
+ die "unknown protocol: $options{p}\n";
+ }
+ }
+} else {
+ $options{p} = $Chipcard::PCSC::SCARD_PROTOCOL_T0 | $Chipcard::PCSC::SCARD_PROTOCOL_T1;
+}
+
+# reader option
+if ($options{r}) {
+ print STDERR "Using given card reader: $options{r}\n";
+} else {
+ my @readers_list = $hContext->ListReaders ();
+ die ("Can't get readers list\n") unless defined $readers_list[0];
+ print STDERR "No reader given: using $readers_list[0]\n";
+ $options{r} = $readers_list[0];
+}
+
+$hCard = new Chipcard::PCSC::Card ($hContext, $options{r}, $Chipcard::PCSC::SCARD_SHARE_SHARED, $options{p});
+die ("Can't allocate Chipcard::PCSC::Card object: $Chipcard::PCSC::errno\n") unless defined $hCard;
+
+if ($hCard->{dwProtocol} == $Chipcard::PCSC::SCARD_PROTOCOL_T0) {
+ print "Using T=0 protocol\n";
+} else {
+ if ($hCard->{dwProtocol} == $Chipcard::PCSC::SCARD_PROTOCOL_T1) {
+ print "Using T=1 protocol\n";
+ }
+ else {
+ print "Using an unknown protocol (not T=0 or T=1)\n";
+ }
+}
+
+# file option
+if ($ARGV[0]) {
+ open (IN_FILEHANDLE, "<$ARGV[0]") or die ("Can't open $ARGV[0]: $!\n");
+ print STDERR "Using given file: $ARGV[0]\n";
+ $echo=1;
+} else {
+ *IN_FILEHANDLE = *STDIN;
+ print STDERR "Reading commands from STDIN\n";
+ $echo=0;
+}
+
+*OUT_FILEHANDLE = *STDOUT;
+
+my $cmd;
+my $match = ".. " x 24;
+while (<IN_FILEHANDLE>) {
+ my $tmp_value;
+ my ($SendData, $RecvData, $sw);
+
+ print if ($echo);
+ last if /exit/i;
+ next if /^\s*$/;
+ next if /^#/;
+
+ if (/reset/i) {
+ print OUT_FILEHANDLE "> RESET\n";
+ if (defined $hCard->Reconnect ($Chipcard::PCSC::SCARD_SHARE_SHARED,
+ $options{p},
+ $Chipcard::PCSC::SCARD_RESET_CARD)) {
+ my @s = $hCard->Status();
+ print OUT_FILEHANDLE "< OK: ";
+ print map { sprintf ("%02X ", $_) } @{$s[3]};
+ print OUT_FILEHANDLE "\n";
+ } else {
+ print OUT_FILEHANDLE "< KO: $Chipcard::PCSC::errno\n";
+ }
+ next;
+ }
+ chomp;
+
+ # if the command does not contains spaces (00A4030000) we expand it
+ s/(..)/$1 /g if (! m/ /);
+
+ # continue if line ends in \
+ if (m/\\$/)
+ {
+ chop; # remove the \
+ s/ *$/ /; # replace any spaces by ONE space
+ $cmd .= $_;
+ next; # read next line
+ }
+
+ $cmd .= $_;
+
+ # convert in an array (internal format)
+ $SendData = Chipcard::PCSC::ascii_to_array($cmd);
+
+ print OUT_FILEHANDLE "> $cmd\n";
+ $RecvData = $hCard->Transmit($SendData);
+ die ("Can't get info: $Chipcard::PCSC::errno\n") unless defined $RecvData;
+ my $res = Chipcard::PCSC::array_to_ascii($RecvData);
+ $sw = Chipcard::PCSC::Card::ISO7816Error(substr($res, -5));
+ $res =~ s/($match)/$1\n/g;
+ print OUT_FILEHANDLE "< $res : $sw\n";
+
+ # empty the command
+ $cmd = "";
+}
+
+close (IN_FILEHANDLE);
+$hCard->Disconnect($Chipcard::PCSC::SCARD_LEAVE_CARD);
+$hCard = undef;
+$hContext = undef;
+
+# End of File
+
diff --git a/src/Makefile b/src/Makefile
new file mode 100644
index 0000000..e71a413
--- /dev/null
+++ b/src/Makefile
@@ -0,0 +1,16 @@
+all: ckpasswd.o xmalloc.o messages.o ckpasswd
+
+ckpasswd.o: ckpasswd.c
+ gcc ckpasswd.c -c
+
+xmalloc.o: xmalloc.c
+ gcc xmalloc.c -c
+
+messages.o: messages.c
+ gcc messages.c -c
+
+ckpasswd: ckpasswd.o
+ gcc ckpasswd.o xmalloc.o messages.o -o ckpasswd -lpam -lcrypt
+
+clean:
+ rm -f ckpasswd.o xmalloc.o messages.o ckpasswd
diff --git a/src/ckpasswd.c b/src/ckpasswd.c
new file mode 100644
index 0000000..04b4b64
--- /dev/null
+++ b/src/ckpasswd.c
@@ -0,0 +1,366 @@
+/* $Id: ckpasswd.c 7565 2006-08-28 02:42:54Z eagle $
+**
+** The default username/password authenticator.
+**
+** This program is intended to be run by nnrpd and handle usernames and
+** passwords. It can authenticate against a regular flat file (the type
+** managed by htpasswd), a DBM file, the system password file or shadow file,
+** or PAM.
+*/
+
+/* Used for unused parameters to silence gcc warnings. */
+#define UNUSED __attribute__((__unused__))
+
+/* Make available the bool type. */
+#if INN_HAVE_STDBOOL_H
+# include <stdbool.h>
+#else
+# undef true
+# undef false
+# define true (1)
+# define false (0)
+# ifndef __cplusplus
+# define bool int
+# endif
+#endif /* INN_HAVE_STDBOOL_H */
+
+#include <stdlib.h>
+#include <string.h>
+#include <crypt.h>
+#include <fcntl.h>
+#include <pwd.h>
+#include <grp.h>
+
+#define DB_DBM_HSEARCH 1
+#include <db.h>
+#define OPT_DBM "d:"
+
+#if HAVE_GETSPNAM
+# include <shadow.h>
+# define OPT_SHADOW "s"
+#else
+# define OPT_SHADOW ""
+#endif
+
+/* The functions are actually macros so that we can pick up the file and line
+ number information for debugging error messages without the user having to
+ pass those in every time. */
+#define xcalloc(n, size) x_calloc((n), (size), __FILE__, __LINE__)
+#define xmalloc(size) x_malloc((size), __FILE__, __LINE__)
+#define xrealloc(p, size) x_realloc((p), (size), __FILE__, __LINE__)
+#define xstrdup(p) x_strdup((p), __FILE__, __LINE__)
+#define xstrndup(p, size) x_strndup((p), (size), __FILE__, __LINE__)
+
+#include <security/pam_appl.h>
+
+/* Holds the authentication information from nnrpd. */
+struct auth_info {
+ char *username;
+ char *password;
+};
+
+/*
+** The PAM conversation function.
+**
+** Since we already have all the information and can't ask the user
+** questions, we can't quite follow the real PAM protocol. Instead, we just
+** return the password in response to every question that PAM asks. There
+** appears to be no generic way to determine whether the message in question
+** is indeed asking for the password....
+**
+** This function allocates an array of struct pam_response to return to the
+** PAM libraries that's never freed. For this program, this isn't much of an
+** issue, since it will likely only be called once and then the program will
+** exit. This function uses malloc and strdup instead of xmalloc and xstrdup
+** intentionally so that the PAM conversation will be closed cleanly if we
+** run out of memory rather than simply terminated.
+**
+** appdata_ptr contains the password we were given.
+*/
+static int pass_conv(int num_msg, const struct pam_message **msgm UNUSED, struct pam_response **response, void *appdata_ptr)
+{
+ int i;
+
+ *response = malloc(num_msg * sizeof(struct pam_response));
+ if (*response == NULL)
+ return PAM_CONV_ERR;
+ for (i = 0; i < num_msg; i++) {
+ (*response)[i].resp = strdup((char *)appdata_ptr);
+ (*response)[i].resp_retcode = 0;
+ }
+ return PAM_SUCCESS;
+}
+
+
+/*
+** Authenticate a user via PAM.
+**
+** Attempts to authenticate a user with PAM, returning true if the user
+** successfully authenticates and false otherwise. Note that this function
+** doesn't attempt to handle any remapping of the authenticated user by the
+** PAM stack, but just assumes that the authenticated user was the same as
+** the username given.
+**
+** Right now, all failures are handled via die. This may be worth revisiting
+** in case we want to try other authentication methods if this fails for a
+** reason other than the system not having PAM support.
+*/
+
+static bool auth_pam(const char *username, char *password)
+{
+ pam_handle_t *pamh;
+ struct pam_conv conv;
+ int status;
+
+ conv.conv = pass_conv;
+ conv.appdata_ptr = password;
+ status = pam_start("nnrpd", username, &conv, &pamh);
+ if (status != PAM_SUCCESS)
+ die("pam_start failed: %s", pam_strerror(pamh, status));
+ status = pam_authenticate(pamh, PAM_SILENT);
+ if (status != PAM_SUCCESS)
+ die("pam_authenticate failed: %s", pam_strerror(pamh, status));
+ status = pam_acct_mgmt(pamh, PAM_SILENT);
+ if (status != PAM_SUCCESS)
+ die("pam_acct_mgmt failed: %s", pam_strerror(pamh, status));
+ status = pam_end(pamh, status);
+ if (status != PAM_SUCCESS)
+ die("pam_end failed: %s", pam_strerror(pamh, status));
+
+ /* If we get to here, the user successfully authenticated. */
+ return true;
+}
+
+
+/*
+** Try to get a password out of a dbm file. The dbm file should have the
+** username for the key and the crypted password as the value. The crypted
+** password, if found, is returned as a newly allocated string; otherwise,
+** NULL is returned.
+*/
+#if !(defined(HAVE_DBM) || defined(HAVE_BDB_DBM))
+static char *
+password_dbm(char *user UNUSED, const char *file UNUSED)
+{
+ return NULL;
+}
+#else
+static char *
+password_dbm(char *name, const char *file)
+{
+ datum key, value;
+ DBM *database;
+ char *password;
+
+ database = dbm_open(file, O_RDONLY, 0600);
+ if (database == NULL)
+ return NULL;
+ key.dptr = name;
+ key.dsize = strlen(name);
+ value = dbm_fetch(database, key);
+ if (value.dptr == NULL) {
+ dbm_close(database);
+ return NULL;
+ }
+ password = xmalloc(value.dsize + 1);
+ strlcpy(password, value.dptr, value.dsize + 1);
+ dbm_close(database);
+ return password;
+}
+#endif /* HAVE_DBM || HAVE_BDB_DBM */
+
+
+/*
+** Try to get a password out of the system /etc/shadow file. The crypted
+** password, if found, is returned as a newly allocated string; otherwise,
+** NULL is returned.
+*/
+#if !HAVE_GETSPNAM
+static char *
+password_shadow(const char *user UNUSED)
+{
+ return NULL;
+}
+#else
+static char *
+password_shadow(const char *user)
+{
+ struct spwd *spwd;
+
+ spwd = getspnam(user);
+ if (spwd != NULL)
+ return xstrdup(spwd->sp_pwdp);
+ return NULL;
+}
+#endif /* HAVE_GETSPNAM */
+
+
+/*
+** Try to get a password out of the system password file. The crypted
+** password, if found, is returned as a newly allocated string; otherwise,
+** NULL is returned.
+*/
+static char *
+password_system(const char *username)
+{
+ struct passwd *pwd;
+
+ pwd = getpwnam(username);
+ if (pwd != NULL)
+ return xstrdup(pwd->pw_passwd);
+ return NULL;
+}
+
+
+/*
+** Try to get the name of a user's primary group out of the system group
+** file. The group, if found, is returned as a newly allocated string;
+** otherwise, NULL is returned. If the username is not found, NULL is
+** returned.
+*/
+static char *
+group_system(const char *username)
+{
+ struct passwd *pwd;
+ struct group *gr;
+
+ pwd = getpwnam(username);
+ if (pwd == NULL)
+ return NULL;
+ gr = getgrgid(pwd->pw_gid);
+ if (gr == NULL)
+ return NULL;
+ return xstrdup(gr->gr_name);
+}
+
+
+/*
+** Output username (and group, if desired) in correct return format.
+*/
+static void
+output_user(const char *username, bool wantgroup)
+{
+ if (wantgroup) {
+ char *group = group_system(username);
+ if (group == NULL)
+ die("group info for user %s not available", username);
+ printf("User:%s@%s\n", username, group);
+ }
+ else
+ printf("User:%s\n", username);
+}
+
+
+/*
+** Main routine.
+**
+** We handle the variences between systems with #if blocks above, so that
+** this code can look fairly clean.
+*/
+int
+main(int argc, char *argv[])
+{
+ enum authtype { AUTH_NONE, AUTH_SHADOW, AUTH_FILE, AUTH_DBM };
+
+ int opt;
+ enum authtype type = AUTH_NONE;
+ bool wantgroup = false;
+ const char *filename = NULL;
+ struct auth_info *authinfo = NULL;
+ char *password = NULL;
+
+ //message_program_name = "ckpasswd";
+
+ while ((opt = getopt(argc, argv, "gf:u:p:" OPT_DBM OPT_SHADOW)) != -1) {
+ switch (opt) {
+ case 'g':
+ if (type == AUTH_DBM || type == AUTH_FILE)
+ die("-g option is incompatible with -d or -f");
+ wantgroup = true;
+ break;
+ case 'd':
+ if (type != AUTH_NONE)
+ die("only one of -s, -f, or -d allowed");
+ if (wantgroup)
+ die("-g option is incompatible with -d or -f");
+ type = AUTH_DBM;
+ filename = optarg;
+ break;
+ case 'f':
+ if (type != AUTH_NONE)
+ die("only one of -s, -f, or -d allowed");
+ if (wantgroup)
+ die("-g option is incompatible with -d or -f");
+ type = AUTH_FILE;
+ filename = optarg;
+ break;
+ case 's':
+ if (type != AUTH_NONE)
+ die("only one of -s, -f, or -d allowed");
+ type = AUTH_SHADOW;
+ break;
+ case 'u':
+ if (authinfo == NULL) {
+ authinfo = xmalloc(sizeof(struct auth_info));
+ authinfo->password = NULL;
+ }
+ authinfo->username = optarg;
+ break;
+ case 'p':
+ if (authinfo == NULL) {
+ authinfo = xmalloc(sizeof(struct auth_info));
+ authinfo->username = NULL;
+ }
+ authinfo->password = optarg;
+ break;
+ default:
+ exit(1);
+ }
+ }
+ if (argc != optind)
+ die("extra arguments given");
+ if (authinfo != NULL && authinfo->username == NULL)
+ die("-u option is required if -p option is given");
+ if (authinfo != NULL && authinfo->password == NULL)
+ die("-p option is required if -u option is given");
+
+// /* Unless a username or password was given on the command line, assume
+// we're being run by nnrpd. */
+// if (authinfo == NULL)
+// authinfo = get_auth_info(stdin);
+// if (authinfo == NULL)
+// die("no authentication information from nnrpd");
+// if (authinfo->username[0] == '\0')
+// die("null username");
+
+ /* Run the appropriate authentication routines. */
+ switch (type) {
+ case AUTH_SHADOW:
+ password = password_shadow(authinfo->username);
+ if (password == NULL)
+ password = password_system(authinfo->username);
+ break;
+// case AUTH_FILE:
+// password = password_file(authinfo->username, filename);
+// break;
+ case AUTH_DBM:
+ password = password_dbm(authinfo->username, filename);
+ break;
+ case AUTH_NONE:
+ if (auth_pam(authinfo->username, authinfo->password)) {
+ output_user(authinfo->username, wantgroup);
+ exit(0);
+ }
+ password = password_system(authinfo->username);
+ break;
+ }
+
+ if (password == NULL)
+ die("user %s unknown", authinfo->username);
+ if (strcmp(password, crypt(authinfo->password, password)) != 0)
+ die("invalid password for user %s", authinfo->username);
+
+ /* The password matched. */
+ output_user(authinfo->username, wantgroup);
+ exit(0);
+}
diff --git a/src/messages.c b/src/messages.c
new file mode 100644
index 0000000..7a54e0a
--- /dev/null
+++ b/src/messages.c
@@ -0,0 +1,493 @@
+/* $Id: messages.c 5496 2002-06-07 13:59:06Z alexk $
+**
+** Message and error reporting (possibly fatal).
+**
+** Usage:
+**
+** extern int cleanup(void);
+** extern void log(int, const char *, va_list, int);
+**
+** message_fatal_cleanup = cleanup;
+** message_program_name = argv[0];
+**
+** warn("Something horrible happened at %lu", time);
+** syswarn("Couldn't unlink temporary file %s", tmpfile);
+**
+** die("Something fatal happened at %lu", time);
+** sysdie("open of %s failed", filename);
+**
+** debug("Some debugging message about %s", string);
+** trace(TRACE_PROGRAM, "Program trace output");
+** notice("Informational notices");
+**
+** message_handlers_warn(1, log);
+** warn("This now goes through our log function");
+**
+** These functions implement message reporting through user-configurable
+** handler functions. debug() only does something if DEBUG is defined,
+** trace() supports sending trace messages in one of a number of configurable
+** classes of traces so that they can be turned on or off independently, and
+** notice() and warn() just output messages as configured. die() similarly
+** outputs a message but then exits, normally with a status of 1.
+**
+** The sys* versions do the same, but append a colon, a space, and the
+** results of strerror(errno) to the end of the message. All functions
+** accept printf-style formatting strings and arguments.
+**
+** If message_fatal_cleanup is non-NULL, it is called before exit by die and
+** sysdie and its return value is used as the argument to exit. It is a
+** pointer to a function taking no arguments and returning an int, and can be
+** used to call cleanup functions or to exit in some alternate fashion (such
+** as by calling _exit).
+**
+** If message_program_name is non-NULL, the string it points to, followed by
+** a colon and a space, is prepended to all error messages logged through the
+** message_log_stdout and message_log_stderr message handlers (the former is
+** the default for notice, and the latter is the default for warn and die).
+**
+** Honoring error_program_name and printing to stderr is just the default
+** handler; with message_handlers_* the handlers for any message function can
+** be changed. By default, notice prints to stdout, warn and die print to
+** stderr, and the others don't do anything at all. These functions take a
+** count of handlers and then that many function pointers, each one to a
+** function that takes a message length (the number of characters snprintf
+** generates given the format and arguments), a format, an argument list as a
+** va_list, and the applicable errno value (if any).
+*/
+
+/* Used for unused parameters to silence gcc warnings. */
+#define UNUSED __attribute__((__unused__))
+
+/* Make available the bool type. */
+#if INN_HAVE_STDBOOL_H
+# include <stdbool.h>
+#else
+# undef true
+# undef false
+# define true (1)
+# define false (0)
+# ifndef __cplusplus
+# define bool int
+# endif
+#endif /* INN_HAVE_STDBOOL_H */
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <errno.h>
+#include <syslog.h>
+#include <crypt.h>
+#include <fcntl.h>
+#include <pwd.h>
+#include <grp.h>
+
+/* The functions are actually macros so that we can pick up the file and line
+ number information for debugging error messages without the user having to
+ pass those in every time. */
+#define xcalloc(n, size) x_calloc((n), (size), __FILE__, __LINE__)
+#define xmalloc(size) x_malloc((size), __FILE__, __LINE__)
+#define xrealloc(p, size) x_realloc((p), (size), __FILE__, __LINE__)
+#define xstrdup(p) x_strdup((p), __FILE__, __LINE__)
+#define xstrndup(p, size) x_strndup((p), (size), __FILE__, __LINE__)
+
+/* These are the currently-supported types of traces. */
+enum message_trace {
+ TRACE_NETWORK, /* Network traffic. */
+ TRACE_PROGRAM, /* Stages of program execution. */
+ TRACE_ALL /* All traces; this must be last. */
+};
+
+/* The reporting functions. The ones prefaced by "sys" add a colon, a space,
+ and the results of strerror(errno) to the output and are intended for
+ reporting failures of system calls. */
+extern void trace(enum message_trace, const char *, ...)
+ __attribute__((__format__(printf, 2, 3)));
+extern void notice(const char *, ...)
+ __attribute__((__format__(printf, 1, 2)));
+extern void sysnotice(const char *, ...)
+ __attribute__((__format__(printf, 1, 2)));
+extern void warn(const char *, ...)
+ __attribute__((__format__(printf, 1, 2)));
+extern void syswarn(const char *, ...)
+ __attribute__((__format__(printf, 1, 2)));
+extern void die(const char *, ...)
+ __attribute__((__noreturn__, __format__(printf, 1, 2)));
+extern void sysdie(const char *, ...)
+ __attribute__((__noreturn__, __format__(printf, 1, 2)));
+
+/* Debug is handled specially, since we want to make the code disappear
+ completely unless we're built with -DDEBUG. We can only do that with
+ support for variadic macros, though; otherwise, the function just won't do
+ anything. */
+#if !defined(DEBUG) && (INN_HAVE_C99_VAMACROS || INN_HAVE_GNU_VAMACROS)
+# if INN_HAVE_C99_VAMACROS
+# define debug(format, ...) /* empty */
+# elif INN_HAVE_GNU_VAMACROS
+# define debug(format, args...) /* empty */
+# endif
+#else
+extern void debug(const char *, ...)
+ __attribute__((__format__(printf, 1, 2)));
+#endif
+
+/* Set the handlers for various message functions. All of these functions
+ take a count of the number of handlers and then function pointers for each
+ of those handlers. These functions are not thread-safe; they set global
+ variables. */
+extern void message_handlers_debug(int count, ...);
+extern void message_handlers_trace(int count, ...);
+extern void message_handlers_notice(int count, ...);
+extern void message_handlers_warn(int count, ...);
+extern void message_handlers_die(int count, ...);
+
+/* Enable or disable tracing for particular classes of messages. */
+extern void message_trace_enable(enum message_trace, bool);
+
+/* Some useful handlers, intended to be passed to message_handlers_*. All
+ handlers take the length of the formatted message, the format, a variadic
+ argument list, and the errno setting if any. */
+extern void message_log_stdout(int, const char *, va_list, int);
+extern void message_log_stderr(int, const char *, va_list, int);
+extern void message_log_syslog_debug(int, const char *, va_list, int);
+extern void message_log_syslog_info(int, const char *, va_list, int);
+extern void message_log_syslog_notice(int, const char *, va_list, int);
+extern void message_log_syslog_warning(int, const char *, va_list, int);
+extern void message_log_syslog_err(int, const char *, va_list, int);
+extern void message_log_syslog_crit(int, const char *, va_list, int);
+
+/* The type of a message handler. */
+typedef void (*message_handler_func)(int, const char *, va_list, int);
+
+/* If non-NULL, called before exit and its return value passed to exit. */
+extern int (*message_fatal_cleanup)(void);
+
+/* If non-NULL, prepended (followed by ": ") to all messages printed by either
+ message_log_stdout or message_log_stderr. */
+extern const char *message_program_name;
+
+/* The default handler lists. */
+static message_handler_func stdout_handlers[2] = {
+ message_log_stdout, NULL
+};
+static message_handler_func stderr_handlers[2] = {
+ message_log_stderr, NULL
+};
+
+/* The list of logging functions currently in effect. */
+static message_handler_func *debug_handlers = NULL;
+static message_handler_func *trace_handlers = NULL;
+static message_handler_func *notice_handlers = stdout_handlers;
+static message_handler_func *warn_handlers = stderr_handlers;
+static message_handler_func *die_handlers = stderr_handlers;
+
+/* If non-NULL, called before exit and its return value passed to exit. */
+int (*message_fatal_cleanup)(void) = NULL;
+
+/* If non-NULL, prepended (followed by ": ") to messages. */
+const char *message_program_name = NULL;
+
+/* Whether or not we're currently outputting a particular type of trace. */
+static bool tracing[TRACE_ALL] = { false /* false, ... */ };
+
+
+/*
+** Set the handlers for a particular message function. Takes a pointer to
+** the handler list, the count of handlers, and the argument list.
+*/
+static void
+message_handlers(message_handler_func **list, int count, va_list args)
+{
+ int i;
+
+ if (*list != stdout_handlers && *list != stderr_handlers)
+ free(*list);
+ *list = xmalloc(sizeof(message_handler_func) * (count + 1));
+ for (i = 0; i < count; i++)
+ (*list)[i] = (message_handler_func) va_arg(args, message_handler_func);
+ (*list)[count] = NULL;
+}
+
+
+/*
+** There's no good way of writing these handlers without a bunch of code
+** duplication since we can't assume variadic macros, but I can at least make
+** it easier to write and keep them consistent.
+*/
+#define HANDLER_FUNCTION(type) \
+ void \
+ message_handlers_ ## type(int count, ...) \
+ { \
+ va_list args; \
+ \
+ va_start(args, count); \
+ message_handlers(& type ## _handlers, count, args); \
+ va_end(args); \
+ }
+HANDLER_FUNCTION(debug)
+HANDLER_FUNCTION(trace)
+HANDLER_FUNCTION(notice)
+HANDLER_FUNCTION(warn)
+HANDLER_FUNCTION(die)
+
+
+/*
+** Print a message to stdout, supporting message_program_name.
+*/
+void
+message_log_stdout(int len UNUSED, const char *fmt, va_list args, int err)
+{
+ if (message_program_name != NULL)
+ fprintf(stdout, "%s: ", message_program_name);
+ vfprintf(stdout, fmt, args);
+ if (err)
+ fprintf(stdout, ": %s", strerror(err));
+ fprintf(stdout, "\n");
+}
+
+
+/*
+** Print a message to stderr, supporting message_program_name. Also flush
+** stdout so that errors and regular output occur in the right order.
+*/
+void
+message_log_stderr(int len UNUSED, const char *fmt, va_list args, int err)
+{
+ fflush(stdout);
+ if (message_program_name != NULL)
+ fprintf(stderr, "%s: ", message_program_name);
+ vfprintf(stderr, fmt, args);
+ if (err)
+ fprintf(stderr, ": %s", strerror(err));
+ fprintf(stderr, "\n");
+}
+
+
+/*
+** Log a message to syslog. This is a helper function used to implement all
+** of the syslog message log handlers. It takes the same arguments as a
+** regular message handler function but with an additional priority
+** argument.
+*/
+static void
+message_log_syslog(int pri, int len, const char *fmt, va_list args, int err)
+{
+ char *buffer;
+
+ buffer = malloc(len + 1);
+ if (buffer == NULL) {
+ fprintf(stderr, "failed to malloc %u bytes at %s line %d: %s",
+ len + 1, __FILE__, __LINE__, strerror(errno));
+ exit(message_fatal_cleanup ? (*message_fatal_cleanup)() : 1);
+ }
+ vsnprintf(buffer, len + 1, fmt, args);
+ syslog(pri, err ? "%s: %m" : "%s", buffer);
+ free(buffer);
+}
+
+
+/*
+** Do the same sort of wrapper to generate all of the separate syslog logging
+** functions.
+*/
+#define SYSLOG_FUNCTION(name, type) \
+ void \
+ message_log_syslog_ ## name(int l, const char *f, va_list a, int e) \
+ { \
+ message_log_syslog(LOG_ ## type, l, f, a, e); \
+ }
+SYSLOG_FUNCTION(debug, DEBUG)
+SYSLOG_FUNCTION(info, INFO)
+SYSLOG_FUNCTION(notice, NOTICE)
+SYSLOG_FUNCTION(warning, WARNING)
+SYSLOG_FUNCTION(err, ERR)
+SYSLOG_FUNCTION(crit, CRIT)
+
+
+/*
+** Enable or disable tracing for particular classes of messages.
+*/
+void
+message_trace_enable(enum message_trace type, bool enable)
+{
+ if (type > TRACE_ALL)
+ return;
+ if (type == TRACE_ALL) {
+ int i;
+
+ for (i = 0; i < TRACE_ALL; i++)
+ tracing[i] = enable;
+ } else {
+ tracing[type] = enable;
+ }
+}
+
+
+/*
+** All of the message handlers. There's a lot of code duplication here too,
+** but each one is still *slightly* different and va_start has to be called
+** multiple times, so it's hard to get rid of the duplication.
+*/
+
+#ifdef DEBUG
+void
+debug(const char *format, ...)
+{
+ va_list args;
+ message_handler_func *log;
+ int length;
+
+ if (debug_handlers == NULL)
+ return;
+ va_start(args, format);
+ length = vsnprintf(NULL, 0, format, args);
+ va_end(args);
+ if (length < 0)
+ return;
+ for (log = debug_handlers; *log != NULL; log++) {
+ va_start(args, format);
+ (**log)(length, format, args, 0);
+ va_end(args);
+ }
+}
+#elif !INN_HAVE_C99_VAMACROS && !INN_HAVE_GNU_VAMACROS
+void debug(const char *format UNUSED, ...) { }
+#endif
+
+void
+trace(enum message_trace type, const char *format, ...)
+{
+ va_list args;
+ message_handler_func *log;
+ int length;
+
+ if (trace_handlers == NULL || !tracing[type])
+ return;
+ va_start(args, format);
+ length = vsnprintf(NULL, 0, format, args);
+ va_end(args);
+ if (length < 0)
+ return;
+ for (log = trace_handlers; *log != NULL; log++) {
+ va_start(args, format);
+ (**log)(length, format, args, 0);
+ va_end(args);
+ }
+}
+
+void
+notice(const char *format, ...)
+{
+ va_list args;
+ message_handler_func *log;
+ int length;
+
+ va_start(args, format);
+ length = vsnprintf(NULL, 0, format, args);
+ va_end(args);
+ if (length < 0)
+ return;
+ for (log = notice_handlers; *log != NULL; log++) {
+ va_start(args, format);
+ (**log)(length, format, args, 0);
+ va_end(args);
+ }
+}
+
+void
+sysnotice(const char *format, ...)
+{
+ va_list args;
+ message_handler_func *log;
+ int length;
+ int error = errno;
+
+ va_start(args, format);
+ length = vsnprintf(NULL, 0, format, args);
+ va_end(args);
+ if (length < 0)
+ return;
+ for (log = notice_handlers; *log != NULL; log++) {
+ va_start(args, format);
+ (**log)(length, format, args, error);
+ va_end(args);
+ }
+}
+
+void
+warn(const char *format, ...)
+{
+ va_list args;
+ message_handler_func *log;
+ int length;
+
+ va_start(args, format);
+ length = vsnprintf(NULL, 0, format, args);
+ va_end(args);
+ if (length < 0)
+ return;
+ for (log = warn_handlers; *log != NULL; log++) {
+ va_start(args, format);
+ (**log)(length, format, args, 0);
+ va_end(args);
+ }
+}
+
+void
+syswarn(const char *format, ...)
+{
+ va_list args;
+ message_handler_func *log;
+ int length;
+ int error = errno;
+
+ va_start(args, format);
+ length = vsnprintf(NULL, 0, format, args);
+ va_end(args);
+ if (length < 0)
+ return;
+ for (log = warn_handlers; *log != NULL; log++) {
+ va_start(args, format);
+ (**log)(length, format, args, error);
+ va_end(args);
+ }
+}
+
+void
+die(const char *format, ...)
+{
+ va_list args;
+ message_handler_func *log;
+ int length;
+
+ va_start(args, format);
+ length = vsnprintf(NULL, 0, format, args);
+ va_end(args);
+ if (length >= 0)
+ for (log = die_handlers; *log != NULL; log++) {
+ va_start(args, format);
+ (**log)(length, format, args, 0);
+ va_end(args);
+ }
+ exit(message_fatal_cleanup ? (*message_fatal_cleanup)() : 1);
+}
+
+void
+sysdie(const char *format, ...)
+{
+ va_list args;
+ message_handler_func *log;
+ int length;
+ int error = errno;
+
+ va_start(args, format);
+ length = vsnprintf(NULL, 0, format, args);
+ va_end(args);
+ if (length >= 0)
+ for (log = die_handlers; *log != NULL; log++) {
+ va_start(args, format);
+ (**log)(length, format, args, error);
+ va_end(args);
+ }
+ exit(message_fatal_cleanup ? (*message_fatal_cleanup)() : 1);
+}
diff --git a/src/xmalloc.c b/src/xmalloc.c
new file mode 100644
index 0000000..4d00c52
--- /dev/null
+++ b/src/xmalloc.c
@@ -0,0 +1,163 @@
+/* $Id: xmalloc.c 5381 2002-03-31 22:35:47Z rra $
+**
+** malloc routines with failure handling.
+**
+** Usage:
+**
+** extern xmalloc_handler_t memory_error;
+** extern const char *string;
+** char *buffer;
+**
+** xmalloc_error_handler = memory_error;
+** buffer = xmalloc(1024);
+** xrealloc(buffer, 2048);
+** free(buffer);
+** buffer = xcalloc(1024);
+** free(buffer);
+** buffer = xstrdup(string);
+** free(buffer);
+** buffer = xstrndup(string, 25);
+**
+** xmalloc, xcalloc, xrealloc, and xstrdup behave exactly like their C
+** library counterparts without the leading x except that they will never
+** return NULL. Instead, on error, they call xmalloc_error_handler,
+** passing it the name of the function whose memory allocation failed, the
+** amount of the allocation, and the file and line number where the
+** allocation function was invoked (from __FILE__ and __LINE__). This
+** function may do whatever it wishes, such as some action to free up
+** memory or a call to sleep to hope that system resources return. If the
+** handler returns, the interrupted memory allocation function will try its
+** allocation again (calling the handler again if it still fails).
+**
+** xstrndup behaves like xstrdup but only copies the given number of
+** characters. It allocates an additional byte over its second argument and
+** always nul-terminates the string.
+**
+** The default error handler, if none is set by the caller, prints an error
+** message to stderr and exits with exit status 1. An error handler must
+** take a const char * (function name), size_t (bytes allocated), const
+** char * (file), and int (line).
+**
+** xmalloc will return a pointer to a valid memory region on an xmalloc of 0
+** bytes, ensuring this by allocating space for one character instead of 0
+** bytes.
+**
+** The functions defined here are actually x_malloc, x_realloc, etc. The
+** header file defines macros named xmalloc, etc. that pass the file name
+** and line number to these functions.
+*/
+
+/* Used for unused parameters to silence gcc warnings. */
+#define UNUSED __attribute__((__unused__))
+
+/* Make available the bool type. */
+#if INN_HAVE_STDBOOL_H
+# include <stdbool.h>
+#else
+# undef true
+# undef false
+# define true (1)
+# define false (0)
+# ifndef __cplusplus
+# define bool int
+# endif
+#endif /* INN_HAVE_STDBOOL_H */
+
+#include <stdlib.h>
+#include <string.h>
+#include <crypt.h>
+#include <fcntl.h>
+#include <pwd.h>
+#include <grp.h>
+
+/* Failure handler takes the function, the size, the file, and the line. */
+typedef void (*xmalloc_handler_t)(const char *, size_t, const char *, int);
+
+/* Assign to this variable to choose a handler other than the default, which
+ just calls sysdie. */
+extern xmalloc_handler_t xmalloc_error_handler;
+
+/* The default error handler. */
+void
+xmalloc_fail(const char *function, size_t size, const char *file, int line)
+{
+ sysdie("failed to %s %lu bytes at %s line %d", function,
+ (unsigned long) size, file, line);
+}
+
+/* Assign to this variable to choose a handler other than the default. */
+xmalloc_handler_t xmalloc_error_handler = xmalloc_fail;
+
+void *
+x_malloc(size_t size, const char *file, int line)
+{
+ void *p;
+ size_t real_size;
+
+ real_size = (size > 0) ? size : 1;
+ p = malloc(real_size);
+ while (p == NULL) {
+ (*xmalloc_error_handler)("malloc", size, file, line);
+ p = malloc(real_size);
+ }
+ return p;
+}
+
+void *
+x_calloc(size_t n, size_t size, const char *file, int line)
+{
+ void *p;
+
+ n = (n > 0) ? n : 1;
+ size = (size > 0) ? size : 1;
+ p = calloc(n, size);
+ while (p == NULL) {
+ (*xmalloc_error_handler)("calloc", n * size, file, line);
+ p = calloc(n, size);
+ }
+ return p;
+}
+
+void *
+x_realloc(void *p, size_t size, const char *file, int line)
+{
+ void *newp;
+
+ newp = realloc(p, size);
+ while (newp == NULL && size > 0) {
+ (*xmalloc_error_handler)("realloc", size, file, line);
+ newp = realloc(p, size);
+ }
+ return newp;
+}
+
+char *
+x_strdup(const char *s, const char *file, int line)
+{
+ char *p;
+ size_t len;
+
+ len = strlen(s) + 1;
+ p = malloc(len);
+ while (p == NULL) {
+ (*xmalloc_error_handler)("strdup", len, file, line);
+ p = malloc(len);
+ }
+ memcpy(p, s, len);
+ return p;
+}
+
+char *
+x_strndup(const char *s, size_t size, const char *file, int line)
+{
+ char *p;
+
+ p = malloc(size + 1);
+ while (p == NULL) {
+ (*xmalloc_error_handler)("strndup", size + 1, file, line);
+ p = malloc(size + 1);
+ }
+ memcpy(p, s, size);
+ p[size] = '\0';
+ return p;
+}
diff --git a/usr/bin/cryptosmartcard.sh b/usr/bin/cryptosmartcard.sh
new file mode 100755
index 0000000..d885248
--- /dev/null
+++ b/usr/bin/cryptosmartcard.sh
@@ -0,0 +1,88 @@
+#!/bin/sh
+
+# Part of passwordless cryptofs setup in Debian Etch.
+# See: http://wejn.org/how-to-make-passwordless-cryptsetup.html
+# Author: Wejn <wejn at box dot cz>
+#
+# Updated by Rodolfo Garcia (kix) <kix at kix dot com>
+# For multiple partitions
+# http://www.kix.es/
+#
+# Updated by TJ <linux@tjworld.net> 7 July 2008
+# For use with Ubuntu Hardy, usplash, automatic detection of USB devices,
+# detection and examination of *all* partitions on the device (not just partition #1),
+# automatic detection of partition type, refactored, commented, debugging code.
+#
+# Update by Timothy Pearson <kb9vqf@pearsoncomputing.net> 8/28/2008
+# Modified for use with SmartCard script instead of USB key
+
+# define counter-intuitive shell logic values (based on /bin/true & /bin/false)
+TRUE=0
+FALSE=1
+
+# set DEBUG=$TRUE to display debug messages, DEBUG=$FALSE to be quiet
+DEBUG=$FALSE
+
+# Fix the aggressive usplash timeout
+if [ -x /sbin/usplash_write ]; then
+ /sbin/usplash_write "TIMEOUT 180" || true
+fi
+
+# print message to usplash or stderr
+# usage: msg <command> "message" [switch]
+# command: TEXT | STATUS | SUCCESS | FAILURE | CLEAR (see 'man usplash_write' for all commands)
+# switch : switch used for echo to stderr (ignored for usplash)
+# when using usplash the command will cause "message" to be
+# printed according to the usplash <command> definition.
+# using the switch -n will allow echo to write multiple messages
+# to the same line
+msg ()
+{
+ if [ -p /dev/.initramfs/usplash_outfifo ] && [ -x /sbin/usplash_write ]; then
+ usplash_write "TEXT-URGENT $@"
+ else
+ echo "$@" >&2
+ fi
+ return 0
+}
+
+[ $DEBUG -eq $TRUE ] && msg "Executing crypto-usb-key.sh ..."
+# flag tracking key-file availability
+OPENED=$FALSE
+
+# Is the USB driver loaded?
+cat /proc/modules | busybox grep usb_storage >/dev/null 2>&1
+USBLOAD=0$?
+if [ $USBLOAD -gt 0 ]; then
+ [ $DEBUG -eq $TRUE ] && msg "Loading driver 'usb_storage'"
+ modprobe usb_storage >/dev/null 2>&1
+fi
+
+killall pcscd &
+
+# give the system time to settle and open the USB devices
+sleep 5
+
+cd /bin/
+/bin/smartauth.sh > /dev/null 2>&1
+SMARTCARDFILE=/bin/smart.key
+if [ -e $SMARTCARDFILE ]
+then
+ OPENED=$TRUE
+ cat $SMARTCARDFILE
+else
+ OPENED=$FALSE
+fi
+
+if [ $OPENED -eq $FALSE ]; then
+ msg "SmartCard LUKS keyfile invalid or incorrect SmartCard inserted"
+ msg "Try to enter the LUKS password: "
+ read -s -r A </dev/console
+ echo -n "$A"
+else
+ msg "SmartCard authenticated and LUKS keyfile loaded"
+fi
+
+killall pcscd &
+
+
diff --git a/usr/bin/setupcard.sh b/usr/bin/setupcard.sh
new file mode 100755
index 0000000..32ff2b6
--- /dev/null
+++ b/usr/bin/setupcard.sh
@@ -0,0 +1,1010 @@
+#!/bin/bash
+
+# Smart Card Management Tool (c) 2009 Timothy Pearson
+#
+# 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 3 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, see <http://www.gnu.org/licenses/>.
+
+# The [secure] temporary directory for authentication
+SECURE_DIRECTORY=/tmp/smartauth
+
+# Create the secure directory and lock it down
+mkdir -p $SECURE_DIRECTORY
+chown root $SECURE_DIRECTORY
+chgrp root $SECURE_DIRECTORY
+chmod 600 $SECURE_DIRECTORY
+SECURE_DIRECTORY=$(mktemp /tmp/smartauth/setupcard.XXXXXXXXXX)
+rm -rf $SECURE_DIRECTORY
+mkdir -p $SECURE_DIRECTORY
+chown root $SECURE_DIRECTORY
+chgrp root $SECURE_DIRECTORY
+chmod 600 $SECURE_DIRECTORY
+
+# See if required programs are installed
+scriptor=$(whereis scriptor)
+if [[ $scriptor == "scriptor:" ]]; then
+ echo "ERROR: scriptor is not installed! This program cannot continue!"
+ zenity --error --text "ERROR: scriptor is not installed!\nThis program cannot continue!\n\nUsually, scriptor is part of the pcsc-tools package."
+ exit
+fi
+opensc=$(whereis opensc-explorer)
+if [[ $opensc == "opensc-explorer:" ]]; then
+ echo "ERROR: opensc-explorer is not installed! This program cannot continue!"
+ zenity --error --text "ERROR: opensc-explorer is not installed!\nThis program cannot continue!\n\nUsually, opensc-explorer is part of the opensc package."
+ exit
+fi
+
+if [[ $# -eq 0 ]]; then
+ # Get card ATR
+ FOUND_SUPPORTED_CARD=0
+ echo "RESET" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ authokresponse="OK: "
+ response1=$(cat $SECURE_DIRECTORY/response2 | grep "$authokresponse")
+ if [[ $response1 != "" ]]; then
+ cat $SECURE_DIRECTORY/response2 | tr -d '\n' > $SECURE_DIRECTORY/response4
+ stringtoreplace="Using T=0 protocolRESET> RESET< OK: "
+ newstring=""
+ sed -i "s#${stringtoreplace}#${newstring}#g" $SECURE_DIRECTORY/response4
+ smartatr=$(cat $SECURE_DIRECTORY/response4)
+ echo "Got ATR: $smartatr"
+ if [[ $smartatr == "3B BE 18 00 00 41 05 10 00 00 00 00 00 00 00 00 00 90 00 " ]]; then
+ echo "Detected ACOS5 card"
+ COMMAND_MODE="acos"
+ CARD_NICE_NAME="ACOS5"
+ FOUND_SUPPORTED_CARD=1
+ fi
+ if [[ $smartatr == "3B 02 14 50 " ]]; then
+ echo "Detected Schlumberger CryptoFlex card"
+ COMMAND_MODE="cryptoflex"
+ CARD_NICE_NAME="Schlumberger CryptoFlex"
+ FOUND_SUPPORTED_CARD=1
+ fi
+ else
+ echo "No card detected!"
+ zenity --error --text "ERROR: No SmartCard detected!"
+ exit 1
+ fi
+
+ if [[ $FOUND_SUPPORTED_CARD -eq 0 ]]; then
+ echo "Unsupported SmartCard detected! ATR: $smartatr"
+ zenity --error --text "ERROR: Unsupported SmartCard detected!\n\nATR: $smartatr"
+ exit 1
+ fi
+
+ if [[ $COMMAND_MODE == "cryptoflex" ]]; then
+ GET_CHALLENGE="C0 84 00 00 08"
+ EXTERNAL_AUTH="C0 82 00 00 07 01"
+ SELECT_FILE="C0 A4 00 00 02"
+ DELETE_FILE="F0 E4 00 00 02"
+ fi
+
+ if [[ $COMMAND_MODE == "acos" ]]; then
+ GET_CHALLENGE="00 84 00 00 08"
+ EXTERNAL_AUTH1="00 82 00 81 08"
+ EXTERNAL_AUTH2="00 82 00 82 08"
+ EXTERNAL_AUTH3="00 82 00 83 08"
+ SELECT_FILE="00 A4 00 00 02"
+ DELETE_FILE="00 E4 00 00 00"
+ READ_BINARY="00 B0 00 00 FF"
+ UPDATE_BINARY="00 D6 00 00 FF"
+ ACTIVATE_FILE="00 44 00 00 02"
+ fi
+fi
+
+CREATE_LIFE_CYCLE="01"
+
+createfile ()
+{
+ if [[ $COMMAND_MODE == "cryptoflex" ]]; then
+ # Create transparent file with permissions:
+ # delete, terminate, activate, deactivate, update, read for Key 1 and Key 2 only
+ echo "F0 E0 00 FF 10 FF FF 00 $1 $2 01 3F 44 FF 44 01 03 11 FF 11" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2 2>/dev/null
+ fi
+
+ if [[ $COMMAND_MODE == "acos" ]]; then
+ # Create transparent file with permissions:
+ # delete, terminate, activate, deactivate, update, read for Key 1, Key 2, and Key 3 only (SE 04)
+ # created in DF 1000 under MF, SE file is 10FE
+ # SIZE TRANSPARENT
+
+ echo "00 E0 00 00 1A 62 18 80 02 00 $1 82 01 01 83 02 $2 8A 01 $CREATE_LIFE_CYCLE 8C 08 7F 04 04 04 04 04 04 04" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2 2>/dev/null
+ echo $(cat $SECURE_DIRECTORY/response2)
+ fi
+}
+
+updatekey ()
+{
+ if [[ $COMMAND_MODE == "cryptoflex" ]]; then
+ echo "$SELECT_FILE 00 11" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2 2>/dev/null
+ echo "C0 D6 00 0D 0C 08 00 $1 05 05" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2 2>/dev/null
+ fi
+}
+
+hexcvt ()
+{
+ echo ""$1" "16" o p" | dc
+}
+
+initializeacos () {
+ if [[ $COMMAND_MODE == "acos" ]]; then
+ # Set MF Offset
+ echo "00 D6 30 86 02 80 00" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+
+ # Set EEPROM Limit
+ echo "00 D6 30 8C 02 FF FF" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+
+ # Enable Clear Card
+ echo "00 D6 30 88 01 00" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+
+ # Create MF
+ echo "00 E0 00 00 0A 62 08 82 02 3F FF 83 02 3F 00" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+
+ # Select MF
+ echo "00 A4 00 00 00" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+
+ # Create DF 1000 under MF, SE file is 10FE
+ echo "00 E0 00 00 2C 62 2A 82 01 38 83 02 10 00 84 10 10 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 8A 01 $CREATE_LIFE_CYCLE 8C 08 7F 04 04 04 04 04 04 04 8D 02 10 FE" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+
+ # Select DF 1000 under MF
+ echo "$SELECT_FILE 10 00" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+
+ # Under DF 1000, create Key File EF2, file ID 10FD, read access never, SFI 02
+ echo "00 E0 00 00 1D 62 1B 82 05 0C 01 00 15 04 83 02 10 FD 88 01 02 8A 01 $CREATE_LIFE_CYCLE 8C 08 7F 04 04 04 04 04 04 FF" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+
+ # Select EF 10FD under DF 1000
+ echo "$SELECT_FILE 10 FD" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+
+ # Initialize key records in file 10FD
+ # Key 1, 8-byte 1DES authentication only
+ autkey=""
+ while [[ ${#autkey} != 16 ]]; do
+ autkey=$(zenity --entry --hide-text --title="SmartCard Transport Key" --text="Please enter the new 16-character Smart Card transport key [AUT1] in hexidecimal. Example: 0123456789abcdef")
+ done
+ autkey2=${autkey:0:2}
+ autkey2="${autkey2} ${autkey:2:2}"
+ autkey2="${autkey2} ${autkey:4:2}"
+ autkey2="${autkey2} ${autkey:6:2}"
+ autkey2="${autkey2} ${autkey:8:2}"
+ autkey2="${autkey2} ${autkey:10:2}"
+ autkey2="${autkey2} ${autkey:12:2}"
+ autkey2="${autkey2} ${autkey:14:2}"
+ echo "00 DC 00 00 0C 81 01 55 05 $autkey2" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+ # Key 2, 8-byte 1DES authentication only
+ autkey=""
+ while [[ ${#autkey} != 16 ]]; do
+ autkey=$(zenity --entry --hide-text --title="SmartCard Transport Key" --text="Please enter the new 16-character Smart Card transport key [AUT2] in hexidecimal. Example: 0123456789abcdef")
+ done
+ autkey2=${autkey:0:2}
+ autkey2="${autkey2} ${autkey:2:2}"
+ autkey2="${autkey2} ${autkey:4:2}"
+ autkey2="${autkey2} ${autkey:6:2}"
+ autkey2="${autkey2} ${autkey:8:2}"
+ autkey2="${autkey2} ${autkey:10:2}"
+ autkey2="${autkey2} ${autkey:12:2}"
+ autkey2="${autkey2} ${autkey:14:2}"
+ echo "00 DC 00 02 0C 82 01 55 05 $autkey2" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+ # Key 3, 8-byte 1DES authentication only
+ autkey=""
+ while [[ ${#autkey} != 16 ]]; do
+ autkey=$(zenity --entry --hide-text --title="SmartCard Transport Key" --text="Please enter the new 16-character Smart Card transport key [AUT3] in hexidecimal. Example: 0123456789abcdef")
+ done
+ autkey2=${autkey:0:2}
+ autkey2="${autkey2} ${autkey:2:2}"
+ autkey2="${autkey2} ${autkey:4:2}"
+ autkey2="${autkey2} ${autkey:6:2}"
+ autkey2="${autkey2} ${autkey:8:2}"
+ autkey2="${autkey2} ${autkey:10:2}"
+ autkey2="${autkey2} ${autkey:12:2}"
+ autkey2="${autkey2} ${autkey:14:2}"
+ echo "00 DC 00 02 0C 83 01 55 05 $autkey2" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+
+ # Create SE file 10FE, SFI 03
+ echo "00 E0 00 00 1C 62 1A 82 05 0C 01 00 11 04 83 02 10 FE 88 01 03 8A 01 $CREATE_LIFE_CYCLE 8C 07 7E 04 04 04 04 04 04" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+
+ # Select MF
+ echo "00 A4 00 00 00" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+
+ # Select DF 1000 under MF
+ echo "$SELECT_FILE 10 00" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+
+ # Select EF 10FE under DF 1000
+ echo "$SELECT_FILE 10 FE" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+
+ # Initialize SE file 10FE
+ # SE 01: External authentication of local key 1
+ echo "00 DC 00 00 0B 80 01 01 A4 06 83 01 81 95 01 80" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+ # SE 02: External authentication of local key 2
+ echo "00 DC 00 02 0B 80 01 02 A4 06 83 01 82 95 01 80" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+ # SE 03: External authentication of local key 3
+ echo "00 DC 00 02 0B 80 01 03 A4 06 83 01 83 95 01 80" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+ # SE 04: External authentication of local key 1, 2, or 3
+ echo "00 DC 00 02 11 80 01 04 A4 0C 83 01 81 83 01 82 83 01 83 95 01 80" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+
+ # Create authentication files
+ createfile "FF" "10 01"
+ createfile "FF" "10 02"
+ createfile "FF" "10 03"
+ createfile "FF" "10 04"
+ createfile "FF" "10 05"
+ createfile "FF" "10 06"
+ createfile "FF" "10 07"
+ createfile "FF" "10 08"
+ createfile "FF" "10 09"
+ createfile "FF" "10 0A"
+
+ # Activate security on files
+ echo "$ACTIVATE_FILE 10 01" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+ echo "$ACTIVATE_FILE 10 02" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+ echo "$ACTIVATE_FILE 10 03" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+ echo "$ACTIVATE_FILE 10 04" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+ echo "$ACTIVATE_FILE 10 05" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+ echo "$ACTIVATE_FILE 10 06" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+ echo "$ACTIVATE_FILE 10 07" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+ echo "$ACTIVATE_FILE 10 08" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+ echo "$ACTIVATE_FILE 10 09" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+ echo "$ACTIVATE_FILE 10 0A" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+ echo "$ACTIVATE_FILE 10 FD" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+ echo "$ACTIVATE_FILE 10 FE" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+ fi
+}
+
+authenticatecard () {
+ if [[ $authenticated != "1" ]]; then
+ autkey=$(zenity --entry --hide-text --title="SmartCard Transport Key" --text="Please enter the 16-character Smart Card transport key [$1] in hexidecimal. Example: 0123456789abcdef")
+ if [[ ${#autkey} -eq 16 ]]; then
+ if [[ $COMMAND_MODE == "acos" ]]; then
+ # Select MF
+ echo "00 A4 00 00 00" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+ # Make sure DF 1000 is selected
+ echo "$SELECT_FILE 10 00" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+ fi
+
+ # Authenticate card
+ echo $GET_CHALLENGE > $SECURE_DIRECTORY/authscript
+
+ scriptor $SECURE_DIRECTORY/authscript | grep 'Normal processing' > $SECURE_DIRECTORY/challenge
+ perl -pi -e 's/ //g' $SECURE_DIRECTORY/challenge
+ perl -pi -e 's/:Normalprocessing.//g' $SECURE_DIRECTORY/challenge
+ perl -pi -e 's/<//g' $SECURE_DIRECTORY/challenge
+ xxd -r -p $SECURE_DIRECTORY/challenge $SECURE_DIRECTORY/challenge
+
+ # Now DES encrypt the challenge
+ # Later, change the initialization vector to random if possible
+ openssl des-ecb -in $SECURE_DIRECTORY/challenge -out $SECURE_DIRECTORY/response -K $autkey -iv 1
+
+ if [[ $COMMAND_MODE == "acos" ]]; then
+ # Truncate to 8 bytes
+ dd if=$SECURE_DIRECTORY/response of=$SECURE_DIRECTORY/response2 bs=1 count=8
+
+ # Expand to standard hex listing format
+ xxd -g 1 $SECURE_DIRECTORY/response2 $SECURE_DIRECTORY/response
+ dd if=$SECURE_DIRECTORY/response of=$SECURE_DIRECTORY/response2 bs=1 count=23 skip=9
+ fi
+
+ if [[ $COMMAND_MODE == "cryptoflex" ]]; then
+ # Truncate to 6 bytes
+ dd if=$SECURE_DIRECTORY/response of=$SECURE_DIRECTORY/response2 bs=1 count=6
+
+ # Expand to standard hex listing format
+ xxd -g 1 $SECURE_DIRECTORY/response2 $SECURE_DIRECTORY/response
+ dd if=$SECURE_DIRECTORY/response of=$SECURE_DIRECTORY/response2 bs=1 count=17 skip=9
+ fi
+
+ # Assemble the response file
+ response2=$(cat $SECURE_DIRECTORY/response2)
+ if [[ $COMMAND_MODE == "acos" ]]; then
+ if [[ $1 == "AUT1" ]]; then
+ response1="$EXTERNAL_AUTH1 ${response2}"
+ fi
+ if [[ $1 == "AUT2" ]]; then
+ response1="$EXTERNAL_AUTH2 ${response2}"
+ fi
+ if [[ $1 == "AUT3" ]]; then
+ response1="$EXTERNAL_AUTH3 ${response2}"
+ fi
+ fi
+
+ if [[ $COMMAND_MODE == "cryptoflex" ]]; then
+ response1="$EXTERNAL_AUTH ${response2}"
+ fi
+ echo $response1 > $SECURE_DIRECTORY/response
+
+ # Send the response!
+ scriptor $SECURE_DIRECTORY/response > $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+
+ # Get the result
+ authokresponse="< 90 00 : Normal processing"
+ response1=$(cat $SECURE_DIRECTORY/response2 | grep "$authokresponse")
+ echo $response1
+ if [[ $response1 != "" ]]; then
+ echo "Smart card validation successfull!"
+ echo "Smart card login successfull!"
+ authenticated="1"
+ else
+ echo "Login failed"
+ zenity --error --text "That transport key is incorrect!\n\nPlease remember that there are a limited number\nof failed login attempts for this key,\nafter which your SmartCard will become useless."
+ fi
+ else
+ echo "AUT1 key not 16 characters!"
+ zenity --error --text "That transport key is invalid!"
+ fi
+ fi
+}
+
+get_file () {
+ if [[ $COMMAND_MODE == "acos" ]]; then
+ # Select EF $1 under DF 1000
+ echo "$SELECT_FILE $1" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+
+ # Read binary
+ echo "$READ_BINARY" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ authokresponse="90 00 : Normal processing"
+ response1=$(cat $SECURE_DIRECTORY/response2 | grep "$authokresponse")
+ if [[ $response1 != "" ]]; then
+ cat $SECURE_DIRECTORY/response2 | tr -d '\n' > $SECURE_DIRECTORY/response4
+ stringtoreplace="Using T=0 protocol00 B0 00 00 FF> 00 B0 00 00 FF< "
+ newstring=""
+ sed -i "s#${stringtoreplace}#${newstring}#g" $SECURE_DIRECTORY/response4
+ stringtoreplace=" 90 00 : Normal processing."
+ newstring=""
+ sed -i "s#${stringtoreplace}#${newstring}#g" $SECURE_DIRECTORY/response4
+ if [[ $2 == "text" ]]; then
+ stringtoreplace=" 00"
+ newstring=""
+ sed -i "s#${stringtoreplace}#${newstring}#g" $SECURE_DIRECTORY/response4
+ fi
+ echo $(cat $SECURE_DIRECTORY/response4)
+ rm -f $SECURE_DIRECTORY/lukskey
+ xxd -r -p $SECURE_DIRECTORY/response4 $SECURE_DIRECTORY/lukskey
+ RESPONSE=$SECURE_DIRECTORY/lukskey
+ fi
+ fi
+
+ if [[ $COMMAND_MODE == "cryptoflex" ]]; then
+ FILE=${1/ /}
+ echo "get $FILE" | opensc-explorer
+ RESPONSE="3F00_$FILE"
+ fi
+}
+
+update_file () {
+ if [[ $COMMAND_MODE == "acos" ]]; then
+ # Select EF $1 under DF 1000
+ echo "$SELECT_FILE $1" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+
+ # Update existing file
+ # Zero pad input file
+ dd if=/dev/zero of=$SECURE_DIRECTORY/response2 bs=1 count=255
+ dd if=$2 of=$SECURE_DIRECTORY/response2 bs=1 count=255 conv=notrunc
+
+ # Truncate to 255 bytes and expand to standard hex listing format
+ xxd -l 255 -ps -c 1 $SECURE_DIRECTORY/response2 > $SECURE_DIRECTORY/response
+ cat $SECURE_DIRECTORY/response | tr '\n' ' ' > $SECURE_DIRECTORY/hexready
+ echo "$UPDATE_BINARY $(cat $SECURE_DIRECTORY/hexready)" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2 2>/dev/null
+ echo $(cat $SECURE_DIRECTORY/response2)
+ fi
+
+ if [[ $COMMAND_MODE == "cryptoflex" ]]; then
+ # Delete old file
+ echo "$DELETE_FILE $1" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2 2>/dev/null
+ echo $(cat $SECURE_DIRECTORY/response2)
+
+ # Create new file
+ createfile "FF" $1
+ FILE=${1/ /}
+ echo "put $FILE $2" | opensc-explorer
+ fi
+}
+
+insertnewtext () {
+ FOUNDTEXT=$(cat $2 | grep $1)
+ echo $FOUNDTEXT;
+ if [[ $FOUNDTEXT != "" ]]; then
+ echo "$1 already exists in $2"
+ else
+ echo $1 >> $2
+ fi
+}
+
+getcolumn () {
+ perl -ne '@cols = split; print "$cols['$1']\n"' ;
+}
+
+function createlukskey {
+ ROOTPARTITION=$(mount | grep 'on / ' | getcolumn 0)
+ if [ -e $ROOTPARTITION ]; then
+ ROOTPARTITION=$(echo $ROOTPARTITION | sed 's/\/dev\/mapper\///')
+ CRYPTPARTITION=$(cat /etc/crypttab | grep $ROOTPARTITION | getcolumn 1)
+ if [ -e $CRYPTPARTITION ]; then
+ zenity --question --ok-label="Yes" --cancel-label="No" --text="I have detected that $ROOTPARTITION is your root partition, \nand therefore $CRYPTPARTITION is your encrypted root partition. \nIs this correct?"
+ correct=$?
+ if [[ correct -eq 0 ]] ; then
+ echo "Confirmed--proceeding"
+ insertnewtext dm_mod /etc/initramfs-tools/modules
+ insertnewtext dm_crypt /etc/initramfs-tools/modules
+ insertnewtext aes_x86_64 /etc/initramfs-tools/modules
+ insertnewtext sha256 /etc/initramfs-tools/modules
+ insertnewtext vfat /etc/initramfs-tools/modules
+ insertnewtext fat /etc/initramfs-tools/modules
+ insertnewtext nls_cp437 /etc/initramfs-tools/modules
+ insertnewtext nls_iso8859_1 /etc/initramfs-tools/modules
+ insertnewtext hci_usb /etc/initramfs-tools/modules
+ insertnewtext usb_storage /etc/initramfs-tools/modules
+ insertnewtext libusual /etc/initramfs-tools/modules
+ insertnewtext ehci_hcd /etc/initramfs-tools/modules
+ insertnewtext uhci_hcd /etc/initramfs-tools/modules
+ insertnewtext usbcore /etc/initramfs-tools/modules
+ insertnewtext ext2 /etc/initramfs-tools/modules
+ insertnewtext reiserfs /etc/initramfs-tools/modules
+ echo "/etc/initramfs-tools/modules updated"
+ mkdir -p /etc/crypto
+ head -c 255 /dev/urandom > /etc/crypto/smart.key
+ chown -R root /etc/crypto
+ chgrp -R root /etc/crypto
+ chmod -R 600 /etc/crypto
+ echo "$(zenity --entry --hide-text --title="LUKS Password" --text="Please enter the LUKS password for $CRYPTPARTITION")" > $SECURE_DIRECTORY/lukspass
+ cat $SECURE_DIRECTORY/lukspass | cryptsetup luksAddKey $CRYPTPARTITION /etc/crypto/smart.key
+ rm $SECURE_DIRECTORY/lukspass
+ correct=$?
+ if [[ correct -eq 0 ]] ; then
+ echo "OK!"
+ OLDCRYPTLINE=$(cat /etc/crypttab | grep $ROOTPARTITION)
+ NEWCRYPTLINE="$ROOTPARTITION $CRYPTPARTITION smart.key luks,keyscript=/usr/bin/cryptosmartcard.sh"
+ sed -i "s#${OLDCRYPTLINE}#${NEWCRYPTLINE}#g" /etc/crypttab
+ echo "Crypttab updated"
+ cp -Rp /etc/smartauth/smartauth.sh.in /usr/bin/smartauth.sh
+ OLDKEY="<your key in hexidecimal>"
+ authenticatecard "AUT3"
+ if [[ $authenticated = "1" ]]; then
+ NEWKEY=$autkey
+ echo $NEWKEY > /etc/smartauth/smartauth.key
+ sed -i "s#${OLDKEY}#${NEWKEY}#g" /usr/bin/smartauth.sh
+ chmod 600 /usr/bin/smartauth.sh
+ chmod a+x /usr/bin/smartauth.sh
+ echo "Updating initramfs"
+ update-initramfs -u all
+ echo "Securing directories..."
+ chmod 600 "/boot/initrd.img-$(uname -r)"
+ chmod -R 600 /etc/smartauth
+ else
+ rm -rf /etc/crypto/smart.key
+ rm -rf /usr/share/initramfs-tools/hooks/cryptlukssc
+ rm -f /usr/bin/smartauth.sh
+ fi
+ else
+ echo "LUKS add key failed!"
+ zenity --error --text "Failed to add LUKS key!\nReverting all changes..."
+ rm -rf /etc/crypto/smart.key
+ rm -rf /usr/share/initramfs-tools/hooks/cryptlukssc
+ fi
+ fi
+ else
+ zenity --error --text "Either I am unable to properly detect your encrypted partition,\nor your hard disk is not encrypted.\nNo changes to your system have been made."
+ fi
+ else
+ zenity --error --text "I am unable to properly detect your root partition.\nNo changes to your system have been made."
+ fi
+}
+
+function importlukskey {
+ ROOTPARTITION=$(mount | grep 'on / ' | getcolumn 0)
+ if [ -e $ROOTPARTITION ]; then
+ ROOTPARTITION=$(echo $ROOTPARTITION | sed 's/\/dev\/mapper\///')
+ CRYPTPARTITION=$(cat /etc/crypttab | grep $ROOTPARTITION | getcolumn 1)
+ if [ -e $CRYPTPARTITION ]; then
+ zenity --question --ok-label="Yes" --cancel-label="No" --text="I have detected that $ROOTPARTITION is your root partition, \nand therefore $CRYPTPARTITION is your encrypted root partition. \nIs this correct?"
+ correct=$?
+ if [[ correct -eq 0 ]] ; then
+ echo "Confirmed--proceeding"
+ FILE=$(zenity --file-selection --title="Select the new LUKS encryption key file")
+ case $? in
+ 0)
+ continueluksupdate=1;;
+ 1)
+ continueluksupdate=0;;
+ -1)
+ continueluksupdate=0;;
+ esac
+ if [[ $continueluksupdate -eq 1 ]]; then
+ echo "File selected--proceeding"
+ insertnewtext dm_mod /etc/initramfs-tools/modules
+ insertnewtext dm_crypt /etc/initramfs-tools/modules
+ insertnewtext aes_x86_64 /etc/initramfs-tools/modules
+ insertnewtext sha256 /etc/initramfs-tools/modules
+ insertnewtext vfat /etc/initramfs-tools/modules
+ insertnewtext fat /etc/initramfs-tools/modules
+ insertnewtext nls_cp437 /etc/initramfs-tools/modules
+ insertnewtext nls_iso8859_1 /etc/initramfs-tools/modules
+ insertnewtext hci_usb /etc/initramfs-tools/modules
+ insertnewtext usb_storage /etc/initramfs-tools/modules
+ insertnewtext libusual /etc/initramfs-tools/modules
+ insertnewtext ehci_hcd /etc/initramfs-tools/modules
+ insertnewtext uhci_hcd /etc/initramfs-tools/modules
+ insertnewtext usbcore /etc/initramfs-tools/modules
+ insertnewtext ext2 /etc/initramfs-tools/modules
+ insertnewtext reiserfs /etc/initramfs-tools/modules
+ echo "/etc/initramfs-tools/modules updated"
+ mkdir -p /etc/crypto
+ cp -Rp $FILE /etc/crypto/smart.key
+ chown -R root /etc/crypto
+ chgrp -R root /etc/crypto
+ chmod -R 600 /etc/crypto
+ echo "$(zenity --entry --hide-text --title="LUKS Password" --text="Please enter the LUKS password for $CRYPTPARTITION")" > $SECURE_DIRECTORY/lukspass
+ cat $SECURE_DIRECTORY/lukspass | cryptsetup luksAddKey $CRYPTPARTITION /etc/crypto/smart.key
+ rm $SECURE_DIRECTORY/lukspass
+ correct=$?
+ if [[ correct -eq 0 ]] ; then
+ echo "OK!"
+ OLDCRYPTLINE=$(cat /etc/crypttab | grep $ROOTPARTITION)
+ NEWCRYPTLINE="$ROOTPARTITION $CRYPTPARTITION smart.key luks,keyscript=/usr/bin/cryptosmartcard.sh"
+ sed -i "s#${OLDCRYPTLINE}#${NEWCRYPTLINE}#g" /etc/crypttab
+ echo "Crypttab updated"
+ cp -Rp /etc/smartauth/smartauth.sh.in /usr/bin/smartauth.sh
+ OLDKEY="<your key in hexidecimal>"
+ authenticatecard "AUT3"
+ if [[ $authenticated = "1" ]]; then
+ NEWKEY=$autkey
+ echo $NEWKEY > /etc/smartauth/smartauth.key
+ sed -i "s#${OLDKEY}#${NEWKEY}#g" /usr/bin/smartauth.sh
+ chmod 600 /usr/bin/smartauth.sh
+ chmod a+x /usr/bin/smartauth.sh
+ echo "Updating initramfs"
+ update-initramfs -u all
+ echo "Securing directories..."
+ chmod 600 "/boot/initrd.img-$(uname -r)"
+ chmod -R 600 /etc/smartauth
+ else
+ rm -rf /etc/crypto/smart.key
+ rm -rf /usr/share/initramfs-tools/hooks/cryptlukssc
+ rm -f /usr/bin/smartauth.sh
+ fi
+ else
+ echo "LUKS add key failed!"
+ zenity --error --text "Failed to add LUKS key!\nReverting all changes..."
+ rm -rf /etc/crypto/smart.key
+ rm -rf /usr/share/initramfs-tools/hooks/cryptlukssc
+ fi
+ else
+ zenity --error --text "No changes to your system have been made."
+ fi
+ fi
+ else
+ zenity --error --text "Either I am unable to properly detect your encrypted partition,\nor your hard disk is not encrypted.\nNo changes to your system have been made."
+ fi
+ else
+ zenity --error --text "I am unable to properly detect your root partition.\nNo changes to your system have been made."
+ fi
+}
+
+function loadlukskey {
+ echo "Loading LUKS key..."
+ authenticatecard "AUT1"
+ if [[ $authenticated = "1" ]]; then
+ update_file "10 01" "/etc/crypto/smart.key"
+ fi
+}
+
+function loadusername {
+ echo "Loading username..."
+ authenticatecard "AUT1"
+ if [[ $authenticated = "1" ]]; then
+ zenity --entry --title="SmartCard Username" --text="Please enter the username of the account to be associated with this SmartCard" > $SECURE_DIRECTORY/username
+ update_file "10 02" "$SECURE_DIRECTORY/username"
+ rm -f $SECURE_DIRECTORY/username
+ fi
+}
+
+function loadpassword {
+ echo "Loading password..."
+ authenticatecard "AUT1"
+ if [[ $authenticated = "1" ]]; then
+ zenity --entry --hide-text --title="SmartCard Password" --text="Please enter the password of the account that is associated with this SmartCard" > $SECURE_DIRECTORY/password
+ update_file "10 03" "$SECURE_DIRECTORY/password"
+ rm -f $SECURE_DIRECTORY/password
+ fi
+}
+
+GREETER="Welcome to the SmartCard authentication setup utility!\n\nAUT1 is the manual update key\nAUT2 is the login key\nAUT3 is the LUKS decrypt key\n\nCard ATR: $smartatr\nDetected: $CARD_NICE_NAME\n\nPlease select an action from the list below:"
+
+while [[ 1 -eq 1 ]]; do
+ if [ -e "/usr/bin/smartauthmon.sh" ]; then
+ LOGINOPTION="Disable automatic login for KDE3.5"
+ else
+ LOGINOPTION="Enable automatic login for KDE3.5"
+ fi
+
+ if [[ $COMMAND_MODE == "acos" ]]; then
+ ACOS_INIT_OPTION="FALSE Initialize-blank-ACOS"
+
+ # See if the card has an MF yet
+ # Select MF
+ echo "00 A4 00 00 00" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+ authokresponse="< 61 "
+ response1=$(cat $SECURE_DIRECTORY/response2 | grep "$authokresponse")
+ echo $response1
+ if [[ $response1 != "" ]]; then
+ echo "MF exists, checking for DF 1000"
+ # MF exists, check for DF 1000
+ echo "00 A4 00 00 02 10 00" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+ authokresponse="< 61 "
+ response1=$(cat $SECURE_DIRECTORY/response2 | grep "$authokresponse")
+ echo $response1
+ if [[ $response1 != "" ]]; then
+ echo "DF 1000 exists, this card was already initialized!"
+ ACOS_INIT_OPTION=""
+ fi
+ fi
+ fi
+
+ if [[ $COMMAND_MODE == "cryptoflex" ]]; then
+ ACOS_INIT_OPTION=""
+ fi
+
+ if [[ $# -eq 0 ]]; then
+ if [ -e "/etc/crypto/smart.key" ]; then
+ selection=$(zenity --width=400 --height=550 --list --radiolist --title="SmartCard Authentication Setup" \
+ --text="$GREETER" \
+ --column="" --column="Action" \
+ TRUE "Update LUKS Initramfs Transport Key [AUT3]" \
+ FALSE "Import LUKS encryption key from file to system" \
+ FALSE "Get LUKS encryption key from Smart Card [File 1001]" \
+ FALSE "Load LUKS encryption key into Smart Card [File 1001]" \
+ FALSE "Load username into Smart Card [File 1002]" \
+ FALSE "Load password into Smart Card [File 1003]" \
+ FALSE "Update Smart Card Transport Keys [AUT1-AUT3]" \
+ FALSE "$LOGINOPTION" \
+ $ACOS_INIT_OPTION);
+ else
+ selection=$(zenity --width=400 --height=550 --list --radiolist --title="SmartCard Authentication Setup" \
+ --text="$GREETER" \
+ --column="" --column="Action" \
+ TRUE "First-Time Setup Wizard" \
+ FALSE "Create New LUKS Key" \
+ FALSE "Update LUKS Initramfs Transport Key [AUT3]" \
+ FALSE "Import LUKS encryption key from file to system" \
+ FALSE "Get LUKS encryption key from Smart Card [File 1001]" \
+ FALSE "Load LUKS encryption key into Smart Card [File 1001]" \
+ FALSE "Load username into Smart Card [File 1002]" \
+ FALSE "Load password into Smart Card [File 1003]" \
+ FALSE "Update Smart Card Transport Keys [AUT1-AUT3]" \
+ FALSE "$LOGINOPTION" \
+ $ACOS_INIT_OPTION);
+ fi
+ else
+ if [[ $1 = "upgrade" ]]; then
+ echo "Upgrade mode"
+ if [ -e "/etc/smartauth/smartauth.key" ]; then
+ OLDKEY="<your key in hexidecimal>"
+ NEWKEY=$(cat /etc/smartauth/smartauth.key)
+ cp -Rp /etc/smartauth/smartauth.sh.in /usr/bin/smartauth.sh
+ sed -i "s#${OLDKEY}#${NEWKEY}#g" /usr/bin/smartauth.sh
+ chmod 600 /usr/bin/smartauth.sh
+ chmod a+x /usr/bin/smartauth.sh
+ echo "Updating initramfs"
+ update-initramfs -u all
+ echo "Securing directories..."
+ chmod 600 "/boot/initrd.img-$(uname -r)"
+ chmod -R 600 /etc/smartauth
+ fi
+
+ if [ -e "/etc/smartauth/smartauthmon.key" ]; then
+ OLDKEY="<your key in hexadecimal>"
+ NEWKEY=$(cat /etc/smartauth/smartauthmon.key)
+ cp -Rp /etc/smartauth/smartauthmon.sh.in /usr/bin/smartauthmon.sh
+ sed -i "s#${OLDKEY}#${NEWKEY}#g" /usr/bin/smartauthmon.sh
+ chmod 600 /usr/bin/smartauthmon.sh
+ chmod a+x /usr/bin/smartauthmon.sh
+ fi
+ fi
+ fi
+
+ if [[ $selection = "Import LUKS encryption key from file to system" ]]; then
+ importlukskey
+ fi
+
+ if [[ $selection = "First-Time Setup Wizard" ]]; then
+ echo "Running first-time setup wizard..."
+ zenity --info --text "This setup wizard will prepare your encrypted computer for automatic LUKS unlock and login via SmartCard"
+ createlukskey
+ if [[ $authenticated = "1" ]]; then
+ loadlukskey
+ loadusername
+ loadpassword
+ fi
+ fi
+
+ if [[ $selection = "Create New LUKS Key" ]]; then
+ echo "Creating new LUKS key..."
+ createlukskey
+ fi
+
+ if [[ $selection = "Get LUKS encryption key from Smart Card [File 1001]" ]]; then
+ echo "Getting LUKS key..."
+ authenticatecard "AUT1"
+ if [[ $authenticated = "1" ]]; then
+ get_file "10 01"
+ zenity --info --text "LUKS key is currently in file:\n$RESPONSE\n\nThis file will be deleted upon completion of this script."
+ fi
+ fi
+
+ if [[ $selection = "Load LUKS encryption key into Smart Card [File 1001]" ]]; then
+ loadlukskey
+ fi
+
+ if [[ $selection = "Load username into Smart Card [File 1002]" ]]; then
+ loadusername
+ fi
+
+ if [[ $selection = "Load password into Smart Card [File 1003]" ]]; then
+ loadpassword
+ fi
+
+ if [[ $selection = "Update LUKS Initramfs Transport Key [AUT3]" ]]; then
+ cp -Rp /etc/smartauth/smartauth.sh.in /usr/bin/smartauth.sh
+ OLDKEY="<your key in hexidecimal>"
+ authenticatecard "AUT3"
+ if [[ $authenticated = "1" ]]; then
+ NEWKEY=$autkey
+ echo $NEWKEY > /etc/smartauth/smartauth.key
+ sed -i "s#${OLDKEY}#${NEWKEY}#g" /usr/bin/smartauth.sh
+ chmod 600 /usr/bin/smartauth.sh
+ chmod a+x /usr/bin/smartauth.sh
+ echo "Updating initramfs"
+ update-initramfs -u all
+ echo "Securing directories..."
+ chmod 600 "/boot/initrd.img-$(uname -r)"
+ chmod -R 600 /etc/smartauth
+ if [ -e "/usr/bin/smartauthmon.sh" ]; then
+ echo "KDE3.5 login disabled; not altering"
+ else
+ selection="Enable automatic login for KDE3.5"
+ fi
+ else
+ zenity --error --text "A SmartCard authentication error has occurred.\nNo changes have been made to your system."
+ fi
+ fi
+
+ if [[ $selection = "Update Smart Card Transport Keys [AUT1-AUT3]" ]]; then
+ echo "Updating AUT1..."
+ authenticatecard "AUT1"
+ if [[ $authenticated = "1" ]]; then
+ if [[ $COMMAND_MODE == "acos" ]]; then
+ # Select EF 10FD under DF 1000
+ echo "$SELECT_FILE 10 FD" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+
+ # Initialize key records in file 10FD
+ # Key 1, 8-byte 1DES authentication only
+ autkey=""
+ while [[ ${#autkey} != 16 ]]; do
+ autkey=$(zenity --entry --hide-text --title="SmartCard Transport Key" --text="Please enter the new 16-character Smart Card transport key [AUT1] in hexidecimal. Example: 0123456789abcdef")
+ done
+ autkey2=${autkey:0:2}
+ autkey2="${autkey2} ${autkey:2:2}"
+ autkey2="${autkey2} ${autkey:4:2}"
+ autkey2="${autkey2} ${autkey:6:2}"
+ autkey2="${autkey2} ${autkey:8:2}"
+ autkey2="${autkey2} ${autkey:10:2}"
+ autkey2="${autkey2} ${autkey:12:2}"
+ autkey2="${autkey2} ${autkey:14:2}"
+ echo "00 DC 00 00 0C 81 01 55 05 $autkey2" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+ # Key 2, 8-byte 1DES authentication only
+ autkey=""
+ while [[ ${#autkey} != 16 ]]; do
+ autkey=$(zenity --entry --hide-text --title="SmartCard Transport Key" --text="Please enter the new 16-character Smart Card transport key [AUT2] in hexidecimal. Example: 0123456789abcdef")
+ done
+ autkey2=${autkey:0:2}
+ autkey2="${autkey2} ${autkey:2:2}"
+ autkey2="${autkey2} ${autkey:4:2}"
+ autkey2="${autkey2} ${autkey:6:2}"
+ autkey2="${autkey2} ${autkey:8:2}"
+ autkey2="${autkey2} ${autkey:10:2}"
+ autkey2="${autkey2} ${autkey:12:2}"
+ autkey2="${autkey2} ${autkey:14:2}"
+ echo "00 DC 00 02 0C 82 01 55 05 $autkey2" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+ # Key 3, 8-byte 1DES authentication only
+ autkey=""
+ while [[ ${#autkey} != 16 ]]; do
+ autkey=$(zenity --entry --hide-text --title="SmartCard Transport Key" --text="Please enter the new 16-character Smart Card transport key [AUT3] in hexidecimal. Example: 0123456789abcdef")
+ done
+ autkey2=${autkey:0:2}
+ autkey2="${autkey2} ${autkey:2:2}"
+ autkey2="${autkey2} ${autkey:4:2}"
+ autkey2="${autkey2} ${autkey:6:2}"
+ autkey2="${autkey2} ${autkey:8:2}"
+ autkey2="${autkey2} ${autkey:10:2}"
+ autkey2="${autkey2} ${autkey:12:2}"
+ autkey2="${autkey2} ${autkey:14:2}"
+ echo "00 DC 00 02 0C 83 01 55 05 $autkey2" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+ fi
+
+ if [[ $COMMAND_MODE == "cryptoflex" ]]; then
+ autkey4=$(zenity --entry --hide-text --title="SmartCard Transport Key" --text="Please enter the new 16-character Smart Card transport key [AUT1] in hexidecimal. Example: 0123456789abcdef")
+ if [[ ${#autkey4} -eq 16 ]]; then
+ autkey2=${autkey4:0:2}
+ autkey2="${autkey2} ${autkey4:2:2}"
+ autkey2="${autkey2} ${autkey4:4:2}"
+ autkey2="${autkey2} ${autkey4:6:2}"
+ autkey2="${autkey2} ${autkey4:8:2}"
+ autkey2="${autkey2} ${autkey4:10:2}"
+ autkey2="${autkey2} ${autkey4:12:2}"
+ autkey2="${autkey2} ${autkey4:14:2}"
+ echo "Attempting Smart Card key update..."
+ updatekey ${autkey2}
+ autkey=$autkey4
+ if [[ $authenticated = "1" ]]; then
+ cp -Rp /etc/smartauth/smartauth.sh.in /usr/bin/smartauth.sh
+ OLDKEY="<your key in hexidecimal>"
+ authenticatecard "AUT3"
+ if [[ $authenticated = "1" ]]; then
+ NEWKEY=$autkey
+ echo $NEWKEY > /etc/smartauth/smartauth.key
+ sed -i "s#${OLDKEY}#${NEWKEY}#g" /usr/bin/smartauth.sh
+ chmod 600 /usr/bin/smartauth.sh
+ chmod a+x /usr/bin/smartauth.sh
+ echo "Updating initramfs"
+ update-initramfs -u all
+ echo "Securing directories..."
+ chmod 600 "/boot/initrd.img-$(uname -r)"
+ chmod -R 600 /etc/smartauth
+ if [ -e "/usr/bin/smartauthmon.sh" ]; then
+ selection="Enable automatic login for KDE3.5"
+ else
+ echo "KDE3.5 login disabled; not altering"
+ fi
+ else
+ zenity --error --text "A SmartCard authentication error has occurred."
+ fi
+ else
+ zenity --error --text "A SmartCard authentication error has occurred."
+ fi
+ else
+ echo "AUT1 key not 16 characters!"
+ zenity --error --text "The new transport key is invalid!"
+ fi
+ fi
+ fi
+ fi
+
+ if [[ $selection = "Enable automatic login for KDE3.5" ]]; then
+ cp -Rp /etc/smartauth/smartauthmon.sh.in /usr/bin/smartauthmon.sh
+ OLDKEY="<your key in hexadecimal>"
+ authenticatecard "AUT2"
+ if [[ $authenticated = "1" ]]; then
+ NEWKEY=$autkey
+ echo $NEWKEY > /etc/smartauth/smartauthmon.key
+ sed -i "s#${OLDKEY}#${NEWKEY}#g" /usr/bin/smartauthmon.sh
+ chmod 600 /usr/bin/smartauthmon.sh
+ chmod a+x /usr/bin/smartauthmon.sh
+ update-rc.d smartauthlogin defaults
+ /etc/init.d/smartauthlogin stop
+ /etc/init.d/smartauthlogin start
+ fi
+ fi
+
+ if [[ $selection = "Disable automatic login for KDE3.5" ]]; then
+ /etc/init.d/smartauthlogin stop
+ rm -rf /usr/bin/smartauthmon.sh
+ rm -rf /etc/smartauth/smartauthmon.key
+ update-rc.d -f smartauthlogin remove
+ fi
+
+ #if [[ $selection = "Initialize blank ACOS card" ]]; then
+ if [[ $selection = "Initialize-blank-ACOS" ]]; then
+ initializeacos
+ fi
+
+ if [[ $selection = "" ]]; then
+ echo "Exiting!"
+ rm -rf $SECURE_DIRECTORY
+ chmod -R 600 /etc/smartauth
+ chown -R root /etc/smartauth
+ chmod a+x /usr/bin/smartauth.sh
+ chmod a+x /usr/bin/smartauthmon.sh
+ chmod 600 "/boot/initrd.img-$(uname -r)"
+ chown root "/boot/initrd.img-$(uname -r)"
+ exit
+ fi
+done
diff --git a/usr/bin/setupslavecard.sh b/usr/bin/setupslavecard.sh
new file mode 100755
index 0000000..cdf3adf
--- /dev/null
+++ b/usr/bin/setupslavecard.sh
@@ -0,0 +1,502 @@
+#!/bin/bash
+
+# Smart Card Management Tool (c) 2009 Timothy Pearson
+#
+# 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 3 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, see <http://www.gnu.org/licenses/>.
+
+# The [secure] temporary directory for authentication
+SECURE_DIRECTORY=/tmp/smartauth
+
+# Create the secure directory and lock it down
+mkdir -p $SECURE_DIRECTORY
+chown root $SECURE_DIRECTORY
+chgrp root $SECURE_DIRECTORY
+chmod 600 $SECURE_DIRECTORY
+SECURE_DIRECTORY=$(mktemp /tmp/smartauth/setupcard.XXXXXXXXXX)
+rm -rf $SECURE_DIRECTORY
+mkdir -p $SECURE_DIRECTORY
+chown root $SECURE_DIRECTORY
+chgrp root $SECURE_DIRECTORY
+chmod 600 $SECURE_DIRECTORY
+
+# See if required programs are installed
+scriptor=$(whereis scriptor)
+if [[ $scriptor == "scriptor:" ]]; then
+ echo "ERROR: scriptor is not installed! This program cannot continue!"
+ zenity --error --text "ERROR: scriptor is not installed!\nThis program cannot continue!\n\nUsually, scriptor is part of the pcsc-tools package."
+ exit
+fi
+opensc=$(whereis opensc-explorer)
+if [[ $opensc == "opensc-explorer:" ]]; then
+ echo "ERROR: opensc-explorer is not installed! This program cannot continue!"
+ zenity --error --text "ERROR: opensc-explorer is not installed!\nThis program cannot continue!\n\nUsually, opensc-explorer is part of the opensc package."
+ exit
+fi
+
+# Get card ATR
+FOUND_SUPPORTED_CARD=0
+echo "RESET" > $SECURE_DIRECTORY/query
+scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+authokresponse="OK: "
+response1=$(cat $SECURE_DIRECTORY/response2 | grep "$authokresponse")
+if [[ $response1 != "" ]]; then
+ cat $SECURE_DIRECTORY/response2 | tr -d '\n' > $SECURE_DIRECTORY/response4
+ stringtoreplace="Using T=0 protocolRESET> RESET< OK: "
+ newstring=""
+ sed -i "s#${stringtoreplace}#${newstring}#g" $SECURE_DIRECTORY/response4
+ smartatr=$(cat $SECURE_DIRECTORY/response4)
+ echo "Got ATR: $smartatr"
+ if [[ $smartatr == "3B BE 18 00 00 41 05 10 00 00 00 00 00 00 00 00 00 90 00 " ]]; then
+ echo "Detected ACOS5 card"
+ COMMAND_MODE="acos"
+ CARD_NICE_NAME="ACOS5"
+ FOUND_SUPPORTED_CARD=1
+ fi
+ if [[ $smartatr == "3B 02 14 50 " ]]; then
+ echo "Detected Schlumberger CryptoFlex card"
+ COMMAND_MODE="cryptoflex"
+ CARD_NICE_NAME="Schlumberger CryptoFlex"
+ FOUND_SUPPORTED_CARD=1
+ fi
+else
+ echo "No card detected!"
+ zenity --error --text "ERROR: No SmartCard detected!"
+ exit 1
+fi
+
+if [[ $FOUND_SUPPORTED_CARD -eq 0 ]]; then
+ echo "Unsupported SmartCard detected! ATR: $smartatr"
+ zenity --error --text "ERROR: Unsupported SmartCard detected!\n\nATR: $smartatr"
+ exit 1
+fi
+
+
+if [[ $COMMAND_MODE == "cryptoflex" ]]; then
+ GET_CHALLENGE="C0 84 00 00 08"
+ EXTERNAL_AUTH="C0 82 00 00 07 01"
+ SELECT_FILE="C0 A4 00 00 02"
+ DELETE_FILE="F0 E4 00 00 02"
+fi
+
+if [[ $COMMAND_MODE == "acos" ]]; then
+ GET_CHALLENGE="00 84 00 00 08"
+ EXTERNAL_AUTH="00 82 00 81 08"
+ SELECT_FILE="00 A4 00 00 02"
+ DELETE_FILE="00 E4 00 00 00"
+ READ_BINARY="00 B0 00 00 FF"
+ UPDATE_BINARY="00 D6 00 00 FF"
+ ACTIVATE_FILE="00 44 00 00 02"
+fi
+
+CREATE_LIFE_CYCLE="01"
+
+createfile ()
+{
+ if [[ $COMMAND_MODE == "cryptoflex" ]]; then
+ # Create transparent file with permissions:
+ # delete, terminate, activate, deactivate, update, read for Key 1 and Key 2 only
+ echo "F0 E0 00 FF 10 FF FF 00 $1 $2 01 3F 44 FF 44 01 03 11 FF 11" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2 2>/dev/null
+ fi
+
+ if [[ $COMMAND_MODE == "acos" ]]; then
+ # Select MF
+ echo "00 A4 00 00 00" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+
+ # Select DF 1000 under MF
+ echo "$SELECT_FILE 10 00" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+ # Create transparent file with permissions:
+ # delete, terminate, activate, deactivate, update, read for Key 1, Key 2, and Key 3 only (SE 04)
+ # created in DF 1000 under MF, SE file is 10FE
+ # SIZE TRANSPARENT
+
+ echo "00 E0 00 00 1A 62 18 80 02 00 $1 82 01 01 83 02 $2 8A 01 $CREATE_LIFE_CYCLE 8C 08 7F 04 04 04 04 04 04 04" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2 2>/dev/null
+ echo $(cat $SECURE_DIRECTORY/response2)
+ fi
+}
+
+updatekey ()
+{
+ if [[ $COMMAND_MODE == "cryptoflex" ]]; then
+ echo "$SELECT_FILE 00 11" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2 2>/dev/null
+ echo "C0 D6 00 0D 0C 08 00 $1 05 05" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2 2>/dev/null
+ fi
+}
+
+hexcvt ()
+{
+ echo ""$1" "16" o p" | dc
+}
+
+authenticatecard () {
+ if [[ $authenticated != "1" ]]; then
+ if [[ -e /etc/smartauth/slave.key ]]; then
+ autkey=$(cat /etc/smartauth/slave.key)
+ else
+ autkey=$(zenity --entry --hide-text --title="SmartCard Transport Key" --text="Please enter the 16-character Smart Card transport key [AUT1] in hexidecimal. Example: 0123456789abcdef")
+ fi
+ if [[ ${#autkey} -eq 16 ]]; then
+ if [[ $COMMAND_MODE == "acos" ]]; then
+ # Select MF
+ echo "00 A4 00 00 00" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+ # Make sure DF 1000 is selected
+ echo "$SELECT_FILE 10 00" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+ fi
+
+ # Authenticate card
+ echo $GET_CHALLENGE > $SECURE_DIRECTORY/authscript
+
+ scriptor $SECURE_DIRECTORY/authscript | grep 'Normal processing' > $SECURE_DIRECTORY/challenge
+ perl -pi -e 's/ //g' $SECURE_DIRECTORY/challenge
+ perl -pi -e 's/:Normalprocessing.//g' $SECURE_DIRECTORY/challenge
+ perl -pi -e 's/<//g' $SECURE_DIRECTORY/challenge
+ xxd -r -p $SECURE_DIRECTORY/challenge $SECURE_DIRECTORY/challenge
+
+ # Now DES encrypt the challenge
+ # Later, change the initialization vector to random if possible
+ openssl des-ecb -in $SECURE_DIRECTORY/challenge -out $SECURE_DIRECTORY/response -K $autkey -iv 1
+
+ if [[ $COMMAND_MODE == "acos" ]]; then
+ # Truncate to 8 bytes
+ dd if=$SECURE_DIRECTORY/response of=$SECURE_DIRECTORY/response2 bs=1 count=8
+
+ # Expand to standard hex listing format
+ xxd -g 1 $SECURE_DIRECTORY/response2 $SECURE_DIRECTORY/response
+ dd if=$SECURE_DIRECTORY/response of=$SECURE_DIRECTORY/response2 bs=1 count=23 skip=9
+ fi
+
+ if [[ $COMMAND_MODE == "cryptoflex" ]]; then
+ # Truncate to 6 bytes
+ dd if=$SECURE_DIRECTORY/response of=$SECURE_DIRECTORY/response2 bs=1 count=6
+
+ # Expand to standard hex listing format
+ xxd -g 1 $SECURE_DIRECTORY/response2 $SECURE_DIRECTORY/response
+ dd if=$SECURE_DIRECTORY/response of=$SECURE_DIRECTORY/response2 bs=1 count=17 skip=9
+ fi
+
+ # Assemble the response file
+ response2=$(cat $SECURE_DIRECTORY/response2)
+ response1="$EXTERNAL_AUTH ${response2}"
+ echo $response1 > $SECURE_DIRECTORY/response
+
+ # Send the response!
+ scriptor $SECURE_DIRECTORY/response > $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+
+ # Get the result
+ authokresponse="< 90 00 : Normal processing"
+ response1=$(cat $SECURE_DIRECTORY/response2 | grep "$authokresponse")
+ echo $response1
+ if [[ $response1 != "" ]]; then
+ echo "Smart card validation successfull!"
+ echo "Smart card login successfull!"
+ echo $autkey > /etc/smartauth/slave.key
+ authenticated="1"
+ else
+ echo "Login failed"
+ if [[ -e /etc/smartauth/slave.key ]]; then
+ rm -f /etc/smartauth/slave.key
+ authenticatecard
+ else
+ zenity --error --text "That transport key is incorrect!\n\nPlease remember that there are a limited number\nof failed login attempts for this key,\nafter which your SmartCard will become useless."
+ fi
+ fi
+ else
+ echo "AUT1 key not 16 characters!"
+ zenity --error --text "That transport key is invalid!"
+ fi
+ fi
+}
+
+get_file () {
+ if [[ $COMMAND_MODE == "acos" ]]; then
+ # Select EF $1 under DF 1000
+ echo "$SELECT_FILE $1" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+
+ # Read binary
+ echo "$READ_BINARY" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ authokresponse="90 00 : Normal processing"
+ response1=$(cat $SECURE_DIRECTORY/response2 | grep "$authokresponse")
+ if [[ $response1 != "" ]]; then
+ cat $SECURE_DIRECTORY/response2 | tr -d '\n' > $SECURE_DIRECTORY/response4
+ stringtoreplace="Using T=0 protocol00 B0 00 00 FF> 00 B0 00 00 FF< "
+ newstring=""
+ sed -i "s#${stringtoreplace}#${newstring}#g" $SECURE_DIRECTORY/response4
+ stringtoreplace=" 90 00 : Normal processing."
+ newstring=""
+ sed -i "s#${stringtoreplace}#${newstring}#g" $SECURE_DIRECTORY/response4
+ if [[ $2 == "text" ]]; then
+ stringtoreplace=" 00"
+ newstring=""
+ sed -i "s#${stringtoreplace}#${newstring}#g" $SECURE_DIRECTORY/response4
+ fi
+ echo $(cat $SECURE_DIRECTORY/response4)
+ rm -f $SECURE_DIRECTORY/lukskey
+ xxd -r -p $SECURE_DIRECTORY/response4 $SECURE_DIRECTORY/lukskey
+ RESPONSE=$SECURE_DIRECTORY/lukskey
+ fi
+ fi
+
+ if [[ $COMMAND_MODE == "cryptoflex" ]]; then
+ FILE=${1/ /}
+ echo "get $FILE" | opensc-explorer
+ RESPONSE="3F00_$FILE"
+ fi
+}
+
+update_file () {
+ if [[ $COMMAND_MODE == "acos" ]]; then
+ # Select EF $1 under DF 1000
+ echo "$SELECT_FILE $1" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+
+ # Update existing file
+ # Zero pad input file
+ dd if=/dev/zero of=$SECURE_DIRECTORY/response2 bs=1 count=255
+ dd if=$2 of=$SECURE_DIRECTORY/response2 bs=1 count=255 conv=notrunc
+
+ # Truncate to 255 bytes and expand to standard hex listing format
+ xxd -l 255 -ps -c 1 $SECURE_DIRECTORY/response2 > $SECURE_DIRECTORY/response
+ cat $SECURE_DIRECTORY/response | tr '\n' ' ' > $SECURE_DIRECTORY/hexready
+ echo "$UPDATE_BINARY $(cat $SECURE_DIRECTORY/hexready)" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2 2>/dev/null
+ echo $(cat $SECURE_DIRECTORY/response2)
+ fi
+
+ if [[ $COMMAND_MODE == "cryptoflex" ]]; then
+ # Delete old file
+ echo "$DELETE_FILE $1" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2 2>/dev/null
+ echo $(cat $SECURE_DIRECTORY/response2)
+
+ # Create new file
+ createfile "FF" $1
+ FILE=${1/ /}
+ echo "put $FILE $2" | opensc-explorer
+ fi
+}
+
+insertnewtext () {
+ FOUNDTEXT=$(cat $2 | grep $1)
+ echo $FOUNDTEXT;
+ if [[ $FOUNDTEXT != "" ]]; then
+ echo "$1 already exists in $2"
+ else
+ echo $1 >> $2
+ fi
+}
+
+getcolumn () {
+ perl -ne '@cols = split; print "$cols['$1']\n"' ;
+}
+
+function loadusername {
+ echo "Loading username..."
+ authenticatecard
+ if [[ $authenticated = "1" ]]; then
+ zenity --entry --title="SmartCard Username" --text="Please enter the username of the account to be associated with this SmartCard" > $SECURE_DIRECTORY/username
+ update_file "10 02" "$SECURE_DIRECTORY/username"
+ rm -f $SECURE_DIRECTORY/username
+ fi
+}
+
+function loadpassword {
+ echo "Loading password..."
+ authenticatecard
+ if [[ $authenticated = "1" ]]; then
+ zenity --entry --hide-text --title="SmartCard Password" --text="Please enter the password of the account that is associated with this SmartCard" > $SECURE_DIRECTORY/password
+ update_file "10 03" "$SECURE_DIRECTORY/password"
+ rm -f $SECURE_DIRECTORY/password
+ fi
+}
+
+function loadminutes {
+ echo "Loading minutes..."
+ authenticatecard
+ if [[ $authenticated = "1" ]]; then
+ echo "$(zenity --entry --hide-text --title="SmartCard Computer Minutes" --text="Please enter the number of computer minutes for this SmartCard")" > $SECURE_DIRECTORY/password
+ update_file "10 05" "$SECURE_DIRECTORY/password"
+ rm -f $SECURE_DIRECTORY/password
+ fi
+}
+
+function enablerestrictedmode {
+ echo "Enabling restricted mode..."
+ authenticatecard
+ if [[ $authenticated = "1" ]]; then
+ echo "SLAVE" > $SECURE_DIRECTORY/password
+ update_file "10 04" "$SECURE_DIRECTORY/password"
+ rm -f $SECURE_DIRECTORY/password
+ fi
+}
+
+function disablerestrictedmode {
+ echo "Disabling restricted mode..."
+ authenticatecard
+ if [[ $authenticated = "1" ]]; then
+ echo "NORMAL" > $SECURE_DIRECTORY/password
+ update_file "10 04" "$SECURE_DIRECTORY/password"
+ rm -f $SECURE_DIRECTORY/password
+ fi
+}
+
+GREETER="Welcome to the SmartCard slave authentication setup utility!\n\nCard ATR: $smartatr\nDetected: $CARD_NICE_NAME\n\nPlease select an action from the list below:"
+
+while [[ 1 -eq 1 ]]; do
+ if [[ $# -eq 0 ]]; then
+ selection=$(zenity --width=400 --height=400 --list --radiolist --title="SmartCard Authentication Setup" \
+ --text="$GREETER" \
+ --column="" --column="Action" \
+ TRUE "Load Computer Minutes into Smart Card [File 1005]" \
+ FALSE "Enable Restricted Mode [File 1004]" \
+ FALSE "Disable Restricted Mode [File 1004]" \
+ FALSE "Load username into Smart Card [File 1002]" \
+ FALSE "Load password into Smart Card [File 1003]" \
+ FALSE "Update Smart Card Transport Key [AUT1]");
+ fi
+
+ if [[ $selection = "Load username into Smart Card [File 1002]" ]]; then
+ loadusername
+ fi
+
+ if [[ $selection = "Load password into Smart Card [File 1003]" ]]; then
+ loadpassword
+ fi
+
+ if [[ $selection = "Load Computer Minutes into Smart Card [File 1005]" ]]; then
+ loadminutes
+ fi
+
+ if [[ $selection = "Enable Restricted Mode [File 1004]" ]]; then
+ enablerestrictedmode
+ fi
+
+ if [[ $selection = "Disable Restricted Mode [File 1004]" ]]; then
+ disablerestrictedmode
+ fi
+
+ if [[ $selection = "Update Smart Card Transport Key [AUT1]" ]]; then
+ echo "Updating AUT1..."
+ authenticatecard
+ if [[ $authenticated = "1" ]]; then
+ if [[ $COMMAND_MODE == "acos" ]]; then
+ # Select MF
+ echo "00 A4 00 00 00" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+
+ # Select DF 1000 under MF
+ echo "$SELECT_FILE 10 00" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+
+ # Select EF 10FD under DF 1000
+ echo "$SELECT_FILE 10 FD" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+
+ # Initialize first key record in file 10FD
+ # Key 1, 8-byte 1DES authentication only
+ autkey=""
+ while [[ ${#autkey} != 16 ]]; do
+ autkey=$(zenity --entry --hide-text --title="SmartCard Transport Key" --text="Please enter the new 16-character Smart Card transport key [AUT1] in hexidecimal. Example: 0123456789abcdef")
+ done
+ autkey2=${autkey:0:2}
+ autkey2="${autkey2} ${autkey:2:2}"
+ autkey2="${autkey2} ${autkey:4:2}"
+ autkey2="${autkey2} ${autkey:6:2}"
+ autkey2="${autkey2} ${autkey:8:2}"
+ autkey2="${autkey2} ${autkey:10:2}"
+ autkey2="${autkey2} ${autkey:12:2}"
+ autkey2="${autkey2} ${autkey:14:2}"
+ echo "00 DC 00 00 0C 81 01 55 05 $autkey2" > $SECURE_DIRECTORY/query
+ scriptor $SECURE_DIRECTORY/query 1> $SECURE_DIRECTORY/response2
+ echo $(cat $SECURE_DIRECTORY/response2)
+ fi
+
+ if [[ $COMMAND_MODE == "cryptoflex" ]]; then
+ autkey4=$(zenity --entry --hide-text --title="SmartCard Transport Key" --text="Please enter the new 16-character Smart Card transport key [AUT1] in hexidecimal. Example: 0123456789abcdef")
+ if [[ ${#autkey4} -eq 16 ]]; then
+ autkey2=${autkey4:0:2}
+ autkey2="${autkey2} ${autkey4:2:2}"
+ autkey2="${autkey2} ${autkey4:4:2}"
+ autkey2="${autkey2} ${autkey4:6:2}"
+ autkey2="${autkey2} ${autkey4:8:2}"
+ autkey2="${autkey2} ${autkey4:10:2}"
+ autkey2="${autkey2} ${autkey4:12:2}"
+ autkey2="${autkey2} ${autkey4:14:2}"
+ echo "Attempting Smart Card key update..."
+ updatekey ${autkey2}
+ autkey=$autkey4
+ if [[ $authenticated = "1" ]]; then
+ cp -Rp /etc/smartauth/smartauth.sh.in /usr/bin/smartauth.sh
+ OLDKEY="<your key in hexidecimal>"
+ authenticatecard
+ if [[ $authenticated = "1" ]]; then
+ NEWKEY=$autkey
+ echo $NEWKEY > /etc/smartauth/smartauth.key
+ sed -i "s#${OLDKEY}#${NEWKEY}#g" /usr/bin/smartauth.sh
+ chmod 600 /usr/bin/smartauth.sh
+ chmod a+x /usr/bin/smartauth.sh
+ echo "Updating initramfs"
+ update-initramfs -u all
+ echo "Securing directories..."
+ chmod 600 "/boot/initrd.img-$(uname -r)"
+ chmod -R 600 /etc/smartauth
+ if [ -e "/usr/bin/smartauthmon.sh" ]; then
+ selection="Enable automatic login for KDE3.5"
+ else
+ echo "KDE3.5 login disabled; not altering"
+ fi
+ else
+ zenity --error --text "A SmartCard authentication error has occurred."
+ fi
+ else
+ zenity --error --text "A SmartCard authentication error has occurred."
+ fi
+ else
+ echo "AUT1 key not 16 characters!"
+ zenity --error --text "The new transport key is invalid!"
+ fi
+ fi
+ fi
+ fi
+
+ if [[ $selection = "" ]]; then
+ echo "Exiting!"
+ rm -rf $SECURE_DIRECTORY
+ chmod -R 600 /etc/smartauth
+ chown -R root /etc/smartauth
+ chmod a+x /usr/bin/smartauth.sh
+ chmod a+x /usr/bin/smartauthmon.sh
+ chmod 600 "/boot/initrd.img-$(uname -r)"
+ chown root "/boot/initrd.img-$(uname -r)"
+ exit
+ fi
+done
diff --git a/usr/bin/smartauth.sh b/usr/bin/smartauth.sh
new file mode 100644
index 0000000..d0ab03a
--- /dev/null
+++ b/usr/bin/smartauth.sh
@@ -0,0 +1,74 @@
+#!/bin/sh
+
+# Smart Card Authentication Helper (c) 2008 Timothy Pearson
+#
+# 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 3 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, see <http://www.gnu.org/licenses/>.
+
+
+authscript="C0 84 00 00 08"
+echo $authscript > authscript
+
+scriptor_standalone authscript | grep 'Normal processing' > challenge
+perl -pi -e 's/ //g' challenge
+perl -pi -e 's/:Normalprocessing.//g' challenge
+perl -pi -e 's/<//g' challenge
+xxd -r -p challenge challenge
+
+# Now DES encrypt the challenge
+openssl des-ecb -in challenge -out response -K 0000000000000000 -iv 1
+
+# Truncate to 6 bytes
+dd if=response of=response2 bs=1 count=6
+
+# Expand to standard hex listing format
+xxd -g 1 response2 response
+dd if=response of=response2 bs=1 count=17 skip=9
+
+# Assemble the response file
+response2=$(cat response2)
+response1="C0 82 00 00 07 01 ${response2}"
+echo $response1 > response
+
+# Send the response!
+scriptor_standalone response > response2
+
+# Get the result
+dd if=response2 of=response bs=1 count=5 skip=95
+perl -pi -e 's/ //g' response
+response1=$(cat response)
+authokresponse="9000"
+if [ "$response1" = "$authokresponse" ]; then
+ echo "Smart card validation successfull!"
+ # Get encryption key
+ authscript="C0 A4 00 00 02 10 01"
+ echo $authscript > authscript
+ scriptor_standalone authscript
+ #authscript="C0 B0 00 00 00"
+ authscript=""
+ echo $authscript > authscript
+ scriptor_standalone authscript > smart
+ mkdir smartcard
+ cd smartcard
+ echo "get 1001" | opensc-explorer
+ cd ..
+ rm smart
+ mv smartcard/*_1001 smart.key
+else
+ echo "Authentication failed!"
+fi
+
+rm authscript &
+rm response &
+rm response2 &
+rm challenge &
diff --git a/usr/share/applications/smartcardauth.desktop b/usr/share/applications/smartcardauth.desktop
new file mode 100644
index 0000000..a033a89
--- /dev/null
+++ b/usr/share/applications/smartcardauth.desktop
@@ -0,0 +1,10 @@
+[Desktop Entry]
+Type=Application
+Exec=gksudo /usr/bin/setupcard.sh
+Icon=smartcardauth
+Terminal=false
+X-KDE-StartupNotify=true
+
+Name=SmartCard Authentication Setup
+GenericName=SmartCard Authentication Setup
+Categories=KDE;System;
diff --git a/usr/share/applications/smartcardrestrict.desktop b/usr/share/applications/smartcardrestrict.desktop
new file mode 100644
index 0000000..7dfdc79
--- /dev/null
+++ b/usr/share/applications/smartcardrestrict.desktop
@@ -0,0 +1,10 @@
+[Desktop Entry]
+Type=Application
+Exec=gksudo /usr/bin/setupslavecard.sh
+Icon=smartcardauth
+Terminal=false
+X-KDE-StartupNotify=true
+
+Name=SmartCard Restriction Setup
+GenericName=SmartCard Restriction Setup
+Categories=KDE;System;
diff --git a/usr/share/icons/hicolor/16x16/apps/smartcardauth.png b/usr/share/icons/hicolor/16x16/apps/smartcardauth.png
new file mode 100644
index 0000000..ffb6269
--- /dev/null
+++ b/usr/share/icons/hicolor/16x16/apps/smartcardauth.png
Binary files differ
diff --git a/usr/share/icons/hicolor/32x32/apps/smartcardauth.png b/usr/share/icons/hicolor/32x32/apps/smartcardauth.png
new file mode 100644
index 0000000..1b68a02
--- /dev/null
+++ b/usr/share/icons/hicolor/32x32/apps/smartcardauth.png
Binary files differ
diff --git a/usr/share/initramfs-tools/hooks/cryptlukssc b/usr/share/initramfs-tools/hooks/cryptlukssc
new file mode 100755
index 0000000..aabc7fe
--- /dev/null
+++ b/usr/share/initramfs-tools/hooks/cryptlukssc
@@ -0,0 +1,65 @@
+#!/bin/sh
+
+set -e
+
+PREREQ="cryptroot"
+
+prereqs()
+{
+ echo "$PREREQ"
+}
+
+case $1 in
+ prereqs)
+ prereqs
+ exit 0
+ ;;
+esac
+
+. /usr/share/initramfs-tools/hook-functions
+
+# Hooks for loading smartcard reading software into the initramfs
+
+# Install directories needed by smartcard reading daemon, command, and
+# key-script
+for dir in etc/opensc usr/lib/pcsc var/run tmp ; do
+ if [ ! -d ${DESTDIR}/${dir} ] ; then mkdir -p ${DESTDIR}/${dir} ; fi
+done
+
+# Install pcscd daemon, drivers, conf file, and include libgcc as well since
+# pcscd utilizes pthread_cancel
+mkdir -p ${DESTDIR}/lib
+copy_exec /usr/sbin/pcscd /sbin
+copy_exec /lib/libgcc_s.so.1 /lib
+copy_exec /lib/libpcsclite.so.1 /lib
+cp -r /usr/lib/pcsc ${DESTDIR}/usr/lib
+cp /etc/reader.conf ${DESTDIR}/etc
+
+# Install opensc commands and conf file
+copy_exec /usr/bin/opensc-tool /bin
+copy_exec /usr/bin/pkcs15-crypt /bin
+cp /etc/opensc/opensc.conf ${DESTDIR}/etc/opensc
+
+# Install other required utilities
+copy_exec /bin/grep /bin
+copy_exec /bin/mv /bin
+copy_exec /bin/cat /bin
+copy_exec /bin/sleep /bin
+copy_exec /usr/bin/opensc-explorer /bin
+copy_exec /usr/bin/openssl /bin
+copy_exec /usr/bin/perl /bin
+copy_exec /bin/rm /bin
+copy_exec /usr/bin/xxd /bin
+copy_exec /usr/bin/killall /bin
+copy_exec /bin/sed /bin
+copy_exec /usr/bin/tr /bin
+copy_exec /bin/bash /bin
+
+# Main scripts
+copy_exec /usr/bin/scriptor_standalone /bin
+copy_exec /usr/bin/smartauth.sh /bin
+
+# Libraries
+cp /usr/lib/libltdl.so* ${DESTDIR}/usr/lib
+cp /lib/libncurses.so.5 ${DESTDIR}/lib
+cp /lib/libncursesw.so.5 ${DESTDIR}/lib