SlideShare ist ein Scribd-Unternehmen logo
1 von 58
ASP.NET Security

Darren Sim
MVP (ASP.NET / IIS)
Member, Microsoft Developer Guidance Web Advisory Council
Director, Singapore Software Quality Testing Board (SGTQB)
ASP.NET Page Model
Authentication

•   Authentication in ASP.NET
    – IIS authentication
    – ASP.NET authentication



•   ASP.NET authentication providers
    –   Forms, Windows, Passport, Default, and Custom
Forms Authentication

•   Uses cookie to authenticate
•   Uses session to authenticate
•   Enables SSL for logon page
•   Often used for personalization
Forms Authentication Workflow
Forms Authentication Configuration

•   Enable anonymous access in IIS
•   Configure <authentication> section
    – Set mode to ―Forms‖
    – Add the <forms> section

•   Configure <authorization> section
    –   Deny access to anonymous user
•   Create logon page
    – Validate the user
    – Provide authentication cookie
    – Redirect the user to the requested page
<forms> Section Attributes

•    loginUrl: unauthenticated request are redirected to this page
•    name: name of the authentication cookie
•    path: path of the authentication cookie
•    protection: All | None | Encryption | Validation
•    timeout: authentication cookie expiration time in minutes
    <authentication mode="Forms">
    <forms name=".ASPXAUTH“
           loginUrl="login.aspx"
           protection="All"
           timeout="30"
           path="/" />
    </authentication>
Forms Authentication Code


If FormsAuthentication.Authenticate(txtUserName.Value,txtUserPass.value)
Then
   FormsAuthentication.RedirectFromLoginPage(txtUserName.Value, _
chkPersistCookie.Checked)
Else
  Response.Redirect("logon.aspx", false)
End If
Windows Authentication

•   Can be used in combination with Basic, NTLM, Digest, Kerberos, and
    so forth
•   User is authenticated by IIS
•   Easiest of all
•   Request flow
    – Client makes request
    – IIS authenticates request, forwards to ASP.NET
    – Impersonation turned on?
    – ASP.NET returns response to client
Windows Authentication Configuration

•   Set mode to ―Windows‖
•   Configure <authorization> section
•   Example


<authentication mode=" Windows" />
<authorization>
   <deny users="?" />
   <allow users= "*" />
</authorization>
Authorization

•   Process of determining whether a user is allowed to perform a
    requested action
•   File-based authorization
    –   Performed by FileAuthorizationModule
    –   Performs checks against Windows ACLs
•   Custom – handle AuthorizeRequest event
    –   Application level (global.asax)
    –   HTTP module (implement IHttpModule)
•   URL-based authorization
    –   Performed by UrlAuthorizationModule
    –   Positive and negative assertions
    –   Can selectively allow or deny access to URI namespaces
URL Authorization Configuration

•   Add <authorization> section
•   Add <allow> and <deny> sections
•   Example - allow ―Admins‖ or ―WebUsers‖ and deny all others:


<authorization>
   <allow roles="Admins" />
   <allow roles="WebUsers" />
   <deny users="*" />
</authorization>
Architecture of a Three-Tier Application

    Supporting Software
                                         App User Interface
                                                              C
      User Interface                                          L
                                                              I
                                         Application Logic    E
     Database Engine                                          N
                                                              T
         Database                          Database API


   DBMS / Database Server                Application Server


          Architecture of a Three-Tier Application
Architecture of a Four-Tier Application

  Supporting Software
                                       App User Interface
                                                            WEB   WEB
    User Interface
                                                             S     C
                                        Application Logic    E     L
   Database Engine                                           R     I
                                                             V     E
       Database                           Database API       E     N
                                                             R     T

 DBMS / Database Server                Application Server


        Architecture of a Four-Tier Application
ADO .NET

ADO.NET is the database API for managed applications
  (application servers) to talk to database servers (DBMS:
  Database Management Systems).
 a database API for managed applications;
 a set of classes in .NET FCL System.Data namespace;
 designed to work over the Web;
 integrates effortlessly with XML;
 maps very well to stateless, text-based protocol HTTP;
 accesses databases through modules known as data providers
  ( a set of APIs that make the accesses easy to program).
Two Data Providers
1.       The SQL Server .NET provider
          interfaces to Microsoft SQL Server (7.0 or later)
          all managed code
          code runs faster
          code not portable to other databases
2.       The OLE DB .NET provider
          OLE: Object Linking and Imbedding
          interfaces to databases through unmanaged OLE DB
           providers: SQLOLEDB for SQL Server (6.5 or
           earlier), MSDAORA for Oracle and Microsoft, Jet.OLEDB.4.0 for
           Microsoft Jet database engine.
          code runs slower
          code portable to other databases
The System.Data.SqlClient and System.Data.OleDb Namespaces

Classes in System.Data.SqlClient are for SQL Server .NET
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection
  ("server=localhost;database=pubs;uid=sa;pwd=");
try { conn.Open ();
SqlCommand cmd = new SqlCommand ("select * from titles", conn);
  SqlDataReader reader = cmd.ExecuteReader ();
  while (reader.Read ()) Console.WriteLine (reader["title"]);
} catch (SqlException ex) {
  Console.WriteLine (ex.Message);
} finally { conn.Close (); }
The System.Data.SqlClient and System.Data.OleDb Namespaces

 Classes in System.Data.OleDb are for OLE DB .NET
 using System.Data.OleDb;
  OleDbConnection conn = new
OleDbConnection("provider=sqloledb;server=localhost;database=pubs;uid=sa;pwd=");
 try { conn.Open ();
    OleDbCommand cmd =
      new OleDbCommand ("select * from titles", conn);
    OleDbDataReader reader = cmd.ExecuteReader ();
    while (reader.Read ()) Console.WriteLine (reader["title"]);
 } catch (OleDbException ex) {
    Console.WriteLine (ex.Message);
 } finally { conn.Close (); }
Pattern of database programming
 Create a connection object.
 Open the connection.

 Create a command object.

 Execute the command.

 Access the data.

 Close the connection.
Connections, Commands, and DataReaders
 Connection objects represent physical connections to a
database.
   SqlConnection or OleDbConnection
 Command objects represent the commands performed on
