Showing posts with label object oriented programming. Show all posts
Showing posts with label object oriented programming. Show all posts

Wednesday, 6 January 2021

Steps to resolve VAPT Issues

  
1. Error: Web Parameter Tampering
Resolution:  
Add attribute "enableViewStateMac="false"" inside <pages> tag.
Eg:
<system.web>
    <pages enableViewStateMac="false"/>
</system.web>
 
 
2.  Error: Authentication Bypass Using default credentials
Resolution:
Add "<httpCookies requireSSL="true" />" inside <system.web> tag
Eg:
  <system.web>
     <httpCookies requireSSL="true" />
  </system.web>
 
 
3.  Error: Communication in cleartext
Resolution:  
Implement authorization and authentication in application
Eg:
  <authorization>
      <deny verbs="OPTIONS" users="?"/>
</authorization>
 
  <authentication mode="Forms">
      <forms loginUrl="Login2.aspx" defaultUrl="RedirectionPage.aspx">
      </forms>
</authentication>
 
 
4.  Error: Session Fixation
Resolution:
Add below source code on logout click
     Session.Clear();
     Session.Abandon();
     Session.RemoveAll();
 
     if (Request.Cookies["ASP.NET_SessionId"] != null)
     {
      Response.Cookies["ASP.NET_SessionId"].Value = string.Empty;
         Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddMonths(-20);
     }
 
     if (Request.Cookies["AuthToken"] != null)
     {
      Response.Cookies["AuthToken"].Value = string.Empty;
         Response.Cookies["AuthToken"].Expires = DateTime.Now.AddMonths(-20);
     }
 
 
5.  Error: Cleartext submission of Password
  Resolution: Implement password encryption while sending to database
Eg of function:
public static string Encrypt(string clearText)
    {
        string EncryptionKey = "TEST123";
        byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(clearBytes, 0, clearBytes.Length);
                    cs.Close();
                }
                clearText = Convert.ToBase64String(ms.ToArray());
            }
        }
        return clearText;
}
 
 
6.  Error: Unencrypted __VIEWSTATE parameter
Resolution: Add attribute “viewStateEncryptionMode="Always"" inside <pages> tag.
Eg:
<system.web>
    <pages viewStateEncryptionMode="Always"/>
</system.web>
 
 
7.  Error: Server version disclosure
Resolution: Add “<httpRuntime enableVersionHeader="false" /> “ inside <system.web> tag.
Eg:
<system.web>
    <httpRuntime enableVersionHeader="false" />
</system.web>
 
 
8.  Error: Cookie Without HTTP Only Flag Set
Resolution:
Add "<httpCookies requireSSL="true" />" inside <system.web> tag
Eg:
  <system.web>
     <httpCookies requireSSL="true" />
  </system.web>
 
 
9.  Error: ASP.NET padding oracle vulnerability
Resolution:
Add attribute "redirectMode="ResponseRewrite"" inside <customErrors> tag
Eg:
<customErrors redirectMode="ResponseRewrite"  
defaultRedirect="customerror.htm" mode="On" />
 
 
10.  Error: Clickjacking
 Resolution:
 Add below code in Global.asax file
     void Application_BeginRequest(object sender, EventArgs e)
      {
         HttpContext.Current.Response.AddHeader("x-frame-options", "DENY");
 }
 
 
11.  Error: options method is enabled
 Resolution:
 Add below tag in "<system.webServer>" tag
    <security>
      <requestFiltering>
         <verbs allowUnlisted="true">
           <add verb="OPTIONS" allowed="false" />
         </verbs>
     </requestFiltering>
 </security>
 

Friday, 22 May 2020

CSharp Webconfig Interview Questions


CSharp Webconfig Interview Questions and Answers


1). What is web.config file in asp.net?
Web.config is the configurationsettings of an ASP.NET web application. The file is an xml document that defines configuration information regarding the web application.This file stores the information about how the web application will act. 

2). Does web.config file case-sensitive?
Yes.

3). Web.config file is stored in which form?
Web.config files are stored in XML format.

4). Can one directory contain multiple web.config files?
No. One directory can contain only one file.

5). Can you tell the location of the root web.config file from which all web.config file inherit ?
All the Web.config files inherit the root Web.config file available at the following location: Systemroot\Microsoft.NET\Framework\VersionNumber\CONFIG\Web.config


