Clickjacking remediation via domain name comparison - javascript

I'm working on hardening our application to cross frame scripting/clickjacking attacks. Our application is hosted under multiple, different parent sites within an iframe. Each of these parent sites shares the same high level domain name (ex. *.foo.com). I would like be able to ensure that the parent, framing site is always the same as our application domain. For example:
Parent sites: apple.foo.com, pear.foo.com, banana.foo.com
Our site: mysite.foo.com
I know I can do something like this via Javascript but I would prefer not to embed our domain name within the code for portability reasons.
<script type="text/javascript">
var topFrameHostname = "";
try
{
topFrameHostname = top.location.hostname;
}
catch (err)
{
topFrameHostname = "";
}
if (self !== top && document.referrer.match(/^https?:\/\/([^\/]+\.)?foo\.com(\/|$)/i)) == null &&
topFrameHostname != self.location.hostname)
{
top.location = self.location;
}
else
{
var antiClickjack = document.getElementById("antiClickjack");
antiClickjack.parentNode.removeChild(antiClickjack);
}
</script>
So my question is can I use regular expressions to compare the domain name from the top.location and self.location values? This way I would be able to ensure it is always only a parent site from the same high level domain framing our application. Looking for a little help with the regular expression coding. Is this approach sound?

why does anyone think that regex is the one and only magic bullet when talking about matching anything?
How about this:
function domain(url){
if(typeof url === "string") url = new URL(url); //sugar, to handle strings
return url.hostname.split('.').slice(-2).join('.').toLowerCase();
}
domain(top.location) === domain(self.location)

I had to remove the reference to top.location and use document.referrer instead in order avoid the permissions error. Also, the URL function will not work in IE so I just used string functions to extract and compare the URLs:
<style id="antiClickjack">body{display:none !important;}</style>
<script type="text/javascript">
var topFrameHostname = "";
var ref = document.referrer;
var tophld = ref.split("/")[2].split(".").slice(1).join(".");
var selfhld = self.location.hostname.split(".").slice(1).join(".");
try
{
topFrameHostname = top.location.hostname;
}
catch (err)
{
topFrameHostname = "";
}
if (self !== top && tophld !== selfhld &&
topFrameHostname != self.location.hostname)
{
top.location = self.location;
}
else
{
var antiClickjack = document.getElementById("antiClickjack");
antiClickjack.parentNode.removeChild(antiClickjack);
}
</script>
This seems to be doing the trick and passing the clickjack.html test page.

Related

How to match specific URL in JavaScript or jQuery?

I would like to match the specific URL like "http://www.google.com" in JavaScript
var str = "http://wwww.google.com"
var test = match(str)
if(test) {
alerT(match with the url)
}
Please suggest me how to do it.
If you want to test if the variable matches the specific url, you can use a simple expression.
var str = "http://wwww.google.com";
if(str == "http://wwww.google.com"){
alert('string matches');
}
It can be http or https, so better to verify the URL in two steps:
var str = "http://www.google.com";
var protocol = str.match(/http/gi);
if (protocol != null){
var url = str.match(/wwww.google.com/gi);
if(url != null){
//Do your work
}
}

How to store a clicked URL as a variable to use in an if statement?

Here is my issue. I want window.open(TargetLink1[0].href); to only be activated if the element alertboxHeader does not exist, TargetLink1 is true and on only the page that was opened when I clicked a link. I have successfully done the first two and the issue is with getting, storing or checking for the right url, I don't know where the issue is. This is my code. The URL clicked would as have to be able to be changed if a new URL is clicked.
var varurl;
var TargetLink1 = $("a:contains('Accept')")
if ((!document.getElementById('alertboxHeader') && (TargetLink1.length) && (window.location.href.indexOf("" + varurl + "") > -1) )) {
window.open(TargetLink1[0].href);
}
function storeurl() {
var varurl = document.URL;
}
document.onclick = storeurl;
I think what you want is something like:
var validSource = (document.referrer !== "") ? (document.location.href.indexOf(document.referrer) == 0) : false;
But be aware that the above compares the document.referrer URL to the current URL as two strings, so that if your referrer were:
http://example.org?q=test
and the current URL (the link they followed) is:
http://example.org/1
it would handle it as not matching because of the query string in the referrer URL.
Here's a better way to handle it, using the URL object prototype (which is not necessarily supported in all browsers, but works in Chrome and FF):
var referrerOrigin = new URL(document.referrer).origin;
var currentOrigin = document.location.origin;
var validSource = ( referrerOrigin == currentOrigin );
The problem is here: document.onclick = storeurl; You should give any id from the document.For Example:
document.getElementById("IdHere").onclick = storeurl;

