Syed Jahanzaib – Personal Blog to Share Knowledge !

August 12, 2015

Passing PHP variables to Shell Script with CAPTCHA code [Example renew account via web]

Filed under: Linux Related, Radius Manager — Tags: , , , , — Syed Jahanzaib / Pinochio~:) @ 2:05 PM


For my personnel archive purpose only:

All of these tests were made in lab and later on tested on production network as well and worked perfectly. BUT before deploying it in production, one must ensure security , specially try to host it on https server, MUST add captcha in form to prevent BOTS attack, + one should consider BASH security and trimming + some functions to match with real live environment. all can be done easily if you have some knowledge on html/php/bash.


 

Scenario:

A simple portal page is required where user can input there user name and refill code in order to renew there internet account on billing system [in this example radius manager is being used]. then this html page will pass the user name and card number variable to php page which will execute an shell script to trigger renewal action based on the supplied variables. The shell script will check for following

  • Check for Valid Users name in Billing
  • Check for Valid Card number in billing refill card database
  • Check if card is used or not
  • Check the user current package and compare it with the card value
  • If all OK, renew the user account for next 30 days (or whatever actions is required)
  • Output the result to browser

 


 

Following file will present FORM where user can enter there user name and pin code/refill code.

input.html

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Refill your account ! </title>
</head>
<body>
<h1>Refill your account using scratch code:</h1>
<form method="post" action="function.php">
User Name: <br />
<input type="text" name="USERNAME" size="35" />
<br />
Card No: <br />
<input type="text" name="CARDNO" size="35" />
<br /> <br />
<input type="submit" value="Submit:" />
<br />
</form>
</body>
</html>

Following file will execute the SHELL script with the supplied username and pincode variable and echo there result in the browser.

function.php

<?php
$USERNAME = $_POST[‘USERNAME’];
$CARDNO = $_POST[‘CARDNO’];

if(empty($USERNAME ) || empty($CARDNO )) {
echo “<h2>You must fill in all fields</h2>\n” ;
die (“Click Back to start again.”);
}
echo “<h2>You have entered the following information:</h2>”;
echo “<pre>Customer name\t=\t$USERNAME <br></pre> “;
echo “<pre>Card No\t\t=\t$CARDNO</pre>”;

echo “<h2>BILLING RESPONSE</h2>”;
echo “======================”;
$var = shell_exec(“TERM=xterm /var/www/html/renew.sh $USERNAME $CARDNO”);
echo “<pre>$var</pre>”;
?>



BASH Shell script which will be executed by the function.php file

Contents of /var/www/html/renew.sh

{lab testing version, working ok, it may contain lot of junk or it can be trimmed, it’s upto you to make it look pro}

#!/bin/bash
#set -x
# SCRIPT TO RENEW USER ACCOUNT IN RADIUS MANAGER VIA WEB PORTAL
SQLUSER=”root”
SQLPASS=”zaib1234″
echo $1 $2 > /tmp/user-card
USR=`cat /tmp/user-card | awk {‘ print $1 ‘}`
CARD=`cat /tmp/user-card | awk {‘ print $2 ‘}`
NEXTEXPIRYADD=$(date +”%Y-%m-%d” -d “+31 days”)

#LOOK FOR EMPTY CARD NO IF ENTERED , EXIT
if [ “$1” == “” ]; then
echo -e “ERROR: ENTER USER NAME WITH CARD NUMBER PLEASE!”
exit 0
fi

#LOOK FOR VALID USER IN RADIUS
USRVALID=`mysql -u$SQLUSER -p$SQLPASS -e “use radius; SELECT srvid FROM radius.rm_users WHERE rm_users.username = ‘$USR’;”`
if [ “$USRVALID” == “” ]; then
echo -e “ERROR: USER NOT FOUND IN BILLING SYSTEM!!”
exit 0
fi

#LOOK FOR EMPTY CARD NO IF ENTERED , EXIT
if [ “$2” == “” ]; then
echo -e “ERROR: PLEASE ENTER CARD NUMBER!!”
exit 0
fi

