Href Links as HTTP POST (complex DOM solution)

The earlier post, while easy to implement, has some well known security issues. Now lets get around them. First we’ll remove the FORM from the HTML itself, and instead build it dynamically and insert it into the BODY via the DOM and then submit it with JavaScript.

Again, if you’ve already implemented my prior solutions, this is just a small code refactor.

<html>
<head>
<title>Example FORM Post - DOM</title>
<script type="text/javascript">
/*
* Uses "location.replace()" vs. "location.href()" for all valid links.
* 'replace' has side-effect of 'restricting' back-button, or 'location'
* @param obj Object clicked
* @param x URL
*/
function xlinkObj(obj,url){
//Consider replacing w/ "return xlinkFrm(obj,url); " if you want POST behavior.
window.location.replace(uniqueUrl(url));
return false;
}
/*
* uses a FORM for the requested URL, could be POSTed!
* This is a simple solution, more complex solution COULD build the FORM and then parse attributes into INPUT's
* NOTE: you probably SHOULD NOT use this for external links, unless you intend for them to receive your params!
* @param obj Object clicked (NOT USED in this Example)
* @param x URL
*/
function xlinkFrm(obj,x){
var url=uniqueUrl(x);
var frmObj=xlinkFrmHelp(url);
if(frmObj!=null){
frmObj.submit();
}else{
alert('ERROR!');
}
return false;
}
/*
* Expects URL with queryString as param href
* @param x URL
* @return obj Object of the generated FORM
*/
function xlinkFrmHelp(x){
var rc=null;
try{
var ar = x.split("?");
var act = ar[0];
var str = ar[1];
var id="frm" + xmillis();
var oFORM=document.createElement("form");
oFORM.setAttribute("id",id);
oFORM.setAttribute("method","post");
oFORM.setAttribute("action",act);
if(str!=null){
var parms=str.split('&');
for(i=0; i < parms.length; i++){
var parm=parms[i];
var pair=parm.split('=');
var oINPUT=document.createElement("input");
oINPUT.setAttribute("type","hidden");
oINPUT.setAttribute("name",pair[0]);
oINPUT.setAttribute("value",pair[1]);
oFORM.appendChild(oINPUT);
}
}
var oBODY=document.getElementsByTagName("body")[0];
oBODY.appendChild(oFORM);
rc=oFORM;
}catch(e){
alert("Error"+e);
}
return rc;
}
/*
* generates a timestamp as a number
*/
function xmillis(){
return new Date().getTime();
}
/*
* adds timestamp to URLs to make them unique
* @param URL String
*/
function uniqueUrl(x){
return urlAppender(x,'time',xmillis());
}
/*
* helps to add parms to the url
* @param URL String
* @param aname String
* @param avalue String
*/
function urlAppender(x,aname,avalue){
var delim = "?";
if(x.indexOf("?") >=0) { delim = "&"; }
return x + delim + aname + '=' + avalue;
}
/*
* Abstracts "document.getElementById()" with appropriate error handling.
* @param id String
* @returns Object (NULL when not found!)
*/
function xgetHelper(id){
var obj = null;
try {
obj = document.getElementById(id);
} catch(z) {
var dummy=alert("Error:" + z);
}
return obj;
}
</script>
<a href="javascript:void(0);" onclick="return xlinkObj(this,'index.php');">REFRESH</a>
<a href="javascript:void(0);" onclick="return xlinkFrm(this,'index.php');">TEST-POST</a>
<a href="javascript:void(0);" onclick="return xlinkFrm(this,'index.php?a=b');">TEST-POST2</a>
<a href="javascript:void(0);" onclick="return xlinkFrm(this,'http://www.skotfred.com/hello');">TEST-XSS</a>
</body>
</html>

Cheers!

Href Links as HTTP POST (simple solution)

Another interesting challenge, The standard <a href=”…”></a> style link performs an HTTP GET, however you might want to perform a POST in some cases. HTML does not natively support this behavior, but it can be accomplished in JavaScript. If you have already implemented some of my security ‘hacks’ from previous posts this is only a small change. As usual I’ve included the minimum code required for this task in the example, but you should be able to easily merge the different features back into this!