Using XMLHttpRequest to get words from another website

As of current I am learning to use JavaScript to create web applications. I have just finished developing a hangman game (code will be provided later on). I have used an array of words to get a random word to play with. But as a next step I want to use an XMLHttpRequest to get a random word from a separate website, I was wondering if someone could point me towards a tutorial or give me some information on how to start!
Thanks in advance!
<script type="text/javascript">
var myWords = new Array("first", "hello", "goodbye", "random", "word", "last");
var item = myWords[Math.floor(Math.random() * myWords.length)];
var length = item.length;
var guessedLetters = "";
var error = 0;
function partialWords(item, letters) {
var returnLetter = "";
for (i = 0; i < item.length; i++) {
if (letters.indexOf(item[i]) !== -1) {
returnLetter = returnLetter + item[i];
} else {
returnLetter = returnLetter + '_';
}
}
return returnLetter;
}
function load() {
var input = document.getElementById("hangmanID").value;
var myWords2 = (item.indexOf(input) >= 0);
if (myWords2 === false) {
console.log("That letter is not in the word");
document.getElementById("hangmanID").value = "";
document.getElementById("error").innerHTML = "That letter was wrong!";
document.getElementById("success").innerHTML = "";
error++;
if (error > 0) {
document.getElementById('hangmanImg').innerHTML = "<img src='assets/" + error + ".png'>";
} else {
document.getElementById('hangmanImg').innerHTML = "No Errors yet!";
}
} else {
console.log("That letter is correct");
var string = item.indexOf(input, 0);
console.log(string);
document.getElementById("hangmanID").value = "";
document.getElementById("success").innerHTML = "That letter was right!";
document.getElementById("error").innerHTML = "";
}
guessedLetters = guessedLetters + input;
document.getElementById('hangman').innerHTML = partialWords(item, guessedLetters);
document.getElementById("lettersUsed").innerHTML = guessedLetters;
}
</script>
UPDATE:
PLEASE NOTE THAT I AM ALLOWED TO USE JSONP
Due to same-origin-policy, XMLHttpRequest is not normally allowed to fetch data from other domains. There are work-arounds such as CORS or using a proxy on your domain or using an embedded flash or java applets.
However, JSONP is a different story. That's because JSONP does not technically return data. JSONP returns a javascript file. As such, getting data using JSONP simply requires you to add a script tag to your page:
<script src="http://other.server.com/path/to/jsonp/data"></script>
To do it programmatically:
var jsonp = document.createElement('script');
jsonp.src = "http://other.server.com/path/to/jsonp/data";
document.body.appendChild(jsonp);
The problem with this is that script tags don't return anything. To solve this, the JSONP protocol passes a function name to the server so that the server will wrap that function around the JSON data.
For example, if your regular JSON data looks like this:
{"result":"something"}
The JSONP equivalent would look something like this:
callback({"result":"something"})
So, to take the original example, our new code would now be:
function processResult (obj) {
console.log(obj);
}
var jsonp = document.createElement('script');
jsonp.src = "http://other.server.com/path/to/jsonp/data?jsonp=processResult";
document.body.appendChild(jsonp);
Notice how we're passing the name of the function to handle the return value in the query param of the URL.
Note that while in this example the parameter is "jsonp" the server may implement it using some other name. Another common one is "callback", as in callback=processResult. Read the API documentation of the server you're connecting to.

How do you get the current sessid from web address and use it in javascript?

