v2.0 Release

Use TDE builtins for almost all functions
This package now only provides the initramfs LUKS configuration and related program(s)
pull/1/head
Timothy Pearson 9 years ago
parent a87c27c808
commit 640e6672c3

@ -1,21 +1,15 @@
FPACKAGE = smartcardauth
VERSION = 1.0
VERSION = 2.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
./build_cardpincheck
mkdir -p $(DESTDIR)/usr
cp -Rp src/ckpasswd usr/bin/smartauthckpasswd
cp -Rp src/smartauthmon usr/bin/smartauthmon
cp -Rp src/cardpincheck usr/bin/cardpincheck
cp -Rp usr/* $(DESTDIR)/usr/
mkdir -p $(DESTDIR)/etc

@ -1,14 +0,0 @@
# smartauthlogin - smart card login manager
#
description "smart card login monitor"
start on (filesystem
and started tdm-trinity)
stop on stopping tdm-trinity
script
if [ -e /usr/bin/smartauthmon ]; then
/usr/bin/smartauthmon
fi
end script

@ -1,177 +0,0 @@
#!/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 &

@ -1,583 +0,0 @@
#!/bin/bash
# Smart Card TDE Authentication Script (c) 2010-2011 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!"
echo "TAuthenticating SmartCard..." > /tmp/tdesocket-global/kdesktoplockcontrol &
# 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!"
echo "EInvalid SmartCard Inserted" > /tmp/tdesocket-global/kdesktoplockcontrol &
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=$(/opt/trinity/bin/tdmctl -g list)
if [[ $result == "ok" ]]; then
noactivesessions=1
result="okbutempty"
fi
echo $result
resultbkp=$result
if [[ $errcode -eq 0 ]]; then
# Allow TDM 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/trinity/bin/dcop kdesktop KScreensaverIface quit"
su $smartcard_username -c "export DISPLAY=$udisplay; /opt/trinity/bin/dcop kdesktop KScreensaverIface enable false"
/opt/trinity/bin/tdmctl activate $udisplay
else
echo "EUnauthorized SmartCard Inserted" > /tmp/tdesocket-global/kdesktoplockcontrol &
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/trinity/bin/tdmctl -g reserve
/opt/trinity/bin/tdmctl -g login $newdisplay now $smartcard_username $(cat $SECURE_DIRECTORY/password)
sleep 2
/opt/trinity/bin/tdmctl -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
echo "C" > /tmp/tdesocket-global/kdesktoplockcontrol &
TIMER=60
OUTPUT=0
while [[ $OUTPUT -eq 0 ]]; do
sleep 1
su $smartcard_username -c "export DISPLAY=$udisplay; /opt/trinity/bin/dcop kdesktop KScreensaverIface quit"
su $smartcard_username -c "export DISPLAY=$udisplay; /opt/trinity/bin/dcop kdesktop KScreensaverIface enable false"
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=$(/opt/trinity/bin/tdmctl -g list)
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/trinity/bin/tdmctl -g activate $udisplay
su $smartcard_username -c "export DISPLAY=$udisplay; /opt/trinity/bin/dcop kdesktop KScreensaverIface enable true"
su $smartcard_username -c "export DISPLAY=$udisplay; /opt/trinity/bin/dcop kdesktop KScreensaverIface lock"
blankresult=$(su $smartcard_username -c "export DISPLAY=$udisplay; /opt/trinity/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
echo "C" > /tmp/tdesocket-global/kdesktoplockcontrol &
fi
done

@ -1,48 +0,0 @@
/* $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 */

@ -1,78 +0,0 @@
/* $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 */

@ -1,66 +0,0 @@
/* $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 */

@ -1,60 +0,0 @@
/* $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 */

@ -1,110 +0,0 @@
/* $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

@ -1,211 +0,0 @@
/* $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 */

@ -1,51 +0,0 @@
/* $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 */

@ -1,79 +0,0 @@
/* $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 */

@ -1,99 +0,0 @@
/* $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 */

@ -1,33 +0,0 @@
/* $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 */

@ -1,49 +0,0 @@
/* $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 */

@ -1,21 +0,0 @@
/* $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 */

@ -1,38 +0,0 @@
/* $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 */

@ -1,88 +0,0 @@
/* $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 */

@ -1,87 +0,0 @@
/* $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 */

@ -1,46 +0,0 @@
/* $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 */

@ -1,171 +0,0 @@
#!/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

@ -1,25 +1,10 @@
all: ckpasswd.o xmalloc.o messages.o ckpass.o ckpasswd smartauthmon
all: cardpincheck.o cardpincheck
ckpass.o: ckpass.c
gcc ckpass.c -c
cardpincheck.o: cardpincheck.c
gcc cardpincheck.c -c
ckpasswd.o: ckpasswd.c
gcc ckpasswd.c -c
xmalloc.o: xmalloc.c
gcc xmalloc.c -c
messages.o: messages.c
gcc messages.c -c
smartauthmon.o: smartauthmon.cpp
g++ -I/usr/include/tqt -I/usr/include/qt3 -I/usr/include/tqt3 smartauthmon.cpp -c
ckpasswd: ckpasswd.o
gcc ckpasswd.o xmalloc.o messages.o -o ckpasswd -lpam -lcrypt
smartauthmon: smartauthmon.o ckpass.o
gcc smartauthmon.o ckpass.o xmalloc.o messages.o -o smartauthmon -ltqt -lpam -lcrypt -ltqt-mt -lstdc++
cardpincheck: cardpincheck.o
gcc cardpincheck.o -o cardpincheck -ldl -lpthread -lgnutls -lcrypto -lpkcs11-helper
clean:
rm -f ckpasswd.o xmalloc.o messages.o ckpasswd
rm -f cardpincheck.o cardpincheck

