JavaScript Session Timeout Warning

August 5, 2010



//***********************************
// Global variables
var SECONDS = 60000;
var WarningMins = 1; //In Minutes
var TimeOutMins = 2; //In Minutes
var ThresholdMils = SECONDS * WarningMins;
var WarningTimer = null;
var LOGINPAGE = "Login.aspx";
var TimeOutWindow = null;
var Content = "";

var StartMils = Date.parse(new Date().toLocaleString());
var TimeOutMils = StartMils + (SECONDS * TimeOutMins);
//***********************************

function BuildContent()
{
Content = '<body bgcolor="#ffffff" onLoad="self.focus"><font face="arial,helvetica" size="2">';
Content += 'Due to inactivity, you are about to be logged out. ';
Content += 'If you wish to stay logged in, click "Yes" below.';
Content += 'If you select "No" or do not respond to this screen,
Content += 'you will automatically be logged out for security reasons.';
Content += '<p><div align="center"><a ';
Content += 'href="javascript:opener.ResetTimer();top.parent.opener.focus();self.close();">Yes</a>';
Content += '</div></p></font></body></html>';
}

function CountDown()
{
clearTimeout(WarningTimer);

var w = 400;
var h = 200;

if (document.all || document.layers)
{
w = screen.availWidth;
h = screen.availHeight;
}

var popW = 400;
var popH = 200;
var leftPos = (w - popW) / 2;
var topPos = (h - popH) / 2;

if (TimeOutWindow && !TimeOutWindow.closed)
TimeOutWindow.close();

var params = 'menubar=0,toolbar=0,status=0,scrollbars=0,resizable=0,width=';
params += popW + ',height='+ popH + ',top=' + topPos + ',left=' + leftPos;

TimeOutWindow = window.open('','TimeOut',params);
TimeOutWindow.document.writeln('<html><head><title>TimeOut</title></head><body bgcolor=white onLoad="self.focus()">'+Content+'</body></html>');
TimeOutWindow.document.close();

WarningTimer = setTimeout('CountDown()', ThresholdMils);
}

function ValidateSession()
{
//******************************************
//Call AJAX Function to Check Session Check
//******************************************
return true;
}

function ResetTimer()
{
window.focus();
setTimeout(top.window.focus, 1000);
alert("Your Session will be extended!!!");

clearTimeout(WarningTimer);

var SessionCheck = ValidateSession();

if (SessionCheck)
{
StartMils = Date.parse(new Date().toLocaleString());
TimeOutMils = StartMils + (SECONDS * TimeOutMins);
WarningTimer = setTimeout('CountDown()', ThresholdMils);
TimeOutWindow = null;
}
else
{
//****************
//Logout the User
//****************
}
}

var CurrentWindowUrl = window.location.href;

//******************************
//IF THE PAGE IS NOT LOGIN PAGE
//******************************
if (CurrentWindowUrl.indexOf(LOGINPAGE) == -1)
{
BuildContent();
WarningTimer = setTimeout('CountDown()', ThresholdMils);
}


XmlSerializer Memory Leak

February 19, 2010

XML serialization is the process of converting an object’s public properties and fields to a serial format (in this case, XML) for storage or transport. Deserialization re-creates the object in its original state from the XML output. You can think of serialization as a way of saving the state of an object into a stream or buffer. For example, ASP.NET uses the XmlSerializer class to encode XML Web service messages.

Some of the Overloaded XmlSerializer constructors internally calls XmlSerializer.GenerateTempAssembly to generate the temporary assembly every time the constructor is called. The bad part is it does not reuse the existing created assembly, rather it creates the new temporary assembly for every call, which in turn increases the memory foot print.

One of the solutions is to cache the reference and reuse the assembly using the below code:

