Sunday, April 3, 2016

Hotspot self registration PHP form with captcha and SMS/Email function

c

TASK:

It is required that user can connect to open WiFi network (probably running Mikrotik hotspot system) and upon browsing he will see the login page with REGISTER option as well. User can self register his account on radius billing system by using PHP FORM[for example can be used in FREE WiFi environment, exhibition, conference rooms, resorts etc].
It is also useful if you want to provide trial/free internet access but want to log all the required info , like mobile numbers, contacts, and there usage with control.
Upon submissions, PHP form will execute Linux bash script with the supplied data, and then it should perform various checks , example.
  • User must enter no less or more  then 11 numeric digits in MOBILE field.
  • User must enter no less or more  then 13 numeric digits in CNIC field.
  • User must enter correct CAPTCHA image code in order to submit the form. It is required in order to prevent BRUTE force attack using automated scripting.
  • If the user is registering for the first time, his account will be registered with specific service (the service must be added by admin, and its name is configurable in reg.sh script file. The system will send SMS (and print screen , you can configure it as per the requirements) to user mobile number supplied in the form with the login , validity and other information.
  • The user should be allowed 3 hours for the current day (or as per the profile configured in reg.sh)
  • If the user consumed 3 hours within the same date and try to register again, he will be denied with the information message that he have already registered with the same mobile and account status will be provided like still ACTIVE or EXPIRED and that he should try again next day (date).
  • If the user still have balance and account is active, he should be informed accordingly.
  • If the user have expired (dueto DATE OR UPTIME hours limit) and next date arrived, he can register again, and INFO SMS message (and print screen , you can configure it as per the requirements) will be sent to use informing that his previously registered account got renewed with the login , validity and other information.


Components Used:

1- Ubuntu
2- Apache Web Server
3- Radius Manager as Billing system in working condition
4- GSM Modem used to send SMS to containing the information
5- KANNEL as SMS gateway
6- Captcha code software for prevention of BRUTE force attack, Make sure to install it in /var/www/reg/securimage, test it to make sure its showing images properly.


SCRIPTS:

Following PHP page and scripts should be copied to /var/www/reg folder [for ubuntu]
  1. user.php [User Input Registration Form]
  2. reg-display.php [Displays the User Input Result and execute the Script which executes the action]
  3. reg.sh [main script that executes the action based on supplied information by reg-display.sh]




1- user.php [User Input Registration Form]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<!DOCTYPE html>
<html>
<head>
<script>
$(document).ready(function() {
$("#start_datepicker").datepicker({ dateFormat: 'yy-mm-dd' });
$("#end_datepicker").datepicker({ dateFormat: 'yy-mm-dd' }).bind("change",function(){
var minValue = $(this).val();
minValue = $.datepicker.parseDate("yy-mm-dd", minValue);
minValue.setDate(minValue.getDate()+1);
$("#to").datepicker( "option", "minDate", minValue );
})
});
</script>
</head>
<body style="font-size:62.5%;">
<form action="reg-display.php" method="post">
<h1><font color="blue">Register yourself to get one hour internet access for current day.<br></font> <br><br>
 
<pre>
MOBILE NUMBER    : <input pattern=".{11,11}" onkeypress='return event.charCode >= 48 && event.charCode <= 57' name="mobile" cnic="11 characters minimum" maxlength="11">  [11 Numeric Digits Only Without dash/space]
 
CNIC NO        : <input pattern=".{13,13}" onkeypress='return event.charCode >= 48 && event.charCode <= 57' name="cnic" cnic="13 characters minimum"maxlength="13">  [13 Numeric Digits Only Without dash/space]
 
FIRST NAME    : <input type="text" name="firstname">
 
LAST NAME    : <input type="text" name="lastname">
 
<br></h1>
</pre>
<input type="submit" value="Submit:">
 
<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>
</body>
<br>
<br>
 
<?php
$ip = "";
if (!empty($_SERVER["HTTP_CLIENT_IP"]))
{
//check for ip from share internet
$ip = $_SERVER["HTTP_CLIENT_IP"];
}
elseif (!empty($_SERVER["HTTP_X_FORWARDED_FOR"]))
{
// Check for the Proxy User
$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
}
else
{
$ip = $_SERVER["REMOTE_ADDR"];
}
echo "<pre><h2>YOUR IP Address is        : $ip</h2></pre>";
?>
 
<h3><font color="red">This System is powered by Syed_Jahanzaib aacable@hotmail.com
</html>



2- reg-display.sh [Displays the User Input Result and execute the Script which executes the action]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?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;
}
 