a database.
   SqlCommand or OleDbCommand
 DataReader objects represent the data obtained by the
commands.
   SqlDataReader or OleDbDataReader
Connection Objects
The SqlConnection Class
The ConnectionString


SqlConnection conn = new SqlConnection ();
conn.ConnectionString =
     "server=localhost;database=pubs;uid=sa;pwd=";
or
SqlConnection conn = new SqlConnection
     ("server=localhost;database=pubs;uid=sa;pwd=");


Errors in the connection string only throws exceptions at runtime.
Server
 Server
 Server=localhost or Server=(local) or Data Source=(local)


 SQL Server permits different instances of servers to be installed on a given
machine.


  server=db1 (an database server computer named ―db1‖ at the CS department
of UA)


  server=hawkeyewintellect (an instance of SQL Server named Wintellect on a
remote machine named Hawkeye)


 Database or Initial Catalog: database name (e.g. Pubs)
 UID or User ID, Pwd: tempdb, tempdb
Server
Min Pool Size and Max Pool Size, the size of the connection pool (the
defaults are 0 and 100)
 Integrated Security: default to false, otherwise uses Windows access tokens
for authentication.
 Connect Timeout: how many seconds to wait for a connection to open
(default=15).


    SqlConnection conn = new SqlConnection
    ("server=hawkeyewintellect;database=pubs;uid=sa;pwd=;" +
    "min pool size=10;max pool size=50;connect timeout=10");
Exceptions and Closing Open Connections
 Exceptions should never go uncaught, and open connections should always be closed
before terminating. (Calling Close on a connection that‘s not open isn‘t harmful.)
    SqlConnection conn = new SqlConnection

        ("server=localhost;database=pubs;uid=sa;pwd="); //before try block

    try {conn.Open ();

        // TODO: Use the connection

    }

    catch (SqlException e) {

        Console.WriteLine (e.Message);

        // TODO: Handle the exception

    }

    finally { conn.Close ();}
Command Classes: SqlCommand and OleDbCommand.

 – Encapsulate SQL commands performed on a database.
 – Rely on connections established.
 – Include methods to execute the commands encapsulated inside.




 Example, delete a record from the Pubs database‘s ―Titles‖ table using an SQL
DELETE command:


 SqlCommand cmd = new SqlCommand
  ("delete from titles where title_id = 'BU1032'", conn);
 cmd.CommandTimeout = 10; // Allow 10 seconds, default 30.
 cmd.ExecuteNonQuery (); // Execute the command
The ExecuteNonQuery Method
For executing DML and DDL commands: CREATE, INSERT, UPDATE,
DELETE, …
   Not getting any data back.
   Examples:

    SqlCommand cmd = new SqlCommand
        ("create database MyDatabase", conn);
         cmd.ExecuteNonQuery ();
      SqlCommand cmd = new SqlCommand
        ("create table titles …", conn);
      cmd.ExecuteNonQuery ();
      SqlCommand cmd = new SqlCommand
        ("insert into titles (title_id, title, type, pubdate) " +
        "values ('JP1001', 'Programming Microsoft .NET', " +
        "'business', 'May 2002')", conn);
      cmd.ExecuteNonQuery ();
The ExecuteNonQuery Method
 SqlCommand cmd = new SqlCommand
    ("update titles set title_id = 'JP2002' " +
    "where title_id = 'JP1001'", conn);
  cmd.ExecuteNonQuery ();


  SqlCommand cmd = new SqlCommand
    ("delete from titles where title_id = 'JP2002'", conn);
  cmd.ExecuteNonQuery ();
The ExecuteScalar Method

 Executes a query command and returns a single value in the
result set, such as COUNT, AVG, MIN, MAX, and SUM.


   SqlCommand cmd = new SqlCommand
      ("select min (price) from titles", conn);
   decimal amount = (decimal) cmd.ExecuteScalar ();
   Console.WriteLine ("ExecuteScalar returned {0:c}", amount);
The ExecuteScalar Method
Another   common use for ExecuteScalar is to retrieve BLOBs
(binary large objects) from databases.
For example, retrieving an image from the ―Logo‖ field of the
Pubs database‘s ―Pub_info‖ table and encapsulates it in a
bitmap:
use System.IO;
use System.Drawing;
use System.Data.SqlClient;
SqlCommand cmd = new SqlCommand
     ("select logo from pub_info where pub_id='0736'", conn);
  byte[] blob = (byte[]) cmd.ExecuteScalar ();
  stream.Write (blob, 0, blob.Length);
  Bitmap bitmap = new Bitmap (stream);
  stream.Close ();
Write a BLOB to a database.
FileStream stream = new FileStream("Logo.jpg", FileMode.Open);


byte[] blob = new byte[stream.Length];
stream.Read (blob, 0, (int) stream.Length);
stream.Close ();


SqlCommand cmd = new SqlCommand
("insert into pub_info (pub_id, logo) values ('9937', @logo)", conn);
cmd.Parameters.Add ("@logo", blob);


cmd.ExecuteNonQuery ();
The ExecuteReader Method
 For performing database queries and obtain the results as quickly and
efficiently as possible.
   Returns a DataReader object.
 Pulls back only the data to be ―Read‖ by the DataReader not all
records satisfying the query condition.


      SqlCommand cmd = new SqlCommand ("select * from titles", conn);
      SqlDataReader reader = cmd.ExecuteReader ();
      while (reader.Read ()) Console.WriteLine (reader["title"]);


   Each call to ―Read‖ returns one row from the result set.
   It uses a property indexer to extract the value of the record‘s ―title‖ field.
   Fields can be referenced by name or by numeric index (0-based).
DataReader
   Reads data.
   Reads schema (meta data) .
   Stream-based access to the results of database queries.
   Fast and efficient.
   Read-only and forward-only.
   Closing a DataReader: reader.Close( )
    does NOT close the connection, only frees it for others
    to use.
   D-E-F-E-N-S-I-V-E P-R-O-G-R-A-M-M-I-N-G.
DataSets
   Set-based Database Accesses
   capture an entire query in memory
   support backward and forward traversal
   edit data and propagate the changes back to the
    database.
