Accepting get/post requests only from localhost - php

Because the data size isn't little that my web app needs to load, it gets pretty slow some times so therefor I decided to add some jQuery ajax functions to load certain data upon request and then save it in a cache.
What I would like to know is how can I limit any GET or POST requests only from localhost/same server/same ip so I can avoid any calls from outside to my app?
That means that my php functions that returns data, should return data only if requested from localhost.
My web app runs on CodeIgniter's framework and my web server's configuration is a LAMP running on ubuntu.
Any ideas?

in the constructor you could use
if ($_SERVER['SERVER_ADDR'] != $_SERVER['REMOTE_ADDR']){
$this->output->set_status_header(400, 'No Remote Access Allowed');
exit; //just for good measure
}
However if this method isnt what you're looking for.. use .htaccess you can perform a quick google search to return a specific example for denying get/post to all and then allow for 127.0.0.1/localhost.

Using .htaccess is probably the best way, allow only from your local address and 127.0.0.1.
I found this example at petergasser.com and changed it only slightly:
AuthName "bla"
AuthType Basic
<Limit GET POST>
order deny,allow
deny from all
allow from 127.0.0.1
allow from <your-ip-here>
</Limit>

Use a key (think of API keys) to send along the request to your server. Then on your server you check that key and if it's the right one you return data.

I use like this, thanks to #gorelative
if(
isset($_SERVER['REMOTE_ADDR']) AND ( $_SERVER['REMOTE_ADDR'] !== $_SERVER['SERVER_ADDR'] )
){
die(' Access Denied, Your IP: ' . $_SERVER['REMOTE_ADDR'] );
}

Related

Secure Php execution on server

I have a php script which updates a database. I want to be sure that no one else can call my script remotely and execute it.
I tried this code but it did not work, the refer was always empty because I use https connection.
if (strpos($_SERVER['HTTPS_REFERER'], 'linkedfilm.com') == false)
{
exit();
}
The server is Apache server.
Thanks.
Hello Daina Hodges,
You got a few options to secure this .php script.
You can secure this script by moving it into another directory outside of your DOCUMENT_ROOT
You can add the .htaccess
You can allow only local ip
You could use .htaccess and put your script in a password protected directory.
Or you could use some sort of login and authentication routines on your site so you can login and access that script.
Or you could pass a 'secret' key with you call to the script, quick and dirty
if( $_GET['secret'] != "mysecret" ) exit();

Getting name of logged in Windows user via Php on Apache [duplicate]

