Thursday, 31 May 2018

C# Programs



  1. Reverse Each Word in a Sentence without using any Function/String Variables in C#

  1. string sentense = "This is a good day";  
  2. char[] arr = sentense.ToCharArray();  
  3. int temp = 0;  
  4.   
  5. //Logic to iterate up to end of the line.  
  6. for (int fl = 0; fl <= arr.Length - 1;fl++ )  
  7. {  
  8.     int count = temp;  
  9.     int num1 = 1;  
  10.     //To get the word before space or the last word  
  11.     if (arr[fl] == ' ' || fl == arr.Length - 1)  
  12.     {  
  13.         if (fl == arr.Length - 1)  
  14.         {  
  15.             for (int c = fl; c >= temp; c--)  
  16.             {  
  17.                 //Swap the word  
  18.                 if (num1 <= (fl - temp) / 2)  
  19.                 {  
  20.                     char tempC = arr[count];  
  21.                     arr[count] = arr[c];  
  22.                     arr[c] = tempC;  
  23.                     count++;  
  24.                     num1++;  
  25.                 }  
  26.             }  
  27.         }  
  28.         else  
  29.         {  
  30.             for (int c = fl - 1; c >= temp; c--)  
  31.             {  
  32.   
  33.                 if (num1 <= (fl - temp) / 2)  
  34.                 {  
  35.                     char tempC = arr[count];  
  36.                     arr[count] = arr[c];  
  37.                     arr[c] = tempC;  
  38.                     count++;  
  39.                     num1++;  
  40.                 }  
  41.             }  
  42.         }  
  43.         temp = fl + 1;                  
  44.     }  
  45.   
  46. }  
  47.   
  48. string newLine = new string(arr);  


2) Find Second largest digit in given number without using any collection like array list

int n= 4719; int max=0, x=0, secondhighestnum =0; while(n>0) { x=n%10; if(x>max) { max =x; } if(x > secondhighestnum && x < max) { secondhighestnum = x; } n= n/10; } Console.WriteLine(secondhighestnum)


1)

public static void Main(string[] args)
        {
            for (int row = 8; row >= 1; --row)
            {
                for (int col = 1; col <= row; ++col)
                {
                    Console.Write("*");
                }             
           
                Console.WriteLine();
            }
        }

Output
********
*******
******
*****
****
***
**
*
http://www.csharpstar.com/star-pattern-programs-in-csharp/
2)

public class Program
    {

        public static void Main(string[] args)
        {
            for (int row = 1; row <= 8; ++row)
            {
                for (int col = 1; col <= row; ++col)
                {
                    Console.Write("*");
                }

                Console.WriteLine();
            }
        }

    }

Output

*
**
***
****
*****
******
*******
********

3)
public class Program
    {
        public static void Main(string[] args)
        {
            int val = 8;
            int i, j, k;
            for (i = 1; i <= val; i++)
            {
                for (j = 1; j <= val - i; j++)
                {
                    Console.Write(" ");
                }
                for (k = 1; k <= i; k++)
                {
                    Console.Write("*");
                }
                Console.WriteLine("");
            }
            Console.ReadLine();
        }

    }

Output
Star Pattern in C#

Sunday, 27 May 2018

Secure Your ASP.NET MVC Applications

Lot of ASP.NET MVC developers are great in delivery , writing high performance code and so on. But when it comes to security there is no planning done. So in this article we will run through 10 points which will help us to make our MVC code secure.

  • Security Misconfiguration (Error Handling Must Setup Custom Error Page)
  •  Cross-Site Request Forgery (CSRF)
  •  Cross-Site Scripting (XSS) attacks
  •  Malicious File Upload.
  •  Version Discloser
  •  SQL Injection Attack.
  •  Sensitive Data Exposure
  •  Audit trail
  •  Broken authentication and session management
  •  Unvalidated Redirects and Forwards


·       Security Misconfiguration (Error Handling Must Setup Custom Error Page)

In this kind of attack the attacker intercepts form data which is submitted by end User and changes values and sends the modified data to the server.
So for such kind of scenarios developers do put proper validations in place but when these validations display error lot of information of the server is revealed.

Solution: -

So the solution here is we need to set some kind of error page which does not show the internal technical error but rather shows a custom error message.
We have two approaches for it :-
  1. Create a custom Error handling Attribute.
  2. Setting Custom Error page from Web.config file
Solution 1:-
Create a custom Error handling Attribute using HandleErrorAttribute or using IExceptionFilterFilter
Showing example using HandleErrorAttribute
using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Web.Mvc;

