I created an "embed code" within my site, which is simply an iframe
I would give this code to embed only certain users but do not know how to do. a user could get inspecting the html code from the authorized sites and get the code without permission.
how do I make my site that only authorized users?
I thought about taking $ _SERVER ['HTTP_REFERER'] but as soon as you click a link to the internal frame the referrer is lost.
You can't really avoid authorized person inspecting the URL of the inline frame and revealing it to an unauthorized person. The right course of action is to serve an empty/error page to an unauthorized user.
You could achieve that by creating a session upon user login and verifying that session in the source code the of page displayed in the inline frame.
Do not rely on referrer, it is easily spoofable and some browsers won't even set it. Session cookie is not spoofable unless the user knows the credentials used to create it, which makes them authorized, whether or not they are authenticated.
Verify the user with js.
<iframe src="verify.php">...
Verify.php contains:
<?php
session_start();
$id= generate sth random;
$_SESSION["id"]=$id;
?>
<script>
window.location="http:yourdomain/site.php?id=<?php echo $id;?>&referrer="+document.referrer;
</script>
Loading...
Now you can check the referrer, to verify if the site is correct and the id to check if nobody tried to trick you...
<?php
session_start();
if($_SESSION["id"]!=$_GET["id"] or $$_GET["referrer"]!="allowedsite.com"){
echo "not valid";
die();
}
?>
As Thomas Hübelbauer noted, people could still copy your code. The only thing you can do against it is obfuscation and the use of relative links. That makes it hard to copy.
Related
I am creating a user authentication system using PHP, JQuery, and AJAX. On submit, a request will be sent to 'authenticate.php' with data: username & password using AJAX. The PHP code checks a database for the record and returns 0 on success, 1 on failure. Then if the returned value is 0, the page will be redirected to the 'user private page' using 'window.location="user.php"'.
Now, the question is, is it safe and proper way to authenticate like this? Are there any security problems to use jQuery/JavaScript to redirect page?
Now, the question is, is it safe and proper way to authenticate like this?
Only if inside your user.php you check again if the user has successfully authenticated already. (This is usually where sessions come into play.)
Otherwise, of course everyone who knows the URL of user.php can access it directly.
Are there any security problems to use jquery/js to redirect page?
The only difference between window.location="user.php" (which is wrong, btw. – correct would be window.location.href="user.php") and, say, a normal link to that page, foo, is that the first one happens automatically, and the second one would require the user to click the link first.
So, it is as “secure” as if you had used a simple link. What that actually means here in this case, depends what I said above.
Depends on how secure and compliant you want you application to be. According to RFCs its not recommended to login like that, but keep the form on server side and integrate the login form on frontend (via iframe), then just redirect with redirect url and token, scopes etc to a local html which then eg. sends a window postmessage to your frontend application.
https://www.rfc-editor.org/rfc/rfc6749#page-19
If you just want to be quick and dirty you can go for window.location.href or document.location.href.
Or a bit more secure, send the user to the server and let this be redirected back, but can end up in redirection hell, as its not easy to get back to the state where the user was (including settings and stuff).
Anyways, you will always have to check for the current users's session state whatever you do afterwards with serverside (Sessions).
Since you are working with PHP already i don't recommend using JS to redirect the user. You can use PHP for that:
if($user == $db['user'] && $password == $db['password']){
$_SESSION['logged_in'] = true;
header('location:user.php');
}else{
echo 'username of password is wrong';
}
Then on your user.php file:
if(isset($_SESSION['logged_in'] && $_SESSION['logged_in'] == true){
echo 'welcome to the user page';
}else{
header('location:index.php');//Go back to login page
}
If people go directly to the user.php page, they will be redirected to the index.php page.
I've read a several ways to redirect users to homepage, but, what if I need to redirect them just if they got to that page through a search engine like Google or Bing.
I need this because I'm building a cigar webpage and in some countries is demanded to be a certain age to view the content.
You could set a cookie or session through PHP/JavaScript on the first website visit, and check on all upcoming visits if the cookie already exists. If not, redirect them to the homepage.
In PHP you can use the function:
$_SERVER['HTTP_REFERER'];
I believe this will also retrieve the full URL you was referred from.
See: http://php.net/manual/en/reserved.variables.server.php
Ignore the above answer as I read the question wrong. Best thing to do would be store within a session. If a session key exists then do not redirect, if it doesn't then do a redirect.
<?php
session_start();
$_SESSION['existingUser'] = true;
print_r($_SESSION);
?>
I need to run this code:
<?PHP
$pin=$_GET["pin"];
unlink("../users/$pin/host.php");
unlink("../users/$pin/votes.php");
unlink("../users/$pin/guest.php");
rmdir("../users/$pin");
echo "Session ended";
?>
Which is located at php/endsesh.php
Basically, when you start a session it creates you a folder with a pin number, and it places a host, guest and votes file.
I need this PHP script to run when the tab is closed, so it can delete all those files (Otherwise I'm just overloading my server with files)
So far I'm trying this with no luck:
<script>
window.onbeforeunload = function() {
alert("<?php include("http://musicdemo.hol.es/php/endsesh.php?pin=" . $_GET["pin"]; ?>");
$.get("http://musicdemo.hol.es/php/endsesh.php?pin=<?php echo $_GET["pin"]; ?>");
return false;
return "If you exit this page your session will not end. Please either allow the pop-up, by staying in this page and closing again, or click the link saying 'Close this session'";
}
</script>
neither the alert or the $.get commands work.
onbeforeunload is a highly secured, sandboxed event. It's really designed solely to catch people with "are you sure you want to close this window" messages, so I'm pretty sure it doesn't allow more advanced features such as an ajax call. To do so would open up security holes that allow malicious sites to prevent you from closing the window.
I think doing an ajax call to clean up server side session files is not the appropriate strategy anyway, since the browser could easily crash, laptop could lose power, user could lose network connectivity preventing the ajax call etc. You can't rely on that ajax call succeeding.
PHP already has very good session handling capabilities via session_start() and the $_SESSION global variable, which already has a built in cleanup feature for expiring old sessions.
If you absolutely must keep your current solution, what I would do is run a cron job every hour, day, week, whatever, that searches for any of your files that haven't been accessed in say 24 hours and deletes them.
Also I should note that taking a $_GET and passing it directly to unlink is one of the worst, most insecure things you can do in php. If you have that running on a server right now, you need to fix it immediately, since a malicious user could potentially do something like http://musicdemo.hol.es/php/endsesh.php?pin=../../../../../../etc/passwd. if 'pin' is a number, you should at least do something like:
<?PHP
$pin=$_GET["pin"];
$pin = (int) $pin; // ensure pin is converted to an integer
unlink("../users/$pin/host.php");
unlink("../users/$pin/votes.php");
unlink("../users/$pin/guest.php");
rmdir("../users/$pin");
echo "Session ended";
?>
This code looks to be incorrect, try:
<script>
window.onbeforeunload = function() {
$.get("http://musicdemo.hol.es/php/endsesh.php?pin=<?php echo $_GET["pin"]?>");
return false;
return "If you exit this page your session will not end. Please either allow the pop-up, by staying in this page and closing again, or click the link saying 'Close this session'";
}
</script>
It looks like your alert line is messing this up.
remove alert().
keep $.get.
Have you seen the apache logs?
Probably you could have a permission problems (chmod +x endsesh.php).
I think i will give a try with exec (http://it2.php.net/function.exec).
But before you have to understand if endsesh.php is reached.
My company has a setup as follows:
subdomain1.domain1.com
subdomain2.domain1.com
subdomain3.domain1.com
subdomain4.domain1.com
subdomain5.domain1.com
subdomain6.domain1.com
subdomain1.domain2.com
subdomain2.domain2.com
subdomain3.domain2.com
subdomain4.domain2.com
subdomain5.domain2.com
subdomain6.domain2.com
On each site, bearing in mind there can be a hundred sites per subdomain, users can log in. We, as developers, have to test frontends across several browsers, but some work may only be required on a section once logged in.
I have written a userscript which enables us to save a username and password (and other details which I cannot mention because of confidentiality). The script checks to see if the user account exists by filling in the login form and clicking the submit button. If not, it registers for us - thus automating the registration process.
Sharing cookies between subdomains on the same domain is easy. If I am on subdomain1.domain1.com I can save a cookie which can be retrieved by subdomain2.domain1.com. However, I would also like to save these for domain2. I do not appear to be able to get this to work.
I can see two solutions from here - either:
1) attach an iFrame using the userscript, which loads a site on domain2. This then uses the querystring to decide what to set to what, or;
2) use a form with method="POST", and simply post to a file on each domain.
Either way will be resource intensive, particularly if the cookies are updated each time a cookie changes. We also have URL masking in place. So we'd also have to take into account sites like abc.clientdomain1.com, abc.clientdomain2.com etc.
Does anyone know of an easier way to do achieve this?
This answer is a slightly different version of my answer on the question "Set cookie on multiple domains with PHP or JavaScript".
Do what Google is doing. Create a PHP (or any other server language file) file that sets the cookie on all 3 domains. Then on the domain where the login is going to be set, create a HTML file that would load the PHP file that sets cookie on the other 2 domains. Example:
<html>
<head></head>
<body>
Please wait..........
<img src="http://domain2.com/setcookie.php?user=encryptedusername"/>
<img src="http://domain3.com/setcookie.php?user=encryptedusername"/>
</body>
</html>
Then add an onload callback on body tag. The document will only load when the images completely load that is when cookies are set on the other 2 domains. Onload Callback :
<head>
<script>
function loadComplete(){
window.location="http://domain1.com";//URL of domain1
}
</script>
</head>
<body onload="loadComplete()">
Now cookies are set on the three domains.
Source
Create a common domain specifically for your cookies and use it as a getter/setter API.
http://cookie.domain.com/set/domain1
http://cookie.domain.com/get/domain1
http://cookie.domain.com/set/domain2
http://cookie.domain.com/get/domain2
and so on.
Include a script tag from domain2 that sets the cookie using a username and hashed password:
<script type="text/javascript" src="http://domain2.com/cookie_login_page.php?username=johnsmith&hash=1614aasdfgh213g"></script>
You can then check to ensure that the hashed passwords match (one way).
Key points:
Make the hashes in the URL time sensitive by appending a timestamp that will be agreed upon by the server (for example, 16:00, 16:10, etc) before hashing the string. If you're using HTTPS this is less of an issue.
If your passwords are already hashed, it wont hurt to double-hash the passwords assuming the salts are the same on both servers.
Sample PHP code:
src:
<script type="text/javascript" src="/cookie_login_page.php?username=<?php echo $username; ?>&hash=<?php echo md5($password . date('H')); ?>"></script>
dest:
<?php
$password = get_password($_GET['username']);
if($_GET['hash'] == md5($password . date('H')) {
// set the cookie
}
For security reasons, sites cannot set or retrieve cookies on other domains. Scripting the form submit via javascript is likely the easiest to do, and will still store the cooikes you need in the browser cache.
As stated by others, you can't access cookies across domains. However, if you have control of the server code, you can return information in the body, and allow your client to read and store that information per server.
In my case, I'm connecting a single client to multiple servers, maintaining an authenticated connection to each one. I need to know when the session for each one is going to expire, so the authentication service returns the cookie, plus it modifies the body of the response to send the relevant data back, so that I can read that data and set my own cookies.
By doing this, I can manually track what I need. Won't work in every scenario, but might for some like me.
I have been using PHP and JavaScript for building my dad's website. He wants to incorporate a login system into his website, and I have the design for the system using PHP. My problem is how do I show buttons if the person is logged in?
For Example - You have Home, Products, About Us, and Contact. I want to have buttons for Dealer, Distributor, and maybe other information if the user is logged in. So I will have Home, Products, About Us, Contacts, Dealer (if dealer login), Distributor (if distributor login), and so forth.
Would JavaScript be a good way to do this or would PHP, or maybe even both? Using JavaScript to show and hide buttons, and PHP to check to see which buttons to show.
Regarding security, you cannot trust what comes from the client:
The visitor can see all your code (HTML and Javascript, not PHP) and try stuff
The visitor may not even use a browser; it's trivially easy to send a request with a script
This means hiding the buttons is good User Interface design (because you can't use them if you are not logged in). But it's not a security feature. The security feature is checking, on the server, that the visitor is logged in before each action that requires it.
If you don't intend to show the buttons, it's not useful to send the HTML and images to the browser and then hide them with Javascript. I would check with PHP.
In your menu file or w/e you put:
<? require 'auth.php' ?>
<ul>
<li>Home</li>
<li>Products</li>
<? if( loggedin() ): ?><li>Secret area</li><? endif; ?>
</ul>
Then in pages that require auth just do this:
<?php
require 'auth.php';
require_login();
?>
Where auth.php may contain:
<?php
function loggedin(){
return isset( $_SESSION['loggedin'] );
}
function require_login(){
if( !loggedin() ){
header( 'Location: /login.php?referrer='.$_SERVER['REQUEST_URI'] );
exit;
}
}
?>
If you use javascript to hide the buttons, you open a security hole in the application. A malicious user could either disable javascript or apply some of their own to get around your security.
I suggest using PHP to chose to either render the buttons or not. I do this in .NET quite often.
You should be able to check the user's access on the server-side whenever they try to use a restricted button as well.
What we have done at my work is have a library the provides functions such as checking if the user is logged in. For example:
<?php
require_once 'Auth.php';
// output some html
if (isLoggedIn()) {
echo 'html for logged in user';
}
// rest of html
For pages that only authenicated users should see, the controller checks if they are logged in and if not it redirects them to the login page.
<?php
public function viewCustomer($customerId) {
if (!isLoggedIn())
redirectToLoginPage();
}
Everything that Christian Lescuyer wrote is correct. Notice, however, that he said "I would" and not "you should". The choice is not that easy.
First of all, security is not an issue in the choice. You should have security check on server when you execute an action. Which code decides to show/hide the button that leads to the action is irrelevant.
That leaves us with only one drawback of doing show/hide logic in Javascript - the HTML sent to user is bigger than necessary. This may not be a big deal.
Having show/hide logic in PHP does have a minus, though. The PHP code required is usually a tag soup. Akira's code provides a good example of how it is usually done.
Corresponding Javascript code would probably look something like this:
if (logged())
{
elementSecretArea.style.display = "list-item";
}
(assuming that elements that could be hidden have display:none by default).
This style also allows nice "Ajax" scenario: user sees a page w/o secret area, inputs password, sees the secret area all without refreshing the page.
So, if you already have a script that runs when your document load for other reasons, I would seriously consider having show/hide logic there.
Basically where you have your menu in html, say as a list <ul> <li>Home</li> </ul> you add php after </li> of the last item:
<?php
if($session-logged_in) {
?>
<li>My Account</li>
<?php
}
?>