6). What is the root tag of web.config file?
<configuration> tag is the root element of the Web.config file under which it has all the remaining sub elements.

7). What is the use of customErrors tag in web.config file ?
CustomErrors tag provides information about custom error messages for an  application. The customErrors element can be defined at any level in the application file hierarchy.

<customErrors defaultRedirect ="ErrorPage.aspx" mode ="Off">
   <error statusCode ="401" redirect ="UnauthorizedPage.aspx"/>
</customErrors>

The customErrors section consists of defaultRedirect and mode attributes which specify the default redirect page and the on/off mode respectively.
Error status code:

  • 400 Bad Request
  • 401 Unauthorized
  • 404 Not Found
  • 408 Request Timeout

8). Can you describe the funcnalitity of <httpHandlers> tab in web.config?
HttpHandler is a code that executes when an http request for a specific resource is made to the server. For example, request an .aspx page the ASP.NET page handler is executed, similarly if an .asmx file is requested, the ASP.NET service handler is executed. An HTTP Handler is a component that handles the ASP.NET requests at a lower level than ASP.NET is capable of handling.

9). What is authentication tag/section in web.config?
ASP.NET implements additional authentication schemes using authentication providers, which are separate from and apply only after the IIS authentication schemes. ASP.NET supports the following authentication providers:

  • Windows (default)
  • Forms
  • Passport
  • None
To enable an authentication provider for an ASP.NET application, use the authentication element in either machine.config or Web.config as follows:

<system.web>
   <!-- mode=[Windows|Forms|Passport|None] -->
   <authentication mode="Windows" />
</system.web>


10). For which purpose you use <appSettings> tag?
AppSettings tag helps us to store the application settings information like connection strings, file paths, URLs, port numbers, custom key value pairs, etc.

<appSettings>
    <add key="ConnectionString" value="Data Srouce=....."/>
</appSettings>


11). What is the use of connectionStrings tag?
<ConnectionStrings> is the most common section of web.config file which allows you to store multiple connection strings that are used in the application.

<connectionStrings>
    <add name ="ConnectionString" connectionString ="Initial Catalog = dotnet;
        Data Source =localhost; Integrated Security = true"/>
</connectionStrings>


You can find more blogs on our website: Trigya Technologies

MVC Life Cycle



MVC Life Cycle
MVC Life Cycle

  1. Creating the request object: -The request object creation has four major steps. Below is the detail explanation of the same.
  2. Step 1 Fill route: - MVC requests are mapped to route tables which in turn specify which controller and action to be invoked. So if the request is the first request the first thing is to fill the route table with routes collection. This filling of route table happens in the global.asax file.
  3. Step 2 Fetch route: - Depending on the URL sent “UrlRoutingModule” searches the route table to create “RouteData” object which has the details of which controller and action to invoke.
  4. Step 3 Request context created: - The “RouteData” object is used to create the “RequestContext” object.
  5. Step 4 Controller instance created: - This request object is sent to “MvcHandler” instance to create the controller class instance. Once the controller class object is created it calls the “Execute” method of the controller class.
  6. Creating Response object: - This phase has two steps executing the action and finally sending the response as a result to the view.


You can find more blogs on our website: Trigya Technologies

Monday, 18 May 2020

CSharp MVC Interview Questions and Answers

CSharp MVC Interview Questions and Answers


To call only derived class method

namespace ConsoleApplication1
{
    class A
    {
        protected A()
        {
            Console.WriteLine("A is called");
        }
        void print()
        {
            Console.WriteLine("A's Print is called");
        }
    }
    class B : A
    {
        B()
        {
            Console.WriteLine("B is called");
        }
        new void print()
        {
            Console.WriteLine("B's Print is called");
        }
        static void Main(string[] args)
        {
            B p = new B();
            p.print();
        }
    }
}

Output:
A is called
B is called
B’s Print is called

Note: The access specifier for constructor A is applied because we need to achieve through inheritance and it won’t be accessible due to protection level if it is applied.



To call base and derived class method

namespace ConsoleApplication1
{
    class A
    {
        protected A()
        {
            Console.WriteLine("A is called");
        }
        protected void print()
        {
            Console.WriteLine("A's Print is called");
        }
    }
    class B : A
    {
        B()
        {
            Console.WriteLine("B is called");
        }
        protected void print()
        {
            base.print();
            Console.WriteLine("B's Print is called");
        }
        static void Main(string[] args)
        {
            B p = new B();
            p.print();
        }
    }
}