Sorry if this is a noob question, network admin unknowingly turned into web developer :) I am trying to understand how to get the current sessid and put it into the javascript where sessid= (current sessid), its on the web address and is generated when you visit the search page. ex: http://www.southerntiredirect.com/shop/catalog/search?sessid=uUQgRHQyekRGJcyWwTFwf5hxep7cdYlV4CdKfunmjxNOQPEgDZdJD2tNgRsD7Prm&shop_param=
<script language="JavaScript">
var url= "http://www.southerntiredirect.com/online/system/ajax_search_manufacturer?sessid=????????";
</script><script type="text/javascript" src="http://www.southerntiredirect.com/online/templatemedia/all_lang/manufacturer.js"></script><input type="hidden" name="sessid" value="sessid??????">
Use my handy-dandy library URLTools!
Library
//URLTools- a tiny js library for accessing parts of the url
function urlAnalyze(url) {
if (url == undefined) {var url = document.location.toString();}
url = url.replace(/\%20/g," ");
//seperates the parts of the url
var parts = url.split("?");
//splits into sperate key=values
if (parts[1] == undefined) {return 1;}
var keyValues = parts[1].split("&");
var key = function () {}
keyValues.forEach(function (keyValue) {
var keyAndValue = keyValue.split("=");
key[keyAndValue[0]] = keyAndValue[1];
});
return key;
}
Then, just call URLAnalyze and get the sessid key.
Usage
var urlKeys = urlAnalyze(),
sessid = urlKeys["sessid"];
here is a great function that grabs whatever you want and returns the key, value for it.
The main portion of this function gets the url using window.location.href and then performs a regular expression on it to find botht he key and the value.
I DO NOT TAKE CREDIT FOR THIS CODE.
Please go the link to see the full example
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(
/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
}
You could use a simple regexp:
var url = "http://www.southerntiredirect.com/shop/catalog/search?sessid=uUQgRHQyekRGJcyWwTFwf5hxep7cdYlV4CdKfunmjxNOQPEgDZdJD2tNgRsD7Prm&shop_param=";
var match = url.match(/sessid=([^&]+)/);
if (match === null) {
throw new Error("now what? D:");
}
var sessid = match[1];
The regexp in English: look for "sessid=" then capture anything that isn't an &

Jquery Redirect Based on URL location

This is what I'm trying to solve for...
Only if the URL explicitly contains /foldername/index.htm && /foldername/ on mydomain.com then redirect to http://www.example.com
Should the URL contain any URL parameter /foldername/index.htm?example it should not redirect
All other URLs should not redirect
This is my javascript which is incomplete, but is ultimately what I'm trying to solve for...
var locaz=""+window.location;
if (locaz.indexOf("mydomain.com") >= 0) {
var relLoc = [
["/foldername/index.htm"],
["/foldername/"]
];
window.location = "http://www.example.com";
}
This is for the purpose to manage a URL that some users are hitting based on a particular way like a bookmark. Without removing the page, we want to monitor how many people are hitting the page before we take further action.
Won't the page always be on the same domain, also if the url contains /foldername/pagename.htm won't it also already include /foldername? So an && check there would be redundant.
Try the below code.
var path = window.location.pathname;
if ( (path === '/foldername' || path === '/foldername/index.html') && !window.location.search ) {
alert('should redirect');
} else {
alert('should not redirect');
}
var url = window.location;
var regexDomain = /mydomain\.com\/[a-zA-Z0-9_\-]*\/[a-zA-Z0-9_\-]*[\/\.a-z]*$/
if(regexDomain.test(url)) {
window.location = "http://www.example.com";
}
Familiarize with the location object. It provides pathname, search and hostname as attributes, sparing you the RegExp hassle (you'd most like get wrong anyways). You're looking for something along the lines of:
// no redirect if there is a query string
var redirect = !window.location.search
// only redirect if this is run on mydomain.com or on of its sub-domains
&& window.location.hostname.match(/(?:^|\.)mydomain\.com$/)
// only redirect if path is /foldername/ or /foldername/index.html
&& (window.location.pathname === '/foldername/' || window.location.pathname === '/foldername/index.html');
if (redirect) {
alert('boom');
}

Categories

Resources