Friday, July 26, 2013

NORMALIZATION

What is normalization?
Database Design Technique used for avoiding redundant data and dependency data.


Before going to view the rules lets understand some basics,

Primary Key – unique identify for the database records without duplication.
        Following Characteristics of Primary Key,
·         Primary key does not allow null value
·         Primary key must be unique
·         Primary values cannot be changed
·         Primary key created when new records inserted.

Composite Key – Combination of multicolumn values for identity a record unique.

Foreign Key –
Foreign Key - insert record in foreign key table will throw error if foreign Key doesn’t have entry in Primary Key.


Transitive Functional Dependencies
A transitive functional dependency is when changing a non-key column , might cause any of the other non-key columns to change




1NF - (no duplication of data/ single value for each column)
    1NF Rules:
·         Each column contain single value
·         Each rows inserted must be unique
  
2NF – (Use of Referential integrity, Primary Key and Foreign Key)
 2NF Rules

·         Follow  1NF
·         Single column Primary Key
3NF Rules
·         Follow 2NF
·         Has no transitive Functional Dependencies


Boyce-Codd Normal Form (BCNF)

Even when a database is in 3rd Normal Form, still there would be anomalies resulted if it has more than one Candidate Key.  
Sometimes is BCNF is also referred as 3.5 Normal Form.


4th Normal Form
If no database table instance contains two or more, independent and multivalued data describing the relevant entity , then it is in 4th Normal Form.

5th Normal Form
A table is in 5th Normal Form only if it is in 4NF and it cannot be decomposed in to any number of smaller tables without loss of data.











Wednesday, July 3, 2013

C# - Broken Authentication and Session Management

Definition by OWASP:
                   Application functions related to authentication and session management are often not implemented correctly, allowing attackers to compromise passwords, keys, session tokens, or exploit other implementation flaws to assume other users’ identities.

·         The attackers may be external attackers or the users who are using the application can steal account information of other.
·         Attackers will make use the flaws or leaks found in the application authentication and session management function will lead to loss of sensitive information, passwords to impersonate users. 
·         Developers of the application use custom authentication and session management deploy correctly is very hard.
·         Such flaw may allow some or even all user account information to be hacked successfully.
·         The above risk is not clearly defined just like injection and XSS. Broken is a bit of all different vulnerabilities, some may explicitly looked up such as insecure cryptographic storage and insufficient transport layer authentication.

           Hackers will intercept session from cookie or requested URL.

ASP.Net Session State

           Programmatically, session state is nothing more than memory in the shape of a dictionary or hash table, e.g. key-value pairs, which can be set and read for the duration of a user's session.

Session Management

ASP maintains session state by providing the client with a unique key assigned to the user when the session begins. This key is stored in an HTTP cookie that the client sends to the server on each request. The server can then read the key from the cookie and re-inflate the server session state.

With cookie

      Enter user name and password for login page. Cookie information stored properly in this page and used further use.

 

// assume successful authentication against an account source...
Session ["Username"] = username;
                lblUsername.Text = username == null? "Unknown”: username.ToString ();



Cookie information stored can be viewed and obtained easily.

Cookieless State Information

Use cookieless state in asp.net session management. Store session information in particular position in the URL .
   <sessionState cookieless="true" />

          http://yourserver/folder/(session ID here)/default.aspx



Page contain Cookieless state hold session information will have identical information for both cookie and cookieless state.

Use Asp.net Membership provider and Role provider

        Practice use of asp.net member ship provider and role provider will help in reducing the attacks




<asp:LoginView ID="HeadLoginView" runat="server" EnableViewState="false">
<AnonymousTemplate>
 [ <a href="~/Account/Login.aspx" id="HeadLoginStatus" runat="server">Log In</a> ]
 </AnonymousTemplate>
 <LoggedInTemplate>
Welcome
<span class="bold">
<asp:LoginName ID="HeadLoginName" runat="server" />
</span>
! [ <asp:LoginStatus ID="HeadLoginStatus" runat="server" LogoutAction="Redirect" LogoutText="Log Out" LogoutPageUrl="~/" /> ]
 </LoggedInTemplate>
 </asp:LoginView>


Use asp.net membership provider control provided in .net control toolbox and customizable role provider done using this control. Avoid using your own or custom authentication and session management for the application don’t attempt to rewrite code without proper need of it.



Implement Proper Password Strength Controls
                Password Length
·         Set minimum length of 10 and make it as strong.
·         Weak password strength will lead to crack the password.
·         Make sure maximum password length to be 20-30 Characters.

