Thursday, August 1, 2013

bash - putting complicated strings/text into a variable

It is a usual practice to generate commands within a script and later execute them with eval. Or one simply want to put into a variable some weird string containing quotes and other special characters. To avoid having to quote or escape everything, just write what you want to see into the variable, here's a simple way to do it... looking at it seems so obvious but truth is I never thought about that approach before:
read -r myvar << "EOF"
STRING with quotes (') and other special characters like $ and ! and #
I came to it while trying to use sed to insert another sed command into a script. Here is how it ended up like:
read -r sed_cmd <<"EOL"
sed -i -e 's#<systemPropertyVariables#<systemPropertyVariables combine.children="append"#' testsuite/integration/*/pom.xml
sed -i -e "s%mvn%$sed_cmd\nmvn%"

gauthj2me vs LinOTP

Update: one of best TOTP j2me program out there is: totp-me. It is small enough to fit in older phones memory and is intuitive, easy to use and feature rich (sha1, sha-256, sha-512, multiple accounts, key generator). Use the below notes only if totp-me does not work for you for some reason.

Writing this to hopefully safe somebody's time trying to setup LinOTP with the gauthj2me soft token generator. There is no documentation on site so I had to look at the source to see how it works.
Why gauthj2me? It's only 34k and fits in even most constrained phone memory like old s40 nokias (tested on nokia 6070 with a 128k jar limit/ 150k installing from internet). Still it features sha1 which seems required for LinOTP TOTP setup. Thus it has a limit of 32 base32 digits (160bits). With more recent devices another alternative is lwuitgauthj2me which is more feature rich but over 220k. There seems to be another alternative - DS3 Oath which should also work based on their documentation. It is HOTP unlike gauthj2me which is TOTP (access number vs time based).

Anyways, here you find my quick notes on setting that up (shell commands for fedora 18):
# Download and install to phone
# go to LinOTP self service console -> Enroll TOTP
# enter seed in hex digits (see below), sha1, 30 seconds
# click on the button "enroll TOTP Token"
# go to Resync Token tab to sync and test your soft token

#  Prepare a base32 encoder (thanks to cjc)
yum install perl-MIME-Base32
cat > << "EOF"

use MIME::Base32 qw( RFC );

undef $/;  # in case stdin has newlines
$string = ;

$encoded = MIME::Base32::encode($string);

print "$encoded\n";
chmod 755

#  enable hardware enthropy sources
#  /funny how slow is random without a hw rng/
sudo systemctl enable rngd
sudo systemctl start rngd

#  generate ranndom 160bit key
# gauthj2me supports up to 32 base32 places (160bits)
dd if=/dev/random of=/tmp/key bs=1 count=20
# enter as seed in LinOTP management console
cat /tmp/key | xxd -ps
# enter this in Swarte Token Generator /that is PITA/
cat /tmp/key | ./