namespaceMvcSecurity.Filters
{
publicclassCustomErrorHandler : HandleErrorAttribute
    {
publicoverridevoidOnException(ExceptionContextfilterContext)
        {
Exception e = filterContext.Exception;
filterContext.ExceptionHandled = true;
var result = newViewResult()
            {
ViewName = "Error"
            }; ;
result.ViewBag.Error = "Error Occur While Processing Your Request Please Check After Some Time";
filterContext.Result = result;     
        }
    }
After creating custom Error attribute we need to apply this globally for entire application. For doing this we need to call this attribute in FilterConfig class which is in App_Start Folder as show below.
usingMvcSecurity.Filters;
usingSystem.Web;
usingSystem.Web.Mvc;

namespaceMvcSecurity
{
publicclassFilterConfig
    {
publicstaticvoidRegisterGlobalFilters(GlobalFilterCollection filters)
        {
filters.Add(newCustomErrorHandler());
        }
    }
}
Whenever error occurs the CustomErrorHandler attribute will get called and it will redirect toError.cshtml page. And any message you want to pass then you can pass through @ViewBag.Errorfrom CustomErrorHandler attribute.
Html Error Page code snippet
@{
    Layout = null;
}

<!DOCTYPEhtml>
<html>
<head>
<metaname="viewport"content="width=device-width"/>
<title>Error</title>
</head>
<body>
<hgroup>Error.

@ViewBag.Error 

</body> </html>
Error Page View


2) Cross-Site Request Forgery (CSRF)

A CSRF vulnerability allows an attacker to force a validated and logged in user to perform actions without their consent or unknowingly.
Take this simple example.
  • User logs in to the bank server.
  • Bank authorizes and a secure session is established between user and the bank server.
  • The attacker sends an email with a malicious link saying “Earn 100000$ now” to the user.
  • User clicks on the malicious link and the site tries transfer money from your account to the attackers account. Because the secure session is established the malicious code can execute successfully.
Microsoft has recognized this threat and for preventing the same we have something called as AntiForgeryToken.
Solution:-
We need to add @Html.AntiForgeryToken()helper in your form inside form tag . And on the Action Method which handles your post ([HttpPost])Request we need to put[ValidateAntiForgeryToken] attribute which will check if the token is valid.
Adding [AntiForgeryToken] helper to View
Fig 13.Adding AntiForgeryToken on View.
Adding [ValidateAntiForgeryToken] Attribute to HttpPost[HttpPost] Method.
Fig 14.Adding ValidateAntiForgeryTokenon [HttpPost] Method (Index).

3) Cross-Site Scripting (XSS) attacks

Cross-site Scripting (XSS) is an attack in which malicious scripts is injected via input fields this attack is most common and allows an attacker to steal credentials and valuable data that can lead to a big security breach.
Fig 17. Cross Site Scripting (XSS).
In this attack attacker visits a website and tries to execute a malicious scripts in form comment box. Now if website has not checked for Malicious code then the code can get executed on the server causing damage.
Lets try to understand the same using a example.Below is simple Employee form which we are trying to save data. Now in the text box I am trying to execute some malicious code using javascript using the SCRIPT tag. But if we try to submit the same MVC throws an error that something bad is happening.
In short by default ASP.NET prevents Cross Site Script attack.
Understanding the Error Displayed
A potentially dangerous Request.Form value was detected from the client (worktype="<script>alert('hi');").
This error occurs because MVC is validating data which is entered by User and if User tried to execute such script it does not allow and that’s a good news.
Fig 18.SubmittingMaliciousscripts in Input fields which lead to Error.
But now what if we want to put SCRIPT tag. For example programming sites like codeproject has a genuine need that end user should submit code and script snippets. In those scenarios we would like the end user to post code through the UI.
So lets us understand how to do the same but at the same time not compromise on security.
So we have four things via which we can allow scripts to be posted.
Solution: -
  1. [ValidateInput(false)]
  2. [AllowHtml]
  3. [RegularExpressionAttribute]
  4. AntiXSS Library
  5. Solution 1:-
    ValidateInput
    [ValidateInput] is an attribute which can be applied on Controller or Action Method on which we want the script to go through.
    If we want Mark up to be allowed then we need to set enableValidation Properties to False([ValidateInput(false)]) which will not validate input if we set to true then[ValidateInput(true)]) It will validate input.In the same way, if you apply it on Controller then it appliesto entire action methods inside thecontroller and if you apply it on Action Method then it will only be specific to that action method.
    But ValidateInputattributewill apply to all properties of Model (EmployeeDetails).
    Snapshot of Applying ValidateInputAttributeon HttpPostMethod.
    Fig 19.Applying ValidateInput Attribute on HttpPost Method.
    Snapshot after Applying ValidateInputAttribute
     Fig 20.After adding ValidateInput Attributeon HttpPost Method it allows submitting script.

Malicious File Upload.