# LOOK FOR USED CARDS
CARDSTATUS=`mysql -u$SQLUSER -p$SQLPASS -e “use radius; SELECT SQL_CALC_FOUND_ROWS cardnum, used, revoked, expiration, value, date, owner FROM rm_cards WHERE cardtype = ‘1’ AND cardnum = ‘$2’  ORDER BY cardnum ASC LIMIT 0, 50;” |  awk {‘print $8}’`
if [ -n “$CARDSTATUS” ]; then
echo -e “CARD IS ALREADY USED”
exit 0
fi

######################
# ACCOUNT EXPIRY CHECK
######################

TODAY=$(date +”%Y-%m-%d”)
TODAYDIGIT=`echo $TODAY  | sed -e ‘s/-//g’`
MONTH=$(date +”-%m”)
CMONTH=`echo $MONTH  | sed -e ‘s/-//g’`
MONTHYEAR=$(date +”%B-%Y”)
ALPHAMONTHYEAR=`echo $MONTHYEAR #| sed -e ‘s/-//g’`
SRVEXPIRYFULL=`mysql -u$SQLUSER -p$SQLPASS -e “use radius; SELECT expiration FROM radius.rm_users WHERE username = ‘$USR’;” |awk ‘FNR == 2’`
SRVEXPIRYFULLD=`mysql -u$SQLUSER -p$SQLPASS -e “use radius; SELECT expiration FROM radius.rm_users WHERE username = ‘$USR’;” |awk ‘{print $1}’ | sed ‘s/expiration//’`
SRVEXPIRY=`mysql -u$SQLUSER -p$SQLPASS -e “use radius; SELECT expiration FROM radius.rm_users WHERE username = ‘$USR’;” |awk ‘FNR == 2’ | sed -e ‘s/-//g’ | sed ‘s/00:.*//’`
LOGOFFDATE=`mysql -u$SQLUSER -p$SQLPASS -e “use radius; SELECT lastlogoff FROM radius.rm_users WHERE username = ‘$USR’;”  |awk ‘FNR == 2 {print $1,$2}’`
SRVID=`mysql -u$SQLUSER -p$SQLPASS -e “use radius; SELECT srvid FROM radius.rm_users WHERE rm_users.username = ‘$USR’;” |awk ‘FNR == 2 {print $1}’`
SRVPRICE=`mysql -u$SQLUSER -p$SQLPASS -e “use radius;  SELECT unitprice FROM radius.rm_services WHERE rm_services.srvid = $SRVID;” |awk ‘FNR == 2 {print $1}’ | cut -f1 -d”.”`
CARDPRICE=`mysql -u$SQLUSER -p$SQLPASS -e “use radius;  SELECT value FROM rm_cards WHERE cardnum = $CARD;” |awk ‘FNR == 2 {print $1}’ | cut -f1 -d”.”`
#LOOK FOR USER ACTUAL SERVICE NAME
PKGNAME=`mysql -u$SQLUSER -p$SQLPASS -e “use radius; SELECT srvname FROM radius.rm_services WHERE rm_services.srvid = ‘$SRVID’;” |awk ‘FNR == 2’`
# Look for Pakacge Quota trafficunitcomb
PKGQUOTA=`mysql -u$SQLUSER -p$SQLPASS -e “use radius; SELECT trafficunitcomb FROM rm_services WHERE srvid= ‘$SRVID’;” |awk ‘FNR == 2’`
PKGQUOTAB=$(($PKGQUOTA / 1024))
# Acount Registration FIRST n LAST NAME
USERFLNAME=`mysql -u$SQLUSER -p$SQLPASS -e “use radius; SELECT firstname,lastname FROM radius.rm_users WHERE rm_users.username = ‘$1’;” |awk ‘FNR == 2 {print $1,$2,$3}’;`

# LOOK FOR VALID REFILL CARD CODE IN RADIUS CARDS LIST
CARDVALIDATION=`mysql -u$SQLUSER -p$SQLPASS -e “use radius; SELECT value, expiration FROM rm_cards WHERE cardnum = ‘$CARD’ AND used = ‘0000-00-00 00:00:00’;”`
if [ “$CARDVALIDATION” == “” ]; then
echo -e “ERROR: INVALID CARD NUMBER!”
exit 0
else