public class XmlSerializerCache{
private static object SyncRoot = new object();
private static Dictionary Serializers = new Dictionary();
public static XmlSerializer GetSerializer(Type type, Type[] types)
{
StringBuilder keyBuilder = new StringBuilder(60);
keyBuilder.Append(type.FullName);
if (null != types && types.Length > 0)
{
foreach (Type t in types)
keyBuilder.Append(“#”).Append(t.FullName);
}
string key = keyBuilder.ToString();
XmlSerializer serializer = null;
if (false == Serializers.TryGetValue(key, out serializer))
{
lock (SyncRoot)
{
if (false == Serializers.TryGetValue(key, out serializer))
{
serializer = new XmlSerializer(type, types);
Serializers.Add(key, serializer);
}
}
}
return serializer as XmlSerializer;
}
}

.NET Web Security

February 14, 2010

1. Session Cleanup
Create a new Session before Login Page is presented to avoid Session hijacking.
Please refer to http://support.microsoft.com/kb/899918
Session.Abandon();
Response.Cookies.Add(new HttpCookie(“ASP.NET_SessionId”, “”));

2. Web.Config Changes
Make the following changes to web.config to secure external facing web app.
- Instead of <forms cookieless=”UseUri”> , use <forms cookieless=”UseCookies”>

- Instead of <forms requireSSL=”false”>, use <forms requireSSL=”true”>

- Use <httpCookies httpOnlyCookies=”true”> is a useful measure against Cross-Site Script attacks. (works only on IE 6 & above, FireFox 3 & above, Chrome, in future other browser would embrace)

- Instead of <customErrors mode=”Off”>, Use <customErrors mode=”RemoteOnly”>

- Use <trace enabled=”false” localOnly=”true”>

- Use <compilation debug=”false”>

- <pages> validateRequest should be set to “true” which is default.

3. Expire Pages
Add the following changes to all the pages which need to be expired.

Cache-Control : no-cache, max-age=0, s-maxage=0,must-revalidate,proxy-revalidate,no-store,private
Pragma : no-cache
Expires : -1

4. Cookie Cleanup during Logout
Add the following changes to all the pages which need to be expired.

5. Request.MapPath
If we use MapPath to map a supplied virtual path to a physical path on the server, use the overloaded Request.MapPath method that accepts a bool parameter so that we can prevent cross-application mapping. This means that a user cannot successfully supply a path that contains “..” to traverse outside of application’s virtual directory hierarchy.

6. Avoid Persistence Cookies
Use Session cookies to store information instead of using persistence cookies. This will avoid information stored in the user’s computer.

7. SSL (HTTPS) for all Form Logins
Make sure Login Pages are served using SSL Session instead of serving over HTTP.

8. Enforce Strong Passwords
Ensure that passwords are complex enough to prevent users guessing other users’ passwords and to prevent successful dictionary attacks against user credential store.

9. Do Not Reveal Exception Details to the Client
When exceptions occur, return concise error messages to the client and log specific details on the server. Do not reveal internal system or application details, such as stack traces, SQL statement fragments, and table or database names to the client. Ensure that this type of information is not allowed to propagate to the end user or beyond current trust boundary. A malicious user could use system-level diagnostic information to learn about application and probe for weaknesses to exploit in future attacks.

Configure a Custom Error Page to display all Application/System related Errors.

10. View State
- Avoid Storing Sensitive Data in View State
- Using SSL protects ViewState between Server and Browser, but it does not stop it being viewed and modified on the user’s computer
- Use the following setting to encrypt View State

And

When validation was set to 3DES, ViewState was encrypted before being rendered in the page.

11. Configure the MachineKey to Use the Same Keys on All Servers in a Web Farm
Configuration files on each server share hashing and encryption keys. These are used by ASP.NET to protect ViewState and forms authentication tickets. Manually generated, common keys are required because we cannot guarantee which server will handle successive requests.

12. Set the Correct Character Encoding
To successfully restrict valid data for Web pages, we should limit the ways in which the input data can be represented. This prevents malicious users from using canonicalization and multi-byte escape sequences to trick input validation routines.

13. Use the innerText Property Instead of innerHTML
Wherever we use innerHTML property to build a page and if the HTML is based on potentially untrusted input, we must use HtmlEncode to make it safe. To avoid having to remember to do this, use innerText instead. The innerText property renders content safe and ensures that scripts are not executed.

14. Block All “403” Forbidden Errors
Instead of displaying 403 forbidden errors to the end user, always display Custom Error page to the user. 403 forbidden errors expose the web server directory structure to the user.

15. Consider Using Page.ViewStateUserKey to Counter One-Click Attacks
Consider using Page.ViewStateUserKey to counter one-click attacks. If you authenticate your callers and use ViewState, set the Page.ViewStateUserKey property in the Page_Init event handler to prevent one-click attacks.

void Page_Init (object sender, EventArgs e) {
if (Session["ViewStateUserKey"] == null)
Session["ViewStateUserKey"] = new Guid().ToString();
this.Page.ViewStateUserKey = Session["ViewStateUserKey"].ToString();
}

The server has no way of knowing that the ViewState originated from the attacker. ViewState validation and HMACs do not counter this attack because the ViewState is valid and the page is executed under the security context of the user.

By setting the ViewStateUserKey property, when the attacker browses to a page to create the ViewState, the property is initialized to his or her name. When the legitimate user submits the page to the server, it is initialized with the attacker’s name. As a result, the ViewState HMAC check fails and an exception is generated.

XslCompiledTransform memory leak

February 14, 2010

The XslCompiledTransform class is an XSLT processor that supports the XSLT 1.0 syntax. It is a new implementation and includes performance gains when compared to the obsolete XslTransform class. The structure of the XslCompiledTransform class is very similar to the XslTransform class. The Load method loads and compiles the style sheet, while the Transform method executes the XSLT transform.

1. This class has 2 overloaded constructor with enableDebug parameter is set to true as default. Setting this to true enables you to debug the style sheet with the Microsoft Visual Studio Debugger. Please use the overloaded constructor with enableDebug value to false.

// Instantiate XSL Compiled Transformer
XslCompiledTransform xct = new XslCompiledTransform(false);

2. The XslCompiledTransform uses the CodeDom to compile the scripts
within the xsl file into .NET assembly and load them into the current
AppDomain. The Application memory space keeps growing up if we compile more XSL Files which have scripts. It is hard to release the resources loaded in your AppDomain, thus increases the Application Heap.

The possible solutions are: a) using extension objects
instead of msxsl:script blocks; b) recycling the AppDomain from time to time.