DataSet, DataTable and DataAdapter
   .NET supports set-based database accesses through three
    classes:


   DataSet: equivalent of an in-memory database.
    It consists of a collection of DataTables.


   DataTables are created by a DataAdapter (SqlDataAdapter and
    OleDbDataAdapter).


   DataSet doesn‘t interact with databases directly. DataAdapter
    reads the physical data sources and fills DataTables and DataSets
DataSets vs. DataReaders
 To simply query a database and read through the records one at a time
until you find the one you‘re looking for, then DataReader is the right tool.
DataReaders (1) retrieve only the data that you actually use, and (2) they
don‘t consume memory by not storing every record that you read, but (3)
they can‘t iterate backward.


 To use all the query results and to iterate backward and forward
through a result set, or to cache the result set in memory, use a DataSet.


Many controls that support DataSets are perfectly capable of binding to
DataReaders.
DataGrid (GUI)

•   DataGrid is an ASP control for displaying datasets.
•   Database displaying procedure:
    – Use DataAdapter to get data from the database.
    – Fill the data into a DataSet
    – Bind the DataSet to a DataGrid
    – Select the fields (columns) to be displayed and their header texts.
Example:
  DataAdapter, DataSet and DataGrid (GUI)

<asp:DataGrid ID="MyDataGrid"
     OnItemCommand="OnItemCommand" RunAt="server">
   <Columns>
      <asp:BoundColumn HeaderText="Title"
        DataField="title" />
      <asp:BoundColumn HeaderText="Price"
        DataField="price" DataFormatString="{0:c}"/>
      <asp:ButtonColumn HeaderText="Action"
       Text="Add to Cart" CommandName="AddToCart" />
    </Columns>
</asp:DataGrid>



Examples/C9/Congo-MySQL/ViewCart.aspx
Example:
DataAdapter, DataSet and DataGrid (GUI)

 void Page_Load (Object sender, EventArgs e)
  {
     if (!IsPostBack) {
         string ConnectString =
             ConfigurationSettings.AppSettings["connectString"];
         MySqlDataAdapter adapter = new MySqlDataAdapter
            ("select * from titles where price != 0", ConnectString);
         DataSet ds = new DataSet ();
         adapter.Fill (ds);
         MyDataGrid.DataSource = ds;
         MyDataGrid.DataBind ();//Bind data to GUI
     }
  }
Transaction Commands
   A transaction is a logical unit of operations grouped together.


   If one of the operations fails, the others will fail (or be rolled back).


Distributed transactions — transactions that span two or more
databases.


   The .NET Framework supports distributed transactions.


   The .NET supports local transactions (one database):
Transacted Commands
// Start a local transaction
  trans = conn.BeginTransaction (IsolationLevel.Serializable);
  // Create and initialize a SqlCommand object
  SqlCommand cmd = new SqlCommand ();
  cmd.Connection = conn;
  cmd.Transaction = trans;
  // Debit $1,000 from account 1111
  cmd.CommandText = "update accounts set balance = " +
     "balance - 1000 where account_id = '1111'";
  cmd.ExecuteNonQuery ();
  // Credit $1,000 to account 2222
  cmd.CommandText = "update accounts set balance = " +
     "balance + 1000 where account_id = '2222'";
  cmd.ExecuteNonQuery ();
  // Commit the transaction (commit changes)
  trans.Commit ();
Transacted Commands
 IsolationLevel.Serializable locks down the records while
they‘re updated so that they can‘t be read or written.


Committing the transaction writes the changes to the
database.
Uses DataGrid to represent a DataSet in XML
 DataSet ds = new DataSet ();
 ds.ReadXml (Server.MapPath ("Bonuses.xml"));
 MyDataGrid.DataSource = ds;
SQL Injection

•   How Web pages works?
•   INPUT rendered from Textbox Web Control
•   Query String
•   Use values concat a SQL command
    – Search knowledge base
    – Paged results
    – Look for specific record
        • User credentials
What really exists!

•   DON‘T LIKE
    –   More comfort for the user

        string sql = "select * from KB where
               content like '" + search.Text + "'

•   Hacker types: %

        string sql = "select * from KB where
               content like '%'

•   User authentication!
SQL Injection Attack

•   Developer concate SQL statements

    string sql = "select * from Users where
          user ='" + User.Text + "'
          and pwd='" + Password.Text + "'"


•   Hacker types: ‗ or 1=1 --‗

    string sql = "select * from Users where
          user =' ' or 1=1 --' and pwd=''"

•   Result is the first database entry
    –   Maybe the Admin
SQL Injection Attack

•   Take over control
•   User types: ; xp_cmdshell 'format c: /q /yes '; drop database myDB; --

    select * from tabelle where id=1;
    xp_cmdshell 'format c: /q /yes ';
     drop database myDB; --


•   Result: Hacker can do everything
    –   SQL process runs with system privileges
SQL Injection Attack

•   Never use ―sa‖
    – Default blank password
    – Hacker knows a lot about sa
    – Trusted Security
    – Application user
        • Only with needed access rights

•   Storing Connection Strings
    –   Web.Config
        • Hashed not clear text
    –   error case source code is often visible
Best Solution

•   Use parameterized Select

    sql = "select * from Users where
        user = @user and pwd = @pwd";
    SqlCommand cmd = new SqlCommand(sql,con);
    cmd.Parameters.Add("@user",User.Text);
    cmd.Parameters.Add("@pwd",Password.Text);


•   Use Stored Procedures
•   Cookie & URL Injection
Cross site-scripting

•   User Input is stored in Database
•   Database content is presented
•   Injection of
    – HTML code
    – JScript code

•   A different denial of service
        <script>

•   Redirect the user to dialer page
        <script language=Jscript>
        window.navigate('net.htm');</script>
Cross site-scripting

•   Don‘t trust the user
    –   Use validators controls
    –   Use regexp
        • Remove: < > " ' % ; ) ( & + -
    – Check for the length
    – Use Server.HtmlEncode

•   .NET 1.1
    – Default no HTML code in Textboxes
    – Page Attribut ValidateRequest =false
HTTP Harvesting

•   Database driven websites
•   Display result based on
    –   Text Input, Querystring, Cookie
•   Special type of SQL query language
•   Datagrid list with detail link
    –   Detail.aspx?id=1
