I have a massive of scripts that my core application
include('JS/gramp.php');
include('JS/est.php');
include('JS/curest.php');
include('JS/memomarker.php');
include('JS/local----------.php');
include('JS/poirel.php');
include('JS/maplayers.php');
include('JS/trafficinc.php');
include('JS/plannedtraffic.php');
include('JS/transportissues.php');
include('JS/cams_traff.php');
include('JS/places2.php');
Now these are all being moved to a on the fly loading, to reduce the size of the application on load
if(button_case_curtime==true){
$(".jsstm").load("<?php echo $core_dir; ?>JS/curresttime.php?la=<?php echo $caseset['iplat']; ?>&lo=<?php echo $caseset['iplong']; ?>&h=<?php echo $days_h; ?>");
rendermap = true;
}
issue! the application requires these files to be secure, the data involved requires that no one can access.
The ONLY file that will ever request these files will be index.php
Any input or idears would be fantastic!
There is no way to provide a file to the browser without also providing it to a user.
You could configure your server to only supply the files given an extra HTTP header (which you could add with JS), but nothing would stop people from sending that header manually or just digging the source out of the browser's debugging tools.
Any user you give the files to will have access to the files. If you want to limit which users have access to them, then you have to use auth/authz (which you'll want to apply to the index.php file as well so that unauthorised users don't just get JS errors or silent failure states).
No. What you are trying to do is not possible. Ajax requests are not special. They are just HTTP requests. End points created for Ajax should be secured with authentication/authorization just like any other HTTP request end point.
This is a trivial solution that will solve your problem half-way. Request them via a POST request, like so:
$.post('JS/maplayers.php', {'ajax':true}, function(){});
Notice the POST variable 'ajax'. In the file maplayers.php, add to the beginning the following code:
if((!isset($_POST['ajax']))) {
die('Invalid request, only ajax requests are permitted');
}
Related
I want to deny direct access to a file, but allow access to use it in <script> tags only at my website.
Can someone please help me using PHP or .htaccess?
You cannot. The src attribute of a <script> tag is just a regular URL that can be accessed like any other URL. Nothing more, nothing less.
However, if you want to:
Prevent unauthorised access
Move the JS file outside of the web server document root, so as to prevent direct access. Serve the JS file from a server-side script, only to authorised parties. Example in PHP:
file: publicScript.php
<?php
if(access_granted()) { // use your usual authentication routine here
header('Content-Type: application/javascript');
readfile('/path/outsideOf/documentRoot/hiddenScript.js');
} else {
echo 'alert("access denied");';
}
file: page.html
...
<head>
<script src="//publicScript.php"></script>
</head>
...
Prevent unauthorised use of the JS
If the JS is supposed to issue HTTP requests (Ajax), keep in mind that it will also send session information (e.g. cookies) along. In fact, queries issued from JS are impossible to distinguish from a regular request (eg. click on a link), as far as the server is concerned. Such requests can be authenticated by your server just like any other request.
Prevent reverse-engineering
Obfuscate your JS file. A quick search on your favourite search engine will return thousands of options.
If this still poses a security concern to you, then it is likely that your JS code is doing too much. Take critical features away from the JS and have your JS call a server-side API instead.
I'm using a jquery script that uploads files with ajax and PHP. It sends a request to upload_a_file.php which then uploads files.
Is there a way that I can make sure upload_a_file.php is not loaded directly in a browser?
I tried putting upload_a_file.php above my public_html folder. But can't seem to get javascript to load upload_a_file.php.
Here is the url format I use in the javascript to request upload_a_file.php:
../upload_a_file.php
Is it even possible to access files above public_html with javascript?
JS cannot access anything on a server that you yourself as a user cannot. If a file is outside of the site's document root, it is NOT accessible by a user, or by JS. Imagine the fun place the web would be if JS could magically bypass access restrictions on a server and grab any more. "Aww, I was going to grab this bank's accounts list, but it's not in the document root. Good thing I've got Javascript, it can do everything!"
It'd be like every episode of 24, where "patching into the subnet" can magically bypass any firewall and get data from machines which aren't even online or (better yet) not even powered up. Amazing things, those subnets.
You can check the HTTP header X_REQUESTED_WITH is present and has a value of XMLHttpRequest. This is not non-standard header but most JavaScript frameworks, including jQuery, Prototype, and mootools follow this convention.
In PHP you can access it $_SERVER['HTTP_X_REQUESTED_WITH'];
for example:
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
// do something
}
The javascript is running in the browser. It makes its requests through the browser. So, No, there's no way to access a page through ajax but not directly from the browser.
No, not directly. You can call other script (PHP or whatever) that will either "call" your script with include or e.g. with fopen or curl.
Nothing can access files above public_html, because the web server will not serve them. Doing so would have obvious security vulnerabilities, like being able to view any file on your filesystem.
If you want to restrict the file to only being able to be loaded via your javascript, I would think you'd want to look at the $_SERVER['HTTP_REFERER'] variable in php. This should be set to the page the javascript is located on when it is being accessed properly. If it is anything else or empty, the user is accessing it in some other manner.
Using this method shouldn't be relied on for security however, because the referer can be spoofed with the right tools.
Since direct browser access to a page is a GET request by PHP, here is a very basic access control method to keep someone from inadvertently going directly to upload_a_file.php:
In your jquery script, use an ajax request with type "POST":
$.ajax({
url: "../upload_a_file.php",
dataType: "json",
type: "POST"
});
and use this in your upload_a_file.php:
if ($_SERVER['REQUEST_METHOD'] == "POST") {
// upload a file
} else {
header("Location: http://example.com/myPublicUploadPage.php");
die();
}
In my CMS, I have a page which loads lots of mini-interfaces into a panel using AJAX. Those interfaces come from various PHP files in a /ajax directory.
Would it be possible somehow to only allow access to those files using ajax, and not just by browsing to them?
My concern is, of course, that someone finds out about the /ajax directory, and gets access to the core functionality of the CMS without even having to login. Of course I could import my user class and authenticate each of the AJAX files individually, but would it be possible to only allow access through AJAX?
Would it be possible somehow to only allow access to those files using ajax, and not just by browsing to them?
No.
You could add extra HTTP headers, or modify existing ones (such as Accept) when you make the request from JavaScript … but since you are trying to do this for security reasons, that would be insufficient.
Of course I could import my user class and authenticate each of the AJAX files individually
Do that. Ajax requests are not special. They are just HTTP requests. End points created for Ajax should be secured with authentication/authorization just like any other HTTP request end point.
No. A hacker could just fake Ajax requests, anyway. You need to authenticate everywhere or you'll get screwed.
From outside a browser, it's possible for anybody to initiate HTTP requests to any public URL on your site. There's nothing special about AJAX requests other than headers, and those can be spoofed easily.
Now what can't be easily spoofed is a secure session mechanism. If you're requiring people to log in, then you should be doing that anyway.
Simple answer, "no".
Your ajax files should also validate the user is logged in the same way as the front end of your system does.
AJAX is almost same request as Standart request you can check header but this is not secure way. So short you can't do this. Authetificate on server side what you have proposed.
Authenticate your AJAX files. If there are lots of them, create a class and extend it in each individual AJAX file.
/ajax/abstract.php:
<?php
abstract class AjaxHandler {
public function __construct() {
// import authentication handler
if ($authenticated) {
$this->display();
}
else {
header('HTTP/1.1 401 Unauthorized');
exit;
}
}
}
Then in each file, i.e. /ajax/get_user_profile.php:
<?php
class GetUserProfile extends AjaxHandler {
public function display() {
// do your routine
}
}
Well, an alternative option you could have is to use post method to get the content from the php, and in your php you should set a key for the post method. And then system wide remove cross origin access. :)
I am trying to write a script for uploading large files (>500MB). I would like to do some authentication before the upload is processed, eg:
$id = $_GET['key'];
$size = $_GET['size'];
$time = $_GET['time'];
$signature = $_GET['signature'];
$secret = 'asdfgh123456';
if(sha1($id.$size.$time.$secret) != $signature){
echo 'invalid signature';
exit;
}
process upload...
unfortunately php only runs this code after the file has been uploaded to a temp directory, taking up valuable server resources. Is there a way to do this before the upload happens? I have tried similar things with perl/cgi but the same thing happens.
Wow, already 5 answers telling how it can't be done. mod_perl to the rescue, here you can reject a request before the whole request body is uploaded.
Apache is taking care of the upload before the PHP script is even invoked so you won't be able to get at it.
You can either split up the process into two pages (authentication, file upload page) or, if you need to do it all in one page, use an AJAX-esque solution to upload the file after authentication parameters are checked.
As far as I know, you cannot do that in PHP. PHP script is launched in response to a request, but a request is not "sent" until the file is uploaded, since the file being uploaded is a part of the request.
This is definitely not possible inside the PHP script you're uploading to.
The most simple possibility is indeed to provide authentication one step before the upload takes place.
If that is not an option, one slightly outlandish possibility comes to mind - using a RewriteMap and mapping it to an external program (it should be possible to make that program a PHP script).
Using RewriteMap it is possible to rewrite an URL based on the output of a command line program. If you use this directive to call a (separate) PHP script - you won't be able to use the user's session, though! - you would have access to the GET parameters before the request is processed.
If the processing fails (= the credentials are invalid), you could redirect the request to a static resource which would at least prevent PHP from starting up. (I assume the uploaded will be hogging some resources anyway, but probably less than if it were redirected to PHP.)
No guarantees whether this'll work! I have no own experience with RewriteMap.
This is due to the fact that each HTTP request is a single contains all the of form/POST data, including the file upload data.
As such, I don't believe it's possible to handle a file upload request in this fashion irrespective of which scripting language you use.
I don't think you can do this. The best you can do is probably to run an AJAX function onSubmit to do your validation first, then if it returns valid then execute the POST to upload the file. You could set a $_SESSION in your AJAX script if the authentication is valid, then check for that session var in the upload script to allow the upload.
one of my php page returns data like this:
<?php
//...
echo "json string";
?>
but someone else use file_get_contents() to get my data and use in other website.
can anybody tell me what can i do to prevent such thing happen.
i consider if i can get the request's domain name to echo something else.but i dont know
the function to get request's domain name.and if the request is sent by a server,that
will be unhelpful. My English is poor, to express doubts, please bear with.
you can also use sessions. if somewhere in your application, before the user gets the json data, you start a session, then in this page where you are outputting json data, you can check for the session variable. this way only users that have passed the session generator page, can view your output.
suppose you have page A.php that generates the session. use this code before outputting anything in this page.
session_start();
$_SESSION['approvedForJson'] = true;
then in your page where you are outputting json data, before outputting anything, call session_start() again. the beginning of your PHP code is a good place to call it.
then before outputting the json data, check if the session variable for approved users exists, or not.
if ( isset($_SESSION['approvedForJson']) && $_SESSION['approvedForJson'] ) {
echo "json data";
} else {
// bad request
}
You can use $_SERVER['REMOTE_ADDR'] to get the address of the client address. You can also check $_SERVER['HTTP_REFERER'] and block external requests that way, but it's less reliable. There's probably a few other techniques involving $_SERVER that you can try.
Your fighting an uphill battle here. I am assuming your serverside process that responds in json is being consumed via javascript in your users browsers... so there is no easy way to encrypt it. You might try some of the techniques used to prevent xspf (see http://en.wikipedia.org/wiki/Cross-site_request_forgery ). If you developed the client to pass along some session token that is uniq per client you could reduce some of the problem. But, chances are whoever is stealing your data is gonna figure out whatever mechanism you put in place ... assuming this is some sort of ajax type thing. If its a server-server thing then as sli mentions, setting up some restrictions based on the remote ip would help, plus setting up some sort of API authentication tokens would help even more (see oauth for some pointers)
You could also using .htaccess with apache block every external request to the page if it get's called internally or block every request that is not from your domain:
Google search thingie
EDIT
You could also use some php file which includes the file which can not be read. So for example you have file.php:
<?php
$allowedFiles[] = 'somefile.php';
$allowedFiles[] = 'someotherFile.php';
$allowedFiles[] = 'jsonReturnFile.php';
if(in_array($_GET['file'], $allowedFiles)){
include( "include/".$_GET['file'] );
}
?>
Then you can allow file_ get _contents() on that file and write a rewriteRule in your .htacces to disallow any request to the include/ folder.
RewriteRule include* - [F,NC]
That will return a 403 forbidden error for a request to that directory or any file in the directory.
Then you can do you JSON request to something like: file.php?file=jsonReturnFile.php&someothherParamReadByJsonFile=1
And when someone tries to get the file contents for the JSON file they will get the forbidden error, and getting the file contents for the include.php won't return anything usefull.