$MOBILE = $_POST['mobile'];
$CNIC = $_POST['cnic'];
$FIRSTNAME = $_POST['firstname'];
$LASTNAME = $_POST['lastname'];
 
$ip = "";
 
if (!empty($_SERVER["HTTP_CLIENT_IP"]))
{
//check for ip from share internet
$ip = $_SERVER["HTTP_CLIENT_IP"];
}
elseif (!empty($_SERVER["HTTP_X_FORWARDED_FOR"]))
{
// Check for the Proxy User
$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
}
else
{
$ip = $_SERVER["REMOTE_ADDR"];
}
 
echo "<h2><u>You have entered the following information:</u></h2>";
echo "<pre>Mobile        : $MOBILE</pre>";
echo "<pre>CNIC No        : $CNIC</pre>";
echo "<pre>Firstname    : $FIRSTNAME</pre>";
echo "<pre>Lastname    : $LASTNAME</pre>";
echo "<pre>IP Address is    : $ip</pre>";
 
 
echo "<h2><u>BILLING RESPONSE</u></h2>";
$var = shell_exec("TERM=xterm /var/www/reg/reg.sh $MOBILE $CNIC $ip $FIRSTNAME $LASTNAME");
echo "<pre>$var</pre>";
 
?>


3- reg.sh [main script that executes the action based on supplied information by reg-display.sh]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
#!/bin/sh
# CREATE NEW USER VIA PHP/HTML INPUT FORMS AND ADD IN MYSQL DB, MADE FOR RADIUS MANAGER
# LOTS OF VAROIUS CHECKS added
# CREATED : 17-FEB-2016
# LAST MODIFIED =
# set -x
 
# ========================================================================================================================
# Service name (exact) you want to provide to temporary hotspot users - CHANGE IT FOR SURE - valid for RADIUS MANAGER only
SRVNAME="hotspot1mb"
# ========================================================================================================================
 
 
SQLUSER="root"
SQLPASS="MYSQL_PASSWORD"
COMPANY="JAHANZAIB-PVT-LTD"
NEXTEXPIRYADD=$(date +"%Y-%m-%d" -d "+1 days")
CURDATE=$(date +"%Y-%m-%d")
CURDATEWOD=`date +%Y%m%d`
TIME=`date | awk {'print $4'}`
 
# KANNEL RELATED INFORMATION
KID="kannel"
KPASS="KANNEL_PASSWORD"
KHOST="127.0.0.1"
 
#################################
###### DONOT EDIT BELOW  ########
#################################
 
# Create temporary holder if not already there, for the user data and empty it as well
touch /tmp/$1.txt
> /tmp/$1.txt
echo $1 $2 $3 $4 $5  >> /tmp/$1.txt
 
MOBILE=`cat /tmp/$1.txt |awk '{print $1}'`
CNIC=`cat /tmp/$1.txt |awk '{print $2}'`
IP=`cat /tmp/$1.txt |awk '{print $3}'`
FIRSTNAME=`cat /tmp/$1.txt |awk '{print $4}'`
LASTNAME=`cat /tmp/$1.txt |awk '{print $5}'`
 
# Look for user service ID - Example 1mbps service
SRVID=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT srvid FROM radius.rm_services WHERE rm_services.srvname = '$SRVNAME';" |awk 'FNR == 2 {print $1}'`
 
# Look for user Registration date
REGDATE=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT createdon FROM radius.rm_users WHERE rm_users.username = '$MOBILE';" |awk 'FNR == 2 {print $1}'`
 
# Look for registration date without digits for comparision
REGDATEWOD=`mysql -u$SQLUSER -p$SQLPASS -e "use radius; SELECT createdon FROM radius.rm_users WHERE rm_users.username = '$MOBILE';" |awk 'FNR == 2 {print $1}' | sed 's/-//g'`
 
#LOOK FOR VALID USER IN RADIUS
USRVALID=`mysql -uroot -p$SQLPASS -e "use radius; SELECT username FROM radius.rm_users WHERE rm_users.username = '$MOBILE';" |awk 'FNR == 2 {print $1}'`
 