•   Session attaching+ pagelink
•   Email address for spammer
Prevent HTTP harvesting

•   Encrypt querystrings
•   Combine user input with textboxes
•   Use Jscript to write the data
•   Draw the data
    –   System.drawing
•   Monitor the web usage
•   Third party review
Canonicalization

•   Character Sets URL, Querystring, Filename
    –   %20=― ―
•   IP Address as decimal
•   Compare values
    –   HTMLDecode
Architecture

•   Operation System
    –   Reduce the rights of accounts
        • Never use Admin Rights
    –   Switch of unused services and ports
•   Web Farm
    –   Use ipsec to encrypt traffic
        • Between SQL Server and Web Application
        • Session Management
    –   IP restrictions
•   Change common used things
    –   Directories, users, path
Page Title
Subhead

•   Copy: Consed te commodipit, velismo digniam iure ver iriure ea core
    do odipsum velisci elissim velendreet lummodiamet, qui enisl utpate
    feuisl eniam nibh eui eugue dolumsandre enim alis nonsequat alit
    loborpero dit laore molore vel iure
•   Copy: Consed te commodipit, velismo digniam iure ver iriure ea core
    do odipsum velisci elissim velendreet lummodiamet, qui enisl utpate
    feuisl eniam nibh eui eugue dolumsandre enim alis nonsequat alit
    loborpero dit laore molore vel iure

Weitere ähnliche Inhalte

Was ist angesagt?

Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postvamsi krishna
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletFahmi Jafar
 
Architecture and tools
Architecture and toolsArchitecture and tools
Architecture and toolssanjay_jha
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technologyvikram singh
 
Java servlets
Java servletsJava servlets
Java servletslopjuan
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1vikram singh
 
Create Home Directories on Storage Using WFA and ServiceNow integration
Create Home Directories on Storage Using WFA and ServiceNow integrationCreate Home Directories on Storage Using WFA and ServiceNow integration
Create Home Directories on Storage Using WFA and ServiceNow integrationRutul Shah
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods pptkamal kotecha
 
Java/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBCJava/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBCFAKHRUN NISHA
 
Java Servlets
Java ServletsJava Servlets
Java ServletsEmprovise
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jspJafar Nesargi
 
ESM v5.0 Service Layer Developer's Guide
ESM v5.0 Service Layer Developer's GuideESM v5.0 Service Layer Developer's Guide
ESM v5.0 Service Layer Developer's GuideProtect724
 

Was ist angesagt? (19)

Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Architecture and tools
Architecture and toolsArchitecture and tools
Architecture and tools
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
 
Servlets
ServletsServlets
Servlets
 
Java servlets
Java servletsJava servlets
Java servlets
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1
 
Create Home Directories on Storage Using WFA and ServiceNow integration
Create Home Directories on Storage Using WFA and ServiceNow integrationCreate Home Directories on Storage Using WFA and ServiceNow integration
Create Home Directories on Storage Using WFA and ServiceNow integration
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
 
Unit5 servlets
Unit5 servletsUnit5 servlets
Unit5 servlets
 
Java Servlets & JSP
Java Servlets & JSPJava Servlets & JSP
Java Servlets & JSP
 
WebLogic FAQs
WebLogic FAQsWebLogic FAQs
WebLogic FAQs
 
Java/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBCJava/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBC
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
 
ESM v5.0 Service Layer Developer's Guide
ESM v5.0 Service Layer Developer's GuideESM v5.0 Service Layer Developer's Guide
ESM v5.0 Service Layer Developer's Guide
 
Servlets lecture1
Servlets lecture1Servlets lecture1
Servlets lecture1
 

Andere mochten auch

HTML 5, CSS3 and ASP.NET Best Practices by Example
HTML 5, CSS3 and ASP.NET Best Practices by ExampleHTML 5, CSS3 and ASP.NET Best Practices by Example
HTML 5, CSS3 and ASP.NET Best Practices by ExampleDarren Sim
 
c# training in bangalore | asp.net with c# training | vb.net code projects,as...
c# training in bangalore | asp.net with c# training | vb.net code projects,as...c# training in bangalore | asp.net with c# training | vb.net code projects,as...
c# training in bangalore | asp.net with c# training | vb.net code projects,as...shashinm
 
The Web Development Eco-system with VSTS, ASP.NET 2.0 & Microsoft Ajax
The Web Development Eco-system with VSTS, ASP.NET 2.0 & Microsoft AjaxThe Web Development Eco-system with VSTS, ASP.NET 2.0 & Microsoft Ajax
The Web Development Eco-system with VSTS, ASP.NET 2.0 & Microsoft AjaxDarren Sim
 
Code review for secure web applications
Code review for secure web applicationsCode review for secure web applications
Code review for secure web applicationssilviad74
 
Angular js best practice
Angular js best practiceAngular js best practice
Angular js best practiceMatteo Scandolo
 
SDH/SONET alarms & performance monitoring
SDH/SONET alarms & performance monitoringSDH/SONET alarms & performance monitoring
SDH/SONET alarms & performance monitoringMapYourTech
 
Study: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving CarsStudy: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving CarsLinkedIn
 

Andere mochten auch (10)

HTML 5, CSS3 and ASP.NET Best Practices by Example
HTML 5, CSS3 and ASP.NET Best Practices by ExampleHTML 5, CSS3 and ASP.NET Best Practices by Example
HTML 5, CSS3 and ASP.NET Best Practices by Example
 
c# training in bangalore | asp.net with c# training | vb.net code projects,as...
c# training in bangalore | asp.net with c# training | vb.net code projects,as...c# training in bangalore | asp.net with c# training | vb.net code projects,as...
c# training in bangalore | asp.net with c# training | vb.net code projects,as...
 
Lease 1
Lease 1Lease 1
Lease 1
 
The Web Development Eco-system with VSTS, ASP.NET 2.0 & Microsoft Ajax
The Web Development Eco-system with VSTS, ASP.NET 2.0 & Microsoft AjaxThe Web Development Eco-system with VSTS, ASP.NET 2.0 & Microsoft Ajax
The Web Development Eco-system with VSTS, ASP.NET 2.0 & Microsoft Ajax
 
Code review for secure web applications
Code review for secure web applicationsCode review for secure web applications
Code review for secure web applications
 