@ -0,0 +1,330 @@
/* Cryptographic card PIN check and RSA decryption utility
* Copyright (C) 2015 Timothy Pearson <kb9vqf@pearsoncomputing.net>
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <pkcs11-helper-1.0/pkcs11h-certificate.h>
#include <pkcs11-helper-1.0/pkcs11h-openssl.h>
#define CARD_MAX_LOGIN_RETRY_COUNT 3
char has_plymouth = 0;
char use_cached_pin = 0;
char* cached_pin = NULL;
static PKCS11H_BOOL pkcs_pin_hook(IN void * const global_data, IN void * const user_data, IN const pkcs11h_token_id_t token, IN const unsigned retry, OUT char * const pin, IN const size_t pin_max) {
int pos;
char *line = NULL;
size_t size;
ssize_t read;
if (use_cached_pin && cached_pin) {
// Copy PIN to buffer
snprintf(pin, pin_max, "%s", cached_pin);
// Success
return 1;
}
// Hide input
struct termios oldt;
tcgetattr(STDIN_FILENO, &oldt);
struct termios newt = oldt;
newt.c_lflag &= ~ECHO;
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
if (has_plymouth) {
char buffer[1024];
snprintf(buffer, 1024, "plymouth ask-for-password --prompt=\"Please enter the PIN for '%s'\"", token->display);
system(buffer);
}
else {
fprintf(stderr, "Please enter the PIN for '%s'\n", token->display);
}
fflush(stdout);
read = getline(&line, &size, stdin);
if ((read < 0) || (read >= pin_max)) {
free(line);
// Abort
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
return 0;
}
else {
// Strip newlines
pos = 0;
while (line[pos] != 0) {
if ((line[pos] == '\n') || (line[pos] == '\r')) {
line[pos] = 0;
break;
}
pos++;
}
// Copy PIN to cache
if (cached_pin) {
free(cached_pin);
}
cached_pin= malloc(sizeof(char) * pin_max);
snprintf(cached_pin, pin_max, "%s", line);
// Copy PIN to buffer
snprintf(pin, pin_max, "%s", line);
free(line);
// Success
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
return 1;
}
}
static void pkcs_log_hook(IN void * const global_data, IN unsigned flags, IN const char * const format, IN va_list args) {
if (!has_plymouth) {
vfprintf(stderr, format, args);
fprintf(stderr, "\n");
}
}
int main(int argc, char* argv[]) {
CK_RV rv;
pkcs11h_certificate_id_list_t issuers;
pkcs11h_certificate_id_list_t certs;
has_plymouth = 0;
const char* with_plymount_var = getenv("HAS_PLYMOUTH");
if (with_plymount_var && (with_plymount_var[0] == '1')) {
has_plymouth = 1;
}
if ((argc < 2) || (argv[1][0] == 0)) {
fprintf(stderr, "Usage: ./cardpincheck <opensc provider library> <file to decrypt>\n"
"Example: ./cardpincheck /usr/lib/opensc-pkcs11.so\n");
return -5;
}
char* opensc_provider_library = argv[1];
char decryption_requested = 0;
char* file_to_decrypt = NULL;
if (argc > 2) {
decryption_requested = 1;
file_to_decrypt = argv[2];
}
fprintf(stderr, "Initializing pkcs11-helper\n");
if ((rv = pkcs11h_initialize()) != CKR_OK) {
fprintf(stderr, "pkcs11h_initialize failed: %s\n", pkcs11h_getMessage(rv));
return -1;
}
fprintf(stderr, "Registering pkcs11-helper hooks\n");
if ((rv = pkcs11h_setLogHook(pkcs_log_hook, NULL)) != CKR_OK) {
fprintf(stderr, "pkcs11h_setLogHook failed: %s\n", pkcs11h_getMessage(rv));
return -1;
}
pkcs11h_setLogLevel(PKCS11H_LOG_WARN);
// pkcs11h_setLogLevel(PKCS11H_LOG_DEBUG2);
#if 0
if ((rv = pkcs11h_setTokenPromptHook(_pkcs11h_hooks_token_prompt, NULL)) != CKR_OK) {
fprintf(stderr, "pkcs11h_setTokenPromptHook failed: %s\n", pkcs11h_getMessage(rv));
return -1;
}
#endif
if ((rv = pkcs11h_setMaxLoginRetries(CARD_MAX_LOGIN_RETRY_COUNT)) != CKR_OK) {
fprintf(stderr, "pkcs11h_setMaxLoginRetries failed: %s\n", pkcs11h_getMessage(rv));
return -1;
}
if ((rv = pkcs11h_setPINPromptHook(pkcs_pin_hook, NULL)) != CKR_OK) {
fprintf(stderr, "pkcs11h_setPINPromptHook failed: %s\n", pkcs11h_getMessage(rv));
return -1;
}
fprintf(stderr, "Adding provider '%s'\n", opensc_provider_library);
if ((rv = pkcs11h_addProvider(opensc_provider_library, opensc_provider_library, FALSE, PKCS11H_PRIVATEMODE_MASK_AUTO, PKCS11H_SLOTEVENT_METHOD_AUTO, 0, FALSE)) != CKR_OK) {
fprintf(stderr, "pkcs11h_addProvider failed: %s\n", pkcs11h_getMessage(rv));
return -1;
}
rv = pkcs11h_certificate_enumCertificateIds(PKCS11H_ENUM_METHOD_CACHE, NULL, PKCS11H_PROMPT_MASK_ALLOW_PIN_PROMPT, &issuers, &certs);
if ((rv != CKR_OK) || (certs == NULL)) {
fprintf(stderr, "Cannot enumerate certificates: %s\n", pkcs11h_getMessage(rv));
return -1;
}
int ret = -1;
int i = 0;
pkcs11h_certificate_id_list_t cert;
pkcs11h_certificate_t certificate = NULL;
RSA* rsa_pubkey = NULL;
for (cert = certs; cert != NULL; cert = cert->next) {
rv = pkcs11h_certificate_create(certs->certificate_id, NULL, PKCS11H_PROMPT_MASK_ALLOW_PIN_PROMPT, PKCS11H_PIN_CACHE_INFINITE, &certificate);
if (rv != CKR_OK) {
fprintf(stderr, "Cannot read certificate: %s\n", pkcs11h_getMessage(rv));
pkcs11h_certificate_freeCertificateId(certs->certificate_id);
ret = -1;
break;
}
pkcs11h_certificate_freeCertificateId(certs->certificate_id);
pkcs11h_openssl_session_t openssl_session = NULL;
if ((openssl_session = pkcs11h_openssl_createSession(certificate)) == NULL) {
fprintf(stderr, "Cannot initialize openssl session to retrieve cryptographic objects\n");
pkcs11h_certificate_freeCertificate(certificate);
ret = -1;
break;
}
// Get certificate data
X509* x509_local;
x509_local = pkcs11h_openssl_session_getX509(openssl_session);
if (!x509_local) {
fprintf(stderr, "Cannot get X509 object\n");
ret = -1;
}
// Extract public key from X509 certificate
EVP_PKEY* x509_pubkey = NULL;
x509_pubkey = X509_get_pubkey(x509_local);
if (x509_pubkey) {
rsa_pubkey = EVP_PKEY_get1_RSA(x509_pubkey);
}
// Check PIN
rv = pkcs11h_certificate_ensureKeyAccess(certificate);
if (rv != CKR_OK) {
if (rv == CKR_CANCEL) {
ret = -3;
break;
}
else if ((rv == CKR_PIN_INCORRECT) || (rv == CKR_USER_NOT_LOGGED_IN)) {
ret = -2;
break;
}
else {
ret = -2;
break;
}
}
else {
// Success!
ret = 0;
break;
}
pkcs11h_certificate_freeCertificate(certificate);
certificate = NULL;
i++;
}
if (decryption_requested && (ret == 0)) {
// We know the cached PIN is correct; disable any further login prompts
use_cached_pin = 1;
char abort_decryption = 0;
if (file_to_decrypt) {
long ciphertextfilesize = 0;
FILE *ciphertextfile = fopen(file_to_decrypt, "r");
if (ciphertextfile) {
fseek(ciphertextfile, 0, SEEK_END);
ciphertextfilesize = ftell(ciphertextfile);
fseek(ciphertextfile, 0, SEEK_SET);
char* ciphertext = malloc(ciphertextfilesize + 1);
fread(ciphertext, ciphertextfilesize, 1, ciphertextfile);
fclose(ciphertextfile);
// Verify minimum size
if (ciphertextfilesize < 16) {
fprintf(stderr, "Cannot decrypt: ciphertext too small\n");
abort_decryption = 1;
}
// Try to get RSA parameters and verify maximum size
if (rsa_pubkey) {
unsigned int rsa_length = RSA_size(rsa_pubkey);
if (ciphertextfilesize > rsa_length) {
fprintf(stderr, "Cannot decrypt: ciphertext too large\n");
abort_decryption = 1;
}
}
if (!abort_decryption) {
// Try decryption
size_t size = 0;
// Determine output buffer size
rv = pkcs11h_certificate_decryptAny(certificate, CKM_RSA_PKCS, ciphertext, ciphertextfilesize, NULL, &size);
if (rv != CKR_OK) {
fprintf(stderr, "Cannot determine decrypted message length: %s (%d)\n", pkcs11h_getMessage(rv), rv);
if (rv == CKR_CANCEL) {
ret = -1;
abort_decryption = 1;
}
else if ((rv == CKR_PIN_INCORRECT) || (rv == CKR_USER_NOT_LOGGED_IN)) {
ret = -1;
abort_decryption = 1;
}
else {
abort_decryption = 1;
}
}
else {
// Decrypt data
char* plaintext = malloc(size);
rv = pkcs11h_certificate_decryptAny(certificate, CKM_RSA_PKCS, ciphertext, ciphertextfilesize, plaintext, &size);
if (rv != CKR_OK) {
fprintf(stderr, "Cannot decrypt: %s (%d)\n", pkcs11h_getMessage(rv), rv);
if (rv == CKR_CANCEL) {
ret = -1;
abort_decryption = 1;
}
else if ((rv == CKR_PIN_INCORRECT) || (rv == CKR_USER_NOT_LOGGED_IN)) {
ret = -1;
abort_decryption = 1;
}
}
else {
// Write decrypted data to stdout
fwrite(plaintext, sizeof(char), size, stdout);
fflush(stdout);
}
free(plaintext);
}
}
free(ciphertext);
}
}
}
else if (ret == 0) {
printf("%s", cached_pin);
}
if (certificate) {
pkcs11h_certificate_freeCertificate(certificate);
}
pkcs11h_certificate_freeCertificateIdList(issuers);
return ret;
}

@ -1,284 +0,0 @@
/* $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 routines.
**
** We handle the variences between systems with #if blocks above, so that
** this code can look fairly clean.
*/
int
check_password(const char* username, const char* password)
{
bool wantgroup = false;
struct auth_info *authinfo = NULL;
authinfo = xmalloc(sizeof(struct auth_info));
authinfo->username = username;
authinfo->password = password;
if (auth_pam(authinfo->username, authinfo->password)) {
output_user(authinfo->username, wantgroup);
return 0;
}
password = password_system(authinfo->username);
if (password == NULL)
return 1;
if (strcmp(password, crypt(authinfo->password, password)) != 0)
return 1;
/* The password matched. */
output_user(authinfo->username, wantgroup);
return 0;
}

