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