On this page

Another bug bites the dust - complete guide to a road of happiness
Session hijacking - prevention oriented
Writing secure .Net code for web applications - Lesson 1 - XSS prevention
Obtaining the connection string for a site in sps - Complete Guide
Coding with Threads in .Net - Lesson 1

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: 0
This Month: 0
This Week: 0
Comments: 33

Sign In
Pick a theme:

 Saturday, October 13, 2007
Saturday, October 13, 2007 12:29:56 PM (GMT Standard Time, UTC+00:00) ( Lessons | Development process )

I'm sure that if you reading this blog, you have encountered a bug or two (at least).
Now, as you know, often you have to solve bugs of other people that have been fired/left/not available at the moment or just frustrated from it and need a fresh pair of eyes to look at it.

So, you need to deal with the bug, just you and him, like a dual,
What do you do? , how do you confront this mysterious daemon?
 
Most of the people that inherit a bug, clueless regarding his data, try to confront with it straight forward.
Ask a common developer how would he handle a bug, 9 of 10 answers will be "debug".
well, i think it's wrong, it's like knowing that there is a giant brick wall and still running at full speed right in to it.
(unless you are "The Hulk", it won't work)

here is how I'm dealing with a bug :

  • Bring it to your own game court - whenever you have a situation, it's always happens in some environment.
    it's crucial to know it as it was your own place.
    suppose you have a .Net Web application running on a windows server 2003, you need to know damn sure all the environment laws regarding it.
    thing like how IIS handle requests or how security configurations should be, are vital to your diagnosis of the problem.
  • Understand the symptoms right - i have a TV series that i watch , called "House", it's about a brilliant diagnostician doctor that works mostly in unconventional ways and solves the most bizarre cases by doing that.
    i tend to refer this TV series as an educational show on how to handle strange cases and how to approach them.
    on one of it's episodes they had a brilliant dialog:
    - "House, the patients kidneys are shutting down"
    - "Great, we have another symptom"
  • Write it down - get yourself a notebook or even a giant white-board to write all these symptoms that you have found, it should be right in-front of you all the time until you have solved the case.
  • Ask yourself What can cause it ? - preferably do this out loud, ask your self that question regarding each symptom that you found, maybe even with a team , that could confirm it or deny your theories.
  • What was changed ? - this is the most important question that you need to ask yourself.
    things does not go wild on their own,if it worked before and now does not, then something is changed.
    this would be our biggest clue to solve the problem !
    this could be an environmental change, a change in the situation that the application handles or a coding change,
    each one of these can cause a problem, we need to understand which exactly is it.
  • Develop a theory - this is the fun part, now you have all the data that you need to solve this bug.
    you know how the environment behaves, you have the symptoms to the problem, things that was been changed, and possible causes to our symptoms.
    now you need the sit a few minutes and think what is the reason that fits to all our gathered data.
  • Blind tests are the devil - most of them will give you nothing and consume much of your precious time, Get a theory that you think that fits the symptoms and then test it, not the other way around.
  • Develop a solution to the problem - after we have our theory and we tested it, we need to develop a solution that fixes the problem, this is the easy part.

for example, here is a problem that i have encountered almost a year ago:

8007000e System resource exceeded
Microsoft OLE DB Provider for ODBC Drivers error '8007000e'
[Microsoft][ODBC Microsoft Access Driver] System resource exceeded.

lets try to follow these guidelines and solve the problem:

Bring it to your own game court - this is a windows environment that runs an asp web application based on Microsoft access.
Understand the right symptoms - we have a database that denies any further connections due to resource limits.
Write it down - take a moment to look at those symptoms.
Ask yourself what can cause it - it could be an environmental cause, like connection limits are not enough, or coding mistake that suffers from not closing an opened connection.
What was changed ?  - code wasn't changed, all system configurations was not changed, traffic to your site is doubled.
Develop a theory - since the traffic was doubled, the connections are doubled as well, and thus reaching to the connection limit of our application.
why the application does not clearing the connection resources ? - because the code that opens them does not close them, thus the connections piled up and reaching the connection limit way before the recycling process started.
Test it - recycle the connection pool, simulate traffic that won't be in the connections limit(simultaneously), but can be piled up to reach the limit.
Develop a solution to the problem - if you are intrested for this solution , you can check out my post about it

Comments [0] | | # 
 Friday, March 02, 2007
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, 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, October 11, 2006
Wednesday, October 11, 2006 5:45:58 PM (GMT Standard Time, UTC+00:00) ( Sql Server  | .Net | Lessons | SPS (sharepoint server) | Performance )

As you know, Microsoft didn't intended that you access the SPS database, but via object model only.
the problem that it has many bugs, performance issues, security issues and lots lots problems that will make the programmer's life a living hell.

So, lets see how can we break the 1st guideline of SPS programming - "do not use the SPS database directly".
man , I'm feeling like a criminal now, presenting a guide how to do something that Microsoft invested a lot of effort to prevent us from doing.

Lets get down to business,
don't count that the connection string is laying in some property, this one we need to do some dirty work.

A little background how we are going to do it:

The connection string looks like this :

"Integrated Security=SSPI;Server=someServer;database=SomeDatabase"

as you can see, the only thing that can change here is the server name and the database name.

lets create a core function that will receive DB collection and the desired site guid and construct the connection string.

private string GetConnectionStringForSite(SPContentDatabaseCollection DBs, Guid siteGuid)
{
    string rc = "";
    SPContentDatabase oDB = null;

    for(int i=0; i<DBs.Count;i++)
    {
        // Get the database
        oDB = DBs[i];

        SqlCommand c = new SqlCommand();
        string strConn = "Integrated Security=SSPI;Server=" + oDB.Server + ";database=" + oDB.Name;

        using(SqlConnection conn = new SqlConnection(strConn))
        {
            // Set the Connection
            c.Connection = conn;
            try
            {
                // Open the connection
                conn.Open();

                c.CommandText = "SELECT FullUrl FROM Sites where Id=@Id";

                // Set the parameter
                c.Parameters.Add(new SqlParameter("@Id",System.Data.SqlDbType.UniqueIdentifier));
                c.Parameters["@Id"].Value = siteGuid;

                // Execute reader
                SqlDataReader reader = c.ExecuteReader(System.Data.CommandBehavior.SingleRow);

                // check if we have rows
                bool hasRows = reader.HasRows;

                // Close the connection and the reader
                reader.Close();
                conn.Close();

                // Check if it got rows
                if(hasRows)
                {
                    // Set the return value
                    rs = strConn;

                    // Stop iterating through the DB's
                    break;
                }

                // Close the reader
                reader.Close();
            }
            finally
            {
                // Close the connection
                if(conn.State != System.Data.ConnectionState.Closed) conn.Close();
                oDB = null;
            }
        }
    }
    return rc;
}

 

this function will be placed in a dedicated class, i call is "SPSDB"

lets create the class itself and its private members

    public class SPSDB
    {
        private string _conString = "";
        private string _vsUrl = "";

        public String URL
        {
            get{return _vsURL;}
        }
    }

now we need to write the constructor and the connection "factory"

the constructor will look like this :

public SPSDB(string siteUrl)
{
    using(Microsoft.SharePoint.Administration.SPGlobalAdmin ga = new Microsoft.SharePoint.Administration.SPGlobalAdmin())
    {
        Microsoft.SharePoint.Administration.SPVirtualServerCollection VSc = ga.VirtualServers;

        SPVirtualServer vs = null;
        Guid g;
        bool isFound = false;
        
        // Run through all the VS collection
        for(int i=0; i<VSc.Count;i++)
        {
            // Get the virtual server reference
            vs = VSc[i];

            // if the current vs is not from the needed state than continue to the next VS
            if(vs.state != SPVirtualServerState.Ready)
                continue;

            // Run through all the sites in the vs
            for(int j=0; j< vs.Sites.Count;j++)
            {
                using(SPSite s = vs.Sites[j])
                {
                    // Check if we found the needed vs
                    if(s.Url.ToLower() == siteUrl.ToLower())
                    {
                        // Save the needed data
                        isFound = true;
                        g = s.ID;
                        _vsURL = vs.Url.ToString();
                        _conString = GetConnectionStringForSite(vs.ContentDatabases,g);
                        break;
                    }
                }
            }

            // Check if the vs has been found
            if(curVs != null)
                break;

            // Clear the virtual server object
            vs = null;

            // Clear memory
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }

        // Throw an exception if the site guid is not there
        if(!isFound)
            throw new Exception("the given site url cannot be found");
        
    }
}

and the factory method will look like this :

public SqlConnection GetCon()
{
    return new SqlConnection(_conString);
}

thats it!
now to use it you can do it like this :

SPSDB dbstuff = new SPSDB("http://www.krokhmal.com");

using(SqlConnection con = dbstuff.GetCon())
{
    // Your DB code here ...
}

I've added a file attachment to this post with the mentioned class.
enjoy.

SPSDB.rar (1.34 KB)
Comments [0] | | # 
 Monday, September 25, 2006
Monday, September 25, 2006 5:28:14 PM (GMT Standard Time, UTC+00:00) ( .Net | Lessons | Performance | Threading )

the main reason that I've started to play with threads is because the industry WILL (sooner or later) move to a multi-core guided programing, and it WILL become mainstream (mark my words :) ).

any way, lets start from the beginning, and why do we need threads.
according to the definition : "Threads are a way for a program to split itself into two or more simultaneously (or pseudo-simultaneously) running tasks. Threads and processes differ from one operating system to another, but in general, the way that a thread is created and shares its resources is different from the way a process does."

so, in other words, we will use threads when we need to perform simultaneous tasks.
these kind of actions made when you have unused processing time while waiting for other task to finish.

so, back to the .Net world, how would we do that ?

to use threads, we need to include the library :

using System.Threading;

the next thing we need i to know how to to lunch a thread with a task.

  • we need to create a task to be done.
  • a ThredStart delegate which will point to our task.
  • a new thread ( or an old one from a thread pool ) - which is better and when will be explained in some later posts.
  • start the thread.

so :

lets create some task :

        private void BurnCPUwithOneThread()
        {
            for(int i=0; i< 5000000;i++)
            {
                lblcounter.Text = i.ToString();
            }
        }

 

and one more :

        private void BurnCPUwithTwoThreads()
        {
            for(int i=0; i< 5000000;i++)
            {
                lblCounter2.Text = i.ToString();
            }
        }

now we will create the delegate and the threads, and activate them.

        private void button4_Click(object sender, System.EventArgs e)
        {
            //We will run the action in a different thread from the gui
            //so when we do sleep the the tread the gui will not hang up.

            // Create the thread start object
            ThreadStart ts = new ThreadStart(BurnCPUwithOneThread);
            
            // The tread itself
            Thread t = new Thread(ts);
            
            // Starting the thread
            t.Start();

            // Create the thread start object
            ThreadStart ts2 = new ThreadStart(BurnCPUwithTwoThreads);
            
            // The tread itself
            Thread t2 = new Thread(ts2);
            
            // Starting the thread
            t2.Start();

        }

 

  thats it.
   now you have a working little program with 2 threads.
   if you will run this code , you will notice that it is done simultaneously.


   next lessons will handle : sending parameters to threads, synchronizing, thread pool, and more.
   please comment, if you would like me to focus on some specific subject...

Comments [0] | | #