# IF CARD VALUE IS LESS THEN CURRENT PACKAGE PRICE THEN PRINT ERROR AND GOTO END
if [ $CARDPRICE -lt $SRVPRICE ]
then
echo -e “ERROR: CARD PRICE IS NOT SUFFICIENT TO REFRESH $PKGNAME SERVICE”
exit 0
else

# IF CARD VALUE IS EQUAL OR HIGHER  THEN CURRENT PACKAGE PRICE THEN OK
if [ $CARDPRICE -eq $SRVPRICE ]
then
echo
fi

########### ACCOUNT STATUS EXPIRED TODAY ACTION ############
if [ $SRVEXPIRY -eq $TODAYDIGIT ]
then
echo “Account have been EXPIRED TODAY! Last LOGOUT date was $LOGOFFDATE”
NEXTEXPIRYADD=$(date +”%Y-%m-%d” -d “+31 days”)

# PRINT FETCHED VALUES , JUST FOR INFO / ZAIB
echo User Account  = $USR
echo User Actual Package at Billing = $PKGNAME PKR
echo Service Price at Billing = $SRVPRICE PKR
echo This Card Value is    = $CARDPRICE PKR
echo -e “Next Expiry =  $NEXTEXPIRYADD”

# ADD 30 DAYS VALUE TO EXPIRED USER ACCOUNT
mysql -u$SQLUSER -p$SQLPASS -e “use radius; UPDATE rm_users SET expiration = ‘$NEXTEXPIRYADD’ WHERE username = ‘$USR’;”

# ADD COMMENTS
mysql -u$SQLUSER -p$SQLPASS -e “use radius; UPDATE rm_users SET comment = ‘This account was last refresh from scratch code by SMS’ WHERE username = ‘$USR’;”

# ADD SYSLOG ENTRY
mysql -u$SQLUSER -p$SQLPASS -e “use radius; INSERT INTO rm_syslog (datetime, ip, name, eventid, data1) VALUES (NOW(), ‘n/a’, ‘SMSUSER_$USR’, ‘$USR’, ‘$USR renewd service > $PKGNAME’);”

# ADD ENTRY FOR CURRENT DATE TIME IN REFIL CARD TO PREVENT RE-USAGE OF SAME CARD NUMBER
mysql -u$SQLUSER -p$SQLPASS -e “use radius; UPDATE rm_cards SET owner = ‘$USR’, used = NOW() WHERE cardnum = ‘$CARD’;”

########### ACCOUNT STATUS EXPIRED IN PAST ACTION ############

elif [ $SRVEXPIRY -lt $TODAYDIGIT ]
then
echo “ACCOUNT WAS EXPIRED on $SRVEXPIRYFULL !  Last LOGOUT date was $LOGOFFDATE”
NEXTEXPIRYADD=$(date +”%Y-%m-%d” -d “+31 days”)

# PRINT FETCHED VALUES , JUST FOR INFO / ZAIB
echo User Account  = $USR
echo User Actual Package at Billing = $PKGNAME PKR
echo Service Price at Billing = $SRVPRICE PKR
echo This Card Value is    = $CARDPRICE PKR
echo -e “Next Expiry =  $NEXTEXPIRYADD”

# ADD 30 DAYS VALUE TO EXPIRED USER ACCOUNT
mysql -u$SQLUSER -p$SQLPASS -e “use radius; UPDATE rm_users SET expiration = ‘$NEXTEXPIRYADD’ WHERE username = ‘$USR’;”

# ADD COMMENTS
mysql -u$SQLUSER -p$SQLPASS -e “use radius; UPDATE rm_users SET comment = ‘This account was last refresh from scratch code by SMS’;”

# ADD SYSLOG ENTRY
mysql -u$SQLUSER -p$SQLPASS -e “use radius; INSERT INTO rm_syslog (datetime, ip, name, eventid, data1) VALUES (NOW(), ‘n/a’, ‘SMSUSER_$USR’, ‘$USR’, ‘$USR renewd service > $PKGNAME’);”

# ADD ENTRY FOR CURRENT DATE TIME IN REFIL CARD TO PREVENT RE-USAGE OF SAME CARD NUMBER
mysql -u$SQLUSER -p$SQLPASS -e “use radius; UPDATE rm_cards SET owner = ‘$USR’, used = NOW() WHERE cardnum = ‘$CARD’;”