@ -1,368 +0,0 @@
/* $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>
#include <getopt.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 routines.
**
** 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);
}

@ -1,493 +0,0 @@
/* $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);
}

@ -1,839 +0,0 @@
/* Smart Card TDE Authentication Script (c) 2010-2011 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 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, see <http://www.gnu.org/licenses/>.
*/
#define _XOPEN_SOURCE 500
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/select.h>
#include <sys/time.h>
#include <termios.h>
#include <signal.h>
#include <ftw.h>
#include <tqdir.h>
#include <tqstring.h>
#include <tqstringlist.h>
// Maximum number of virtual terminals on this system
#define MAXIMUM_VTS 49
// The [secure] temporary directory for authentication
#define SECURE_DIRECTORY_PATH "/tmp/smartauth"
// The Trinity binary directory
#define TRINITY_BIN_PREFIX "/opt/trinity/bin/"
// Some internal constants
#define CREATE_LIFE_CYCLE "01"
#define TDM_CONTROL_FIFO_DIR "/tmp/tdesocket-global/tdm"
#define TDM_CONTROL_FIFO_FILE "/tmp/tdesocket-global/tdm/tdmctl-%1"
#define TDM_CONTROL_FIFO_SAK_FILE "/tmp/tdesocket-global/tdm/tdmctl-sak-%1"
// In ckpass.o
extern "C" {
int check_password(const char* username, const char* password);
}
static TQString secure_directory;
static TQString command_mode;
static TQString select_file;
static TQString read_binary;
static TQString update_binary;
static TQString delete_file;
static TQString get_challenge;
static TQString external_auth;
static TQString activate_file;
static TQString hexidecimal_key;
static TQString darray[MAXIMUM_VTS];
static FILE* opensc_explorer_file;
struct sigaction usr_action;
sigset_t block_mask;
void handle_sigpipe(int sig)
{
int uidnum;
if (sig == SIGPIPE) {
printf("Got SIGPIPE!\n"); fflush(stdout);
}
}
TQString readfile(const char * filename) {
FILE *fp;
long len;
char *buf;
fp=fopen(filename, "rb");
if (fp == NULL) {
printf("[WARNING] Unable to read from file %s\n", filename); fflush(stdout);
return TQString();
}
fseek(fp,0,SEEK_END); // Seek to end
len=ftell(fp); // Get position at end (length)
fseek(fp,0,SEEK_SET); // Seek to beginning
buf=(char *)malloc(len+1); // Malloc the buffer
fread(buf,len,1,fp); // Read file
fclose(fp);
buf[len]=0;
TQString contents(buf);
free(buf); // Free the buffer
return contents;
}
int writefile(const char * filename, TQString contents) {
int fp;
long len;
char *buf;
fp=open(filename, O_WRONLY | O_NONBLOCK);
if (fp < 0) {
printf("[WARNING] Unable to open file %s for writing\n", filename); fflush(stdout);
return -1;
}
int retcode = write(fp, contents.ascii(), contents.length());
close(fp);
return retcode;
}
TQString exec(const char * cmd) {
TQString bashcommand = cmd;
bashcommand = bashcommand.replace("\"", "\\\"");
bashcommand = TQString("/bin/bash -c \"%1\"").arg(bashcommand);
FILE* pipe = popen(bashcommand.ascii(), "r");
if (!pipe) return "ERROR";
char buffer[128];
TQString result = "";
while(!feof(pipe)) {
if(fgets(buffer, 128, pipe) != NULL) {
result += buffer;
}
}
pclose(pipe);
result.remove(result.length(), 1);
return result;
}
int systemexec(const char * cmd) {
TQString bashcommand = cmd;
bashcommand = bashcommand.replace("\"", "\\\"");
bashcommand = TQString("/bin/bash -c \"%1\"").arg(bashcommand);
return system(bashcommand.ascii()) >> 8;
}
TQString execret(const char * cmd, int * retcode) {
TQString bashcommand = cmd;
bashcommand = bashcommand.replace("\"", "\\\"");
bashcommand = TQString("/bin/bash -c \"%1\"").arg(bashcommand);
FILE* pipe = popen(bashcommand.ascii(), "r");
if (!pipe) return "ERROR";
char buffer[128];
TQString result = "";
while(!feof(pipe)) {
if(fgets(buffer, 128, pipe) != NULL) {
result += buffer;
}
}
*retcode = pclose(pipe) >> 8;
result.remove(result.length(), 1);
return result;
}
int unlink_cb(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf)
{
int rv = remove(fpath);
if (rv)
perror(fpath);
return rv;
}
int rmrf(const char *path)
{
return nftw(path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
}
TQString get_file(TQString prefix, TQString mode) {
if (command_mode == "acos") {
// Select EF prefix under DF 1000
systemexec((TQString("echo \"%1 %2\" > %3/query").arg(select_file).arg(prefix).arg(secure_directory)).ascii());
systemexec((TQString("scriptor %1/query 1> %2/response2").arg(secure_directory).arg(secure_directory)).ascii());
// printf("[DEBUG 100.0] %s\n", readfile((TQString("%1/response2").arg(secure_directory))).ascii()); fflush(stdout);
// Read binary
systemexec((TQString("echo \"%1\" > %2/query").arg(read_binary).arg(secure_directory)).ascii());
systemexec((TQString("scriptor %1/query 1> %2/response2").arg(secure_directory).arg(secure_directory)).ascii());
TQString authokresponse="90 00 : Normal processing";
TQString response1 = exec((TQString("cat %1/response2 | grep \"%2\"").arg(secure_directory).arg(authokresponse)).ascii());
if (response1 != "") {
systemexec((TQString("cat %1/response2 | tr -d '\n' > %2/response4").arg(secure_directory).arg(secure_directory)).ascii());
TQString stringtoreplace="Using T=0 protocol00 B0 00 00 FF> 00 B0 00 00 FF< ";
TQString newstring="";
systemexec((TQString("sed -i \"s#%1#%2#g\" %3/response4").arg(stringtoreplace).arg(newstring).arg(secure_directory)).ascii());
stringtoreplace=" 90 00 : Normal processing.";
newstring="";
systemexec((TQString("sed -i \"s#%1#%2#g\" %3/response4").arg(stringtoreplace).arg(newstring).arg(secure_directory)).ascii());
if (mode == "text") {
stringtoreplace=" 00";
newstring="";
systemexec((TQString("sed -i \"s#%1#%2#g\" %3/response4").arg(stringtoreplace).arg(newstring).arg(secure_directory)).ascii());
}
// printf("[DEBUG 100.1] %s\n", readfile((TQString("%1/response4").arg(secure_directory))).ascii()); fflush(stdout);
unlink((TQString("%1/lukskey").arg(secure_directory)).ascii());
systemexec((TQString("xxd -r -p %1/response4 %2/lukskey").arg(secure_directory).arg(secure_directory)).ascii());
return(TQString("%1/lukskey").arg(secure_directory));
}
}
if (command_mode == "cryptoflex") {
TQString file = TQString(prefix).replace(' ', "");
unlink((TQString("3F00_%1").arg(file)).ascii());
// systemexec((TQString("echo \"get %1\" | opensc-explorer").arg(file)).ascii());
fputs((TQString("get %1\n").arg(file)).ascii(), opensc_explorer_file);
fflush(opensc_explorer_file);
int j;
// Wait up to 2 seconds for the file to be written
for (j=0;j<200;j++) {
FILE* fp1 = fopen((TQString("3F00_%1").arg(file)).ascii(), "r");
if (fp1) {
// file exists
fclose(fp1);
break;
}
usleep(10000);
}
usleep(100000); // [FIXME] Here I assume that the entire file will be written (after it was created) within 100us. This may not be correct in all cases!
return TQString("3F00_%1").arg(file);
}
}
void createfile(TQString prefix, TQString mode)
{
if (command_mode == "cryptoflex") {
// Create transparent file with permissions:
// delete, terminate, activate, deactivate, update, read for Key 1 and Key 2 only
systemexec((TQString("echo \"F0 E0 00 FF 10 FF FF 00 %1 %2 01 3F 44 FF 44 01 03 11 FF 11\" > %3/query").arg(prefix).arg(mode).arg(secure_directory)).ascii());
systemexec((TQString("scriptor %1/query 1> %2/response2 2>/dev/null").arg(secure_directory).arg(secure_directory)).ascii());
}
if (command_mode == "acos") {
// 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
systemexec((TQString("echo \"00 E0 00 00 1A 62 18 80 02 00 %1 82 01 01 83 02 %2 8A 01 %3 8C 08 7F 04 04 04 04 04 04 04\" > %4/query").arg(prefix).arg(mode).arg(CREATE_LIFE_CYCLE).arg(secure_directory)).ascii());
systemexec((TQString("scriptor %1/query 1> %2/response2 2>/dev/null").arg(secure_directory)).ascii());
printf("[DEBUG 300.0] %s\n", readfile((TQString("%1/response2").arg(secure_directory))).ascii()); fflush(stdout);
}
}
void update_file(TQString prefix, TQString mode) {
if (command_mode == "acos") {
// Select EF prefix under DF 1000
systemexec((TQString("echo \"$SELECT_FILE %1\" > %2/query").arg(prefix).arg(secure_directory)).ascii());
systemexec((TQString("scriptor %1/query 1> %2/response2").arg(secure_directory).arg(secure_directory)).ascii());
printf("[DEBUG 200.0] %s\n", readfile((TQString("%1/response2").arg(secure_directory))).ascii()); fflush(stdout);
// Update existing file
// Zero pad input file
systemexec((TQString("dd if=/dev/zero of=%1/response2 bs=1 count=255 2>/dev/null 1>/dev/null").arg(secure_directory)).ascii());
systemexec((TQString("dd if=%1 of=%2/response2 bs=1 count=255 conv=notrunc 2>/dev/null 1>/dev/null").arg(mode).arg(secure_directory)).ascii());
// Truncate to 255 bytes and expand to standard hex listing format
systemexec((TQString("xxd -l 255 -ps -c 1 %1/response2 > %2/response").arg(secure_directory).arg(secure_directory)).ascii());
systemexec((TQString("cat %1/response | tr '\n' ' ' > %1/hexready").arg(secure_directory)).ascii());
TQString hexready = readfile((TQString("%1/hexready").arg(secure_directory)).ascii());
systemexec((TQString("echo \"%1 %2\" > %3/query").arg(update_binary).arg(hexready).arg(secure_directory)).ascii());
systemexec((TQString("scriptor %1/query 1> %2/response2 2>/dev/null").arg(secure_directory).arg(secure_directory)).ascii());
printf("[DEBUG 200.1] %s\n", readfile((TQString("%1/response2").arg(secure_directory))).ascii()); fflush(stdout);
}
if (command_mode == "cryptoflex") {
// Delete old file
systemexec((TQString("echo \"%1 $1\" > %2/query").arg(delete_file).arg(secure_directory)).ascii());
systemexec((TQString("scriptor %1/query 1> %2/response2 2>/dev/null").arg(secure_directory).arg(secure_directory)).ascii());
printf("[DEBUG 200.2] %s\n", readfile((TQString("%1/response2").arg(secure_directory))).ascii()); fflush(stdout);
// Create new file
createfile("FF", prefix);
TQString file = TQString(prefix).replace(' ', "");
systemexec((TQString("echo \"put %1 %2\" | opensc-explorer").arg(file).arg(mode)).ascii());
}
}
int main (int argc, char *argv[])
{
TQString smartcard_username;
TQString oldsmartcard_username;
TQString smartcard_password;
TQString smartcard_slave;
TQString lverify;
TQString cverify;
TQString udisplay;
TQString newdisplay;
TQString logouttest;
TQString blankresult;
TQString smartcard_minutes_raw;
int timer;
int smartcard_minutes;
int internet_minutes;
int newdisplayint;
printf("[DEBUG 390.0] Starting up\n"); fflush(stdout);
// Initialize signal handlers
sigfillset(&block_mask);
usr_action.sa_handler = handle_sigpipe;
usr_action.sa_mask = block_mask;
usr_action.sa_flags = 0;
sigaction(SIGPIPE, &usr_action, NULL);
// Create the secure directory and lock it down
secure_directory = SECURE_DIRECTORY_PATH;
rmrf(secure_directory.ascii());
mkdir(secure_directory.ascii(), 600);
chown(secure_directory.ascii(), 0, 0);
chmod(secure_directory.ascii(), 600);
secure_directory=exec("mktemp " SECURE_DIRECTORY_PATH "/smartauthmon.XXXXXXXXXX");
secure_directory.replace('\n', "");
rmrf(secure_directory.ascii());
mkdir(secure_directory.ascii(), 600);
chown(secure_directory.ascii(), 0, 0);
chmod(secure_directory.ascii(), 600);
// Terminate old pcscd process from initrd
system("killall -9 pcscd");
// See if required programs are installed
TQString scriptor = exec("whereis scriptor");
if ( scriptor == "scriptor:" ) {
printf("ERROR: scriptor is not installed! This program cannot continue!\n"); fflush(stdout);
return 1;
}
TQString opensc = exec("whereis opensc-explorer");
if ( opensc == "opensc-explorer:" ) {
printf("ERROR: opensc-explorer is not installed! This program cannot continue!\n"); fflush(stdout);
return 1;
}
printf("[DEBUG 390.2] Reading keys\n"); fflush(stdout);
// Read hexidecimal_key from the system crypto files
FILE* fpkey = fopen("/etc/smartauth/smartauthmon.key", "rb");
if (fpkey == NULL) {
printf("Smart card login has been disabled. Exiting...\n"); fflush(stdout);
return 1;
}
else {
fclose(fpkey);
}
hexidecimal_key = readfile("/etc/smartauth/smartauthmon.key");
hexidecimal_key.replace('\n', "");
oldsmartcard_username="";
printf("[DEBUG 400.0] Ready...\n"); fflush(stdout);
while (1) {
sleep(1);
int output = systemexec("echo \"exit\" | timeout 1 scriptor 2>/dev/null 1>/dev/null");
if (output == 0) {
printf("[DEBUG 400.1] Card inserted!\n"); fflush(stdout);
systemexec("echo \"TAuthenticating SmartCard...\" > /tmp/tdesocket-global/kdesktoplockcontrol &");
// Get card ATR
systemexec((TQString("echo \"RESET\" > %1/query").arg(secure_directory)).ascii());
systemexec((TQString("scriptor %1/query 1> %2/response2").arg(secure_directory).arg(secure_directory)).ascii());
TQString authokresponse="OK: ";
TQString response1 = exec((TQString("cat %1/response2 | grep \"%2\"").arg(secure_directory).arg(authokresponse)).ascii());
if (response1 != "") {
systemexec((TQString("cat %1/response2 | tr -d '\n' > %2/response4").arg(secure_directory).arg(secure_directory)).ascii());
TQString stringtoreplace="Using T=0 protocolRESET> RESET< OK: ";
TQString newstring="";
systemexec((TQString("sed -i \"s#%1#%2#g\" %3/response4").arg(stringtoreplace).arg(newstring).arg(secure_directory)).ascii());
TQString smartatr = readfile((TQString("%1/response4").arg(secure_directory)).ascii());
printf("[DEBUG 400.2] Got ATR: %s\n", smartatr.ascii()); fflush(stdout);
if (smartatr == "3B BE 18 00 00 41 05 10 00 00 00 00 00 00 00 00 00 90 00 ") {
printf("[DEBUG 400.3] Detected ACOS5 card\n"); fflush(stdout);
command_mode="acos";
}
if (smartatr == "3B 02 14 50 ") {
printf("[DEBUG 400.3] Detected Schlumberger CryptoFlex card\n"); fflush(stdout);
command_mode="cryptoflex";
}
}
else {
printf("[DEBUG 400.3] No card detected!\n"); fflush(stdout);
}
if (command_mode == "cryptoflex") {
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";
}
if (command_mode == "acos") {
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";
}
// Authenticate card
if (command_mode == "acos") {
// Select MF
systemexec((TQString("echo \"00 A4 00 00 00\" > %1/query").arg(secure_directory)).ascii());
systemexec((TQString("scriptor %1/query 1> %2/response2").arg(secure_directory).arg(secure_directory)).ascii());
printf("[DEBUG 400.4] %s\n", readfile((TQString("%1/response2").arg(secure_directory))).ascii()); fflush(stdout);
// Select DF 1000 under MF
systemexec((TQString("echo \"%1 10 00\" > %2/query").arg(select_file).arg(secure_directory)).ascii());
systemexec((TQString("scriptor %1/query 1> %2/response2").arg(secure_directory).arg(secure_directory)).ascii());
printf("[DEBUG 400.5] %s\n", readfile((TQString("%1/response2").arg(secure_directory))).ascii()); fflush(stdout);
}
systemexec((TQString("echo %1 > %2/authscript").arg(get_challenge).arg(secure_directory)).ascii());
systemexec((TQString("scriptor %1/authscript | grep 'Normal processing' > %2/challenge").arg(secure_directory).arg(secure_directory)).ascii());
systemexec((TQString("perl -pi -e 's/ //g' %1/challenge").arg(secure_directory)).ascii());
systemexec((TQString("perl -pi -e 's/:Normalprocessing.//g' %1/challenge").arg(secure_directory)).ascii());
systemexec((TQString("perl -pi -e 's/<//g' %1/challenge").arg(secure_directory)).ascii());
systemexec((TQString("xxd -r -p %1/challenge %2/challenge").arg(secure_directory).arg(secure_directory)).ascii());
// Now DES encrypt the challenge
// Later, change the initialization vector to random if possible
// Create the response from the challenge
systemexec((TQString("openssl des-ecb -in %1/challenge -out %2/response -K %3 -iv 1").arg(secure_directory).arg(secure_directory).arg(hexidecimal_key)).ascii());
if (command_mode == "acos") {
// Truncate to 8 bytes
systemexec((TQString("dd if=%1/response of=%2/response2 bs=1 count=8 2>/dev/null 1>/dev/null").arg(secure_directory).arg(secure_directory)).ascii());
// Expand to standard hex listing format
systemexec((TQString("xxd -g 1 %1/response2 %2/response").arg(secure_directory).arg(secure_directory)).ascii());
systemexec((TQString("dd if=%1/response of=%2/response2 bs=1 count=23 skip=9 2>/dev/null 1>/dev/null").arg(secure_directory).arg(secure_directory)).ascii());
}
if (command_mode == "cryptoflex") {
// Truncate to 6 bytes
systemexec((TQString("dd if=%1/response of=%2/response2 bs=1 count=6 2>/dev/null 1>/dev/null").arg(secure_directory).arg(secure_directory)).ascii());
// Expand to standard hex listing format
systemexec((TQString("xxd -g 1 %1/response2 %2/response").arg(secure_directory).arg(secure_directory)).ascii());
systemexec((TQString("dd if=%1/response of=%2/response2 bs=1 count=17 skip=9 2>/dev/null 1>/dev/null").arg(secure_directory).arg(secure_directory)).ascii());
}
// Assemble the response file
TQString response2 = readfile((TQString("%1/response2").arg(secure_directory)).ascii());
response1 = TQString("%1 %2").arg(external_auth).arg(response2);
systemexec((TQString("echo %1 > %2/response").arg(response1).arg(secure_directory)).ascii());
// Send the response!
systemexec((TQString("scriptor %1/response > %2/response2").arg(secure_directory).arg(secure_directory)).ascii());
// Get the result
authokresponse = "< 90 00 : Normal processing";
response1 = exec((TQString("cat %1/response2 | grep \"%2\"").arg(secure_directory).arg(authokresponse)).ascii());
printf("[DEBUG 400.6] %s\n", response1.ascii()); fflush(stdout);
if (response1 != "") {
printf("[DEBUG 400.7] Smart card validation successfull!\n"); fflush(stdout);
if (command_mode == "cryptoflex") {
opensc_explorer_file = popen("opensc-explorer 2>/dev/null 1>/dev/null", "w");
}
// Get username and password
TQString response = get_file("10 02", "text");
smartcard_username = readfile(response);
smartcard_username = smartcard_username.replace('\n', "");
unlink(response.ascii());
response = get_file("10 03", "text");
smartcard_password = readfile(response.ascii());
smartcard_password = smartcard_password.replace('\n', "");
unlink(response.ascii());
response = get_file("10 04", "text");
smartcard_slave = readfile(response);
smartcard_slave = smartcard_slave.replace('\n', "");
unlink(response.ascii());
if (smartcard_slave == "SLAVE") {
get_file("10 05", "text");
smartcard_minutes_raw = readfile(response);
smartcard_minutes_raw = smartcard_minutes_raw.replace('\n', "");
unlink(response.ascii());
get_file("10 06", "text");
internet_minutes = readfile(response).toInt();
unlink(response.ascii());
}
}
else {
printf("[DEBUG 400.7] This card does not recognize this system!\n"); fflush(stdout);
systemexec("echo \"EInvalid SmartCard Inserted\" > /tmp/tdesocket-global/kdesktoplockcontrol &");
sleep(1);
smartcard_username="";
unlink((TQString("%1/password").arg(secure_directory)).ascii());
smartcard_slave="";
}
if (smartcard_slave == "SLAVE") {
if (smartcard_minutes_raw == "") {
smartcard_minutes=1;
}
else {
smartcard_minutes = smartcard_minutes_raw.toInt();
}
// Decrement minutes on card
if (smartcard_minutes > 0) {
smartcard_minutes=smartcard_minutes-1;
systemexec((TQString("echo %1 > %2/minutes").arg(smartcard_minutes).arg(secure_directory)).ascii());
update_file("10 05", TQString("%1/minutes").arg(secure_directory));
}
if (smartcard_minutes == 0) {
printf("[DEBUG 400.8] Minutes have been used up!\n"); fflush(stdout);
// Prohibit logon
smartcard_username="";
unlink((TQString("%1/password").arg(secure_directory)).ascii());
}
mkdir("/etc/smartmon", 644);
systemexec((TQString("echo %1 > /etc/smartmon/minutesremaining").arg(smartcard_minutes)).ascii());
chmod("/etc/smartmon/minutesremaining", 755);
}
// Initialize variables
int loginok=1;
// Try to do the authentication
TQString result="";
int timeout=0;
int errcode=0;
int waserror=0;
int noactivesessions=0;
result = exec(TRINITY_BIN_PREFIX "tdmctl -g list");
if (result == "ok") {
noactivesessions=1;
result="okbutempty";
}
printf("[DEBUG 400.9] %s\n", result.ascii()); fflush(stdout);
TQString resultbkp=result;
if (errcode == 0) {
// Allow TDM to finish starting
if (waserror == 1) {
sleep(10);
}
// Zero the desktop array
int index=0;
while (index < MAXIMUM_VTS) {
darray[index]="";
index++;
}
if (result != "okbutempty") {
TQStringList sessionList = TQStringList::split('\t', result, false);
for ( TQStringList::Iterator it = sessionList.begin(); it != sessionList.end(); ++it ) {
TQStringList sessionInfoList = TQStringList::split(',', *it, true);
if ((*(sessionInfoList.at(0))).startsWith(":")) {
darray[(*(sessionInfoList.at(0))).mid(1).toInt()] = (*(sessionInfoList.at(2)));
}
}
}
// See if the desired user is already logged in
index=0;
int foundsession=0;
while (index < MAXIMUM_VTS) {
if (darray[index] == smartcard_username) {
if (darray[index] != "") {
printf("[DEBUG 400.a] Found existing session on desktop: %d\n", index); fflush(stdout);
foundsession=1;
udisplay = TQString(":%1").arg(index);
// Check password
if (check_password(smartcard_username.ascii(), smartcard_password.ascii()) == 0) {
systemexec((TQString("su %1 -c \"export DISPLAY=%2; " TRINITY_BIN_PREFIX "dcop kdesktop KScreensaverIface quit\"").arg(smartcard_username).arg(udisplay)).ascii());
systemexec((TQString("su %1 -c \"export DISPLAY=%2; " TRINITY_BIN_PREFIX "dcop kdesktop KScreensaverIface enable false\"").arg(smartcard_username).arg(udisplay)).ascii());
systemexec((TQString(TRINITY_BIN_PREFIX "tdmctl activate %1").arg(udisplay)).ascii());
}
else {
systemexec("echo \"EUnauthorized SmartCard Inserted\" > /tmp/tdesocket-global/kdesktoplockcontrol &");
}
}
else {
printf("[DEBUG 400.b] Username not specified\n"); fflush(stdout);
foundsession=2;
sleep(1);
}
}
index++;
}
if (foundsession == 0) {
printf("[DEBUG 400.c] Existing session not found, starting new...\n"); fflush(stdout);
// Get directory listing of tdm control socket directory
// Also start new X server if needed
bool have_valid_display = false;
bool display_has_sak = false;
bool writeerror = false;
newdisplayint = MAXIMUM_VTS+1;
while (have_valid_display == false) {
display_has_sak = false;
writeerror = false;
TQDir dr(TDM_CONTROL_FIFO_DIR);
dr.setFilter( TQDir::System );
dr.setSorting( TQDir::Name );
const TQFileInfoList *list = dr.entryInfoList();
if (list) {
TQFileInfoListIterator it( *list );
TQFileInfo *fi;
while ( (fi = it.current()) != NULL ) {
bool isint;
int tempdisplayint;
TQString tempdisplaystr;
tempdisplaystr = fi->fileName();
printf( "%s\n", fi->fileName().latin1() ); fflush(stdout);
if (fi->fileName().contains("tdmctl-sak-")) {
tempdisplaystr = tempdisplaystr.replace("tdmctl-sak-", "");
tempdisplayint = tempdisplaystr.toInt(&isint);
if (isint) {
if (tempdisplayint < newdisplayint) {
newdisplayint = tempdisplayint;
display_has_sak = true;
}
}
}
else if (fi->fileName().contains("tdmctl-")) {
tempdisplaystr = tempdisplaystr.replace("tdmctl-", "");
tempdisplayint = tempdisplaystr.toInt(&isint);
if (isint) {
if (tempdisplayint < newdisplayint) {
newdisplayint = tempdisplayint;
display_has_sak = false;
}
}
}
++it;
}
if (display_has_sak) {
if (writefile(TQString(TDM_CONTROL_FIFO_SAK_FILE).arg(newdisplayint), "CLOSE\n") < 0) {
// Uh oh, something failed...
printf("Unable to write to TDM control socket %s\n", (TQString(TDM_CONTROL_FIFO_SAK_FILE).arg(newdisplayint)).ascii()); fflush(stdout);
unlink((TQString(TDM_CONTROL_FIFO_SAK_FILE).arg(newdisplayint)).ascii());
writeerror = true;
}
else {
struct stat buffer;
int status = -1;
int timeout_counter = 0;
while ((status != 0) && (timeout_counter < 30)) {
status = stat((TQString(TDM_CONTROL_FIFO_FILE).arg(newdisplayint)).ascii(), &buffer);
timeout_counter++;
usleep(100000);
}
}
}
else {
// Make sure the control socket is writable
if (writefile(TQString(TDM_CONTROL_FIFO_FILE).arg(newdisplayint), "PING\n") < 0) {
// Uh oh, something failed...
printf("Unable to write to TDM control socket %s\n", (TQString(TDM_CONTROL_FIFO_FILE).arg(newdisplayint)).ascii()); fflush(stdout);
unlink((TQString(TDM_CONTROL_FIFO_FILE).arg(newdisplayint)).ascii());
writeerror = true;
}
}
if (newdisplayint == (MAXIMUM_VTS+1)) {
writeerror = true;
systemexec(TRINITY_BIN_PREFIX "tdmctl -g reserve");
usleep(3000000);
}
if (writeerror)
have_valid_display = false;
else
have_valid_display = true;
}
else
{
// TDM is probably not running yet, as its control directory does not exist
// Wait for 10 seconds and try again
usleep(10000000);
}
}
newdisplay = TQString(":%1").arg(newdisplayint);
printf("[DEBUG 400.f] Logging in on display %s\n", newdisplay.ascii()); fflush(stdout);
// Construct login string
TQString logincommand = TQString("LOGIN\t%1\t%2\n").arg(smartcard_username).arg(smartcard_password);
if (writefile(TQString(TDM_CONTROL_FIFO_FILE).arg(newdisplayint), logincommand) < 0) {
// Uh oh, something failed...
printf("Unable to write to TDM control socket %s\n", (TQString(TDM_CONTROL_FIFO_FILE).arg(newdisplayint)).ascii()); fflush(stdout);
}
systemexec((TQString(TRINITY_BIN_PREFIX "tdmctl -g activate %1").arg(newdisplay)).ascii());
udisplay=newdisplay;
}
if (smartcard_slave == "SLAVE") {
if (smartcard_minutes < 5) {
systemexec((TQString("su %1 -c \"export DISPLAY=%2; zenity --warning --text 'You have less than 5 minutes of computer time remaining' || exit 0\" &").arg(smartcard_username).arg(udisplay)).ascii());
}
}
unlink((TQString("%1/password").arg(secure_directory)).ascii());
// if (loginok == 1) {
// Wait for SmartCard removal
systemexec("echo \"C\" > /tmp/tdesocket-global/kdesktoplockcontrol &");
timer=60;
output=0;
while (output == 0) {
sleep(1);
systemexec((TQString("su %1 -c \"export DISPLAY=%2; " TRINITY_BIN_PREFIX "dcop kdesktop KScreensaverIface quit\"").arg(smartcard_username).arg(udisplay)).ascii());
systemexec((TQString("su %1 -c \"export DISPLAY=%2; " TRINITY_BIN_PREFIX "dcop kdesktop KScreensaverIface enable false\"").arg(smartcard_username).arg(udisplay)).ascii());
output = systemexec("echo \"exit\" | scriptor 2>/dev/null 1>/dev/null");
if (smartcard_slave == "SLAVE") {
timer--;
if (timer == 0) {
// 60 seconds have passed, decrement minutes on card
smartcard_minutes--;
systemexec((TQString("echo %1 > /etc/smartmon/minutesremaining").arg(smartcard_minutes)).ascii());
chmod("/etc/smartmon/minutesremaining", 755);
timer=60;
systemexec((TQString("echo %1 > %2/minutes").arg(smartcard_minutes).arg(secure_directory)).ascii());
update_file("10 05", TQString("%1/minutes").arg(secure_directory));
if (smartcard_minutes == 0) {
printf("[DEBUG 401.0] Minutes have been used up!\n"); fflush(stdout);
// Prohibit logon
smartcard_username="";
unlink((TQString("%1/password").arg(secure_directory)).ascii());
}
mkdir("/etc/smartmon", 644);
systemexec((TQString("echo %1 > /etc/smartmon/minutesremaining").arg(smartcard_minutes)).ascii());
chmod("/etc/smartmon/minutesremaining", 755);
if (smartcard_minutes == 5) {
systemexec((TQString("su %1 -c \"export DISPLAY=%2; zenity --warning --text 'You have less than 5 minutes of computer time remaining' || exit 0\" &").arg(smartcard_username).arg(udisplay)).ascii());
}
if (smartcard_minutes == 0) {
printf("[DEBUG 401.1] Minutes have been used up!\n"); fflush(stdout);
printf("[DEBUG 401.2] Beginning logoff process\n"); fflush(stdout);
output=254;
}
}
}
}
printf("[DEBUG 401.3] Card removed\n"); fflush(stdout);
// Is the user still logged in?
result="ok";
timeout=0;
errcode=0;
result = exec(TRINITY_BIN_PREFIX "tdmctl -g list");
if (result == "ok") {
noactivesessions=1;
result="okbutempty";
}
printf("[DEBUG 401.4] %s\n", result.ascii()); fflush(stdout);
// Zero the desktop array
index=0;
while (index < MAXIMUM_VTS) {
darray[index]="";
index++;
}
TQStringList sessionList = TQStringList::split('\t', result, false);
for ( TQStringList::Iterator it = sessionList.begin(); it != sessionList.end(); ++it ) {
TQStringList sessionInfoList = TQStringList::split(',', *it, true);
if ((*(sessionInfoList.at(0))).startsWith(":")) {
darray[(*(sessionInfoList.at(0))).mid(1).toInt()] = (*(sessionInfoList.at(2)));
}
}
// See if the desired user is still logged in
index=0;
foundsession=0;
while (index != MAXIMUM_VTS) {
if (darray[index] == smartcard_username) {
if (darray[index] != "") {
printf("[DEBUG 401.5] Found existing session on desktop: %d\n", index); fflush(stdout);
udisplay = TQString(":%1").arg(index);
foundsession=1;
errcode=1;
timeout=0;
blankresult="";
while (blankresult != "true") {
systemexec((TQString(TRINITY_BIN_PREFIX "tdmctl -g activate %1").arg(udisplay)).ascii());
systemexec((TQString("su %1 -c \"export DISPLAY=%2; " TRINITY_BIN_PREFIX "dcop kdesktop KScreensaverIface enable true\"").arg(smartcard_username).arg(udisplay)).ascii());
systemexec((TQString("su %1 -c \"export DISPLAY=%2; " TRINITY_BIN_PREFIX "dcop kdesktop KScreensaverIface lock\"").arg(smartcard_username).arg(udisplay)).ascii());
int retcode;
blankresult = execret(TQString("su %1 -c \"export DISPLAY=%2; " TRINITY_BIN_PREFIX "dcop kdesktop KScreensaverIface isBlanked\"").arg(smartcard_username).arg(udisplay).ascii(), &retcode);
if (retcode != 0) {
blankresult="true";
}
blankresult = blankresult.replace('\n', "");
logouttest = exec((TQString("echo %1 | grep 'target display has no VT assigned'").arg(blankresult)).ascii());
if (logouttest != "") {
printf("[DEBUG 401.6] User has logged out\n"); fflush(stdout);
blankresult="true";
}
}
}
else {
printf("[DEBUG 401.7] Username not specified!\n"); fflush(stdout);
sleep(1);
}
}
index++;
}
// }
}
if (command_mode == "cryptoflex") {
pclose(opensc_explorer_file);
}
smartcard_username="";
unlink("/etc/smartmon/minutesremaining");
systemexec("echo \"C\" > /tmp/tdesocket-global/kdesktoplockcontrol &");
}
}
}

@ -1,163 +0,0 @@
/* $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;
}

@ -18,6 +18,9 @@
#
# Updated by Timothy Pearson <kb9vqf@pearsoncomputing.net> 4/19/2010
# Added Plymouth detection and support
#
# Updated by Timothy Pearson <kb9vqf@pearsoncomputing.net> 9/15/2015
# Rewrite to use on-card RSA encryption
# define counter-intuitive shell logic values (based on /bin/true & /bin/false)
TRUE=0
@ -85,24 +88,62 @@ if [ $USBLOAD -gt 0 ]; then
modprobe usb_storage >/dev/null 2>&1
fi
killall pcscd &
# Terminate the PC/SC subsystem
killall pcscd > /dev/null 2>&1 || true
# give the system time to settle and open the USB devices
# 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
# Relaunch the PC/SC subsystem
pcscd > /dev/null 2>&1
CARD_INSERTED=$FALSE
OPENED=$FALSE
LUKS_KEY_DIR=/tde_luks_keys
LUKS_KEY_COUNT=$(ls -1 $LUKS_KEY_DIR/ 2> /dev/null | wc -l)
DISK_UUID=$(blkid -s UUID -o value $CRYPTTAB_SOURCE)
if [ $LUKS_KEY_COUNT -gt 0 ]; then
if [ "$DISK_UUID" != "" ]; then
# Disk UUID found and LUKS keys are present
# Check for card presence...
pkcs15-tool --list-certificates > /dev/null 2>&1
RET=$?
if [ $RET -eq 0 ]; then
# Card present
CARD_INSERTED=$TRUE
msg "SmartCard inserted, attempting to authenticate"
PIN=$(cardpincheck /usr/lib/opensc-pkcs11.so)
RET=$?
if [ $RET -eq 0 ]; then
# PIN valid
msg "SmartCard unlocked"
for KEYFILE in ${LUKS_KEY_DIR}/${DISK_UUID}_slot*; do
# Try decrypting
echo "$PIN" | cardpincheck /usr/lib/opensc-pkcs11.so $KEYFILE 2> /dev/null
RET=$?
if [ $RET -eq 0 ]; then
OPENED=$TRUE
break
fi
done
else
msg "SmartCard authentication failed"
fi
fi
fi
fi
killall pcscd > /dev/null 2>&1 || true
if [ $OPENED -eq $FALSE ]; then
msg "SmartCard LUKS keyfile invalid or incorrect SmartCard inserted"
if [ $CARD_INSERTED -eq $TRUE ]; then
msg "SmartCard LUKS keyfile invalid or incorrect SmartCard inserted"
exit 0
else
msg "No SmartCard inserted or no LUKS keyfiles available on this system"
fi
if [ $HAS_PLYMOUTH -eq 1 ]; then
plymouth ask-for-password --prompt="Please enter the LUKS password"
else
@ -111,10 +152,6 @@ if [ $OPENED -eq $FALSE ]; then
echo -n "$A"
msg "Attempting to authenticate..."
fi
else
msg "SmartCard authenticated and LUKS keyfile loaded"
fi
killall pcscd &
exit 0

File diff suppressed because it is too large Load Diff

@ -1,501 +0,0 @@
#!/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 -k all
echo "Securing directories..."
chmod 600 "/boot/initrd.img-$(uname -r)"
chmod -R 600 /etc/smartauth
if [ -e "/etc/smartauth/smartauthmon.key" ]; then
selection="Enable automatic login for TDE"
else
echo "TDE 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 600 "/boot/initrd.img-$(uname -r)"
chown root "/boot/initrd.img-$(uname -r)"
exit
fi
done

@ -1,74 +0,0 @@
#!/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 &

@ -1,10 +0,0 @@
[Desktop Entry]
Type=Application
Exec=gksudo /usr/bin/setupcard.sh
Icon=smartcardauth
Terminal=false
X-TDE-StartupNotify=true
Name=SmartCard Authentication Setup
GenericName=SmartCard Authentication Setup
Categories=TDE;System;

@ -1,10 +0,0 @@
[Desktop Entry]
Type=Application
Exec=gksudo /usr/bin/setupslavecard.sh
Icon=smartcardauth
Terminal=false
X-TDE-StartupNotify=true
Name=SmartCard Restriction Setup
GenericName=SmartCard Restriction Setup
Categories=TDE;System;

Binary file not shown.

Before

Width:  |  Height:  |  Size: 595 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

@ -6,14 +6,14 @@ PREREQ="cryptroot"
prereqs()
{
echo "$PREREQ"
echo "$PREREQ"
}
case $1 in
prereqs)
prereqs
exit 0
;;
prereqs)
prereqs
exit 0
;;
esac
. /usr/share/initramfs-tools/hook-functions
@ -22,45 +22,77 @@ esac
# 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
for dir in etc/opensc usr/lib 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
if [ -e /lib/*`uname -i`*/libgcc_s.so.1 ]
ARCHDIR=$(uname -i)
if [ "$ARCHDIR" = "unknown" ]; then
ARCHDIR=$(uname -m)
fi
if [ -e /lib/*${ARCHDIR}*/libgcc_s.so.1 ]
then
copy_exec /lib/*`uname -i`*/libgcc_s.so.1 /lib
cp -L /lib/*${ARCHDIR}*/libgcc_s.so.1 ${DESTDIR}/lib
else
copy_exec /lib/libgcc_s.so.1 /lib
cp -L /lib/libgcc_s.so.1 ${DESTDIR}/lib
fi
if [ -e /lib/*`uname -i`*/libpcsclite.so.1 ]
if [ -e /lib/*${ARCHDIR}*/libpcsclite.so.1 ]
then
copy_exec /lib/*`uname -i`*/libpcsclite.so.1 /lib
cp -L /lib/*${ARCHDIR}*/libpcsclite.so.1 ${DESTDIR}/lib
elif [ -e /usr/lib/*${ARCHDIR}*/libpcsclite.so.1 ]
then
cp -L /usr/lib/*${ARCHDIR}*/libpcsclite.so.1 ${DESTDIR}/lib
else
copy_exec /lib/libpcsclite.so.1 /lib
cp -L /lib/libpcsclite.so.1 ${DESTDIR}/lib
fi
if [ -e /usr/lib/*`uname -i`*/libusb-1.0.so.0 ]
if [ -e /usr/lib/*${ARCHDIR}*/libusb-1.0.so.0 ]
then
copy_exec /usr/lib/*`uname -i`*/libusb-1.0.so.0 /usr/lib
else if [ -e /usr/lib/libusb-1.0.so.0 ]
cp -L /usr/lib/*${ARCHDIR}*/libusb-1.0.so.0 ${DESTDIR}/usr/lib
elif [ -e /lib/*${ARCHDIR}*/libusb-1.0.so.0 ]
then
copy_exec /usr/lib/libusb-1.0.so.0 /usr/lib
cp -L /lib/*${ARCHDIR}*/libusb-1.0.so.0 ${DESTDIR}/usr/lib
elif [ -e /usr/lib/libusb-1.0.so.0 ]
then
cp -L /usr/lib/libusb-1.0.so.0 ${DESTDIR}/usr/lib
else
echo "Unable to locate libusb-1.0"
exit 1
fi
cp -r /usr/lib/pcsc ${DESTDIR}/usr/lib
cp -LRp /usr/lib/pcsc ${DESTDIR}/usr/lib/
if [ -e /etc/reader.conf.d ]
then
cp -Rp /etc/reader.conf.d ${DESTDIR}/etc/
cp -L -Rp /etc/reader.conf.d ${DESTDIR}/etc/
else
cp /etc/reader.conf ${DESTDIR}/etc
cp -L /etc/reader.conf ${DESTDIR}/etc/
fi
# 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
copy_exec /usr/bin/opensc-tool /bin/
copy_exec /usr/bin/pkcs15-crypt /bin/
copy_exec /usr/bin/pkcs15-tool /bin/
cp -L /etc/opensc/opensc.conf ${DESTDIR}/etc/opensc/
# Install opensc interface library
if [ -e /usr/lib/*${ARCHDIR}*/opensc-pkcs11.so ]
then
cp -L /usr/lib/*${ARCHDIR}*/opensc-pkcs11.so ${DESTDIR}/usr/lib
elif [ -e /usr/lib/opensc-pkcs11.so ]
then
cp -L /usr/lib/opensc-pkcs11.so ${DESTDIR}/usr/lib
fi
# Install other required utilities
copy_exec /bin/grep /bin
@ -78,15 +110,20 @@ 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
copy_exec /usr/bin/cardpincheck /bin
# Libraries
# cp /usr/lib/libltdl.so* ${DESTDIR}/usr/lib
# cp /lib/libncurses.so.5 ${DESTDIR}/lib
if [ -e /lib/*`uname -i`*/libncursesw.so.5 ]
# cp -L /usr/lib/libltdl.so* ${DESTDIR}/usr/lib
# cp -L /lib/libncurses.so.5 ${DESTDIR}/lib
if [ -e /lib/*${ARCHDIR}*/libncursesw.so.5 ]
then
cp /lib/*`uname -i`*/libncursesw.so.5 ${DESTDIR}/lib
cp -L /lib/*${ARCHDIR}*/libncursesw.so.5 ${DESTDIR}/lib
else
cp /lib/libncursesw.so.5 ${DESTDIR}/lib
cp -L /lib/libncursesw.so.5 ${DESTDIR}/lib
fi
# LUKS keys
cp -LRp /etc/trinity/luks/card ${DESTDIR}/tde_luks_keys
exit 0

Loading…
Cancel
Save