ensuring that a script is only included into certain pages - javascript

The question
I have a service that pushes content to users. To provide this content to their users, customers will include a script on their site. Their script sends a token to my server to identify which customer it is, but here's the problem: if anyone copies the script from the user's site, they can receive this live content, and the customer is billed for users that are not on their site. So, is there a way to ensure that the script is only included on their website? How does google analytics achieve this?
I have an idea, but I don't know if this would be completely secure.
The customer tells me any domains (including subdomains) that they would like to include my script on.
I give the user a very small text file that they store on their servers.
Once my script is loaded, it checks for window.location.host, and tries to fetch the text file from the root of the hosting domain.
If the file is found, and the contents match the content I generated when I gave the customer the file, I activate the service.
would this work?
Why I can not use window.location
Let's say that my script reads window.location, and sends that to the url mydomain.com?token=ABC&locationhost=goodcustomer.com
Now, the owner of baduser.com wants to abuse the account of gooduser.com, so he includes gooduser.com's script. The script now sends an ajax request to mydomain.com?token=ABC&locationhost=badcustomer.com
This would not start the service, because badservice.com is not the domain that the owner of goodcustomer.com entered when he signed up. This is easy to circumvent, because badcustomer.com's owner can take a look at my script, notice that it is sending a request to validate the url, and just send his own request. So he would send a request to mydomain.com?token=ABC&locationhost=goodcustomer.com. My server sees this request, compares the locationhost to the domain associated with the token, and starts giving the content meant for goodcustomer.com's users, to badcustomer.com's users. My server has no way of knowing wether the request was sent by my own script, or by a user trying to impersonate the actual customer.

You cannot make a secure solution to this only with scripts that runs in the end users browser. Someone that want to mimic your customers web site will always be able to do that by creating a copy of every script or file that you send to the browser. You will need to do something on your customers server. That is, your customer must have some kind of secret that is not sent to the browser.
One way to do this would be to give the customer a server side script that generates a one-time token. Let your script call this server-side script to get the token and include this token in the request to your server. Your server must check that the token is correct before it generates the data.
A one time token can be made by sending each customer a 20 character long password. Let the server-side script read the password, add the date and time and hash this value using i.e. SHA-256. It would be quite hard to create a false token if you don't know the password. It would be even better if you add a counter in the server side script. Let the counter increment with one for each request. However, a counter will introduce some syncronization problems if the counter on your site comes out of sync with the counter on the customers site.

You could build a database of what domains a user would be hosting the script on, then when the user loads the script, it sends window.location to your server, then your server sends content if the window location matches that in the database.

Related

Prevent from unauthorized access to .html site using the only Javascript

I am a beginner in web development.
I create a project only in HTML, CSS, and Javascript.
My task is to create the login page and main page, but the user can access the main page only when he is logged.
In the backend are database connector scrip, a login script, and script which checking user is logged.
Before the user opens the main page script creates a request and gets a response from the script in this format:
{
"logged": true,
"uid": 123456
}
I parse JSON and if logged is false I redirect to the login page using window.location.replace().
Is this approach prevent from open the main page when the user is not logged?
I am asking because clients can modify Javascript files in a web browser.
I know that it is easier to create this in PHP using the location header and it can't be modified by the client, but I can't make it in this way.
I am asking because clients can modify Javascript files in a web browser.
Not really. But yes, a check such as what you describe is easily circumvented client-side.
The rule is this: Anything that should not be visible to the user if they aren't authorized and authenticated must not be sent to the client at all unless that authentication has been provided. So the request for the "main page" from the server must be allowed or disallowed by the server, and served non-cacheable.
Usually the page itself isn't all that protected, but the information you show on the page is. E.g., the page is the scaffold and layout and such, but the protected information it shows is provided using ajax or similar, and only when the user has been authenticated.

Storing information in cookies, and cookie manipulation of some other domain