Output:
A is called
B is called
A’s Print is called
B’s Print is called

Note: To access the method of base class whose name is same. This can be achieve using base keyword.
If object of derived class is created and pointing reference towards to base then it will result to compile time error,
Cannot access protected member ‘A.print()’ via a qualifier of type ‘A’; the qualifier must be of type ‘B’.
If the base is abstract class then to the output will be same.

Static Constructor Example with Sequence:

namespace ConsoleApplication1
{
    class A
    {
        protected A()
        {
            Console.WriteLine("A is called");
        }
        static A()
        {
            Console.WriteLine("Static A's is called");
        }
    }
    class B : A
    {
        B()
        {
            Console.WriteLine("B is called");
        }
        static B()
        {
            Console.WriteLine("Static B's is called");
        }
        static void Main(string[] args)
        {
            B p = new B();
        }
    }
}

Output:
Static B’s is called
Static A’s is called
A is called
B is called

Note: Always derived class static constructor is called then base class static constructor will be called and so on.
If object of derived class is created and pointing reference towards to base class then to output will be same.



Abstract Class
Abstract class method can be abstract and non-abstract method.If we declaring any method in abstract class then the method should be prefixed will abstract keyword, the access specifier should be public or protected.To implement the abstract method, we should use override keyword with the same access specifier.

namespace ConsoleApplication1
{
    abstract class A
    {
        protected A()
        {
            Console.WriteLine("Abstract class constructor is called");
        }
        static A()
        {
            Console.WriteLine("Abstract class static constructor is called");
        }
        protected abstract void print();
        protected void display()
        {
            Console.WriteLine("Abstract class display method is called");
        }
    }
    class B : A
    {
        B()
        {
            Console.WriteLine("Derived class constructor is called");
        }
        protected override void print()
        {
            Console.WriteLine("Abstract method is called");
        }
        protected void display()
        {
            base.display();
            Console.WriteLine("Derived class display method is called");
        }
        static void Main(string[] args)
        {
            B p = new B();
            p.print();
            p.display();
        }
    }
}

Output:
Abstract class static constructor is called
Abstract class constructor is called
Derived class constructor is called
Abstract method is called
Abstract class display method is called
Derived class display method is called

Note: Creating object of Derived class and pointing reference to Base class will result to error.



Interface:
1.      An interface is a contract between itself and any class that implements it. This contract states that any class that implements the interface will implement the interface's properties, methods and/or events.
2.      An interface contains no implementation, only the signatures of the functionality the interface provides. An interface can contain signatures of methods, properties, indexers, and events.
3.      Using interface-based design concepts provides loose coupling, component-based programming, easier maintainability, makes your code base more scalable and makes code reuse much more accessible because the implementation is separated from the interface.
4.      Interfaces add a plug and play like architecture into your applications. Interfaces help define a contract (agreement or blueprint, however you chose to define it), between your application and other objects. This indicates what sort of methods, properties, and events are exposed by an object.

namespace ConsoleApplication1
{
    interface I1
    {
        void Paint();
    }
    interface I2
    {
        void Paint();
    }

    class A : I1I2
    {
        void I1.Paint()
        {
            Console.WriteLine("Paint method of I1 is called");
        }
        static void Main(string[] args)
        {
            A a = new A();
            I1 i1 = a;
            I2 i2 = a;
            i1.Paint();
            i2.Paint();

        }
        void I2.Paint()
        {
            Console.WriteLine("Paint method of I2 is called");
        }
    }
}

Output:
Paint method of I1 is called
Paint method of I2 is called




Action Filters:
1.      An action filter is an attribute that you can apply to a controller action -- or an entire controller -- that modifies the way in which the action is executed. 
2.      The ASP.NET MVC framework includes several action filters:
o   OutputCache – This action filter caches the output of a controller action for a specified amount of time.
o   HandleError – This action filter handles errors raised when a controller action executes.
o   Authorize – This action filter enables you to restrict access to a particular user or role.

The ASP.NET MVC framework supports four different types of filters:

1.      Authorization filters – Implements the IAuthorizationFilter attribute.
Authorization filters are used to implement authentication and authorization for controller actions. For example, the Authorize filter is an example of an Authorization filter.

