Monday, October 17, 2016

.NET Core with a Linux server: Hello World!



Hello World in .NET Core Ubuntu


Let’s start our first application on .NET Core - Ubuntu.

Create a new project














Create a folder in your desktop, myprojects, go inside of it and create a new project using the 'dotnet new' command.

You can see Program.cs and project.json file is created. To build our first project in .NET Core, let’s install the Visual Studio Code editor.

Install Visual Studio Code















Download the correct version of Visual Studio Code relevant to Ubuntu and install it.






















Go to your project location and open your project in Visual Studio Code. It shows a message to install an extension. Extensions allow you to add languages, debuggers and tools to your development environment, Click on Show Recommendations to view recommended extensions.











Select C# powered by Omnisharp, since we are using C# code in .NET Core. It provides IntelliSense for .NET. Omnisharp provides a set of tooling and libraries to IDEs like Visual Studio Code, Sublime, Atom, Emacs, Vim and Brackets. After installing the C# extension, enable it.




















program.cs file shows entry point to the application as usual.

project.json File



























project.json file shows NuGet dependencies required to build the application.

Let’s see what is the meaning of these attributes in the project.json file:
  • version”: “1.0.0-* specifies the version of .NET Core. It says version should start with 1.0.0.
  • buildOptions defines how the project should be built.
  • dependencies list all the dependencies in your application.
  • frameworks defines a target framework that will be used with specific dependencies.
  • imports defines where our application runs, When we add dnxcore50 , it says we are running in Core CLR on the dnx.








You can see a message to install build and debug assets, install them. And another message to restore the packages in project.json, restore them as well.













After adding an Assets folder, you can see .vscode folder with launch.json and tasks.json files. All the build errors are gone. Check the output window. It shows package restore is completed.

project.lock.json File





















































After packages restoring is completed, project-lock.json file has been added to the solution.

It’s going to capture entire dependency graph that your application depends on. In the project.json file, you define the top level dependencies, a more detailed level description is available in project-lock.json file.

launch.json File























This file is going to confgure debugging and running in the application. In this example, it’s going to launch the .NET Core console or even we can attatch to .NET Core console.

tasks.json File


























This file is used to automate tasks like building, packaging, testing and deploying software. In this example, it defines a build task and specifies to run as a build command.

Hello World in the terminal

















That’s all we want to know about the .NET Core application, Let’s see the output of our first application, When we run with 'dotnet run' command, it shows the output of the application.

Download Source

TechNet Gallery


GitHub


Saturday, September 24, 2016

Install .NETCore in a Linux server


Install .NETCore on Ubuntu


In .NET framework history, .NET have its full framework from .NET 1.0 to .NET 4.6.2, specially created for windows platform. Latest version of .NET framework is .NET 4.6.2 up to now, In the end of June Microsoft released a new .NET framework called .NET Core for Windows, Linux and Mac. A great feature of .NET core is, a solution build on windows can be run and modify in a linux based environment. We can build an application on Windows, and can host it in a Linux server.

Add dot net apt-get feed












Setup the apt-get feed and update it.

apt-get is a free package manager program. It works with Ubuntu’s APT (Advanced Packaging Tool). Using that command line program, We can Install new packages, remove or upgrade packages.

For this example, I used Ubuntu 16.04, run these commands,

sudo sh -c ‘echo “deb [arch=amd64] https://apt-mo.trafficmanager.net/repos/dotnet-release/ xenial main” > /etc/apt/sources.list.d/dotnetdev.list’


sudo apt-key adv –keyserver apt-mo.trafficmanager.net –recv-keys 417A0893

Then update apt-get feed Using following command,

sudo apt-get update


Install .NETCore top of apt-get






















Install .NETCore using following command,

sudo apt-get install dotnet-dev-1.0.0-preview2-003121

















Check whether .NETCore is properly installed using dotnet command. It shows .NETCore version as 1.0.1


Tuesday, August 30, 2016