Later on (in a different post), I’ll expand this to make it even more secure as this solution simply puts all of the URL into the FORM ‘action’ attribute and it would be better to pass them in the FORM body itself to hide them from the URL shown in the browser.

<html>
<head>
<title>Link to FORM POST simple example</title>
<script type="text/javascript">
/*
* Uses "location.replace()" vs. "location.href()" for all valid links.
* 'replace' has side-effect of 'restricting' back-button, or 'location'
* @param obj Object clicked (NOT used in this example)
* @param x URL
*/
function xlinkObj(obj,url){
//Consider replacing w/ "return xlinkFrm(obj,url); " if you want POST behavior in all cases!
window.location.replace(uniqueUrl(url));
return false;
}
/*
* uses a FORM for the requested URL, could be POST'ed!
* This is a simple solution, using an existing empty FORM on the page.
* A more complex and secure solution COULD build the FORM dynamically and then parse attributes into INPUT's
* NOTE: you probably SHOULD NOT use this for external links, unless you intend for them to receive your params!
* @param obj Object clicked (NOT used in this example)
* @param x URL
*/
function xlinkFrm(obj,x){
var frmObj=xgetHelper('frmXlink');
if(frmObj!=null){
frmObj.action=uniqueUrl(x);
frmObj.submit();
}else{
alert('ERROR!');
}
return false;
}
/*
* generates a timestamp as a number
*/
function xmillis(){
return new Date().getTime();
}
/*
* adds timestamp to URLs to make them unique
* @param URL String
*/
function uniqueUrl(x){
return urlAppender(x,'time',xmillis());
}
/*
* helps to add parms to the url
* @param URL String
* @param aname String
* @param avalue String

*/
function urlAppender(x,aname,avalue){
var delim = "?";
if(x.indexOf("?") >=0) { delim = "&"; }
return x + delim + aname + '=' + avalue;
}
/*
* Abstracts "document.getElementById()" with appropriate error handling.
* @param id String
* @returns Object (NULL when not found!)
*/
function xgetHelper(id){
var obj = null;
try {
obj = document.getElementById(id);
} catch(z) {
var dummy=alert("Error:" + z);
}
return obj;
}
</script>
</head>
<body>
<form id="frmXlink" action="#" method="post"></form>
<a href="javascript:void(0);" onclick="return xlinkObj(this,'index.html');">REFRESH</a>
<a href="javascript:void(0);" onclick="return xlinkFrm(this,'index.html');">TEST-POST</a>
<a href="javascript:void(0);" onclick="return xlinkFrm(this,'index.html?a=b');">TEST-POST PARMS</a>
<a href="javascript:void(0);" onclick="return xlinkFrm(this,'http://www.giantgeek.com/hello');">TEST-XSS</a>
</body>
</html>

This just uses an “empty” FORM in the page and uses the new ‘xlinkFrm()’ method to copy the URL to the FORM ‘action’.

Like i said, this is a simple solution as the params are still on the URL making them less secure. I’ll be refactoring it to parse the params to dynamically build the FORM (that will no longer be hardcoded).

Cheers!

What is a SLD (Second Level Domain)?

I just wrote about the TLD, so this naturally follows:

A SLD includes the TLD name and further identifies the owning organization of a URL.

Second-level domains can be divided into further levels. These subdomains sometimes represent different computers within an organization, but are many times the same machine with different aliases.

Examples:

www.giantgeek.com
mail.giantgeek.com

TLD =  .com
SLD = giantgeek.com
Subdomains = www.gianteek.com & mail.giantgeek.com

NOTE: Refer to HTTP/1.1 for details on how IP addresses, routing and webservers are impacted by this.

Interesting enough, some one character SLD’s do exist,  x.com for example.

References:

Cheers!

What is a TLD (Top Level Domain)?

I occasionally get this question, as many technical people don’t fully understand it.

A TLD is ‘actually” the last section of a URL (owned by the domain registrars themselves).

Examples:

  • .com
  • .net
  • .org
  • .us (and other 2 digit country codes)

You can find a full list of TLD’s here:

Various other TLD’s have been proposed through the years, here are a few common ones (that are in various states of approval or implementation):

  • .museum
  • .info
  • .xxx
  • .biz
  • .mobi

References:

Cheers!

MSIE’s flawed SSL implementation

This has been quite frustrating. It seems that Microsoft has again ventured from complying with the industry web standards in this space too!