# Look for EXPIRATION
CUREXPIRY=`mysql -uroot -p$SQLPASS --skip-column-names  -e "use radius; SELECT expiration FROM radius.rm_users WHERE rm_users.username = '$MOBILE';"`
 
# Look for UPTIME Limit - usually in hour unit format e.g : 1 , also it will be shown for user friendly format later
UPTIMELIMIT=`mysql -uroot -p$SQLPASS --skip-column-names  -e "use radius; SELECT timeunitonline FROM rm_services WHERE srvid = '$SRVID';"`
 
# Get UPTIME limit in seconds so that it can etner correctly in user propfile, seconds format also required for MYSQL TABLE for correct entry
FUPTIME=`echo "$UPTIMELIMIT*60*60" | bc`
 
# Welcome Message for NEW or returning User
if [ "$MOBILE" = "$USRVALID" ]; then
echo "Welcome back Mr. $FIRSTNAME $LASTNAME!"
else
echo "Welcome NEW User"
fi
 
# Check for registered Date, if no previous registeration date found, then treat user as NEW
if [ -z "$REGDATEWOD" ]; then
echo "No registration Date found previosly, treating it as a new user. proceed to new create new user"
 
# Add user in MYSQL TABLE now
mysql -u$SQLUSER -p$SQLPASS -e "use radius; INSERT INTO rm_users (
username, password, downlimit, uplimit, comblimit, firstname, lastname, company,
phone, mobile, email, address, city, zip, country, state, comment, mac, expiration,
enableuser, usemacauth, uptimelimit, srvid, staticipcm, staticipcpe, ipmodecm, ipmodecpe,
createdon, acctype, createdby, taxid, maccm, credits, owner, groupid, custattr, poolidcm, poolidcpe,
contractid, contractvalid, gpslong, gpslat, alertemail, alertsms, lang)
VALUES (
'$MOBILE', MD5('$MOBILE'), '0', '0', '0', '$FIRSTNAME', '$LASTNAME', '',
'', '', '', '', '', '', '', '', '', '', '$NEXTEXPIRYADD',
'1', '', '$FUPTIME', '$SRVID', '', '', '', '0', NOW(), '0',
'admin', '', '', '0.00', 'admin', '1', '', '', '',
'', '', '', '', 1, 1, 'English' );"
 
# Add user access in RADCHECK Table and SYSLOG as well
mysql -u$SQLUSER -p$SQLPASS -e "use radius; INSERT INTO radcheck (UserName, Attribute, op, Value) VALUES ('$MOBILE', 'Cleartext-Password', ':=', '$MOBILE');"
mysql -u$SQLUSER -p$SQLPASS -e "use radius; INSERT INTO radcheck (UserName, Attribute, op, Value) VALUES ('$MOBILE', 'Simultaneous-Use', ':=', '1');"
mysql -u$SQLUSER -p$SQLPASS -e "use radius; INSERT INTO rm_syslog (datetime, ip, name, eventid, data1) VALUES (NOW(), '$IP', 'ROBOT', '0', '$MOBILE');"
#mysql -uroot -p$SQLPASS -e "use radius; INSERT INTO tempuser (mobile, firstname, lastname, cnic, rendate) VALUES ('zaib888mobile', 'testfirst', 'testlast', '234567890', '$CURDATE $TIME');"
 
# Look for EXPIRATION for NEW User (account created above)
CUREXPIRY=`mysql -uroot -p$SQLPASS --skip-column-names  -e "use radius; SELECT expiration FROM radius.rm_users WHERE rm_users.username = '$MOBILE';"`
 
# OUTPUT RESULT FOR USER on SCREEN / OR BETTER TO SEND IT TO USER VIA SMS
echo "Dear $FIRSTNAME $LASTNAME,
 
Your NEW account have been successfuly registered on $COMPANY System.
You can use following login information to connect.
Your IP  = $IP
User ID  = $MOBILE
Password = $MOBILE
Validity = $CUREXPIRY
Uptime   = $UPTIMELIMIT Hours
 
Regard's
$COMPANY" > /tmp/$MOBILE.sms
 
cat /tmp/$MOBILE.sms
 
echo "Sending SMS to the registered Mobile number"
 
# Sending NEW ACCOUNT CREATION INFO  SMS to user mobile numbers
curl "http://$KHOST:13013/cgi-bin/sendsms?username=$KID&password=$KPASS&to=$MOBILE" -G --data-urlencode text@/tmp/$MOBILE.sms
 