# Update QUOTA for the USER
mysql -u$SQLUSER -p$SQLPASS -e “use radius; UPDATE rm_users SET comblimit = ‘$PKGQUOTAB’ WHERE username = ‘$USR’;”

else
########### ACCOUNT STATUS OK! ACTION ############

echo -e “User Billing Info:”
echo “Account STATUS= OK!”

NEXTEXPIRYADD=`mysql -u$SQLUSER -p$SQLPASS -e “use radius; select DATE_ADD(expiration, INTERVAL 31 DAY) as x from rm_users where username= ‘$USR’;” |awk ‘FNR == 2’`

# PRINT FETCHED VALUES , JUST FOR INFO / ZAIB
echo User Account  = $USR
echo Owner = $USERFLNAME
echo User Actual Package at Billing = $PKGNAME PKR
echo Service Price at Billing = $SRVPRICE PKR
echo This Card Value is    = $CARDPRICE PKR
echo -e “Next Expiry =  $NEXTEXPIRYADD”

NEXTEXPIRYADD=`mysql -u$SQLUSER -p$SQLPASS -e “use radius; select DATE_ADD(expiration, INTERVAL 31 DAY) as x from rm_users where username= ‘$USR’;” |awk ‘FNR == 2’`

# ADD 30 DAYS VALUE TO EXPIRED USER ACCOUNT
mysql -u$SQLUSER -p$SQLPASS -e “use radius; UPDATE rm_users SET expiration = ‘$NEXTEXPIRYADD’ WHERE username = ‘$USR’;”

# ADD COMMENTS
mysql -u$SQLUSER -p$SQLPASS -e “use radius; UPDATE rm_users SET comment = ‘This account was last refresh from scratch code by SMS’ WHERE username = ‘$USR’;”

# ADD SYSLOG ENTRY
mysql -u$SQLUSER -p$SQLPASS -e “use radius; INSERT INTO rm_syslog (datetime, ip, name, eventid, data1) VALUES (NOW(), ‘n/a’, ‘SMSUSER_$USR’, ‘$USR’, ‘$USR renewd service > $PKGNAME’);”

# ADD ENTRY FOR CURRENT DATE TIME IN REFIL CARD TO PREVENT RE-USAGE OF SAME CARD NUMBER
mysql -u$SQLUSER -p$SQLPASS -e “use radius; UPDATE rm_cards SET owner = ‘$USR’, used = NOW() WHERE cardnum = ‘$CARD’;”

fi
fi
fi

########### ACCOUNT STATUS EXPIRED TODAY ACTION ############
if [ $PKGQUOTA -eq 0 ]
then
echo -e “Total Quota Allowed = No Quota”
else
echo -e “Total Quota Allowed = $PKGQUOTAB GB”
fi
echo -e “Done/Note: Card Number $CARD is marked as used in DB to prevent re-usege”


 

RESULTS:

1- enter details


 

If the script found that the user name not valid in the billing , spit the error

0- user not found


 

If the script found that the card number is not available in the billing , spit the error

2- invalid number


 

If the script found that the card number entered is already used , spit the error

3- card already used


 

If the script found both fields blank, spit the error

4- you must fill in all fields


 

If the script found user name and card matches, then proceed to renew the account

5- if all ok renew the account

You can also take different actions like send Email / SMS to ADMIN, and user both or any other action.


 


 


 


 


 

re-captcha

ADDING CAPTCHA SECURITY IN FORM

To add captcha security in html form, (which should be must in my opinion for security reasons)

Download secureimage and unzip in your web folder like /var/www/html/secureimage

mkdir /temp

cd /temp

wget https://www.phpcaptcha.org/latest.tar.gz

tar zxvf latest.tar.gz

mv securimage/ /var/www/html/

Now edit the html form to add the captcha facility

TEST.HTML [Red highlighted are our code for captcha]

<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>Refill your account ! </title>
</head>
<body>
<h1>Refill your account using scratch code:</h1>
<form method=”post” action=”test.php”>
User Name: <br />
<input type=”text” name=”USERNAME” size=”35″ />
<br />
Card No: <br />
<input type=”text” name=”CARDNO” size=”35″ />
<br /> <br />
<input type=”submit” value=”Submit:” />
<br />
</body>
<img id=”captcha” src=”/securimage/securimage_show.php” alt=”CAPTCHA Image” />
<input type=”text” name=”captcha_code” size=”10″ maxlength=”6″ />
<a href=”#” onclick=”document.getElementById(‘captcha’).src = ‘/securimage/securimage_show.php?’ + Math.random(); return false”>[ Different Image ]</a>
</form>
</html>