The comments from the Apache HTTP 2.x ‘http-ssl.conf’ files say it all:

#   SSL Protocol Adjustments:
#   The safe and default but still SSL/TLS standard compliant shutdown
#   approach is that mod_ssl sends the close notify alert but doesn't wait for
#   the close notify alert from client. When you need a different shutdown
#   approach you can use one of the following variables:
#   o ssl-unclean-shutdown:
#     This forces an unclean shutdown when the connection is closed, i.e. no
#     SSL close notify alert is send or allowed to received.  This violates
#     the SSL/TLS standard but is needed for some brain-dead browsers. Use
#     this when you receive I/O errors because of the standard approach where
#     mod_ssl sends the close notify alert.
#   o ssl-accurate-shutdown:
#     This forces an accurate shutdown when the connection is closed, i.e. a
#     SSL close notify alert is send and mod_ssl waits for the close notify
#     alert of the client. This is 100% SSL/TLS standard compliant, but in
#     practice often causes hanging connections with brain-dead browsers. Use
#     this only for browsers where you know that their SSL implementation
#     works correctly.
#   Notice: Most problems of broken clients are also related to the HTTP
#   keep-alive facility, so you usually additionally want to disable
#   keep-alive for those clients, too. Use variable "nokeepalive" for this.
#   Similarly, one has to force some clients to use HTTP/1.0 to workaround
#   their broken HTTP/1.1 implementation. Use variables "downgrade-1.0" and
#   "force-response-1.0" for this.

SetEnvIf User-Agent ".*MSIE.*" \
nokeepalive ssl-unclean-shutdown \
downgrade-1.0 force-response-1.0

A little further research indicates that MSIE6 has (probably) partially fixed this (the HTTP/1.0 & KeepAlive issues), so the updated config should use a Regular Expression to look like…

SetEnvIf User-Agent ".*MSIE [1-5].*"
 nokeepalive ssl-unclean-shutdown
 downgrade-1.0 force-response-1.0
SetEnvIf User-Agent ".*MSIE [6-9].*"
 ssl-unclean-shutdown

Related Information:

Cheers!

Pretty Good Privacy (PGP)

I’ve used PGP (Pretty Good Privacy) since I was in college. It provides for both digital signatures and strong encryption and content without the user having to go make extraordinary effort. The process uses what is known as Public Key Encryption and uses a Web Of Trust to certify individual users.

For years I used the original PGP 2.6.2, 5.x and 6.x products that were available as freeware. After PGP was acquired by a much larger commercial entity, most development has shifted to the open-source community that makes it available as GnuPG aka GPG.

There are several plugins available for common Email Clients such as Thunderbird and Outlook to natively integrate the functions into those applications. Additionally plugins are available for Firefox to enable encryption and signing of WebMail services such as GMail (Google Mail).

My public keys are available online at http://www.giantgeek.com/pgpkeys.asc, http://www.skotfred.com/pgpkeys.asc, or through most of the keyservers.

References:

I look forward to your signed/encrypted emails,
Cheers.

MSIE6 CSS issue ‘dotted’ behaves like ‘dashed’

Another fix in MSIE7 (broken before), ‘dotted’ is now implemented, in MSIE6 dotted had the same visual representation as ‘dashed’.

This explains why you might expect to see a line of “……” that appear to be “——“, even when you’re absolutely positive that you’re CSS is correct!
CSS:

border:1px dotted #fff;

HTML Example:

