Search This Blog

Friday, July 22, 2022

Encryption and Decryption of configuration section/web.config section

 We keep some application data in configuration file like app settings, connection strings and many more. It may be some sensitive data like database credentials, SMTP credentials etc., and storing these information in config file as a plain text is not a good idea. To keep these information secure, we should encrypt and then store. 

Before doing the encryption/decryption make sure you are following the proper file naming convention. 

  • Make sure the configuration section content is in a "web.config" file.
  • if not, rename it to the "web.config" file before performing encryption/decryption.
Note: The encryption / decryption must happen on the same machine where it is being used.

Encryption

We will encrypt the below config file's appSettings section in our example.



Lets do the following steps to encrypt the appSettings section of the above configuration file.

  1. Open the command prompt as administrator
  2. Type "c:\windows\Microsoft.NET\Framework\<specificversion>" and press ENTER. Note: "specificversion" is .Net framework version
  3. Type the following command and ENTER
    aspnet_regiis.exe -pef  "<configuration section>" "<Configuration file physical location>"  -prov "<protection configuration provider>"
    • Configuration section - The config section name which you want to encrypt like appSettings, connectionString etc.
    • Configuration file physical location - Web.config file location
    • Protection configuration provider - The encryption take place differently according to provider like "DataProtectionConfigurationProvider" or "RsaProtectedConfigurationProvider".

      Example:
      aspnet_regiis.exe -pef  "appSettings" "c:\encryptionDemo"  -prov "RsaProtectedConfigurationProvider"
  4. After the step 3, the appSettings section in web.config file present at "c:\encryptionDemo" will get encrypted.
The encrypted config file will look like as below-



 


Decryption

The encrypted config section can be decrypted using the following command line.

aspnet_regiis.exe -pdf "appSettings" "c:\encryptionDemo"

The decrypted file will look like -




Conclusion

It is always recommended to store the sensitive data in configuration file as encrypted form only otherwise it can be compromised. Here we went through the very basic way of encryption / decryption. We can do in depth and secure level of encryption and decryption like use-account level and machine-level encryption and decryption.

Sunday, April 12, 2020

ng : File D:\Users\userName\AppData\Roaming\npm\ng.ps1 cannot be loaded because running scripts is disabled on this

Whenever this error comes do the following setting -


  • Open PowerShell as Adminstrator.
  • Run: Set-ExecutionPolicy -ExecutionPolicy Unrestricted

Wednesday, January 2, 2019

Web Security : What is HTTP header "referrer-policy" and why is it important?

By default, the browsers send the current URL path to the next request in HTTP header "referer" no matter whether the request is for the same origin or to other 3rd party origins. If the request is for the same origin then the sending path information is not an issue at all but if it is for 3rd party origin(3rd party web site) then its a big issue because your current URL may have the sensitive information like user id, entity related info .. etc it could be anything which you would not like to pass in referer header or you would like to pass some limited info only instead of whole URL path. We can achieve this using the HTTP header "Referrer-Policy" with some directives like 'no-referrer', 'no-referrer-when-downgrade', 'origin', 'strict-origin' etc.

The browser's default referrer policy is "no-referrer-when-downgrade" it means the browser will send the referer header if transport protocol level is same otherwise referer header will not be sent in HTTP request header

In below example the URL path with data is being sent in referer header "Referer: http://localhost:4200/home?userid=2334"


Always return the referer policy as "no-referrer" in every web response so that the browser doesn't attach the URL path in the request referer header. Similarly, there are few more referrer-policy directives, see the details in below table.