Till now we have learned how to protect all your input fields from attack but still, we are missing one main field it is File upload control we need to protect from taking invalid input most attackers try to upload a malicious file which may cause a security issue. The attacker can change file extension [tuto.exe to tuto.jpeg] and the malicious script can be uploaded as an image file. The Most of the developer just look on the file extension of the file and save in folder or database but file extension is valid not file it may have a malicious script.
Fig 29.This image shows how people try to upload files some try valid files and some invalid files.
Solution:-
  1. First thing we need to do is validate file uploads
  2. Allow only access to files extension which are required
  3. Check the file header.

SQL Injection Attack.

SQL Injection attack is one of the most dangerousattacks it is ranked 1 in top 10 Vulnerabilitiesby OWASP2013 [Open Web Application Security Project] . SQL injection attack can give valuable data to theattacker that can lead to abig security breach and can also take full access to thedatabase server.
In SQL Injection attacker always try to enter malicious SQL statement which will get executed in thedatabase and return unwanted data to the attacker.
Fig 46.Sql injection attack example which shows how attack mostly occurs if you are using inline queries.
Simple View which shows User data
View Shows Single Employee data based on EmployeeID as displayed in below Snapshot.
Fig 47.Employee View which displays user data.
Simple View which shows All User data after SQL Injectionattack
In this Browser View as attacker saw Application URL which contains some valuable data which is ID [http://localhost:3837/EmployeeList/index?Id=2] attacker triesSQL Injectionattack as shown below.
Fig 48.Employee View which displays all User data after SQL injection.
After trying permutation & combination of SQL injection attack , theattackergets access to all User data.
Displaying SQL injection in Debug Mode
Here we can see in details how attacker passed maliciousSQL statement which gets executed in thedatabase.
Fig 49.Debug mode View of index Action Method.
SQL Profiler View of SQL statement
Fig 50.SQL Profiler View.
Solution:-
  1. Validate inputs
  2. Use of low-privileged database logins
  3. Use Parameterized queries
  4. Use ORM (e.g. Dapper , Entity framework )
  5. 5) Use Stored Procedures

Sensitive Data Exposure

All Website and Application always have database in which entire data is been stored .mean while we store Users personal information (which may contains Password , PAN number , Passport details ,Credit Card Numbers) in this we mostly encryptonly password right other data are stored in clear text which can lead to Sensitive Data Exposurewhenever an attacker attack he gets access to database if he finds the table where all this personal and financial details stored steal that information .
Fig 77.Sensitive Data Exposure.

3) Do not store Sensitive data in Database in a clear form
Always Try not to store Credit Card, Debit Card and financial details and other Sensitive details in thedatabasein Clear form . Always Use Strong Hashing techniques to encrypted data and then store in thedatabase. if anattacker gets direct access to thedatabase then all data in clear form can be Breached.
Below is alist of Algorithm which can be Used according to need.
Hash Algorithm
if someonewantsjust Hash then they can use Hash Algorithmwe mostly use Hash function for Encrypting Password.
SymmetricAlgorithm
If someonewants just one key for encryption and decryption then they can useSymmetricAlgorithm.
AsymmetricAlgorithm
If someonewants just one key for encryption (Public key) and another keydecryption (Private key) then they can useAsymmetricAlgorithm. E.g we can usethis when we are sharing Web Services and WebAPI with clients when theuser.
HashAlgorithm
  1. MD5
  2. SHA256
  3. SHA384
  4. SHA512

Audit trail

Audit Trail in IT World is used to keep track of User activity on aWebapplication which he using , it is where important in detecting security problems, performance problems, and ApplicationsLevel Error problems. It also helps us to easily track where theproblemactually is and resolve it.

Unvalidated Redirects and Forwards

In all web application, we do redirect from one page to another page and sometimes we redirect to another application too but while redirect we won't validate URL which we are going redirect which causesUnvalidated Redirects and Forwards Attack.
This attack mostly uses to phish User to get Valuable details (User Credentials) or to install maliciousmalware to the User computer.

Monday, 21 May 2018

SOAP


1) What are Hostings are there?When to use?

SOAP
  • SOAP stands for Simple Object Access Protocol
  • SOAP is an application communication protocol
  • SOAP is a format for sending and receiving messages
  • SOAP is platform independent
  • SOAP is based on XML
  • SOAP is a W3C recommendation

Why SOAP?

It is important for web applications to be able to communicate over the Internet.
The best way to communicate between applications is over HTTP, because HTTP is supported by all Internet browsers and servers. SOAP was created to accomplish this.

A SOAP message is an ordinary XML document containing the following elements:
  • An Envelope element that identifies the XML document as a SOAP message.
  • A Header element that contains header information.
  • A Body element that contains call and response information.
  • A Fault element containing errors and status information.

Syntax Rules