<html>
<head>
<title>dotted-dashed Example</title>
<style type=”text/css”>
fieldset {background-color:#fcfcfc;
width:95%;
padding:15px 10px 0 10px;margin:0 0 20px 0;
border:1px solid #999;
border-top-width:2px;
overflow:hidden;}
fieldset div.buttons {clear:both; padding-top:10px;padding-bottom:10px;margin:3px 0 0 0;border-top:1px dotted #b5b5b5;text-align:left;}
</style>
</head>
<body>
<fieldset>
Some form fields go here…
<div class=”buttons”>
Some buttons go here…
</div>
</fieldset>
</body>
</html>

Cheers!

Clientside Session Timeout’s

There comes a time in web application development that you need to ‘timeout’ idle users. This comes in a variety of ways, here’s a few common reasons that you may desire this activity.

  • Security – you don’t want to leave sensitive data on a users screen when they’ve gone to lunch or left for the day.
  • Server Resources – persisting/keeping an active ‘session’ available on the server takes resources (the exact type varies, but this is usually database, memory or file resources)
  • Server ‘enforced’ session timeout’s and the potential errors and lost data experienced by the users in that circumstance.

My personal approach to this has evolved over time, here’s a brief synopsis:

  1. Use standard server-side session timeout, often leading to a bad user experience when they loose data on a form submit.
  2. Use META REFRESH…where timeout is in seconds, in this example it’s 60 seconds (1 minute).
    <meta http-equiv="refresh" content="60;url=http://www.giantgeek.com/" />
  3. Use javascript 'timeout' (problem is that this is not 'measureable')
    
    <script type="text/javascript">
    setTimeout("javascript:myTimeout();",minutes*60000); // code minutes
    </script>
  4. Use javascript countdown timer and custom code event.

<html>
<head>
<title>Timeout example</title>
<script type=”text/javascript”>
var build=’testing’;
var timerID = 0;
var loadTime = null;
var stopTime = null;
function xload(){
loadTime=grvMillis();
grvWindowStatus(build);
grvSetTimeout();
}
function xclose(){
grvWindowStatus(”);
}
function grvMillis(){
return new Date().getTime();
}
// Start timer
function grvTimerUpdate(){
timerID = grvTimerClear(timerID);
if(loadTime == null){
loadTime=grvMillis();// Start Time
}
// Calculate Current Time in seconds
var timeNow = grvMillis();

var think = calcMinSec( calcTimeDiff(timeNow,loadTime) );
var remain = calcMinSec( calcTimeDiff(stopTime,timeNow) );
grvWindowStatus(build + ” ” + think + ” ” + remain );
timerID = setTimeout(“grvTimerUpdate()”,1000);
}
function calcMinSec(diff){
var mm = removeDecimal(diff/60);
var ss = zeroPad(removeDecimal(diff-(mm*60)),2);
return (mm + “:” + ss);
}
function calcTimeDiff(tmpStart,tmpStop){
var diff = (tmpStart – tmpStop)/1000;
return diff;
}
function removeDecimal(val){
var rc=””;
val = val + “”;
if(val!=””){
var pos = val.indexOf(“.”);
if(pos > -1){
rc=val.substr(0,val.indexOf(“.”));
} else {
rc=val;
}
}
return rc;
}
function zeroPad(x,sz){
x = x + “”;
while(x.length < sz){
x = “0” + x;
}
return x;
}
function grvTimerClear(x){ // this clears a timer from the queue
if(x){
clearTimeout(x);
x = 0;
}
return x;
}
function grvSetTimeout(){
var min=45; xID=grvTimeout(“javascript:grvTimeoutUSER()”,min); // EXAMPLE: this could be conditional!
stopTime = grvCalculateTimeout(min);
grvTimerUpdate();
}
function grvCalculateTimeout(mins){
var timeNow = grvMillis();
var exp = timeNow + (mins*60*1000);
var timeExp = new Date(exp).getTime();
return timeExp;
}
function grvTimeout(x,minutes){ // this sets a timer(request) in a queue
return setTimeout(x,minutes*60000);
}
function grvTimeoutUSER(){
alert(‘Session Inactivity Timeout [USER]’);
// DO WHAT YOU NEED TO HERE!}
function grvWindowStatus(txt){
window.defaultStatus=txt;
}
</script>
</head>
<body onunload=”xclose();” onload=”xload();”>
</body>
</html>

Another benefit of this last solution is that you also have access to the user “Think Time” and can therefore measure how long the user spends on a given page.

Cheers!

Clientside sorting of HTML TABLE in JavaScript

To save network bandwidth and server resources, it is often beneficial to to sorting of tabular data on the client. Here’s a workable solution that I’ve implemented several times.

Additionally, the need to make the solution ‘accessible’ to screen-reader technology and be backward compatible for users without JavaScript often become challenging.

There are some small “quirks” that you should be aware of…

  • The ‘sortTable’ method uses the ID of the ‘TBODY’. Working to remove this requirement through better use of the DOM.
  • Will likely rework this to use Prototype framework which should result in smaller code.
  • Future enhancement will add a class to the header indicating the sort order of the column(s).
  • Creating the ‘SPAN’ for dates to be sorted is best handled by a taglib.
  • Large TABLE’s can take a significant amount of time to sort on a client, so it’s sometimes better to use a server side solution. Developers should use their experience to make this judgment call.

Example code (XHTML logic removed as usual for brevity):

<html>
<head>
<title>Client Side TABLE sorting</title>
<style type=”text/css”>
/* SCROLL */
div.scroll {width:100%;overflow:scroll;}
html>body div.scroll {width:100%;overflow:scroll} /* fixes IE6 hack */
/*** TABULAR ***/
tr.even {background-color:#eee;}
th.first, td.first {border-width:0;}
th.memo {text-align:left;padding:0;}
td.sorted {background-color: #f0f0f0;}
th.sorted {background-color: #99f;}
tr.even td.sorted { background-color: #d0d0d0; }
table.sorted tr.error { background-color:red; }
table.sorted tr.scroll th { background-color:#99f; text-align:left;}
table.sorted tr.scroll th a.sorted { color:#fff; text-decoration:none;}
table.sorted tr.scroll th a.sorted:hover { color:#fff; text-decoration:underline;}
</style>
<script type=”text/javascript”>
//—————————————————————————–
// sortTable(id, col, rev,xcase)
//
// id – ID of the TABLE, TBODY, THEAD or TFOOT element to be sorted.
// col – Index of the column to sort, 0 = first column, 1 = second column, etc.
// rev – If true, the column is sorted in reverse (descending) order initially.
// xcase – makes sort NOT case sensitive.
//
// The following is an example of jsp code for setting up the reformatted copy of a date
// field to allow sorting by date:
//
// <fmt:formatDate var=”varSortDate” value=”${searchResult.dateOfBirth}” pattern=”${sortableDateTimePattern}” />
// <span title=”<c:out value=”${varSortDate}” />”><fmt:formatDate value=”${searchResult.dateOfBirth}” pattern=”${dateFormatPattern}” /></span> | etc.
//
// The above code creates html code that contains, for example, a line like the following:
//
// <span title=”19640101000000″>01/01/1964</span>
//
// This sort routing concatenates the title element and the text node
// content to sort on the following string:
//
// 1964010100000001/01/1964
//
// This effective ignores the date containing slashes and used the yyyyMMdd etc. value.
// Fields that are not dates should not use the span element and title attribute, unless
// it is desired to sort on something other than the text node content.
//—————————————————————————–
function sortTable(id, col, rev, xcase) {
// Get the table or table section to sort.
var tblEl = xgetHelper(id);
if(tblEl != null){
// The first time this function is called for a given table, set up an array of reverse sort flags.
if (tblEl.reverseSort == null) {
tblEl.reverseSort = new Array();
// Also, assume the column zero is initially sorted.
tblEl.lastColumn = 0; // was 1
}

// If this column has not been sorted before, set the initial sort direction.
if (tblEl.reverseSort[col] == null)
tblEl.reverseSort[col] = rev;

// If this column was the last one sorted, reverse its sort direction.
if (col == tblEl.lastColumn)
tblEl.reverseSort[col] = !tblEl.reverseSort[col];

// Remember this column as the last one sorted.
tblEl.lastColumn = col;
// Set the table display style to “none” – necessary for Netscape 6 browsers.
var oldDsply = tblEl.style.display;
tblEl.style.display = “none”;
// Sort the rows based on the content of the specified column using a selection sort.

var tmpEl;
var i, j;
var minVal, minIdx;
var testVal;
var cmp;
for (i = 0; i < tblEl.rows.length – 1; i++) {

// Assume the current row has the minimum value.
minIdx = i;
minVal = getTextValue(tblEl.rows[i].cells[col], xcase);

// Search the rows that follow the current one for a smaller value.
for (j = i + 1; j < tblEl.rows.length; j++) {
testVal = getTextValue(tblEl.rows[j].cells[col], xcase);
cmp = compareValues(minVal, testVal);
// Negate the comparison result if the reverse sort flag is set.
if (tblEl.reverseSort[col])
cmp = -cmp;
// If this row has a smaller value than the current minimum, remember its
// position and update the current minimum value.
if (cmp > 0) {
minIdx = j;
minVal = testVal;
}
}

// By now, we have the row with the smallest value. Remove it from the
// table and insert it before the current row.
if (minIdx > i) {
tmpEl = tblEl.removeChild(tblEl.rows[minIdx]);
tblEl.insertBefore(tmpEl, tblEl.rows[i]);
}
}

// Make it look pretty.
makePretty(tblEl, col);

// Restore the table’s display style.
tblEl.style.display = oldDsply;
}

return false;
}

//—————————————————————————–
// Functions to get and compare values during a sort.
//—————————————————————————–

// This code is necessary for browsers that don’t reflect the DOM constants
// (like IE).
if (document.ELEMENT_NODE == null) {
document.ELEMENT_NODE = 1;
document.TEXT_NODE = 3;
}

function getTextValue(el, xcase){
var i;
var s;
var spanTitleValue;

// Find and concatenate the values of all text nodes contained within the element.
s = “”;

for (i = 0; i < el.childNodes.length; i++) {
if (el.childNodes[i].nodeType == 1) {
if (el.childNodes[i].nodeName != null) {
if (el.childNodes[i].nodeName == “SPAN”) {
spanTitleValue = el.childNodes[i].getAttribute(“Title”);
s += spanTitleValue;
}
}
else {
}
// Use recursion to get text within sub-elements.
s += getTextValue(el.childNodes[i]);
}
else if (el.childNodes[i].nodeType == document.TEXT_NODE) {
s += el.childNodes[i].nodeValue;
}
else {
// Gets here when element is empty! <span title=””></span>
//alert(‘Error — Not element or text node’);
}
}
return normalizeString(s, xcase);
}

function compareValues(v1, v2) {

var f1, f2;
// If the values are numeric, convert them to floats.

f1 = parseFloat(v1);
f2 = parseFloat(v2);
if (!isNaN(f1) && !isNaN(f2)) {
v1 = f1;
v2 = f2;
}

// Compare the two values.
if (v1 == v2)
return 0;
if (v1 > v2)
return 1
return -1;
}

// Regular expressions for normalizing white space.
var whtSpEnds = new RegExp(“^\\s*|\\s*$”, “g”);
var whtSpMult = new RegExp(“\\s\\s+”, “g”);

function normalizeString(s, xcase) {

s = s.replace(whtSpMult, ” “); // Collapse any multiple whites space.
s = s.replace(whtSpEnds, “”); // Remove leading or trailing white space.

var rc = s;
if(xcase == true) {
rc = s.toUpperCase();
}
return rc;
}

//—————————————————————————–
// Functions to update the table appearance after a sort.
//—————————————————————————–

// Style class names.
var rowClsNm = “even”;
var colClsNm = “sorted”;

// Regular expressions for setting class names.
var rowTest = new RegExp(rowClsNm, “gi”);
var colTest = new RegExp(colClsNm, “gi”);

function makePretty(tblEl, col) {
var i, j;
var rowEl, cellEl;

// Set style classes on each row to alternate their appearance.
for (i = 0; i < tblEl.rows.length; i++) {
rowEl = tblEl.rows[i];
rowEl.className = rowEl.className.replace(rowTest, “”);
if (i % 2 != 0)
rowEl.className += ” ” + rowClsNm;
rowEl.className = normalizeString(rowEl.className);
// Set style classes on each column (other than the name column) to
// highlight the one that was sorted.
for (j = 0; j < tblEl.rows[i].cells.length; j++) { /* was j=2 */
cellEl = rowEl.cells[j];
cellEl.className = cellEl.className.replace(colTest, “”);
if (j == col)
cellEl.className += ” ” + colClsNm;
cellEl.className = normalizeString(cellEl.className);
}
}

// Find the table header and highlight the column that was sorted.
var el = tblEl.parentNode.tHead;
rowEl = el.rows[el.rows.length – 1];
// Set style classes for each column as above.
for (i = 2; i < rowEl.cells.length; i++) {
cellEl = rowEl.cells[i];
cellEl.className = cellEl.className.replace(colTest, “”);
// Highlight the header of the sorted column.
if (i == col)
cellEl.className += ” ” + colClsNm;
cellEl.className = normalizeString(cellEl.className);
}
}
function xgetHelper(id){
var obj = null;
try {
obj = document.getElementById(id);
} catch(z) {
//var dummy=alert(“Error:” + z);
}
return obj;
}
</script>
</head>
<body>
<fieldset>
<div id=”ex_div” class=”scroll”>
<table summary=”” id=”names” class=”sorted” cellspacing=”0″>
<colgroup>
<col style=”first labels” />
<col style=”form_fields” />
</colgroup>
<thead>
<tr class=”scroll”>
<th scope=”col” id=”ex_0″><a href=”javascript:void(0);” class=”sorted” onclick=”return sortTable(‘ex_sort’,0,true,true);”>Alpha</a></th>
<th scope=”col” id=”ex_1″><a href=”javascript:void(0);” class=”sorted” onclick=”return sortTable(‘ex_sort’,1,true,true);”>Date</a></th>
<th scope=”col” id=”ex_2″><a href=”javascript:void(0);” class=”sorted” onclick=”return sortTable(‘ex_sort’,2,true,true);”>Url</a></th>
</tr>
</thead>
<tbody class=”scroll” id=”ex_sort”>
<tr class=”even”>
<td headers=”ex_0″>Alpha</td>
<td headers=”ex_1″><span title=”20070701″>July 2, 2007</span></td>
<td headers=”ex_2″><a href=”javascript:void(0);” onclick=”alert(‘view.php?userid=6’);”>5</a></td>
</tr>
<tr class=”odd”>
<td headers=”ex_0″>Bravo</td>
<td headers=”ex_1″><span title=”20050903″>Sept 3, 2005</span></td>
<td headers=”ex_2″><a href=”javascript:void(0);” onclick=”alert(‘view.php?userid=8’);”>4</a></td>
</tr>
<tr class=”even”>
<td headers=”ex_0″>Charlie</td>
<td headers=”ex_1″><span title=”19700709″>July 9, 1970</span></td>
<td headers=”ex_2″><a href=”javascript:void(0);” onclick=”alert(‘view.php?userid=4’);”>2</a></td>
</tr>
<tr class=”odd”>
<td headers=”ex_0″>Delta</td>
<td headers=”ex_1″><span title=”20001213″>Dec. 13, 2000</span></td>
<td headers=”ex_2″><a href=”javascript:void(0);” onclick=”alert(‘view.php?userid=5’);”>3</a></td>
</tr>
<tr class=”even”>
<td headers=”ex_0″>Echo</td>
<td headers=”ex_1″><span title=”20010911″>Sept 11, 2001</span></td>
<td headers=”ex_2″><a href=”javascript:void(0);” onclick=”alert(‘view.php?userid=2’);”>1</a></td>
</tr>
</tbody>
</table>
</div>
</fieldset>
</body>
</html>

Cheers!

Detecting browser SSL capability with JavaScript

If you run a secured website using HTTPS (aka SSL) it’s often wise to stop or notify users that are using a browser or client that doesn’t support the proper encryption level required.

Here’s a short method to “sniff” the capabilities prior to forwarding users to the secure area. You could add logic to inform the user of the problem.

As usual I’ve stripped a lot of the XHTML markup for readability.

<html>
<head>
<!– set ‘sslok’ global variable for testing SSL capability –>
<script type=”text/javascript”>
<!–
var sslok = 0;
//–>
</script>
<!– try including source javascript from secure server, this will set “sslok” to 1 if it works –>
<!– note that the /secure directory is protected so that only 128+bit SSL is allowed –>
<script type=”text/javascript” src=”https://www.example.com/secure/ssl-test.js”></script>
<!– if ssl is 1, our javascript include worked, so SSL is successful – redirect to SSL –>
<script type=”text/javascript”>
<!–
if (sslok == ‘1’) {
window.location = ‘https://www.example.com/secure’;
}
//–>
</script>
</head>
<body>
</body>
</html>

Contents of the ‘ssl-test.js’ file:

<!– set sslok to 1, so we know this include succeeded –>
sslok = ‘1’;

NOTE: If you use the same ‘filesystem’ for HTTP & HTTPS you might want to use a server-side program (PHP or Java for example) to generate the JavaScript.  Benefit of that process would be that you could also interrogate and return other SSL attributes such as cypher strength.

Cheers!