I have a PHP web application on an intranet that can extract the IP and host name of the current user on that page, but I was wondering if there is a way to get/extract their Active Directory/Windows username as well. Is this possible?
Check the AUTH_USER request variable. This will be empty if your web app allows anonymous access, but if your server's using basic or Windows integrated authentication, it will contain the username of the authenticated user.
In an Active Directory domain, if your clients are running Internet Explorer and your web server/filesystem permissions are configured properly, IE will silently submit their domain credentials to your server and AUTH_USER will be MYDOMAIN\user.name without the users having to explicitly log in to your web app.
I've got php mysql running on IIS - I can use $_SERVER["AUTH_USER"] if I turn on Windows Authentication in IIS -> Authentication and turn off Anonymous authentication (important)
I've used this to get my user and domain:
$user = $_SERVER['AUTH_USER'];
$user will return a value like: DOMAIN\username on our network, and then it's just a case of removing the DOMAIN\ from the string.
This has worked in IE, FF, Chrome, Safari (tested) so far.
Look at the PHP LDAP library functions: http://us.php.net/ldap.
Active Directory [mostly] conforms to the LDAP standard.
We have multiple domains in our environment so I use preg_replace with regex to get just the username without DOMAIN\ .
preg_replace("/^.+\\\\/", "", $_SERVER["AUTH_USER"]);
If you're using Apache on Windows, you can install the mod_auth_sspi from
https://sourceforge.net/projects/mod-auth-sspi/
Instructions are in the INSTALL file, and there is a whoami.php example. (It's just a case of copying the mod_auth_sspi.so file into a folder and adding a line into httpd.conf.)
Once it's installed and the necessary settings are made in httpd.conf to protect the directories you wish, PHP will populate the $_SERVER['REMOTE_USER'] with the user and domain ('USER\DOMAIN') of the authenticated user in IE -- or prompt and authenticate in Firefox before passing it in.
Info is session-based, so single(ish) signon is possible even in Firefox...
-Craig
You could probably authenticate the user in Apache with mod_auth_kerb by requiring authenticated access to some files … I think that way, the username should also be available in PHP environment variables somewhere … probably best to check with <?php phpinfo(); ?> once you get it runnning.
If you are looking for retrieving remote user IDSID/Username, use:
echo gethostbyaddr($_SERVER['REMOTE_ADDR']);
You will get something like
iamuser1-mys.corp.company.com
Filter the rest of the domain behind, and you are able to get the idsid only.
For more information visit http://lostwithin.net/how-to-get-users-ip-and-computer-name-using-php/
Use this code:
shell_exec("wmic computersystem get username")
Check out patched NTLM authentication module for Apache
https://github.com/rsim/mod_ntlm
Based on NTLM auth module for Apache/Unix
http://modntlm.sourceforge.net/
Read more at http://blog.rayapps.com/
Source: http://imthi.com/blog/programming/leopard-apache2-ntlm-php-integrated-windows-authentication.php
You can say getenv('USERNAME')
No. But what you can do is have your Active Directory admin enable LDAP so that users can maintain one set of credentials
http://us2.php.net/ldap
get_user_name works the same way as getenv('USERNAME');
I had encoding(with cyrillic) problems using getenv('USERNAME')
Referencing trying to also figure out if AUTH_USER is part of a particular domain group; a clever way to do this is t create a locked down folder with text files (can be blank). Set security to only having the security/distro group you want to validate. Once you run a #file_get_contents (<---will toss a warning)...if the user does not have group access they will not be able to get the file contents and hence, will not have that particular AD group access. This is simple and works wonderfully.
This is a simple NTLM AD integration example, allows single sign on with Internet Explorer, requires login/configuration in other browsers.
PHP Example
<?php
$user = $_SERVER['REMOTE_USER'];
$domain = getenv('USERDOMAIN');
?>
In your apache httpd.conf file
LoadModule authnz_sspi_module modules/mod_authnz_sspi.so
<Directory "/path/to/folder">
AllowOverride All
Options ExecCGI
AuthName "SSPI Authentication"
AuthType SSPI
SSPIAuth On
SSPIAuthoritative On
SSPIOmitDomain On
Require valid-user
Require user "NT AUTHORITY\ANONYMOUS LOGON" denied
</Directory>
And if you need the module, this link is useful:
https://www.apachehaus.net/modules/mod_authnz_sspi/
try this code :
$user= shell_exec("echo %username%");
echo "user : $user";
you get your windows(AD) username in php
I tried almost all of these suggestions, but they were all returning empty values. If anyone else has this issue, I found this handy function on php.net (http://php.net/manual/en/function.get-current-user.php):
get_current_user();
$username = get_current_user();
echo $username;
This was the only way I was finally able to get the user's active directory username. If none of the above answers has worked, give this a try.

block direct access to PHP file and only allow local javascript to access it

I need a way to block all access to a php file but to allow a javascript file that send xmlhttp request to it. that js file is hosted on my server and must stay on my server for it to work
I have the following
header('Access-Control-Allow-Origin: *');
but that allows anyone to access it.
Well, I don't think this would be possible. Anyone can make a request to your server but your server chooses who to respond to and how to respond to a request. Now, if you want only your JS to be responded to by your server, then you will have to inform the server at the time of making an HTTP request from your JS. That cannot be done without exposing your Javscript file's identity on the basis of which your JS can be identified by the server. But anyone can open your JS and read it and figure out how you are making the request and use the same thing.
One possible solution could be, use header('Access-Control-Allow-Origin: *') to allow everyone to make a request to your server but at the server's end, keep a list of allowed domains/origins in a database on your server who may use or are going to use your JS file on their website. Based on the AJAX request that you get, you check from your database that if the origin of the request is allowed or not and respond accordingly. Now, if someone tries to request your PHP file by any other means than your JS, on the basis of the data in your DB you can reject the request or accept the request. If an allowed user/website does this, then they will be knowingly messing around with their own data.
Try this:
if (empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) <> 'xmlhttprequest')
{
die('direct access is not allowed');
}
Also, you can always check referrer like $_SERVER['HTTP_REFERER'] to be sure that only your script from your domain can access it.

PHP detecting human browser in cron job

I want to prevent users from running my cron job manually. Apart from using an unpredictable filename I want to have some sort of check in code.
Obviously using any clientside headers is a waste of time so I thought the easiest way around this would be to detect the presence of $_SERVER['SERVER_NAME'] which as far as I know is not set in CLI.
Are there better ways of doing this?
Have a look at php_sapi_name. It returns the type of interface between web server and PHP.
Example:
<?php
if(php_sapi_name() == 'cli') {
// CLI
}
else {
// HTTP
}
For more information, and additional examples, have a look at http://www.electrictoolbox.com/determine-php-run-via-http-or-cli/.
in your .htaccess
Options -Indexes
order allow deny
deny from all
allow from YOUR SERVER IP ADDRESS ONLY
Check for IP address, if its local, or server ip then run it, otherwise return.
$ip = getenv('REMOTE_ADDR');
My cron jobs are in a folder that is password protected using htpasswd. You can set an easy password and be sure nobody will lose his time trying to access it. I don't use any IP-based techniques because this is a server dependency I don't want to have.

Can you get a Windows (AD) username in PHP?

I have a PHP web application on an intranet that can extract the IP and host name of the current user on that page, but I was wondering if there is a way to get/extract their Active Directory/Windows username as well. Is this possible?
Check the AUTH_USER request variable. This will be empty if your web app allows anonymous access, but if your server's using basic or Windows integrated authentication, it will contain the username of the authenticated user.
In an Active Directory domain, if your clients are running Internet Explorer and your web server/filesystem permissions are configured properly, IE will silently submit their domain credentials to your server and AUTH_USER will be MYDOMAIN\user.name without the users having to explicitly log in to your web app.
I've got php mysql running on IIS - I can use $_SERVER["AUTH_USER"] if I turn on Windows Authentication in IIS -> Authentication and turn off Anonymous authentication (important)
I've used this to get my user and domain:
$user = $_SERVER['AUTH_USER'];
$user will return a value like: DOMAIN\username on our network, and then it's just a case of removing the DOMAIN\ from the string.
This has worked in IE, FF, Chrome, Safari (tested) so far.
Look at the PHP LDAP library functions: http://us.php.net/ldap.
Active Directory [mostly] conforms to the LDAP standard.
We have multiple domains in our environment so I use preg_replace with regex to get just the username without DOMAIN\ .
preg_replace("/^.+\\\\/", "", $_SERVER["AUTH_USER"]);
If you're using Apache on Windows, you can install the mod_auth_sspi from
https://sourceforge.net/projects/mod-auth-sspi/
Instructions are in the INSTALL file, and there is a whoami.php example. (It's just a case of copying the mod_auth_sspi.so file into a folder and adding a line into httpd.conf.)
Once it's installed and the necessary settings are made in httpd.conf to protect the directories you wish, PHP will populate the $_SERVER['REMOTE_USER'] with the user and domain ('USER\DOMAIN') of the authenticated user in IE -- or prompt and authenticate in Firefox before passing it in.
Info is session-based, so single(ish) signon is possible even in Firefox...
-Craig
You could probably authenticate the user in Apache with mod_auth_kerb by requiring authenticated access to some files … I think that way, the username should also be available in PHP environment variables somewhere … probably best to check with <?php phpinfo(); ?> once you get it runnning.
If you are looking for retrieving remote user IDSID/Username, use:
echo gethostbyaddr($_SERVER['REMOTE_ADDR']);
You will get something like
iamuser1-mys.corp.company.com
Filter the rest of the domain behind, and you are able to get the idsid only.
For more information visit http://lostwithin.net/how-to-get-users-ip-and-computer-name-using-php/
Use this code:
shell_exec("wmic computersystem get username")
Check out patched NTLM authentication module for Apache
https://github.com/rsim/mod_ntlm
Based on NTLM auth module for Apache/Unix
http://modntlm.sourceforge.net/
Read more at http://blog.rayapps.com/
Source: http://imthi.com/blog/programming/leopard-apache2-ntlm-php-integrated-windows-authentication.php
You can say getenv('USERNAME')
No. But what you can do is have your Active Directory admin enable LDAP so that users can maintain one set of credentials
http://us2.php.net/ldap
get_user_name works the same way as getenv('USERNAME');
I had encoding(with cyrillic) problems using getenv('USERNAME')
Referencing trying to also figure out if AUTH_USER is part of a particular domain group; a clever way to do this is t create a locked down folder with text files (can be blank). Set security to only having the security/distro group you want to validate. Once you run a #file_get_contents (<---will toss a warning)...if the user does not have group access they will not be able to get the file contents and hence, will not have that particular AD group access. This is simple and works wonderfully.
This is a simple NTLM AD integration example, allows single sign on with Internet Explorer, requires login/configuration in other browsers.
PHP Example
<?php
$user = $_SERVER['REMOTE_USER'];
$domain = getenv('USERDOMAIN');
?>
In your apache httpd.conf file
LoadModule authnz_sspi_module modules/mod_authnz_sspi.so
<Directory "/path/to/folder">
AllowOverride All
Options ExecCGI
AuthName "SSPI Authentication"
AuthType SSPI
SSPIAuth On
SSPIAuthoritative On
SSPIOmitDomain On
Require valid-user
Require user "NT AUTHORITY\ANONYMOUS LOGON" denied
</Directory>
And if you need the module, this link is useful:
https://www.apachehaus.net/modules/mod_authnz_sspi/
try this code :
$user= shell_exec("echo %username%");
echo "user : $user";
you get your windows(AD) username in php
I tried almost all of these suggestions, but they were all returning empty values. If anyone else has this issue, I found this handy function on php.net (http://php.net/manual/en/function.get-current-user.php):
get_current_user();
$username = get_current_user();
echo $username;
This was the only way I was finally able to get the user's active directory username. If none of the above answers has worked, give this a try.

Categories