C#: How to generate a unique key or password using salting + hashing

1. Introduction


When an application develops, we need to protect user passwords from security attacks. When your application operates on a license key, we need to validate the license.

In today's world providing security to your system is bit crucial. We have to face malicious scripts, security threats and unwanted attacks in out there. Let’s see how we can prevent those kind of attacks.


2. Password Hashing


In hashing, we are going to convert password string into a byte array. Hashing is a one way function, we can’t reverse it. We can see many hashing algorithms available.

Let’s say we hashed the users password and stored in our database. When user second time logs in, we have to verify entered password is correct. What we can do is, we can hash the entered text into password field and compare it with the hashed value from the database. Since Hashing is a one way function, we can’t decrypt and retrieve original text.


2.1. Invalid username or password


When user enters wrong password, System should not let the user know it’s Invalid password , instead of it should tell Invalid username or password . Then if hacker tries to login into your system, he doesn’t know whether username or password got wrong.


2.2. Hash Functions


SHA1, MD5 are popular hashing algorithms. SHA1 got inspired from MD algorithms and created SHA algorithms. From these two algorithms, better to use SHA1, Because it’s high secure than MD5. MD5 is going to convert a string into 128 bits. But SHA1 convert a string into 160 bits. In MD5 less no of operations required to crack the message, when compared to SHA1. But MD is faster than SHA1. However it’s better to use SHA1 algorithm instead of MD5, since MD5 can be broken easily.


2.3. Hashes can be cracked easily


Hackers can guess passwords and simply hash them with a hashing algorithm and try it in your system. It takes few seconds to generate a hash. Within a limited amount of time, your passwords can be cracked easily. These type of guessing password and hashing is called as Dictionary attacks and Brute force attacks.

In dictionary attacks, it uses a file with some words. These words can be extracted from a database or else from set of paragraphs. Most hackers guess passwords from common terms like, hello, hellow, he11o3 etc. They take a string and try to replace letters in it, like hello, he33o, heiio, etc. Then these words are hashed and use against the password hash.

Brute Force attacks going to try out every possible of character combinations to a certain string length. It’s a very expensive computational process, But eventually it’s going to find out your password! That’s why we need lengthier passwords, So it will take long time to crack your passwords.

By hashing your passwords, We can’t prevent Dictionary attacks or Brute force attacks, But we can minimize them.

While Dictionary attacks and Brute force attacks are time consuming, Hackers has another kid in their block, It’s Lookup Table. In Lookup table, It’s going to precompute the hashes of passwords and used to store them in a dictionary file. So hundreds of guesses can be done in a second. It’s a very effective method to crack your passwords.

Rainbow Tables, Beware guys, it can crack any 8 characters lengthy MD5 password. Rainbow table is same as Lookup table. In here hash cracking speed is slower, compared to lookup table. But lookup table size is smaller, so more hashes can be stored in the same space. So Rainbow tables are more effective than Lookup tables.


2.4. Salted Password Hashing


If we use a salt with password hashing, It’s impossible to crack your passwords through Rainbow tables and lookup tables. In lookup tables, hackers are going to hash same list of passwords and try out in your system. Let’s say two users are having same password in your system. When we hash these passwords, It’s same password hash. In Salting, we are adding a random number along with hashed password. So two users never get same salted password hash. And mind you don’t use same salt with different user passwords, don’t repeat the salting. If new user registers into your system or else change password, generate a new salt. Use a new salt for every user password. If hacker is smart enough, He may be able to crack a one or two user passwords, But not more than that. Even though many users have same password, Hacker will not be able to crack their passwords using a lookup table. Don’t use shorter salt, Then hacker can create a lookup table to generate every possible salt.


2.5. Let’s see how we can generate a unique key


