Password Complexity
§     at least 1 uppercase character (A-Z)
§     at least 1 lowercase character (a-z)
§     at least 1 digit (0-9)
§     at least 1 special character (punctuation) — do not forget to treat space as special characters too.

 

Implement Secure Password Recovery Mechanism

Instead of sending password via mail reset the password

 

Use SSL with Session

 Using SSL all communication are encrypted (the cookies content been encrypted). Make it nearly impossible to directly access the data cookies.

Get the session expiration automatically or manually
Make the session clear either automatically or manually to avoid maintain for prolong period of time.

<system.web>
 <sessionState timeout="10" />
</system.web>

Summary

 We can protect ourselves by make cookie encrypted using SSL, expire cookie information periodically, Double Checking Password and avoid cookieless information.

C# - Unvalidated Redirects and Forward Access

Definition by OWASP:
          Web applications frequently redirect and forward users to other pages and websites, and use untrusted data to determine the destination pages. Without proper validation, attackers can redirect victims to phishing or malware sites, or use forwards to access unauthorized pages.

·     The users are trick by the attackers making users to submitting request to attackers’ website unknowingly.
·        Attackers link the unvalidated redirect and trick user into clicking it.
·         Unsafe forward to bypass security checks by the attackers.
·         Target page is specified in an unvalidated parameter, allowing attacker to choose destination page.
·         Redirect will attempt to install malware and identify the sensitive information.
·         Unsafe forward may allow access control bypass.
·         Reputation of business can lost and business value of your users trust get affected 

How attackers achieve it

Unvalidated Redirects
Attackers find a page with a redirect on it:








     
    Through phishing or some mechanism attackers get modify the above the URL link make the user to click the link              

 

http:/ / www.mytrustedsite.com/Redirect.aspx?Url=http://myuntrustedsite.com


Clicked on a URL which clearly had the host name of mytrustedsite.com, we’re now on myuntrustedsite.com. What’s more, there’s a logon form asking for credentials which you’d naturally expect would be handled properly under the circumstances.

The code behind the page simply takes the URL parameter from the query string, performs some arbitrary logging then performs a redirect which sends an HTTP 302 response to the browser:

var url = Request.QueryString["Url"];
 LogRedirect(url);
 Response.Redirect(url);

The above mytrustedsite.com is authorised domain so the user will click the URL this will lead to unvalidated redirects.


Redirect can be achieved by JavaScript:
  • location
  • location.href
  • location.pathname
  • location.search
  • location.protocol
  • location.hostname
  • location.assign
  • location.replace