Policy(Directives) Descriptions Source Destination(Navigation to) Referrer Header
no-referrer Referer header will not be included in request header https://example.com/page.html any domain or path no referrer
no-referrer-when-downgrade This is the user agent's default behavior if no policy is specified. The URL is sent as a referrer when the protocol security level stays the same (HTTP -→ HTTP, HTTPS -→HTTPS), but isn't sent to a less secure destination (HTTPS -→ HTTP). Always return the referer policy as "no-referrer" in every web response so that the browser doesn't attach the URL path in the request referer header. Similarly, there are few more referrer-policy directives, see the details in below table. https://example.com/page.html https://example.com/otherpage.html https://example.com/page.html
https://example.com/page.html https://mozilla.org https://example.com/page.html
https://example.com/page.html http://example.org no referrer
origin This policy allows to send the domain details only in request header https://example.com/page.html any domain or path https://example.com/
origin-when-cross-origin Allows to send the whole URL path if the source and destination's origin is same otherwise send the domain details only https://example.com/page.html https://example.com/otherpage.html https://example.com/page.html
https://example.com/page.html https://mozilla.org https://example.com/
https://example.com/page.html http://example.com/page.html https://example.com/
same-origin It allows sending the referer header in request header if the source and destination's origin same otherwise doesn't include referrer header in the request header https://example.com/page.html https://example.com/otherpage.html https://example.com/page.html
https://example.com/page.html https://mozilla.org no referrer
strict-origin Only send the origin of the URL path as the referrer when the protocol security level stays the same (HTTPS→HTTPS), but don't send it to a less secure destination (HTTPS→HTTP) https://example.com/page.html https://mozilla.org https://example.com/
https://example.com/page.html http://example.org no referrer
http://example.com/page.html any domain or path http://example.com/
strict-origin-when-cross-origin Send a full URL path when performing a same-origin request, only send the origin when the protocol security level stays the same (HTTPS→HTTPS) and origins(source and destination) are different and send no header to a less secure destination (HTTPS→HTTP). https://example.com/page.html https://example.com/otherpage.html https://example.com/page.html
https://example.com/page.html https://mozilla.org https://example.com/
https://example.com/page.html http://example.org no referrer
unsafe-url Send a full URL when performing a same-origin or cross-origin request https://example.com/page.html?q=123 any domain or path https://example.com/page.html?q=123

For more detail please visit on https://scotthelme.co.uk/a-new-security-header-referrer-policy/

Conclusion

The Referrer-Policy, response header, restricts to being passed the URL path information through the referrer header in the request header

Monday, December 31, 2018

Web Security: what does mean by http header 'X-Content-Type-Options=nosniff' ?

Before going in details about this HTTP header, let's have a look into how the browser process the content type of a file received from the web server. Whenever a file received from the server by default browser determine its content type by checking the content of file irrespective of file extension and content-type header provided by the server(this is called content sniffing).

Example: Let's save the below HTML content as the zip file (test.zip)

<html>
   <head>
     <script
type="text/javascript" >
       alert("OK");
     </script>
   </head>
   <body>
   </body>
</html>


When you browse the file "test.zip" from your IE browser you will get an alert popup with message "OK" instead of downloading it eventhough the content-type sent by server is "application/x-zip-compressed" and extension is zip.



Now change the content of the file with some normal plain text and browse it. This time you will that it is prompting for download(see as below)



Now we can conclude here as per the above example that the browser does the content checking to decide the content type of the received file before rendering.

It means a channel is open for cross-site-scripting(XSS). Any attacker can play with the content of the file, hence the web application is vulnerable. To overcome on this vulnerability, first Microsoft introduced the below HTTP header with directive "nosniff" which tells the browser to not check the content type of the file and just trust content-type sent by the web server, and later the almost browser implemented this HTTP header.

X-Content-Type-Options : nosniff

Conlusion: To stop the browser from content sniffing, it is recommended to set your web server to return the HTTP header "X-Content-Type-Options : nosniff" in every response. This will prevent from cross-site-scripting(XSS)

Friday, December 28, 2018

Web Security: Why do we need http header "Strict-Transport-Security"?

Web Security: Why do we need to use http header "Strict-Transport-Security"? It is possible that a web site can allow user to access it via HTTP and HTTPS both. In this case user can browse the web site either using Http or using https, we can enforce the connection to use https instead of http by adding HSTS (HTTP Strict-Transport-Security ) policy in web site response header. This header tells browser to use Https even though the user is trying to access it through http. Lets achieve this in following way -

Add the below header in your web site response header -

Strict-Transport-Security: max-age=<expiry-time in seconds>; includeSubDomains; preload

  • max-age=<expiry-time in seconds>: Browser remember this expiry time, this can be any duration in second for days, months or years.
  • includeSubDomains[optional]: This is optional directive, its presence in this header tells browser to apply the same rule (hsts rule) for sub domains as well.
  • preload[optional]: This is optional and is not the part of the specification.