2.      Action filters – Implements the IActionFilter attribute.
Action filters contain logic that is executed before and after a controller action executes. You can use an action filter, for instance, to modify the view data that a controller action returns.
The base ActionFilterAttribute class has the following methods that you can override:
·        OnActionExecuting – This method is called before a controller action is executed.
·        OnActionExecuted – This method is called after a controller action is executed.
·        OnResultExecuting – This method is called before a controller action result is executed.
·        OnResultExecuted – This method is called after a controller action result is executed.


3.      Result filters – Implements the IResultFilter attribute.
Result filters contain logic that is executed before and after a view result is executed. For example, you might want to modify a view result right before the view is rendered to the browser.

4.      Exception filters – Implements the IExceptionFilter attribute.
Exception filters are the last type of filter to run. You can use an exception filter to handle errors raised by either your controller actions or controller action results. You also can use exception filters to log errors.

Difference between static, constant and readonly
1.      Const
Const is nothing but "constant", a variable of which the value is constant but at compile time. And it's mandatory to assign a value to it. By default a const is static and we cannot change the value of a const variable throughout the entire program.
A const field requires a value to be provided.

2.      Readonly
Readonly is the keyword whose value we can change during runtime or we can assign it at run time but only through the non-static constructor.

3.      Static ReadOnly
A Static Readonly type variable's value can be assigned at runtime or assigned at compile time and changed at runtime. But this variable's value can only be changed in the static constructor. And cannot be changed further. It can change only once at runtime.




Main componenets of CLR:
·        Common Language Specification (CLS)
·        Common Type System (CTS)
·        Garbage Collection (GC)
·        Just In – Time Compiler (JIT)

Common Language Specification (CLS):It is responsible for converting the different .NET programming language syntactical rules and regulations into CLR understandable format. Basically, it provides the Language Interoperability. Language Interoperability means to provide the execution support to other programming languages also in .NET framework.
Language Interoperability can be achieved in two ways :
  i.          Managed Code: The MSIL code which is managed by the CLR is known as the Managed Code. For managed code CLR provides three .NET facilities:
                  ·          CAS(Code Access Security)
                  ·          Exception Handling
                  ·          Automatic Memory Management.
 ii.          Unmanaged Code: Before .NET development the programming language like .COM Components & Win32 API do not generate the MSIL code. So these are not managed by CLR rather managed by Operating System which is called unmanaged code.

Common Type System (CTS):Every programming language has its own data type system, so CTS is responsible for the understanding all the data type system of .NET programming languages and converting them into CLR understandable format which will be a common format.
There are 2 Types of CTS that every .NET programming language have :
a.      Value Types: Value Types will directly store the value directly into the memory location. These types work with stack mechanism only. CLR allots memory for these at Compile Time.
b.      Reference Types: Reference Types will contain a memory address of value because the reference types won’t store the variable value directly in memory. These types work with Heap mechanism. CLR allots memory for these at Runtime.

Garbage Collector:It is used to provide the Automatic Memory Management feature. Suppose if there is no garbage collector then programmers have to write the memory management codes which will be a kind of overhead on programmers.

JIT(Just In Time Compiler):It is responsible for converting the CIL(Common Intermediate Language ) into machine code or native code using the Common Language Runtime environment.
Benefits of CLR:
·        It improves the performance by providing a richly interact between programs at the run time.
·        Enhance portability by removing the need of recompiling a program on any operating system that supports it.
·        Security also increases as it analyzes the MSIL instructions whether they are safe or unsafe. Also, the use of delegates in place of function pointers enhance the type safety and security.
·        Support automatic memory management with the help of Garbage Collector.
·        Provides cross-language integration because CTS inside CLR provides a common standard that activates the different languages to extend and share each other’s libraries.
·        Provides support to use the components that developed in other .NET programming languages.
·        Provide language, platform, and architecture independency.
·        It allows the creation of the scalable and multithreaded applications in an easier way as a developer has no need to think about the memory management and security issues.



REF KEYWORD
OUT KEYWORD
It is necessary the parameters should initialize before it pass to ref.
It is not necessary to initialize parameters before it pass to out.
It is not necessary to initialize the value of a parameter before returning to the calling method.
It is necessary to initialize the value of a parameter before returning to the calling method.
The passing of value through ref parameter is useful when the called method also need to change the value of passed parameter.
The declaring of parameter through out parameter is useful when a method return multiple values.
When ref keyword is used the data may pass in bi-directional.
When out keyword is used the data only passed in unidirectional.