Here are some important syntax rules:
  • A SOAP message MUST be encoded using XML
  • A SOAP message MUST use the SOAP Envelope namespace
  • A SOAP message MUST use the SOAP Encoding namespace

Syntax

soap:encodingStyle="URI"

The SOAP Header Element

The optional SOAP Header element contains application-specific information (like authentication, payment, etc) about the SOAP message.
If the Header element is present, it must be the first child element of the Envelope element.
Note: All immediate child elements of the Header element must be namespace-qualified.<?xml version="1.0"?>


<soap:Envelope
xmlns:soap="http://www.w3.org/2003/05/soap-envelope/"
soap:encodingStyle="http://www.w3.org/2003/05/soap-encoding"
>


<soap:Header>
  <m:Trans xmlns:m="https://www.w3schools.com/transaction/"
  soap:mustUnderstand="1"
>
234
  </m:Trans>
</soap:Header>
...
...
</soap:Envelope

----------

2) How to Return a DataTable From WCF Service

[ServiceContract]public interface IService1{
    [OperationContract]
    Employee GetEmployee();
}
Then add DataContract and DataMember:
[DataContract]public class Employee{
    [DataMember]
    public DataTable EmployeeTable
    {
        get;
        set;
    }
}

In this article I am leaving binding to the default, wsHttpBinding.

Step 3: Add the following code in the Service1.svc.cs file inside Service1 class:
public class Service1 : IService1{
    string ConString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
    SqlConnection con;
    SqlCommand cmd;
    SqlDataAdapter sda;
    DataTable dt;
    Employee emp = new Employee(); 
    public Employee GetEmployee()
    {             
        using (con = new SqlConnection(ConString))
        {
            cmd = new SqlCommand("SELECT EmployeeID, FirstName, LastName FROM Employees", con);
            sda = new SqlDataAdapter(cmd);
            dt = new DataTable("Paging");
            sda.Fill(dt);
            emp.EmployeeTable = dt;
            return emp;
        }        
    }
}
We have created our WCF service that will return Employees data as a DataTable. Now its time to consume this service in a Console application.

Step 4: Add a new Console Application named EmployeeServiceClient by right-clicking on the Solution Explorer and selecting Add -> New Project.

Step 5: Add a Service Reference to the WCF service in the Console Application using Add Service Reference dialog box.

Right-click on the Console Application and select Add Service Reference:

wcf2.gif

Step 6: Write following code in the Main function of the Console Application:
static void Main(string[] args)
{
    ServiceReference1.Service1Client MyClient = 
        new ServiceReference1.Service1Client();
    ServiceReference1.Employee emp = 
        new ServiceReference1.Employee();
    emp = MyClient.GetEmployee();
    DataTable dt = new DataTable();
    dt = emp.EmployeeTable;
    Console.WriteLine(" EmpID".PadRight(10) 
        +"FirstName".PadRight(10)
        +"LastName".PadRight(10));
    Console.WriteLine("---------------------------------------");
    for (int i = 1; i < dt.Rows.Count; i++)
    {
        Console.WriteLine(dt.Rows[i][0].ToString().PadRight(10)+ 
            dt.Rows[i][1].ToString().PadRight(10) + 
            dt.Rows[i][2].ToString().PadRight(10));
    } 
    Console.WriteLine(dt.Rows.Count.ToString());
    Console.ReadKey();
}

3) Accessing WCF Service Without Creating Proxy

Normally 
  1. We create a WCF service 
  2. Expose metadata endpoint 
  3. Add service reference at client side to create the proxy.
  4. Using the proxy calls the service operation contracts. 
Normally we call the service as 

1.gif
 
Let us assume we want to call the service using channel without creating proxy or adding the service reference.  We need to follow the below steps 

Create the client.  We are creating a console client to consume the service with channel or without creating proxy.  So follow the below steps 
  1. Do not add the service reference. 
  2. Add the reference of System.ServiceModel.
  3. Add the reference of class library created in step1. 
Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using ContractDll;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            ChannelFactory<MyServiceContract> factory = null;
            try
            {
                BasicHttpBinding binding = new BasicHttpBinding();
                EndpointAddress address = new EndpointAddress("http://localhost:4684/Service1.svc");
                factory = new ChannelFactory<MyServiceContract>(binding, address);
                MyServiceContract channel = factory.CreateChannel();
                string resturnmessage = channel.GetData(9);
                Console.WriteLine(resturnmessage);
                Console.ReadKey(true);
            }
            catch (CommunicationException)
            {
                if (factory != null)
                    factory.Abort();
            }
            catch (TimeoutException)
            {
                if (factory != null)
                    factory.Abort();
            }
            catch (Exception ex)
            {
                if (factory != null)
                    factory.Abort();
                Console.WriteLine(ex.Message);
            }
            Console.WriteLine("Proxy closed");
            Console.ReadKey(true);
        }
    }
}