Technical Implementation:
  • In ASP.Net Core
    Use any of the below approach to implement hsts.
    Approach 1: Use inbuild Hsts middleware(default configuration). This implementation has the 30 days value into max-age parameter by default

    public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
    app.UseHsts(); }

    If you want to override the default setting, add below configuration as well
    public void ConfigureServices(IServiceCollection services)
    {
      services.AddHsts(options=>{
           options.Preload = true;
           options.MaxAge= TimeSpan.FromDays(365);//for one years
           options.IncludeSubDomains = true;
           options.ExcludedHosts.Add("example.com");
           options.ExcludedHosts.Add("www.example.com");
       });

      services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    }

    Approach 2: Add it manually in response header as below

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
       app.Use(async( context, next)=>
       {
           context.Response.Headers.Add("Access-Control-Allow-Origin","http://localhost:4200");
           context.Response.Headers.Add("Strict-Transport-Security","max-age=86400;includeSubDomains;preload");
           await next.Invoke();
       });
       app.UseMvc();
    }
  • In ASP.Net
    Add the custom header in web.config as below to implement hsts in ASP.Net and MVC
    <system.webServer >
      <httpProtocol >
        <customHeaders >
          <add name="Strict-Transport-Security" value="max-age=31536000" / >
        </customHeaders >
      </httpProtocol >
    </system.webServer >

Note: The Strict-Transport-Security header is ignored by the browser when your site is accessed using HTTP; this is because an attacker may intercept HTTP connections and inject the header or remove it. When your site is accessed over HTTPS with no certificate errors, the browser knows your site is HTTPS capable and will honor the Strict-Transport-Security header.



Benefit of Hsts policy

It helps in minimizing the man-in-the-middle-attack till some extends. See the below example scenario described on https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security#Preloading_Strict_Transport_Security

Example Scenario:

You log into a free WiFi access point at an airport and start surfing the web, visiting your online banking service to check your balance and pay a couple of bills. Unfortunately, the access point you're using is actually a hacker's laptop, and they're intercepting your original HTTP request and redirecting you to a clone of your bank's site instead of the real thing. Now your private data is exposed to the hacker.

Strict Transport Security resolves this problem; as long as you've accessed your bank's web site once using HTTPS, and the bank's web site uses Strict Transport Security, your browser will know to automatically use only HTTPS, which prevents hackers from performing this sort of man-in-the-middle attack.


Thursday, December 27, 2018

Web API : How to enable CORS in web api (.net core)?

The browsers don't allow the cross-origin-resource-sharing(CORS) for the security reasons. But nowadays almost websites use the APIs hosted on different origin. To overcome from this problem we need to do the below setting at API side to allow the CORS.
  1. Check if the package "Microsoft.AspnetCore.Cors" is installed into the web api project otherwise install it either from nuget package manager or from below command line in VS Code/ Command --

    dotnet add package Microsoft.AspnetCore.Cors

  2. Open Startup.cs file and do the below setting

    public void ConfigureServices(IServiceCollection services)
    {
       services.AddCors();
      services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
      ...
      app.UseCors(options=> options.WithOrigins("http://www.domainexample.com").AllowAnyMethod() );

      //If you are in development phase or you don't who ever is using you API then the below setting is recommended
      //app.UseCors(options=> options.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());

      ...
    }
    In above code "http://www.domainexample.com" could be any valid domain for which it needs to enable CORS .

Friday, December 29, 2017

BAD_SYSTEM_CONFIG_INFO

The error "BAD_SYSTEM_CONFIG_INFO" comes on the blue screen while booting your windows system and does not allow you to start your system. This could be because you have set all cores(processors) from msconfig tool to speed up your system.

To resolve this issue please follow the below steps:-

  1. Restart your system and press F8 to choose the start option
  2. Choose Repair option
  3. Select keyboard language
  4. Provide Administration login details
  5. Select "Command Prompt" from the repair option
  6. Select keyboard language
  7. Exdecute below command lines in Command Prompt

    bcdedit/deletevalue {default} numproc
    bcdedit/deletevalue {default} truncatememory

  8. Now Close Command promt window
  9. and Restart your machine

Saturday, December 16, 2017