TEST.PHP [Red highlighted are our code for captcha]

<?php
include_once $_SERVER[‘DOCUMENT_ROOT’] . ‘/securimage/securimage.php’;
$securimage = new Securimage();
if ($securimage->check($_POST[‘captcha_code’]) == false) {
  echo “The CAPTCHA security code entered was incorrect. Make Sure You are HUMAN  zaib!<br /><br />”;
  echo “Please go <a href=’javascript:history.go(-1)’>back</a> and try again.”;
  exit;
}
$USERNAME = $_POST[‘USERNAME’];
$CARDNO = $_POST[‘CARDNO’];
if(empty($USERNAME ) || empty($CARDNO )) {
echo “<h2>You must fill in all fields</h2>\n” ;
die (“Click Back to start again.”);
}
echo “<h2>You have entered the following information: zaib</h2>”;
echo “<pre>Customer name\t=\t$USERNAME <br></pre> “;
echo “<pre>Card No\t\t=\t$CARDNO</pre>”;
echo “<h2>BILLING RESPONSE</h2>”;
echo “======================”;
$var = shell_exec(“TERM=xterm /var/www/html/renew.sh $USERNAME $CARDNO”);
echo “<pre>$var</pre>”;
?>

Now result would be as follow

captcha

captcha-wrong


Regard’s
Syed JAHANZAIB