We have a public facing website, in which the user can login using an email address.
After the user logs in, we populate the cookies of that domain with a uniquely generated session id, and the user details, like emailAddress, Name etc, based on which other calls are made to the server like getUserProfile etc.
However the problem, is any user can make changes to his hosts file, and write a simple Servlet to create the cookies of my domain, and can accordingly set any random session id and user details in the cookies, and then can get automatically logged in.
On the client side, how do I maintain that the appropriate session id is correct. If I maintain the session ids on the backend in some caching framework like memcache, then each hit on website every page will hit the server, which is not what i would want.
What is the way to get around this problem and ensure that the fraud user is not able to set my cookies after making changes in his hosts file.
On the client side, how do i maintain that the appropriate session id is correct.
You can't. The browser is controlled by the user. You control the server. You can only perform authentication on the server.

hide the path of the php file in ajax request

I dont know if this possible
But I have an ajax function in my javascript and as all, we know we need to provide php file path in the ajax request and this will be visible to all the users and unfortunately they can see the path of the ajax files and where they are stored .but i dont want this to happen i dont want user or client to see my ajax filed Is there a way to hide this path from the client, from seeing the path of ajax files? i know its something obfuscation but i only want the path to be done is it possible?
Update
so is there any way to stop user from viewing or opening php files from the url, I mean if user enters the path of ajax files and hits enter he can see all my files over there and he can easily hack my data so is there a way to stop user from entering them , i want only my pages to access php files not from users url,Thanks
It is not possible. The browser has to request the URI. The user can see what resources their browser is requesting.
"Ajax files" are not a special case. You need to secure them in exactly the same way as any other resource you provide over HTTP. i.e. use authentication and authorisation to make sure that only users who are allowed to access them do, input validation to make sure that any data sent to them is acceptable, and escaping to make sure that the data doesn't cause you problems if you try to insert it into SQL/HTML/JS/any other data format.
Response to update:
so is there any way to stop user from viewing or opening php files from the url
Still No!
I mean if user enters the path of ajax files and hits enter he can see all my files over there
You can configure your server to not serve a DirectoryIndex. The specifics depend on the server. Alternatively you can put a blank index.html file there.
and he can easily hack my data
How?
so is there a way to stop user from entering them
No.
i want only my pages to access php files not from users
Only an HTTP client can request a URI. There is no way to distinguish between an HTTP client responding to an instruction from JavaScript that you have written from one that is responding to user input.
a possible way would be to obfuscate it so that its not user readible. expl; by using a main script and including the file by switching on some POST/GET param your sending (could be a random string, hash, number).
more efficient obfuscation can be acchieved, when you would redirect all traffic to one script via mod_rewrite. Somewhere in the url, you hide a number, that tells you which file to use. Then you add random string before and after it (with specific length) and read it from your main script. But then the user will find out by looking at the javascript.
but srsly. why do you care? there is no security by obscurity!
/updated to your updated question;
I think you want to be looking at your apache configuration; use .htaccess files or better, disable indexing of a directory all together. The user wont be able to know about all your php files. Only the ones, you made public via links in your application. There is no such thing as "only letting ajax access file but not the user". because ajax IS the user and vice-verca! you are sending ajax request on behalf of the user! and if the user enters the url in the browserbar, its the same as sending an ajax request.
You could add a special header with your ajax call (or use the one already supplied), but that wouldn't change anything, as soon as the user looks at the traffic close enought.
What I think you want is a User Session to only allow privileged users to fully execute a script.
Unless you are using jsp technology with apache tomcat, you can place your folders in the WEB-INF.
No.
This is not possible. The client performs the request and the client is under the users control.

SINGLE SIGN ON SECURITY THREAT! FACEBOOK access_token broadcast in the open/clear