The URL 'http://localhost/xxx' for Web project 'xxx' is configured to use IIS Express as the web server but the URL is currently configured on the local IIS web server. To open this project, you must use IIS Manager to remove the bindings using this URL from the local IIS web server



When you face the following error while loading your web project, please set the value of "UseIISExpress" to "false" in both file ".csproj" and ".csproj.user". After doing this setting reload your project and it will get loaded successfully.

ERROR : The URL 'http://localhost/xxx' for Web project 'xxx' is configured to use IIS Express as the web server but the URL is currently configured on the local IIS web server. To open this project, you must use IIS Manager to remove the bindings using this URL from the local IIS web server.

Sunday, June 11, 2017

Design Pattern : What is unit of work pattern?

Unit of work pattern is the concept to provide single transaction of multiple works(like insert, update, delete and so on.. ) of an entity as well as of multiple entities which has to be done into database in single go. If any one of the activities get failed then non of the activities will get executed in database, in short entire transaction will be roll backed.

Unit of Work design pattern does two important things: first it maintains in-memory updates and second it sends these in-memory updates as one transaction to the database.

So to achieve the above goals it goes through two steps:

  • It maintains lists of business objects in-memory which have been changed (inserted, updated, or deleted) during a transaction.
  • Once the transaction is completed, all these updates are sent as one big unit of work to be persisted physically in a database in one go.

See the below flow of transaction without unit of work and with unit of work

How to implement unit of work pattern in C#

The way to implement this pattern is as :

  1. Define an interface for repository to declare database operation.[Note: I will recommend a generic interface ]
  2. Create a class and implement repository interface.
  3. Create a class for unit of work.
  4. Access and implement unit of work in business logic
Step 1: Define Interface

create a interface to define database operations.

Step 2: Create Repository class

Implement operations defined in above IRepository interface. And create constructor to accept dbContext as parameter.

Step 3: Create Unit of Work class

Unit of work class has the responsibility to provide instance of dbContext to repository(shown as below).

Unit of work class has the three activities

  1. Create instance of dbContext
  2. Create instance of repositories against this single instance of dbContext
  3. Save the changes of dbContext into database(changes could be of one or more repositories)

Step 4: Access and implement unit of work in business logic

In below order class, instance of unit of work class is created to handle all type of communication with database. Here in AddOrder method two instances are created on for order and second for customer details. And both entity is saved into database as a single work unit.

Sunday, May 28, 2017

Design Pattern : What is repository pattern?

Repository Pattern separates the data access logic and maps it to the entities in the business logic. It works with the domain entities and performs data access logic. In the Repository pattern, the domain entities, the data access logic and the business logic talk to each other using interfaces. It hides the details of data access from the business logic. In other words, business logic can access the data object without having knowledge of the underlying data access architecture. For example, in the Repository pattern, business logic is not aware whether the application is using LINQ to SQL or ADO.NET Entity Model ORM. In the future, underlying data sources or architecture can be changed without affecting the business logic.

There are various advantages of the Repository Pattern including:

  • Business logic can be tested without need for an external source
  • Database access logic can be tested separately
  • Database access logic will hide the data access implementation details to the business logic(will create an abstraction between data access logic and business logic)
  • Business logic will not get impacted from the any changes happened in data access logic
  • No duplication of code
  • Caching strategy for the datasource can be centralized
  • Domain driven development is easier
  • Centralizing the data access logic, so code maintainability is easier

Repository acts as a mediator between business logic and data source(database).

How to Implement Repository pattern in C#

The way to implement repository pattern in any application is as:
  1. Define an interface for the repository.The interface declares the database operations.
  2. Create a class which implements the above interface and provides the implementation for the interface methods
  3. Access the repository from the business layer through the interface.

Step 1 : Define interface

Its highly recommended that an architecture must create a generic repository interface only.

Step 2 : Create Repository

Implement the database operation defined in step 1(IRepository)

In above code EntityBase is a base class for all entities which has an ID property of type Int.

Step 2 : Access repository from business logic

To access repository from business logic, create an instance of repository in business logic and use it as per requirement.

Monday, May 22, 2017

Javascript: How to encode and decode HTML using javascript?

Using below jquery code you can encode HTML