14 Comments »

  1. dear jahanzaib plzzz do reply on this post https://aacable.wordpress.com/2015/06/15/sending-email-on-router-reboot-with-logs-and-lastseen-time/#comments
    it needs ur concentration .

    Like

    Comment by Rehmat Ali Gulwating — August 16, 2015 @ 12:22 AM

  2. great efforts from you — thanks for that —
    i have idea that you can add
    why did you canceled the card with a different package however you can change user package to the new one (as the user may change his package by his will)
    so he can renew his package or convert to another package (user can do what he need to without return to server administrator)
    what do you think about that

    Like

    Comment by Ahmed — September 4, 2015 @ 8:55 PM

    • also why name is not automatic selected to prevent any mistakes in entering data –(also have idea for how to do it)–
      contact me please
      best regards

      Like

      Comment by Ahmed — September 4, 2015 @ 9:02 PM

  3. Dear Zabi
    Will thanks you for all the effort and also sharing ur ideas.
    Most really fit my situation and had safe me from loosing clients.

    Can we have simple portal page which will required manager to input the user name and amount of money deposited into user’s internet account .
    Just like the one for refill code.
    Thanks

    Like

    Comment by na — September 25, 2015 @ 10:54 PM

    • @na
      babamusah@gmail.com
      Yes it can be done easily. you can use the same coding with modification to fulfill your task. its EID holidays here, remind me on monday and i will make one for you with addition of security to login to that page as well because this page must be secure otherwise it can fall under wrong hands too 😉 😀

      Like

      Comment by Syed Jahanzaib / Pinochio~:) — September 26, 2015 @ 11:54 AM

      • thanks for replying to me
        i have modified the input.html file to be with code only like that
        ********************

        Refill your account !

        Refill your account using scratch code:

        Card No:

        **********************
        and function.php to be like that
        **********************
        connect_error) {
        die(“Connection failed: ” . $conn->connect_error);
        }

        $sql = “SELECT username FROM radacct WHERE framedipaddress = ‘$ipadd’ ORDER BY radacctid DESC LIMIT 0, 1”;
        $result = $conn->query($sql);
        if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
        $uname = “”.$row[‘username’].””;
        }
        } else {
        echo “0 results”;
        }
        $conn->close();
        if(empty($uname ) || empty($CARDNO )) {
        echo “You must fill in all fields\n” ;
        die (“Click Back to start again.”);
        }
        echo “You have entered the following information:”;
        echo “

        Customer name\t=\t$uname 

        “;
        echo “

        Ip Address\t=\t$ipadd 

        “;
        echo “

        Card No\t\t=\t$CARDNO

        “;

        echo “BILLING RESPONSE”;
        echo “======================”;

        $var = shell_exec(“TERM=xterm /var/www/test/renew.sh $uname $CARDNO”);
        echo “

        $var

        “;
        ?>
        ************************************
        and to that limit it works fin but i found problem in your code with coma’s that made it stop at the beginning but after modifying them it works well until the function.php file but nothing appear in the section server respond seems the file renew.php not working but i don’t know why
        ************************************
        cane it be done if you completely depend on the function.php file to do all the work as it already has a connection with the sql server so it will compare and do all the work???

        Like

        Comment by Ahmed — September 28, 2015 @ 12:05 AM

      • Hi Zabi
        Just reminding you of the adding deposit html.
        Best Regard
        Baba-Musah

        Like

        Comment by na — September 28, 2015 @ 2:47 PM

      • replied you on email already.

        Like

        Comment by Syed Jahanzaib / Pinochio~:) — September 28, 2015 @ 5:08 PM

  4. how can i past my modefied code here

    Like

    Comment by Ahmed — September 28, 2015 @ 12:35 AM

  5. You have entered the following information:

    Customer name = 111
    Card No = 11111
    BILLING RESPONSE

    ======================
    billing response in not showing . I get nothing .!!!!!!!!!!!!!!!!! why billing response is not showing ………… please response ASAp… can you help me to send these codes to my emaid … is there any wrong in coding. how to execute this shell script.
    thanks
    raziv ferdous

    Like

    Comment by ferdous — October 18, 2015 @ 5:24 AM

  6. =================================================
    <?php
    $USERNAME = $_POST[USERNAME];
    $CARDNO = $_POST[CARDNO];

    if(empty($USERNAME ) || empty($CARDNO )) {
    echo You must fill in all fields\n ;
    die (Click Back to start again.);
    }
    echo You have entered the following information:;
    echo

    Customer name\t=\t$USERNAME 

    ;
    echo

    Card No\t\t=\t$CARDNO

    ;

    echo BILLING RESPONSE;
    echo ======================;
    $var = shell_exec(TERM=xterm /var/www/html/renew.sh $USERNAME $CARDNO);
    echo

    $var

    ;
    ?>
    ================================================================
    WHEN I COPY PASTE THESE CODES . IT SHOWS IN MY LINUX MACHINE LIKE THIS !!!!!!!!!!!!!!!!!!!!!!!!! WHERE HAVE I DONE WRONG !!!!!!!!!!!!!!!!!!!

    Like

    Comment by ferdous — October 18, 2015 @ 5:30 AM

  7. <?php
    $USERNAME = $_POST[USERNAME];
    $CARDNO = $_POST[CARDNO];

    if(empty($USERNAME ) || empty($CARDNO )) {
    echo You must fill in all fields\n ;
    die (Click Back to start again.);
    }
    echo You have entered the following information:;
    echo

    Customer name\t=\t$USERNAME 

    ;
    echo

    Card No\t\t=\t$CARDNO

    ;

    echo BILLING RESPONSE;
    echo ======================;
    $var = shell_exec(TERM=xterm /var/www/html/renew.sh $USERNAME $CARDNO);
    echo

    $var

    ;
    ?>

    ================================================================
    WHEN I COPY PASTE THESE CODES . IT SHOWS IN MY LINUX MACHINE LIKE THIS !!!!!!!!!!!!!!!!!!!!!!!!! WHERE HAVE I DONE WRONG !!!!!!!!!!!!!!!!!!!

    Like

    Comment by ferdous — October 18, 2015 @ 5:32 AM

  8. billing response shows nothing …………..!!!!!!!!!!!!!!!!!!!!!!!!!!! please reply ASAP . i m using radius manager 4.0.2

    Like

    Comment by ferdous — November 28, 2015 @ 2:16 AM

  9. Updated link for CAPTCHA software.
    https://github.com/dapphp/securimage/archive/3.6.2.tar.gz
    mv 3.6.2.tar.gz secureimage
    and use it according to the need

    Like

    Comment by Syed Jahanzaib / Pinochio~:) — February 17, 2016 @ 2:56 PM


RSS feed for comments on this post. TrackBack URI

Leave a comment