public class AuthenticationValidator
 {
      KeyGeneratorContext context = new KeyGeneratorContext();
      public bool GenerateSubscriptionKey(string userName, int companyCode)
      {
          bool isSuccess = false;
          byte[] salt = GenerateSalt();
          Company company = context.Companies.Where(c => c.Code == companyCode).FirstOrDefault();
          User user = context.Users.Where(u => u.CompanyId == company.Id && u.UserName == userName).FirstOrDefault();
          string[] hashKeys = GenerateHashKey(userName, companyCode).Split(':');
          Rfc2898DeriveBytes value = new Rfc2898DeriveBytes(hashKeys[0] + hashKeys[1], salt);
          byte[] key = value.GetBytes(64);
          user.Subscription = key;
          user.SaltValue = salt;
          isSuccess = context.SaveChanges() > 0;
          return isSuccess;
   }
    private static byte[] GenerateSalt ()
    {
        int saltLength = 32;
        byte[] salt = new byte[saltLength];
        using (var random = new RNGCryptoServiceProvider())
        {
           random.GetNonZeroBytes(salt);
        }
       return salt;
   }
   private string GenerateHashKey(string userName, int companyCode)
   {
      string key = string.Empty;
      Company company = context.Companies.Where(c => c.Code == companyCode).FirstOrDefault();
      User user = context.Users.Where(u => u.CompanyId == company.Id && u.UserName == userName).FirstOrDefault();
      if (company != null && user != null)
         key = company.Name + ":" + user.UserGuid;
      return key;
    }

In this example, we are passing username and company code to generate a license key. Using GenerateSalt method, we can generate a random number. I used to create a 32 bytes length salt number using RNGCryptoServiceProvider class. Using Rfc289DeriveVytes class we can generate a salted hashing value. Along with the generated license key, we used to store salted number as well.


2.6. Let’s see how we can validate the license key



















public bool ValidateSubscriptionKey(string userName, int companyCode)
{
    bool isValid = false;
    byte[] subscription = new byte[64];
    byte[] saltValue = new byte[32];
    Company company = context.Companies.Where(c => c.Code == companyCode).FirstOrDefault();
    if (company != null)
     {
        User user = context.Users.Where(u => u.CompanyId == company.Id && u.UserName == userName).FirstOrDefault();
        if (user != null)
         {
            subscription = user.Subscription;
             saltValue = new byte[32];
          }
        string[] hashKeys = GenerateHashKey(userName, companyCode).Split(':');
        Rfc2898DeriveBytes value = new Rfc2898DeriveBytes(hashKeys[0] + hashKeys[1], saltValue);
        byte[] key = value.GetBytes(64);
        bool result = subscription.SequenceEqual(key);
        if (result && user.ExpiryDate >= DateTime.Now)
          isValid = true;
      }
     return isValid;
   }

I used 64 byte array as a license key and 32 byte array as a salted value. We can use SequenceEqual method to compare entered license key with stored license key as above.


3. Download

3.1. TechNet Gallery




3.2. GitHub




4. Conclusion


This article explains various mechanisms to secure valuable data. If you go through the code sample, It explains how to secure a license key using salted hashing mechanism.


5. References




Tuesday, July 19, 2016

How to fire an email using a windows service

1. Introduction


If you want to schedule something to run or your program takes long time to process, Sometimes we may have to create a separate service application,

Windows service allows a long running application to run in a own windows process. These services can be managed thorough a services portal available in Windows. A service can be started, stopped, paused or restarted by automatically as well as manually.

I wanted to write an application to send emails in specific time periods, I thought of writing a windows service application.

We can install this service in your server or local computer and configure it to run on intervals using a timer.


2. Create a Windows service


When we create a windows service from visual studio, It gives us a service class with constructor method, OnStart and OnStop methods as follows.












public Scheduler()
{
}
protected override void OnStart(string[] args)
{
}
protected override void OnStop()
{
}


2.1. Scheduling the task with a timer


When program needs to periodically perform a task, for that it needs a timer component, add a timer into the service design from toolbox











2.2. Fill up OnStart method


we need to initialize timer component inside the OnStart method, then I set timer interval and added a elapsed event to track each interval.




















protected override void OnStart(string[] args)
 {
     Debugger.Launch();
     logger.Info("Service is started.");
     try
      {
          Timer tmrEmailScheduler = new Timer();
           tmrEmailScheduler.Interval = 120000;
           tmrEmailScheduler.Elapsed += tmrEmailScheduler_Elapsed;
           tmrEmailScheduler.Start();
           ProcessEmail.CreateEmail();
      }
       catch (Exception ex)
        {
           logger.Error(ExceptionHandler.ToLongString(ex));
        }
 }


2.3. Actual scheduling done in here


inside timer elapsed event, actual task is going to run. elapsed event is called for each 2 minutes according to this code sample








private void tmrEmailScheduler_Elapsed(object sender, ElapsedEventArgs e)
 {
      logger.Info("Timer is ticked");
      ProcessEmail.CreateEmail();
 }


2.4. How to stop the execution


to stop the execution, OnStop event is used.











protected override void OnStop()
 {
    logger.Info("Service is stopped.");
    tmrEmailScheduler.Stop();
 }


3. How to install the windows service


Before installing the service in your pc, we need to create a installer class,








Add installer class as shown above


3.1. Installer Class


In Installer class, we need to give a service name, so we can identify the service by its name.





















[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
     private ServiceProcessInstaller process;
     private ServiceInstaller service;
      public ProjectInstaller()
       {
           InitializeComponent();
           process = new ServiceProcessInstaller();
           process.Account = ServiceAccount.LocalSystem;
           service = new ServiceInstaller();
           service.ServiceName = "test Service";
           Installers.Add(process);
           Installers.Add(service);
        }
   }


3.2. Let’s install the service


service is getting created after we build the application. we can find the .exe file in the bin folder. But we can’t install the service by double clicking on it.

we have to install it to the local pc or server.


3.3. InstallUtil


InstallUtil.exe is used to install/uninstall services in local machine or server. We can run installUtil command from Developer command prompt, type InstallUtil.exe with full path to the service exe file.





But this doesn’t going to install the service, It throws an error.


















It seems like we don’t have access to install the service, Let's try this, run Developer command prompt as administrator, then this permission issue is getting resolved.

We can install a service using cmd as well,



















run cmd as administrator, then we can install the service using cmd as well.


4. View services


We can check available services, by just typing services in your program list.








I gave service name as ‘test service’ in installer class.


5. Windows service on Local Computer started and then stopped


I tried to start the service from the panel, But it didn't work,

this issue comes normally when code has some kind of a error. It’s somewhat difficult to debug a windows service application to find out errors,


6. Debug a windows service application


normally in a windows service, program.cs looks like this.

















If we want to check whether our service implementation has any issue, we can use this trick






















manually start a method that has exact same code as the service implementation, inside of start method implementation, we can check whether service logic works properly.















using this trick, we can identify our service logic is working fine.

Another way of testing the program logic is, create another console application and call service logic method from console app and verify it works fine.


6.1. Debugger Launch


If we want to debug onStart method, we can launch the debugger in start method

























we can launch the debugger like this,
















we can debug the code like this.






















But in here specific file we attached into debugger is getting loaded. So other files are not loaded. Only we can debug the service file as this code sample shows.


7. Windows service can’t connect to the database


In my service, i need to access to the database, But it gives me an error like this, Login failed. Login failed for user ‘NT AUTHORITY\SYSTEM’

windows service is running on ‘NT AUTHORITY\SYSTEM’ login. this login doesn’t seem to have access to the database.

To resolve this, add this in your connectionstring, Integrated Security=SSPI or else create a user account for ‘NT AUTHORITY\SYSTEM’ in your database server and give necessary permissions.


8. Downloads

8.1. TechNet Gallery




8.2. Github




9. Conclusion


This article explains how to configure a windows service to send emails periodically. If you go through the code sample, We have used a timer component to handle the timeline, Windows service is running accordingly in its own process without being idle until it stops.