function htmlEncode(value){
  //create a in-memory div, set it's inner text(which jQuery automatically encodes)
  //then grab the encoded contents back out.  The div never exists on the page.
  return $('<div/>').text(value).html();
}

function htmlDecode(value){
  return $('<div/>').html(value).text();
}

htmlEncode('<b>test</b>')
// result"&lt;b&gt;test&lt;/b&gt;"

Friday, February 10, 2017

HTML: Unicode Decimal code for Indian Rupee Sign

To display Indian currency symbol, ₹ , in your HTML page you can use one of below code
&#8377
or
&#x20B9

Tuesday, December 27, 2016

Kendo: How to clear or reset kendo grid sorting without firing data read?

To clear sorting setting in kendo grid reset sort array with blank object .
var grid = $("#UsersGrid" );

if (grid.data("kendoGrid" ).dataSource != null) {

  if (grid.data("kendoGrid" ).dataSource._sort != null && grid.data("kendoGrid" ).dataSource._sort != undefined)
  {
    grid.data("kendoGrid" ).dataSource._sort[0] = {};
  }

}

Thursday, December 15, 2016

How to generate proxy class from WCF/ASMX using svcutil?

Generate proxy class for WCF

svcutil http://localhost/MyService/ClassName.svc /Language=c# /t:Code /out:ClassNameProxy.cs /config:ClassNameProxy.config


Generate proxy class for ASMX web service


svcutil http://localhost/MyService/ClassName.asmx /Language=c# /t:Code /out:ClassNameProxy.cs /config:ClassNameProxy.config

Note: This command line use runtime serializer by default. To use other serializer like xml serializer user /serializer: attribute in command line as below-

SvcUtil.exe http://localhost/MyService/ClassName.asmx /serializer:XmlSerializer /out:"d:Projects\ClassNameProxy.cs" /config:"d:\projects\ClassNameProxy.config"

Thursday, June 30, 2016

Monday, June 13, 2016

How to enable PUT and DELETE http methods in Web API?

Add below setting in web.config inside <system.webServer> tag to enable PUT and DELETE HTTP methods in web api.


<modules runAllManagedModulesForAllRequests="true">
          <remove name="WebDAVModule"/>
</modules>

Thursday, March 10, 2016

How to call WCF service from classic ASP

DIM xmlhttp, response, objRequest, txtRequest, test
DIM url : url = "http://www.example.com/Services/Service1.svc"



txtRequest = "<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:tem=""http://tempuri.org/"">" & _
        "<soapenv:Header/>" & _
        "<soapenv:Body>" & _
          "<tem:GetVehicleStatus>" & _
            "<tem:OrgId>111</tem:OrgId>" & _
            "<tem:VehicleId>555</tem:VehicleId>" & _
          "</tem:GetVehicleStatus>" & _
        "</soapenv:Body>" & _
      "</soapenv:Envelope>"

set xmlhttp = CreateObject("MSXML2.ServerXMLHTTP")

'xmlhttp.setOption 2, 13056 'ignore certificate errors for development machines
xmlhttp.open "POST", url, false
xmlhttp.setRequestHeader "Content-Type", "text/xml;charset=UTF-8"
xmlhttp.setRequestHeader "SOAPAction", "http://tempuri.org/Services/GetVehicleStatus"
xmlhttp.send txtRequest
response = xmlhttp.responseText
Response.Write (xmlhttp.status& ":::"& xmlhttp.statusText) & "response:::"& response

Tuesday, May 19, 2015

How to validate form using JQuery?

To validate a form use below code
var frmX = $("#formName");

var IsValid = frmX.valid();

Note: .valid() method validate the form and return boolean value which shows whether the form is valid or not.....

Saturday, March 21, 2015

How to create an ASPState session database?

Execute following command line to add ASpState database.

C:\%windir%\Microsoft.NET\Framework\\aspnet_regsql.exe -S ServerName -E -ssadd -sstype p

Friday, February 20, 2015

How to change database to single user mode as well as multi-user mode?

A. To change your database mode to single user mode execute below sql script
ALTER DATABASE Databasename SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

b. To change your database mode to multi-user mode execute below sql script
ALTER DATABASE Databasename SET MULTI_USER WITH ROLLBACK IMMEDIATE;