public class XslCompiledTransformCache
{
private static readonly object _syncRoot = new object();
private static Dictionary _transformers = new Dictionary();

public static XslCompiledTransform GetXslTransform(string xslFilePath)
{
XslCompiledTransform transformer = null;
if (false == _transformers.TryGetValue(xslFilePath, out transformer))
{
lock (_syncRoot)
{
if (false == _transformers.TryGetValue(xslFilePath, out transformer))
{
transformer = new XslCompiledTransform(false);
transformer.Load(xslFilePath);
_transformers.Add(xslFilePath, transformer);
}
}
}
return transformer;
}
}

Search Results Redirected to Unrelated sites

February 14, 2010

1. Open the Browser and check your proxy settings to make sure it has not been changed by the Trojans.
Internet Properties > Connections > LAN Settings > Proxy server

2. Download ComboFix.Exe from
http://www.techsupportforum.com/sectools/sUBs/ComboFix.exe or
http://download.bleepingcomputer.com/sUBs/ComboFix.exe

3. Follow the prompts. When finished, it shall produce a log for you.
Note: Do not open any other program and let the software run now. That may cause ComboFix to stall.

4. Download FixIEDef from http://downloads.malwareteks.com/FixIEDef.exe

5. Download Malwarebytes’ Anti-Malware from http://www.malwarebytes.org/mbam.php, Install and run select “Perform Quick Scan”, then click Scan.

6. Download Avast! Free AntiVirus, Install and do Quick Scan.

Hope this helps!!!

MemoryStream GetBuffer Vs ToArray

February 14, 2010

If you need to read the data from MemoryStream, always use ToArray() method instead of GetBuffer() method.

string Output = Encoding.UTF8.GetString(mstream.ToArray());

MemoryStream.GetBuffer() method returns the entire allocated buffer (even the unused buffer) and with ” padding for the unused buffer space.

Enjoy!!!

Memory DMP

February 14, 2010

You might have noticed a huge memory.dmp file under c:\windows directory.

(Only) If you need to reclaim the space,
- go to Control Panel/System/Advanced tab/Startup and Recovery
settings,
- Under System Failure,
- Change the write debugging to a Mini-Dump (64K)
- Click OK

You are done and it will be the new default after reboot.

Firefox & Auto Form Submit

January 19, 2010

Here is the sample code which can be used to submit form automatically…

<html>
<head></head>
<body>
<form name=”myForm” id=”myForm” method=”post” action=”
http://www.google.com”/>
<script type=”text/javascript”>
//<![CDATA[
this.myForm.submit();
//]]>
</script>
</body>
</html>

Common Mistakes:

  1. Make Sure no form element with “submit” name.
  2. submit function is case sensitive.
  3. Make sure body and form tags are properly closed.

Hope this Helps!!! 


Follow

Get every new post delivered to your Inbox.