else
 
#######################################
# Check for ACCOUNT status for ACTIVE OR EXPIRED
STATUS=""
ESTATUS=""
LTATUS=""
 
QSTATUS=`mysql -uroot -p$SQLPASS --skip-column-names  -e "use radius; SELECT SQL_CALC_FOUND_ROWS username, firstname, lastname, address, city, zip, country, state, phone, mobile,
email, company, taxid, srvid, downlimit, uplimit, comblimit, expiration, uptimelimit, credits, comment,
enableuser, staticipcpe, staticipcm, ipmodecpe, ipmodecm, srvname, limitdl, limitul, limitcomb, limitexpiration,
limituptime, createdon, verifycode, verified, selfreg, acctype, maccm, LEFT(lastlogoff, 10)
, IF (limitdl = 1, downlimit - COALESCE((SELECT SUM(acctoutputoctets) FROM radacct
WHERE radacct.username = tmp.username) -
(SELECT COALESCE(SUM(dlbytes), 0) FROM rm_radacct
WHERE rm_radacct.username = tmp.username), 0), 0),
 
IF (limitul = 1, uplimit - COALESCE((SELECT SUM(acctinputoctets) FROM radacct
WHERE radacct.username = tmp.username) -
(SELECT COALESCE(SUM(ulbytes), 0) FROM rm_radacct
WHERE rm_radacct.username = tmp.username), 0), 0),
 
IF (limitcomb =1, comblimit - COALESCE((SELECT SUM(acctinputoctets + acctoutputoctets) FROM radacct
WHERE radacct.username = tmp.username) -
(SELECT COALESCE(SUM(ulbytes + dlbytes), 0) FROM rm_radacct
WHERE rm_radacct.username = tmp.username), 0), 0),
 
IF (limituptime = 1, uptimelimit - COALESCE((SELECT SUM(acctsessiontime) FROM radacct
WHERE radacct.username = tmp.username) -
(SELECT COALESCE(SUM(acctsessiontime), 0) FROM rm_radacct
WHERE rm_radacct.username = tmp.username), 0), 0)
 
FROM
(
SELECT username, firstname, lastname, address, city, zip, country, state, phone, mobile, email, company,
taxid, rm_users.srvid, rm_users.downlimit, rm_users.uplimit, rm_users.comblimit, rm_users.expiration,
rm_users.uptimelimit, credits, comment, enableuser, staticipcpe, staticipcm, ipmodecpe, ipmodecm, srvname, limitdl,
limitul, limitcomb, limitexpiration, limituptime, createdon, verifycode, verified, selfreg, acctype, maccm,
mac, groupid, contractid, contractvalid, rm_users.owner, srvtype, lastlogoff
FROM rm_users
JOIN rm_services USING (srvid)
 
ORDER BY username ASC
) AS tmp
WHERE 1
AND username LIKE '$MOBILE%'
AND (tmp.acctype = '0'  OR tmp.acctype = '6' )
AND tmp.enableuser = 1 AND
(IF (limitdl = 1, downlimit - (SELECT COALESCE(SUM(acctoutputoctets), 0)
FROM radacct WHERE radacct.username = tmp.username) - (SELECT COALESCE(SUM(dlbytes), 0)
FROM rm_radacct WHERE rm_radacct.username = tmp.username) , 1) <= 0
OR
IF (limitul = 1, uplimit - (SELECT COALESCE(SUM(acctinputoctets), 0)
FROM radacct WHERE radacct.username = tmp.username) - (SELECT COALESCE(SUM(ulbytes), 0)
FROM rm_radacct WHERE rm_radacct.username = tmp.username) , 1) <= 0
OR
IF (limitcomb = 1, comblimit -
(SELECT COALESCE(SUM(acctinputoctets + acctoutputoctets), 0)
FROM radacct WHERE radacct.username = tmp.username) +
(SELECT COALESCE(SUM(ulbytes + dlbytes), 0)
FROM rm_radacct WHERE rm_radacct.username = tmp.username) , 1) <= 0
OR
IF (limituptime = 1, uptimelimit - (SELECT COALESCE(SUM(acctsessiontime), 0)
FROM radacct WHERE radacct.username = tmp.username) + (SELECT COALESCE(SUM(acctsessiontime), 0)
FROM rm_radacct WHERE rm_radacct.username = tmp.username) , 1) <= 0
OR
IF (limitexpiration=1, UNIX_TIMESTAMP(expiration) - UNIX_TIMESTAMP(NOW()), 1) <= 0)
 
LIMIT 0, 50;"`
 
 
# Store STATUS for ACTIVE OR EXPIRED in VARIABLE
if [ -z "$QSTATUS" ]; then
FSTATUS="ACTIVE"
else
FSTATUS="EXPIRED"
fi
 