/<![CDATA[
(function(g){
  var a=location.href.split("#!")[1];
  if(a){g.location=g.HBR=a;}
})(window);
//]]>

Unvalidated Forwards
               
                An application having login page and after successful login a protected page which is not accessible normally. Using Forward bypassing login page go directly access protected page


Avoid unvalidated redirects and forwards

·      To identify the vulnerability one should review the redirects and forwards of their site and verify the target URL in any redirection is an allowable destination.
 For eg:
Response.Redirect(“DestinationPage”);
Server.Transfer(“DestinationPage”);

·      Whitelist more important. All input must be validated against a whitelist of acceptable value ranges.
  var url = Request.QueryString["Url"];
 if (!Uri.IsWellFormedUriString(url, UriKind.Absolute))
{
              // Gracefully exit with a warning message
          }    

This validation will make the  untrusted data conforms to expected pattern of URL.
·         In the case of unvalidated redirects, we don’t need to have the URL in the query string, let’s try it like this:

http://mytrustedsite.com/Redirect.aspx?Id=AD420440-DB7E-4F16-8A61-72C9CEA5D58D
     
The entire code would then look something like this:

var id = Request.QueryString["Id"];
 Guid idGuid;
if (!Guid.TryParse(id, out idGuid))
{ // Gracefully exit with a warning message }
 var db = new MyTrustedSiteEntities();
var allowableUrl = db.AllowableUrls.SingleOrDefault(u => u.Id == idGuid);
if (allowableUrl == null)
{
// Gracefully exit with a warning message
 }
 LogRedirect(allowableUrl.Url);
 Response.Redirect(allowableUrl.Url);

We are still validate against the data type  and checking it against whitelist this code will provide extra protection and ensure against manipulation.

·      Create / use spider crawl your own website(Look at the Log statuses)
300 – Serious Statuses
302 – Old page moved from location
307 – Proper validation.

Prevent unvalidated redirects and forwards
               
·         Avoid using redirects and forwards.
·         If implemented, don’t use user parameter for identify the destination page. This can be usually done while developing.
·          If the destination parameter is unavoidable, ensure the parameter supplied is valid and verified by the user.
·          It is recommended that any such destination parameters be a mapping value, rather than the actual URL or portion of the URL, and that server side code translate this mapping to the target URL.
·         Applications can use ESAPI to override the sendRedirect() method to make sure all redirect destinations are safe.
Avoiding such flaws is extremely important as they are target of phishers trying to gain the user’s trust.

References:


Example Attack Scenarios
Scenario #1: The application has a page called “redirect.jsp” which takes a single parameter named “url”. The attacker crafts a malicious URL that redirects users to a malicious site that performs phishing and installs malware.
http://www.example.com/redirect.jsp?url=evil.com
Scenario #2: The application uses forwards to route requests between different parts of the site. To facilitate this, some pages use a parameter to indicate where the user should be sent if a transaction is successful. In this case, the attacker crafts a URL that will pass the application’s access control check and then forwards the attacker to administrative functionality for which the attacker isn’t authorized.
http://www.example.com/boring.jsp?fwd=admin.jsp


C# - Insufficient Transport Layer protection by Sivanath KS.


Ø  Definition:
“Applications frequently fail to authenticate, encrypt, and protect the confidentiality and integrity of sensitive network traffic. When they do, they sometimes support weak algorithms, use expired or invalid certificates, or do not use them correctly.”

Ø  HTTPS, SSL and TLS are essential staples of website security.
Ø  SSL is Secure Sockets Layer which is the term we used to use to describe the cryptographic protocol used for communicating over the web. SSL provides an asymmetric encryption scheme which both client and server can use to encrypt and then decrypt messages sent in either direction.
Ø  TLS is Transport Layer Security and the successor to SSL. You’ll frequently see TLS version numbers alongside SSL equivalent; TLS 1.0 is SSL 3.1, TLS 1.1 is SSL 3.2, etc. These days, you’ll usually see secure connections expressed as TLS versions:




Ø  HTTPS is Hypertext Transport Protocol Secure and is the implementation of TLS over HTTP. HTTPS is also the URI scheme of website addresses implementing SSL, that is it’s the prefix of an address such as https://www.americanexpress.com and implies the site will be loaded over an encrypted connection with a certificate that can usually be inspected in the browser.
Ø  Example:
·         The iPad is an innocent user of the ASafaWeb website and logged in as an administrator and as such I have the highlighted menu items below:
·         The laptop is the attacker and it has no more rights than any public, non-authenticated user would. Consequently, it’s missing the administrative menu items the iPad had.
·         I’ve taken a ride down to the local McDonald’s which offers free wifi. Both the laptop and the iPad are taking advantage of the service, as are many other customers scattered throughout the restaurant.
·         I had a browse around the ASafaWeb website on the iPad.After letting the process run for a few minutes, I’ve opened up the capture file in “Wireshark” which is a packet capture and analysis tool frequently used for monitoring and inspecting network traffic.

·         Let’s filter those packets further so that only those originating from my iPad are shown:
·         By right clicking on the first packet and following the TCP stream, we can see the entire request:
·         Each request any browser makes to a website includes any cookies the website has set. The request above contains a number of cookies, including one called “.ASPXAUTH”
·         But that’s easily rectified simply by adding a new cookie with the same name and value as we’ve just observed from the iPad.
·         Refresh the page:

·         Finally, insufficient transport layer protection has just allowed us to hijack the session and become an administrator.
Ø  Don’t mix TLS and non-TLS content
·         Loading a page over TLS then including non-TLS content actually causes some fairly major issues.
·         By striking out the padlock icon and the HTTPS scheme in the URL, the browser is sending a very clear warning to the user.
Ø  Prevention:
·         Providing proper transport layer protection can affect the site design. It's easiest to require SSL for the entire site. For performance reasons, some sites use SSL only on private pages. Others use SSL only on 'critical' pages, but this can expose session IDs and other sensitive data. At a minimum, do all of the following:
·         Require SSL for all sensitive pages. Non-SSL requests to these pages should be redirected to the SSL page.
·         Set the 'secure' flag on all sensitive cookies.
·         Configure your SSL provider to only support strong algorithms.
·         Ensure your certificate is valid, not expired, not revoked, and matches all domains used by the site.
·         Backend and other connections should also use SSL or other encryption technologies.

 Thanks for the valuable document by K S Sivanath Contact mail:Sivanathks@hotmail.com