Managed Code:
The code, which is developed in .NET framework, is known as managed code. This code is directly executed by CLR with help of managed code execution. Any language that is written in .NET Framework is managed code. CLR looks after your applications by managing memory.

Unmanaged Code:
Applications that do not run under the control of the CLR are said to be unmanaged, and certain languages such as C++ can be used to write such applications.

Private:These members are available to containing type(class) it is not accessible to outside of the class.
Public : These members are available to any where there is no restrictions.
Protected: These members are available to the existing class as well as to the derived classes.
Internal: It is available anywhere within the containing assembly but gives a compile time error if it is accessed through different assembly.
Protected internal: these members are available anywhere in the assembly and also to the other assembly to the derived class.

Boxing:
1.      The process of Converting a Value Type (char, int etc.) to a Reference Type(object) is called Boxing.
2.      Boxing is implicit conversion process in which object type (super type) is used.
3.      The Value type is always stored in Stack. The Referenced Type is stored in Heap.
Example :
int num = 23; // 23 will assigned to num
Object Obj = num; // Boxing

UnBoxing:
1.      The process of converting reference type into the value type is known as Unboxing.
2.      It is explicit conversion process.
Example :
int num = 23;         // value type is int and assigned value 23
Object Obj = num;    // Boxing
int i = (int)Obj;    // Unboxing




Singleton Design Pattern:

class Singleton
{
    private static Singleton obj;
  
    // private constructor to force use of
    // getInstance() to create Singleton object
    private Singleton() {}
  
    public static Singleton getInstance()
    {
        if (obj==null)
            obj = new Singleton();
        return obj;
    }
}

What is the difference between “HTML.TextBox” and “HTML.TextBoxFor”?

Both provide the same HTML output, “HTML.TextBoxFor” is strongly typed while “HTML.TextBox” isn’t.     Below is a simple HTML code which just creates a simple textbox with “FirstName” as name.

Html.TextBox("FirstName ")
Below is “Html.TextBoxFor” code which creates HTML textbox using the property name ‘FirstName” from object “m”.

Html.TextBoxFor(m => m.CustomerCode)
In the same way, we have for other HTML controls like for checkbox we have “Html.CheckBox” and “Html.CheckBoxFor”.

What is the difference between Temp data, View, and View Bag?
In ASP.NET MVC there are three ways to pass/store data between the controllers and views.

ViewData
ViewData is used to pass data from controller to view.
It is derived from ViewDataDictionary class.
It is available for the current request only.
Requires typecasting for complex data type and checks for null values to avoid error.
If redirection occurs, then its value becomes null.

ViewBag
ViewBag is also used to pass data from the controller to the respective view.
ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0
It is also available for the current request only.
If redirection occurs, then its value becomes null.
Doesn’t require typecasting for complex data type.

TempData
TempData is derived from TempDataDictionary class
TempData is used to pass data from the current request to the next request
It keeps the information for the time of an HTTP Request. This means only from one page to another. It helps to maintain the data when we move from one controller to another controller or from one action to another action
It requires typecasting for complex data type and checks for null values to avoid error. Generally, it is used to store only one time messages like the error messages and validation messages.


What is the use of Keep and Peek in “TempData”?
Once “TempData” is read in the current request it’s not available in the subsequent request. If we want “TempData” to be read and also available in the subsequent request then after reading we need to call “Keep” method as shown in the code below.
@TempData["MyData"];
TempData.Keep("MyData");
 The more shortcut way of achieving the same is by using “Peek”. This function helps to read as well advices MVC to maintain “TempData” for the subsequent request.
string str = TempData.Peek("MyData ").ToString();

Action Result
Helper Method
Description
ViewResult
View
Renders a view
PartialViewResult
PartialView
Renders a partial view, which is a view which can be used inside another view.
RedirectResult
Redirect
Redirects to different action method as specified in the URL.
RedirectToRouteResult
 RedirectToRoute
Redirects to another action method.
ContentResult
Content
Returns the user supplied content type.
JsonResult
Json
Returns a JSON object.


You can find more blogs on our website: Trigya Technologies

Steps to resolve VAPT Issues

    1. Error: Web Parameter Tampering Resolution:   Add attribute " enableViewStateMac = " false " " inside  <pages...