# IF user registered today, then DONOT RE_REGISTER the USER and EXIT THE SCRIPT / zaib
if [ "$REGDATEWOD" -eq "$CURDATEWOD" ]; then
echo "Dear Mr. $FIRSTNAME $LASTNAME
 
INFO: This mobile number is already allowed to use intenret for today!
 
Account Details:
USER ID = $MOBILE
STATUS = $FSTATUS
Expiration    = $CUREXPIRY
Uptime Limit = $UPTIMELIMIT - Hours
 
For same day, you cannot register new account or Renew old account on same mobile number
 
$COMPANY
" > /tmp/$MOBILE.sms
 
cat /tmp/$MOBILE.sms
 
echo "Sending SMS to the registered Mobile number"
 
# Sending DENIAL (already registered and ACTIVE)  SMS to user mobile numbers
curl "http://$KHOST:13013/cgi-bin/sendsms?username=$KID&password=$KPASS&to=$MOBILE" -G --data-urlencode text@/tmp/$MOBILE.sms
 
exit 0
fi
 
# IF Account is ACTIVE AND VALID FOR TODAY, then INFORM USER AND EXIT THE SCRIPT
 
if [ "$FSTATUS" = "ACTIVE" ]; then
echo "Account Already ACTIVE
Validity = $CURDATE
Uptime   = $UPTIMELIMIT Hours"
 
exit 0
fi
 
# IF USER is ALREADY IN DB, AND STATUS IS EXPIRED, AND VALID FOR RENEWAL (24 HOURS PASSWED) THEN RENEW THE USER : ) / zaib
mysql -uroot -p$SQLPASS --skip-column-names  -e "use radius; UPDATE rm_users SET downlimit = '0', uplimit = '0', comblimit = '0', expiration = '$NEXTEXPIRYADD', uptimelimit = '$UPTIMELIMIT', warningsent = 0 WHERE username = '$MOBILE';"
# Add Renewal Info in SYSLOG
mysql -u$SQLUSER -p$SQLPASS -e "use radius; INSERT INTO rm_syslog (datetime, ip, name, eventid, data1) VALUES (NOW(), '$IP', 'ROBOT', '0', '$MOBILE');"
 
# OUTPUT RESULT FOR USER on SCREEN / OR BETTER TO SEND IT TO USER VIA SMS
echo "Dear $FIRSTNAME $LASTNAME,
 
INFO: Your account have been renewed successfully.
You can use following login information.
 
User ID  = $MOBILE
Password = $MOBILE
Validity = $CURDATE
Uptime   = $UPTIMELIMIT Hour
 
Regard's
$COMPANY"  > /tmp/$MOBILE.sms
 
# Output DATA on screen for user
cat /tmp/$MOBILE.sms
 
echo "Sending SMS to the registered Mobile number"
# Sending Renewal SMS to user mobile numbers
curl "http://$KHOST:13013/cgi-bin/sendsms?username=$KID&password=$KPASS&to=$MOBILE" -G --data-urlencode text@/tmp/$MOBILE.sms
 
fi
 
### THE END, SCRIPT ENDS HERE ###
### MADE BY SYED JAHANZAIB ###
### AACALBE AT HOTMAIL DOT COM ###


SCRIPTS OUTPUT :


1- User Registration Page

1- web login form
UPON SUBMISSION YOU MAY GET BELOW RESULTS (AS PER THE INPUT PROVIDED BY THE USER)
finger


2- Successful registration for the NEW user

2- new user registered successfully
and on SMS
m 1


3- Deny registration of same user for the same DATE

3- already registered account and still active
and on SMS
m 2


4- Allow renewal for the OLD users  if there account status is EXPIRED and registration date is not same.

4- old account got reneewedand on sms
m 3

DONE !




0 comments:

Post a Comment