Angular js best practice
Angular js best practiceAngular js best practice
Angular js best practice
 
Null meet Code Review
Null meet Code ReviewNull meet Code Review
Null meet Code Review
 
SDH ALARMS
SDH ALARMSSDH ALARMS
SDH ALARMS
 
SDH/SONET alarms & performance monitoring
SDH/SONET alarms & performance monitoringSDH/SONET alarms & performance monitoring
SDH/SONET alarms & performance monitoring
 
Study: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving CarsStudy: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving Cars
 

Ähnlich wie C# and ASP.NET Code and Data-Access Security

Building microservices sample application
Building microservices sample applicationBuilding microservices sample application
Building microservices sample applicationAnil Allewar
 
Roles y Responsabilidades en SQL Azure
Roles y Responsabilidades en SQL AzureRoles y Responsabilidades en SQL Azure
Roles y Responsabilidades en SQL AzureEduardo Castro
 
Windows Azure and a little SQL Data Services
Windows Azure and a little SQL Data ServicesWindows Azure and a little SQL Data Services
Windows Azure and a little SQL Data Servicesukdpe
 
Rest API and Client OM for Developer
Rest API and Client OM for DeveloperRest API and Client OM for Developer
Rest API and Client OM for DeveloperInnoTech
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing Techglyphs
 
Windows Azure for .NET Developers
Windows Azure for .NET DevelopersWindows Azure for .NET Developers
Windows Azure for .NET Developersllangit
 
Sql Injection and Entity Frameworks
Sql Injection and Entity FrameworksSql Injection and Entity Frameworks
Sql Injection and Entity FrameworksRich Helton
 
SQLSaturday#290_Kiev_WindowsAzureDatabaseForBeginners
SQLSaturday#290_Kiev_WindowsAzureDatabaseForBeginnersSQLSaturday#290_Kiev_WindowsAzureDatabaseForBeginners
SQLSaturday#290_Kiev_WindowsAzureDatabaseForBeginnersTobias Koprowski
 
Using Apache as an Application Server
Using Apache as an Application ServerUsing Apache as an Application Server
Using Apache as an Application ServerPhil Windley
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technologyMinal Maniar
 
Introduction to the Client OM in SharePoint 2010
Introduction to the Client OM in SharePoint 2010Introduction to the Client OM in SharePoint 2010
Introduction to the Client OM in SharePoint 2010Ben Robb
 
Dh2 Apps Training Part2
Dh2   Apps Training Part2Dh2   Apps Training Part2
Dh2 Apps Training Part2jamram82
 
.NET Core Apps: Design & Development
.NET Core Apps: Design & Development.NET Core Apps: Design & Development
.NET Core Apps: Design & DevelopmentGlobalLogic Ukraine
 
Building a chat app with windows azure mobile
Building a chat app with windows azure mobileBuilding a chat app with windows azure mobile
Building a chat app with windows azure mobileFlavius-Radu Demian
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actionsAren Zomorodian
 
OpenStack Identity - Keystone (kilo) by Lorenzo Carnevale and Silvio Tavilla
OpenStack Identity - Keystone (kilo) by Lorenzo Carnevale and Silvio TavillaOpenStack Identity - Keystone (kilo) by Lorenzo Carnevale and Silvio Tavilla
OpenStack Identity - Keystone (kilo) by Lorenzo Carnevale and Silvio TavillaLorenzo Carnevale
 

Ähnlich wie C# and ASP.NET Code and Data-Access Security (20)

Building microservices sample application
Building microservices sample applicationBuilding microservices sample application
Building microservices sample application
 
Roles y Responsabilidades en SQL Azure
Roles y Responsabilidades en SQL AzureRoles y Responsabilidades en SQL Azure
Roles y Responsabilidades en SQL Azure
 
Windows Azure and a little SQL Data Services
Windows Azure and a little SQL Data ServicesWindows Azure and a little SQL Data Services
Windows Azure and a little SQL Data Services
 
Rest API and Client OM for Developer
Rest API and Client OM for DeveloperRest API and Client OM for Developer
Rest API and Client OM for Developer
 
Web Security
Web SecurityWeb Security
Web Security
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
 
Windows Azure for .NET Developers
Windows Azure for .NET DevelopersWindows Azure for .NET Developers
Windows Azure for .NET Developers
 
Sql Injection and Entity Frameworks
Sql Injection and Entity FrameworksSql Injection and Entity Frameworks
Sql Injection and Entity Frameworks
 
SQLSaturday#290_Kiev_WindowsAzureDatabaseForBeginners
SQLSaturday#290_Kiev_WindowsAzureDatabaseForBeginnersSQLSaturday#290_Kiev_WindowsAzureDatabaseForBeginners
SQLSaturday#290_Kiev_WindowsAzureDatabaseForBeginners
 
Using Apache as an Application Server
Using Apache as an Application ServerUsing Apache as an Application Server
Using Apache as an Application Server
 
SQL under the hood
SQL under the hoodSQL under the hood
SQL under the hood
 
Windows Azure
Windows AzureWindows Azure
Windows Azure
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
 
Introduction to the Client OM in SharePoint 2010
Introduction to the Client OM in SharePoint 2010Introduction to the Client OM in SharePoint 2010
Introduction to the Client OM in SharePoint 2010
 
Dh2 Apps Training Part2
Dh2   Apps Training Part2Dh2   Apps Training Part2
Dh2 Apps Training Part2
 
App fabric introduction
App fabric introductionApp fabric introduction
App fabric introduction
 
.NET Core Apps: Design & Development
.NET Core Apps: Design & Development.NET Core Apps: Design & Development
.NET Core Apps: Design & Development
 
Building a chat app with windows azure mobile
Building a chat app with windows azure mobileBuilding a chat app with windows azure mobile
Building a chat app with windows azure mobile
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actions
 
OpenStack Identity - Keystone (kilo) by Lorenzo Carnevale and Silvio Tavilla
OpenStack Identity - Keystone (kilo) by Lorenzo Carnevale and Silvio TavillaOpenStack Identity - Keystone (kilo) by Lorenzo Carnevale and Silvio Tavilla
OpenStack Identity - Keystone (kilo) by Lorenzo Carnevale and Silvio Tavilla
 