02/20/2011:
It was confirmed by Facebook today that indeed there is one call in which the access_token is broadcast in the open . . . it just happens to be one call I use to make sure that the USER is still logged in before saving to my application database. Their recommendation was to use the SSL option provided as of last month for canvase and facebook as a whole. For the most part the Auth and Auth are secure.
Findings:
Subsequent to my posting there was a remark made that this was not really a question but I thought I did indeed postulate one. So that there is no ambiquity here is the question with a lead in:
Since there is no data sent from Facebook during the Canvas Load process that is not at some point divulged, including the access_token, session and other data that could uniquely identify a user, does any one see any other way other than adding one more layer, i.e., a password, sent over the wire via HTTPS along with the access_toekn, that will insure unique untampered with security by the user?
Using Wireshark I captured the local broadcast while loading my Canvas Application page. I was hugely surprised to see the access_token broadcast in the open, viewable for any one to see. This access_token is appended to any https call to the Facebook OpenGraph API.
Using facebook as a single click log on has now raised huge concerns for me. It is stored in a session object in memory and the cookie is cleared upon app termination and after reviewing the FB.Init calls I saw a lot of HTTPS calls so I assumed the access_token was always encrypted.
But last night I saw in the status bar a call from what was simply an http call that included the App ID so I felt I should sniff the Application Canvas load sequence.
Today I did sniff the broadcast and in the attached image you can see that there are http calls with the access_token being broadcast in the open and clear for anyone to gain access to.
Am I missing something, is what I am seeing and my interpretation really correct. If any one can sniff and get the access_token they can theorically make calls to the Graph API via https, even though the call back would still need to be the site established in Facebook's application set up.
But what is truly a security threat is anyone using the access_token for access to their own site. I do not see the value of a single sign on via Facebook if the only thing that was established as secure was the access_token - becuase for what I can see it clearly is not secure. Access tokens that never have an expire date do not change. Access_tokens are different for every user, to access to another site could be held tight to just a single user, but compromising even a single user's data is unacceptable.
http://www.creatingstory.com/images/InTheOpen.png
Went back and did more research on this:
FINDINGS:
Went back an re ran the canvas application to verify that it was not any of my code that was not broadcasting.
In this call: HTTP GET /connect.php/en_US/js/CacheData HTTP/1.1
The USER ID is clearly visible in the cookie. So USER_ID's are fully visible, but they are already. Anyone can go to pretty much any ones page and hover over the image and see the USER ID. So no big threat. APP_ID are also easily obtainable - but . . .
http://www.creatingstory.com/images/InTheOpen2.png
The above file clearly shows the FULL ACCESS TOKEN clearly in the OPEN via a Facebook initiated call.
Am I wrong. TELL ME I AM WRONG because I want to be wrong about this.
I have since reset my app secret so I am showing the real sniff of the Canvas Page being loaded.
Additional data 02/20/2011:
#ifaour - I appreciate the time you took to compile your response.
I am pretty familiar with the OAuth process and have a pretty solid understanding of the signed_request unpacking and utilization of the access_token. I perform a substantial amount of my processing on the server and my Facebook server side flows are all complete and function without any flaw that I know of. The application secret is secure and never passed to the front end application and is also changed regularly. I am being as fanatical about security as I can be, knowing there is so much I don’t know that could come back and bite me.
Two huge access_token issues:
The issues concern the possible utilization of the access_token from the USER AGENT (browser). During the FB.INIT() process of the Facebook JavaScript SDK, a cookie is created as well as an object in memory called a session object. This object, along with the cookie contain the access_token, session, a secret, and uid and status of the connection. The session object is structured such that is supports both the new OAuth and the legacy flows. With OAuth, the access_token and status are pretty much al that is used in the session object.
The first issue is that the access_token is used to make HTTPS calls to the GRAPH API. If you had the access_token, you could do this from any browser:
https://graph.facebook.com/220439?access_token=...
and it will return a ton of information about the user. So any one with the access token can gain access to a Facebook account. You can also make additional calls to any info the user has granted access to the application tied to the access_token. At first I thought that a call into the GRAPH had to have a Callback to the URL established in the App Setup, but I tested it as mentioned below and it will return info back right into the browser. Adding that callback feature would be a good idea I think, tightens things up a bit.
The second issue is utilization of some unique private secured data that identifies the user to the third party data base, i.e., like in my case, I would use a single sign on to populate user information into my database using this unique secured data item (i.e., access_token which contains the APP ID, the USER ID, and a hashed with secret sequence). None of this is a problem on the server side. You get a signed_request, you unpack it with secret, make HTTPS calls, get HTTPS responses back. When a user has information entered via the USER AGENT(browser) that must be stored via a POST, this unique secured data element would be sent via HTTPS such that they are validated prior to data base insertion.
However, If there is NO secured piece of unique data that is supplied via the single sign on process, then there is no way to guarantee unauthorized access. The access_token is the one piece of data that is utilized by Facebook to make the HTTPS calls into the GRAPH API. it is considered unique in regards to BOTH the USER and the APPLICATION and is initially secure via the signed_request packaging. If however, it is subsequently transmitted in the clear and if I can sniff the wire and obtain the access_token, then I can pretend to be the application and gain the information they have authorized the application to see. I tried the above example from a Safari and IE browser and it returned all of my information to me in the browser.
In conclusion, the access_token is part of the signed_request and that is how the application initially obtains it. After OAuth authentication and authorization, i.e., the USER has logged into Facebook and then runs your app, the access_token is stored as mentioned above and I have sniffed it such that I see it stored in a Cookie that is transmitted over the wire, resulting in there being NO UNIQUE SECURED IDENTIFIABLE piece of information that can be used to support interaction with the database, or in other words, unless there were one more piece of secure data sent along with the access_token to my database, i.e., a password, I would not be able to discern if it is a legitimate call. Luckily I utilized secure AJAX via POST and the call has to come from the same domain, but I am sure there is a way to hijack that.
I am totally open to any ideas on this topic on how to uniquely identify my USERS other than adding another layer (password) via this single sign on process or if someone would just share with me that I read and analyzed my data incorrectly and that the access_token is always secure over the wire.
Mahalo nui loa in advance.
I am not terribly familiar with Facebook's authentication/authorization methods, but I do believe that they implement oauth (or something close to it) for delegation, distributed authorization, and "single sign-on".
OAuth is described by RFC-5849
EDIT: Facebook Uses OAuth 2.0 which is still in working draft.
In OAuth, and similar systems, the "access_token" is only part of the picture. There is also typically a secret key, which is known only by the service provider (facebook) and the client application (your app). The secret key is the only part that is expected to stay secret - and that part is never sent over the wire (after it's initial issuance).
In the case of Facebook, I think the secret key is assigned to you when you register your application to use their API, and the 'access_token' is returned to you for a given user, whenever the user agrees to allow your app to access their info.
Messages are sent in the clear, including the user's username, and the relevant "access_token"; However, each message must also include a valid signature in order to be accepted by the server. The signature is a cryptographically computed string, that is created using a technique called HMAC.
Computing the HMAC signature requires both the token and the secret, and includes other key parts of the message as well. Each signature is unique for the given message contents; and each message uses a nonce to ensure that no two messages can ever be exactly identical.
When the server receives a signed message, it starts by extracting the access_token (clear-text), and determining which app the token was issued for. It then retrieves the matching secret from its own local database (the secret is not contained in the message). Finally, the server uses the clear-text message, the clear-text access_token, and the secret to compute the expected HMAC signature for the message. If the computed signature matches the signature on the received message, then the message must have been sent by someone who knows the same secret (i.e. your application).
Have a look at Section 3.1 of RFC-5849 for an OAuth specific example, and further elaboration on the details.
Incidentally, the same approach is used by Amazon to control access to S3 and EC2, as well as most other service providers that offer API access with long-term authorization. Suffice it to say - this approach is secure. It might be a little counter-intuitive at first, but it makes sense once you think it through.
Adding a few links and quotes from Facebook Documentation:
Facebook is indeed using the HMAC-SHA256 algorithm. Registration document (PHP Example reading signed_request section).
Always verify the signed_request:
If you are unable to validate the
signed_request because you can't embed
your application secret (e.g. in
javascript or a desktop application)
then you MUST only use one piece of
information from the payload, the
oauth_token.
The Authentication Document contains a lot of useful info about the different flows you may use to authenticate a user. Also read the Security Considerations section at the bottom of the page:
Cross site request forgery is an
attack in which an trusted
(authenticated and authorized) user
unknowingly performs an action on
website. To prevent this attack, you
should pass an identifier in the state
parameter, and then validate the state
parameter matches on the response. We
strongly recommend that any app
implementing Facebook user login
implement CSRF protection using this
mechanism.
It was confirmed by Facebook that indeed there is one call in which the access_token is broadcast in the open - it just happens to be one call I use to make sure that the user is still logged in before saving to my application database. Their recommendation was to use the SSL option provided as of last month for canvas and Facebook as a whole. For the most part the Auth and Auth are secure.
To ensure a secure interface between a third party application and a Facebook application or even any website that uses Facebook Single Sign on, an identity question would provide the extra layer when used in conjunction with the access_token.
Either that or require your users to use Facebook with the new SSL feature of Facebook and Facebook Canvas Applications. If the access_token is broadcast in the open it cannot be used to uniquely identify anyone in your third party database when needing to have a confirmed identity before database interactions.

Facebook Connect help

According to the Facebook API documentation, most of the work is handled through javascript.
That means that all the processing is done, and then the front end checks if the user is connected to Facebook/authorized. right?
My question is:
Suppose a user goes to my site for the first time ever.
He clicks on "facebook connect". The javascript verifies him as authentic, and it "redirects" to another page on my server. From then on, how do I know that the user is actually authenticated to my website, since everything is done on frontend?
I think this is correct, but aren't there some security issues..:
-After user clicks Login, Facebook redirects to a page on my site. AND they also create a cookie with a specific "Facebook ID" that is retrieved only from this user. My backened will "read" the cookie and grab that ID...and then associate it to my userID.
If that is correct...then it doesn't make sense. What if people steal other people's "facebook ID" and then forge the cookie? And then my backend sees the cookie and thinks it's the real user...?
Am I confused? If I am confused, please help me re-organize and tell me how it's like.
Facebook Connect uses a clever (or insane, depending on your point of view) hack to achieve cross-site communication between your site and Facebook's authentication system from within the browser.
The way it works is as follows:
Your site includes a very simple static HTML file, known as the cross-domain communications channel. This file is called xd_receiver.htm in the FB docs, but it can be named anything you like.
Your site's login page includes a reference to the Javascript library hosted on Facebook's server.
When a user logs in via the "Connect" button, it calls a function in Facebook's JS API which pops up a login dialog. This login box has an invisible iframe in which the cross-domain communications file is loaded.
The user fills out the form and submits it, posting the form to Facebook.
Facebook checks the login. If it's successful, it communicates this to your site. Here's where that cross-domain stuff comes in:
Because of cross-domain security policies, Facebook's login window can not inspect the DOM tree for documents hosted on your server. But the login window can update the src element of any iframe within it, and this is used to communicate with the cross-domain communications file hosted on your page.
When the cross-domain communications file receives a communication indicating that the login was successful, it uses Javascript to set some cookies containing the user's ID and session. Since this file lives on your server, those cookies have your domain and your backend can receive them.
Any further communication in Facebook's direction can be accomplished by inserting another nested iframe in the other iframe -- this second-level iframe lives on Facebook's server instead of yours.
The cookies are secure (in theory) because the data is signed with the secret key that Facebook generated for you when you signed up for the developer program. The JS library uses your public key (the "API key") to validate the cookies.
Theoretically, Facebook's Javascript library handles this all automatically once you've set everything up. In practice, I've found it doesn't always work exactly smoothly.
For a more detailed explanation of the mechanics of cross-domain communication using iframes, see this article from MSDN.
Please someone correct me if I'm wrong - as I am also trying to figure all this stuff out myself. My understanding with the security of the cookies is that there is also a cookie which is a special signature cookie. This cookie is created by combining the data of the other cookies, adding your application secret that only you and FB know, and the result MD5-Hashed. You can then test this hash server-side, which could not easily be duplicated by a hacker, to make sure the data can be trusted as coming from FB.
A more charming explaination can be found here - scroll about halfway down the page.
Same issues here, and I think Scott is closer to the solution.
Also Im using "http://developers.facebook.com/docs/?u=facebook.jslib-alpha.FB.init" there open source js framework. So things are a little different.
For me, via the opensource js framework, facebook provides and sets a session on my site with a signature. So what I am thinking is to recreate that signature on my side. - if they both match then the user is who he says he is.
So basically if a user wanted to save something to my database, grab the session signature set up by facebook and recreate that signature with php and validate it against the one facebook gave me?
if($_SESSION['facebookSignature'] == reGeneratedSignature){
// save to database
}else{
// go away I don't trust you
}
But how do you regenerate that signature? preferably without making more calls to Facebook?

Categories