Kürzlich hochgeladen

Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 

Kürzlich hochgeladen (20)

Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 

C# and ASP.NET Code and Data-Access Security

  • 1. ASP.NET Security Darren Sim MVP (ASP.NET / IIS) Member, Microsoft Developer Guidance Web Advisory Council Director, Singapore Software Quality Testing Board (SGTQB)
  • 3. Authentication • Authentication in ASP.NET – IIS authentication – ASP.NET authentication • ASP.NET authentication providers – Forms, Windows, Passport, Default, and Custom
  • 4. Forms Authentication • Uses cookie to authenticate • Uses session to authenticate • Enables SSL for logon page • Often used for personalization
  • 6. Forms Authentication Configuration • Enable anonymous access in IIS • Configure <authentication> section – Set mode to ―Forms‖ – Add the <forms> section • Configure <authorization> section – Deny access to anonymous user • Create logon page – Validate the user – Provide authentication cookie – Redirect the user to the requested page
  • 7. <forms> Section Attributes • loginUrl: unauthenticated request are redirected to this page • name: name of the authentication cookie • path: path of the authentication cookie • protection: All | None | Encryption | Validation • timeout: authentication cookie expiration time in minutes <authentication mode="Forms"> <forms name=".ASPXAUTH“ loginUrl="login.aspx" protection="All" timeout="30" path="/" /> </authentication>
  • 8. Forms Authentication Code If FormsAuthentication.Authenticate(txtUserName.Value,txtUserPass.value) Then FormsAuthentication.RedirectFromLoginPage(txtUserName.Value, _ chkPersistCookie.Checked) Else Response.Redirect("logon.aspx", false) End If
  • 9. Windows Authentication • Can be used in combination with Basic, NTLM, Digest, Kerberos, and so forth • User is authenticated by IIS • Easiest of all • Request flow – Client makes request – IIS authenticates request, forwards to ASP.NET – Impersonation turned on? – ASP.NET returns response to client
  • 10. Windows Authentication Configuration • Set mode to ―Windows‖ • Configure <authorization> section • Example <authentication mode=" Windows" /> <authorization> <deny users="?" /> <allow users= "*" /> </authorization>
  • 11. Authorization • Process of determining whether a user is allowed to perform a requested action • File-based authorization – Performed by FileAuthorizationModule – Performs checks against Windows ACLs • Custom – handle AuthorizeRequest event – Application level (global.asax) – HTTP module (implement IHttpModule) • URL-based authorization – Performed by UrlAuthorizationModule – Positive and negative assertions – Can selectively allow or deny access to URI namespaces
  • 12. URL Authorization Configuration • Add <authorization> section • Add <allow> and <deny> sections • Example - allow ―Admins‖ or ―WebUsers‖ and deny all others: <authorization> <allow roles="Admins" /> <allow roles="WebUsers" /> <deny users="*" /> </authorization>
  • 13. Architecture of a Three-Tier Application Supporting Software App User Interface C User Interface L I Application Logic E Database Engine N T Database Database API DBMS / Database Server Application Server Architecture of a Three-Tier Application
  • 14. Architecture of a Four-Tier Application Supporting Software App User Interface WEB WEB User Interface S C Application Logic E L Database Engine R I V E Database Database API E N R T DBMS / Database Server Application Server Architecture of a Four-Tier Application
  • 15. ADO .NET ADO.NET is the database API for managed applications (application servers) to talk to database servers (DBMS: Database Management Systems).  a database API for managed applications;  a set of classes in .NET FCL System.Data namespace;  designed to work over the Web;  integrates effortlessly with XML;  maps very well to stateless, text-based protocol HTTP;  accesses databases through modules known as data providers ( a set of APIs that make the accesses easy to program).
  • 16. Two Data Providers 1. The SQL Server .NET provider  interfaces to Microsoft SQL Server (7.0 or later)  all managed code  code runs faster  code not portable to other databases 2. The OLE DB .NET provider  OLE: Object Linking and Imbedding  interfaces to databases through unmanaged OLE DB providers: SQLOLEDB for SQL Server (6.5 or earlier), MSDAORA for Oracle and Microsoft, Jet.OLEDB.4.0 for Microsoft Jet database engine.  code runs slower  code portable to other databases
  • 17. The System.Data.SqlClient and System.Data.OleDb Namespaces Classes in System.Data.SqlClient are for SQL Server .NET using System.Data.SqlClient; SqlConnection conn = new SqlConnection ("server=localhost;database=pubs;uid=sa;pwd="); try { conn.Open (); SqlCommand cmd = new SqlCommand ("select * from titles", conn); SqlDataReader reader = cmd.ExecuteReader (); while (reader.Read ()) Console.WriteLine (reader["title"]); } catch (SqlException ex) { Console.WriteLine (ex.Message); } finally { conn.Close (); }
  • 18. The System.Data.SqlClient and System.Data.OleDb Namespaces Classes in System.Data.OleDb are for OLE DB .NET using System.Data.OleDb; OleDbConnection conn = new OleDbConnection("provider=sqloledb;server=localhost;database=pubs;uid=sa;pwd="); try { conn.Open (); OleDbCommand cmd = new OleDbCommand ("select * from titles", conn); OleDbDataReader reader = cmd.ExecuteReader (); while (reader.Read ()) Console.WriteLine (reader["title"]); } catch (OleDbException ex) { Console.WriteLine (ex.Message); } finally { conn.Close (); }
  • 19. Pattern of database programming  Create a connection object.  Open the connection.  Create a command object.  Execute the command.  Access the data.  Close the connection.
  • 20. Connections, Commands, and DataReaders  Connection objects represent physical connections to a database. SqlConnection or OleDbConnection  Command objects represent the commands performed on a database. SqlCommand or OleDbCommand  DataReader objects represent the data obtained by the commands. SqlDataReader or OleDbDataReader
  • 21. Connection Objects The SqlConnection Class The ConnectionString SqlConnection conn = new SqlConnection (); conn.ConnectionString = "server=localhost;database=pubs;uid=sa;pwd="; or SqlConnection conn = new SqlConnection ("server=localhost;database=pubs;uid=sa;pwd="); Errors in the connection string only throws exceptions at runtime.
  • 22. Server Server Server=localhost or Server=(local) or Data Source=(local) SQL Server permits different instances of servers to be installed on a given machine. server=db1 (an database server computer named ―db1‖ at the CS department of UA) server=hawkeyewintellect (an instance of SQL Server named Wintellect on a remote machine named Hawkeye) Database or Initial Catalog: database name (e.g. Pubs) UID or User ID, Pwd: tempdb, tempdb
  • 23. Server Min Pool Size and Max Pool Size, the size of the connection pool (the defaults are 0 and 100)  Integrated Security: default to false, otherwise uses Windows access tokens for authentication.  Connect Timeout: how many seconds to wait for a connection to open (default=15). SqlConnection conn = new SqlConnection ("server=hawkeyewintellect;database=pubs;uid=sa;pwd=;" + "min pool size=10;max pool size=50;connect timeout=10");
  • 24. Exceptions and Closing Open Connections  Exceptions should never go uncaught, and open connections should always be closed before terminating. (Calling Close on a connection that‘s not open isn‘t harmful.) SqlConnection conn = new SqlConnection ("server=localhost;database=pubs;uid=sa;pwd="); //before try block try {conn.Open (); // TODO: Use the connection } catch (SqlException e) { Console.WriteLine (e.Message); // TODO: Handle the exception } finally { conn.Close ();}
  • 25. Command Classes: SqlCommand and OleDbCommand. – Encapsulate SQL commands performed on a database. – Rely on connections established. – Include methods to execute the commands encapsulated inside. Example, delete a record from the Pubs database‘s ―Titles‖ table using an SQL DELETE command: SqlCommand cmd = new SqlCommand ("delete from titles where title_id = 'BU1032'", conn); cmd.CommandTimeout = 10; // Allow 10 seconds, default 30. cmd.ExecuteNonQuery (); // Execute the command
  • 26. The ExecuteNonQuery Method For executing DML and DDL commands: CREATE, INSERT, UPDATE, DELETE, …  Not getting any data back.  Examples: SqlCommand cmd = new SqlCommand ("create database MyDatabase", conn); cmd.ExecuteNonQuery (); SqlCommand cmd = new SqlCommand ("create table titles …", conn); cmd.ExecuteNonQuery (); SqlCommand cmd = new SqlCommand ("insert into titles (title_id, title, type, pubdate) " + "values ('JP1001', 'Programming Microsoft .NET', " + "'business', 'May 2002')", conn); cmd.ExecuteNonQuery ();
  • 27. The ExecuteNonQuery Method SqlCommand cmd = new SqlCommand ("update titles set title_id = 'JP2002' " + "where title_id = 'JP1001'", conn); cmd.ExecuteNonQuery (); SqlCommand cmd = new SqlCommand ("delete from titles where title_id = 'JP2002'", conn); cmd.ExecuteNonQuery ();
  • 28. The ExecuteScalar Method Executes a query command and returns a single value in the result set, such as COUNT, AVG, MIN, MAX, and SUM. SqlCommand cmd = new SqlCommand ("select min (price) from titles", conn); decimal amount = (decimal) cmd.ExecuteScalar (); Console.WriteLine ("ExecuteScalar returned {0:c}", amount);
  • 29. The ExecuteScalar Method Another common use for ExecuteScalar is to retrieve BLOBs (binary large objects) from databases. For example, retrieving an image from the ―Logo‖ field of the Pubs database‘s ―Pub_info‖ table and encapsulates it in a bitmap: use System.IO; use System.Drawing; use System.Data.SqlClient; SqlCommand cmd = new SqlCommand ("select logo from pub_info where pub_id='0736'", conn); byte[] blob = (byte[]) cmd.ExecuteScalar (); stream.Write (blob, 0, blob.Length); Bitmap bitmap = new Bitmap (stream); stream.Close ();
  • 30. Write a BLOB to a database. FileStream stream = new FileStream("Logo.jpg", FileMode.Open); byte[] blob = new byte[stream.Length]; stream.Read (blob, 0, (int) stream.Length); stream.Close (); SqlCommand cmd = new SqlCommand ("insert into pub_info (pub_id, logo) values ('9937', @logo)", conn); cmd.Parameters.Add ("@logo", blob); cmd.ExecuteNonQuery ();
  • 31. The ExecuteReader Method  For performing database queries and obtain the results as quickly and efficiently as possible.  Returns a DataReader object.  Pulls back only the data to be ―Read‖ by the DataReader not all records satisfying the query condition. SqlCommand cmd = new SqlCommand ("select * from titles", conn); SqlDataReader reader = cmd.ExecuteReader (); while (reader.Read ()) Console.WriteLine (reader["title"]);  Each call to ―Read‖ returns one row from the result set.  It uses a property indexer to extract the value of the record‘s ―title‖ field.  Fields can be referenced by name or by numeric index (0-based).
  • 32. DataReader  Reads data.  Reads schema (meta data) .  Stream-based access to the results of database queries.  Fast and efficient.  Read-only and forward-only.  Closing a DataReader: reader.Close( ) does NOT close the connection, only frees it for others to use.  D-E-F-E-N-S-I-V-E P-R-O-G-R-A-M-M-I-N-G.
  • 33. DataSets  Set-based Database Accesses  capture an entire query in memory  support backward and forward traversal  edit data and propagate the changes back to the database.
  • 34. DataSet, DataTable and DataAdapter  .NET supports set-based database accesses through three classes:  DataSet: equivalent of an in-memory database. It consists of a collection of DataTables.  DataTables are created by a DataAdapter (SqlDataAdapter and OleDbDataAdapter).  DataSet doesn‘t interact with databases directly. DataAdapter reads the physical data sources and fills DataTables and DataSets
  • 35. DataSets vs. DataReaders  To simply query a database and read through the records one at a time until you find the one you‘re looking for, then DataReader is the right tool. DataReaders (1) retrieve only the data that you actually use, and (2) they don‘t consume memory by not storing every record that you read, but (3) they can‘t iterate backward.  To use all the query results and to iterate backward and forward through a result set, or to cache the result set in memory, use a DataSet. Many controls that support DataSets are perfectly capable of binding to DataReaders.
  • 36. DataGrid (GUI) • DataGrid is an ASP control for displaying datasets. • Database displaying procedure: – Use DataAdapter to get data from the database. – Fill the data into a DataSet – Bind the DataSet to a DataGrid – Select the fields (columns) to be displayed and their header texts.
  • 37. Example: DataAdapter, DataSet and DataGrid (GUI) <asp:DataGrid ID="MyDataGrid" OnItemCommand="OnItemCommand" RunAt="server"> <Columns> <asp:BoundColumn HeaderText="Title" DataField="title" /> <asp:BoundColumn HeaderText="Price" DataField="price" DataFormatString="{0:c}"/> <asp:ButtonColumn HeaderText="Action" Text="Add to Cart" CommandName="AddToCart" /> </Columns> </asp:DataGrid> Examples/C9/Congo-MySQL/ViewCart.aspx
  • 38. Example: DataAdapter, DataSet and DataGrid (GUI) void Page_Load (Object sender, EventArgs e) { if (!IsPostBack) { string ConnectString = ConfigurationSettings.AppSettings["connectString"]; MySqlDataAdapter adapter = new MySqlDataAdapter ("select * from titles where price != 0", ConnectString); DataSet ds = new DataSet (); adapter.Fill (ds); MyDataGrid.DataSource = ds; MyDataGrid.DataBind ();//Bind data to GUI } }
  • 39. Transaction Commands  A transaction is a logical unit of operations grouped together.  If one of the operations fails, the others will fail (or be rolled back). Distributed transactions — transactions that span two or more databases.  The .NET Framework supports distributed transactions.  The .NET supports local transactions (one database):
  • 40. Transacted Commands // Start a local transaction trans = conn.BeginTransaction (IsolationLevel.Serializable); // Create and initialize a SqlCommand object SqlCommand cmd = new SqlCommand (); cmd.Connection = conn; cmd.Transaction = trans; // Debit $1,000 from account 1111 cmd.CommandText = "update accounts set balance = " + "balance - 1000 where account_id = '1111'"; cmd.ExecuteNonQuery (); // Credit $1,000 to account 2222 cmd.CommandText = "update accounts set balance = " + "balance + 1000 where account_id = '2222'"; cmd.ExecuteNonQuery (); // Commit the transaction (commit changes) trans.Commit ();
  • 41. Transacted Commands  IsolationLevel.Serializable locks down the records while they‘re updated so that they can‘t be read or written. Committing the transaction writes the changes to the database.
  • 42. Uses DataGrid to represent a DataSet in XML DataSet ds = new DataSet (); ds.ReadXml (Server.MapPath ("Bonuses.xml")); MyDataGrid.DataSource = ds;
  • 43. SQL Injection • How Web pages works? • INPUT rendered from Textbox Web Control • Query String • Use values concat a SQL command – Search knowledge base – Paged results – Look for specific record • User credentials
  • 44. What really exists! • DON‘T LIKE – More comfort for the user string sql = "select * from KB where content like '" + search.Text + "' • Hacker types: % string sql = "select * from KB where content like '%' • User authentication!
  • 45. SQL Injection Attack • Developer concate SQL statements string sql = "select * from Users where user ='" + User.Text + "' and pwd='" + Password.Text + "'" • Hacker types: ‗ or 1=1 --‗ string sql = "select * from Users where user =' ' or 1=1 --' and pwd=''" • Result is the first database entry – Maybe the Admin
  • 46. SQL Injection Attack • Take over control • User types: ; xp_cmdshell 'format c: /q /yes '; drop database myDB; -- select * from tabelle where id=1; xp_cmdshell 'format c: /q /yes '; drop database myDB; -- • Result: Hacker can do everything – SQL process runs with system privileges
  • 47. SQL Injection Attack • Never use ―sa‖ – Default blank password – Hacker knows a lot about sa – Trusted Security – Application user • Only with needed access rights • Storing Connection Strings – Web.Config • Hashed not clear text – error case source code is often visible
  • 48. Best Solution • Use parameterized Select sql = "select * from Users where user = @user and pwd = @pwd"; SqlCommand cmd = new SqlCommand(sql,con); cmd.Parameters.Add("@user",User.Text); cmd.Parameters.Add("@pwd",Password.Text); • Use Stored Procedures • Cookie & URL Injection
  • 49. Cross site-scripting • User Input is stored in Database • Database content is presented • Injection of – HTML code – JScript code • A different denial of service <script> • Redirect the user to dialer page <script language=Jscript> window.navigate('net.htm');</script>
  • 50. Cross site-scripting • Don‘t trust the user – Use validators controls – Use regexp • Remove: < > " ' % ; ) ( & + - – Check for the length – Use Server.HtmlEncode • .NET 1.1 – Default no HTML code in Textboxes – Page Attribut ValidateRequest =false
  • 51. HTTP Harvesting • Database driven websites • Display result based on – Text Input, Querystring, Cookie • Special type of SQL query language • Datagrid list with detail link – Detail.aspx?id=1 • Session attaching+ pagelink • Email address for spammer
  • 52. Prevent HTTP harvesting • Encrypt querystrings • Combine user input with textboxes • Use Jscript to write the data • Draw the data – System.drawing • Monitor the web usage • Third party review
  • 53. Canonicalization • Character Sets URL, Querystring, Filename – %20=― ― • IP Address as decimal • Compare values – HTMLDecode
  • 54. Architecture • Operation System – Reduce the rights of accounts • Never use Admin Rights – Switch of unused services and ports • Web Farm – Use ipsec to encrypt traffic • Between SQL Server and Web Application • Session Management – IP restrictions • Change common used things – Directories, users, path
  • 55.
  • 56.
  • 57.
  • 58. Page Title Subhead • Copy: Consed te commodipit, velismo digniam iure ver iriure ea core do odipsum velisci elissim velendreet lummodiamet, qui enisl utpate feuisl eniam nibh eui eugue dolumsandre enim alis nonsequat alit loborpero dit laore molore vel iure • Copy: Consed te commodipit, velismo digniam iure ver iriure ea core do odipsum velisci elissim velendreet lummodiamet, qui enisl utpate feuisl eniam nibh eui eugue dolumsandre enim alis nonsequat alit loborpero dit laore molore vel iure