Codechef4u is a community for computer professionals,by computer professionals,just like you; who loves sharing and helping each others,Join them
Share your post

Preventive guidelines to stay safe from Wannacry Ransomware or any other cyber-attack

Preventive guidelines from Wannacry Ransomware or any other cyber-attack


Previously I shared around seven post on computer and web security, toady I am sharing this post on latest hot topic Wannacry Ransomware attack and prevention. You can use these guidelines as preventive steps for any other cyber-attacks. Before sharing all steps, I will explain some security terms related to cyberattack.  

What is malware?

This is type of virus(software) which is specifically designed to disrupt, damage, or gain authorized access to a computer system.

What is Ransomware?

This is a malicious software designed to block access to a computer system until a sum of money is paid, Software uses cryptovirology that blocks access to data until a ransom is paid and displays a message requesting payment to unlock it.

What is cryptovirology:

Cryptovirology is a field that studies how to use cryptography to design powerful malicious software.

What is Wanna Cry Ransomware?

A type of virus that infect computers, and then prevent the user from accessing the operating system, or encrypts all the data stored on the computer,
The user asks the ransom to pay a fixed amount of money, as opposed to decrypting files or allowing access again to the operating system.

Top 10 Preventive Measures from Wannacry malware or any other cyber-attack,

    1.  Keep your computers updated

Most cyberattacks targets out-of-date systems frequently, best example is WannaCrypt ransomware worm.

a.      Best preventive measure is keep your computer updated.

b.      Keep all security software’s updated, if you are using any third-party security software/tool keep that updated. 

c.       Keep all your important software’s updated.

Almost all infected computers from Wannacry Ransomware are not updated with Microsoft latest security update or using old XP,2003 operating systems.

Microsoft guidelines to prevent Wannacry are,

To prevent infection, users and organizations are advised to apply patches to Windows systems as mentioned in Microsoft Security Bulletin MS17-010.

https://technet.microsoft.com/library/security/MS17-010

For those using Windows Defender, please use following update

https://www.microsoft.com/security/portal/threat/encyclopedia/Entry.aspx?Name=Ransom:Win32/WannaCrypt

 2.  Create an internal policy

a.      Create data and internet use policy for your employees.

d.      Cerate policy for employees to avoid clicking spam and harmful links/fraudulent messages in email or using a poor password.

e.      Avoid using untrusted videos and attachments from emails and websites.

f.        Ensure integrity of the codes /scripts being used in database, authentication and sensitive systems, check regularly for the integrity of the information stored in the databases.

g.      Restrict users install and run unwanted and not trusted software applications.

h.      Make policy for remote connections and least privileged users.

 

  3.  Regular important data and files backup

 Keep your files backed up regularly and periodically, that includes important database,  software, files/documents backup.

  4.  Security software and required security tools

Its recommended to use Firewalls, network security tools and anti-virus software’s.

  5.  Safe web browsing and external data policy

a.      Block harmful and not trusted website in your network or computer.

b.      Follow safe practices when browsing the web. Ensure the web browsers are secured enough with appropriate content controls.

c.       Deploy web and email filters on the network, Scan all emails, attachments, and downloads both on the host and at the mail gateway with a reputable antivirus solution.

d.      Implement strict External Device (USB drive) usage policy.

  6.  Employee awareness, education and knowledge sharing about information and data  security

a.       Be aware of fraudulent and fake advertise/spam e-mail messages that use names like popular services such as PayePal like PayPal,google like gogle or use popular service names without commas or excessive characters.

b.      Educate employee about data security and security flaws.

c.       Educate people how to use your business system and company data.

d.      Restrict execution of not trusted powershell /WSCRIPT, executable code and Disable macros in MS Office products.

  7.  Hire security experts

a.      There is not a single software\tool available in market with 100% secure, invest in security experts that helps to prevent your business from security risks.

b.      One of the best ways for you to discover if there are any holes or security risks present in your infrastructure is to hire a security consultant.

 

  8.  Create strong passwords and change them frequently

a.      Change your password frequently never use the same password for all your accounts, if you are doing that then you are inviting for attack.

b.      Try to create complex and unique passwords that combine numbers, symbols and other factors to ensure it is safe and secure.

  9.  Security review on your applications

a.      Review your web/mobile application security frequently.

b.      Penetration and full security testing is must for your web and mobile applications.

  10.  Ensure and confirm external links and messages

a.      Never click on a link that you do not trust on a web page and websites, never click links from social media that you do not trust.

b.      If you receive a message from your friend with a link, ask him before opening the link to confirm, (infected machines send random messages with links).

 

References:

https://answers.microsoft.com/en-us/windows/forum/windows_10-security/wanna-cry-ransomware/5afdb045-8f36-4f55-a992-53398d21ed07

http://www.business2community.com/cybersecurity/8-ways-businesses-can-prevent-cyber-attacks-01251164#CdjMTEc9iYyq2pqu.97

http://www.cyberswachhtakendra.gov.in/alerts/wannacry_ransomware.html

https://blogs.microsoft.com/on-the-issues/2017/05/14/need-urgent-collective-action-keep-people-safe-online-lessons-last-weeks-cyberattack/#sm.001pbez1210y9d1510v9ukijwjrbf

HTML Encode and Decode in web application

WebUtility.HtmlEncode and WebUtility.HtmlDecode

Introduction

Previously I shared around six articles on security , in this article I am going to explain what is html encoding and how It prevent from xss attacks in web application and also I a am going to explain html decoding with sample example.

HtmlEncode

WebUtility.HtmlEncode Method converts a string to an HTML-encoded string.

The HTMLEncode method applies HTML encoding to a specified string. This is useful as a quick method of encoding form data and other client request data before using it in your Web application.

WebUtility.HtmlEncode converts characters as follows,

=> The apostrophe character (‘) is converted to '
=> The less-than character (<) is converted to &lt;.
=> The greater-than character (>) is converted to &gt;.
=> The ampersand character (&) is converted to &amp;.
=> The double-quote character (") is converted to &quot;.

Any ASCII code character whose code is greater-than or equal to 0x80 is converted to &#<number>, where is the ASCII character value.

HTML encode and Cross Site Scripting

What is XSS?

Cross Site Scripting (often abbreviated as XSS) when attacker uses web application send or injects malicious code like browser script, to different user. This malicious script executes and access user resources, trusted website data, website critical information. More info… http://www.codechef4u.com/post/2015/06/29/Anti-Cross-Site-Scripting-Library

HTML encode used to prevent possible XSS attack?

Encoding data converts potentially unsafe characters to their HTML-encoded equivalent.

It prevents XSS (cross site scripting) attacks, means that if you are going to save some data In database that allow following script and you used WebUtility.HtmlEncode method to encode string in that case following actual string special characters (i.e “< “is converted to “&lt”) converted into safe plain string.

  In web environment this script will be rendered safely rather than actually executing script.

Actual Script:

<script type="text/javascript">
    function FetchSomeCriticlInfo() { /* some dangerous script code */ }
</script>

In this case, Server.HTMLEncode would encode the <, >, and " characters leaving this:

Encoded Script:

&lt;script type=&quot;text/javascript&quot;&gt;
    function FetchSomeCriticlInfo() { /* some dangerous script code*/ }
&lt;/script&gt;

 

 

This script, if rendered in the browser will look like this

 

<script type="text/javascript"> function FetchSomeCriticlInfo() { /* some dangerous script code */ }
</script>

 

 

HTML Decode

 

WebUtility.HtmlDecode(String) Method converts a string that has been HTML-encoded for HTTP transmission into a decoded string.

 

HtmlDecode(String, TextWriter) overloaded method converts a string that has been HTML-encoded into a decoded string, and sends the decoded string to a TextWriter output stream.

 

Example

Follwing address is encoded using WebUtility.HtmlEncode Method

Encoded Address:

Bill Address
Nagnath Kendre
Kendre&apos;s Villa,Kendrewadi
Mahrashtra,India.

 

If I want to use this address into email or display to user I require to decode this &apos; string to actual character.

 

Following Address is Decoded using WebUtility.HtmlDecode Method

Decoded Address:

Bill Address
Nagnath Kendre
Kendres Villa,Kendrewadi
Mahrashtra,India.

 

धन्यवाद मित्रानो !! Thanks  friends !!

Review SQL queries for security vulnerabilities

Introduction:

After lot of code quality related issues and bad code quality blame game our project team started
New magical process called peer programming.
In this game you are more happy to find mistakes from collogue, and according to me that is perfect definition of magic process called peer programming.

In peer programming I found following code with attribute SuppressMessage and detail as Review SQL queries for security vulnerabilities.

 

[SuppressMessage("Microsoft.Security""CA2100:Review SQL queries for security vulnerabilities")]
        private static bool UpdateProducts(string procedureName, Product product)
        {
            var oConn = new SqlConnection(conString);
          
            oConn.Open();
            var oCmdProducts = new SqlCommand(procedureName, oConn);
            oCmdProducts.CommandType = CommandType.StoredProcedure;
            oCmdProducts.Parameters.Add(new SqlParameter("@ProductId"SqlDbType.Int)).Value =
               product.ProductId;
            oCmdProducts.Parameters.Add(new SqlParameter("@Pice"SqlDbType.Int)).Value =
            product.Price;
            if (oCmdProducts.ExecuteNonQuery() > 0)
            {
                return true// success
            }
            else
            {
                return false//fail
            }
        }
 
I started looking what is meaning of that attribute on MSDN I found these are some warning rules provided by Microsoft Managed Code Analysis tool.

What is Managed Code Analysis tool?

The Managed Code Analysis tool provides warnings that indicate rule violations in managed code libraries. The warnings are organized into rule areas such as design, localization, performance, and security. Each warning signifies a violation of a Managed Code Analysis rule.

Rule CA2100: Review SQL queries for security vulnerabilities

This rule assumes that the string argument contains user input. A SQL command string that is built from user input is vulnerable to SQL injection attacks. In a SQL injection attack, a malicious user supplies input that alters the design of a query in an attempt to damage or gain unauthorized access to the underlying database. Typical techniques include injection of a single quotation mark or apostrophe, which is the SQL literal string delimiter; two dashes, which signifies a SQL comment; and a semicolon, which indicates that a new command follows.

Violations of Rule:

Notice that this rule is violated when the ToString method of a type is used explicitly or implicitly to construct the query string.

Example:

ToString():

string query = "SELECT * FROM Products where CategoryId in (Select id from Categories where
CategoryName="+CategoryName.ToString()+")";

 

In this Example the rule is violated because a malicious user can override the ToString() method.

 

Implicit string conversion:

var TopCount = 10; string query = String.Format("SELECT TOP{0}
Productname,price FROM Products", TopCount);

 

In this example the rule is violated when ToString is used implicitly.

How to Fix Violations

To fix these violations use a parameterized query.

Other some suggestion are,

=> Use a stored procedure.
=> Use a parameterized command string.
=> Validate the user input for both type and content before you build the command string.

Safe code and Unsafe Code Example:

Safe Code example:

  public static List<Product> SafeProductsDeatilCall(string CategoryName)
      {
          var products = new List<Product>();
          var con = new SqlConnection(conString);
          try
          {
              con.Open();
              SqlCommand cmd = new SqlCommand("GetProductDetails", con);
              cmd.Parameters.Add("@CategoryName"SqlDbType.NChar).Value = CategoryName;
              string query = "SELECT * FROM Products where CategoryId in (Select id from Categories where CategoryName=@CategoryName";
              cmd.CommandText = query;
              SqlDataReader dr = cmd.ExecuteReader();
              while (dr.Read())
              {
                  Product p = new Product();
                  p.ProductId = Convert.ToInt32(dr["ProductID"]);
                  p.ProductName = dr["ProductName"].ToString();
                  p.Price = Convert.ToDecimal(dr["Price"].ToString());
                  p.CategoryId = (dr["CategoryId"] != DBNull.Value) ? Convert.ToInt32(dr["CategoryId"]) : 0;
                  p.ImageUrl = (dr["Imageurl"] != DBNull.Value) ? dr["Imageurl"].ToString() : string.Empty;
                  products.Add(p);
              }
              return products;
          }
          catch (Exception ex)
          {
              //log ex
              return null;
          }
          finally
          {
              con.Close();
          }
      }

 

     Unsafe Code Example:

 

      public static List<Product> UnsafeProductsDeatilCall(string CategoryName )
      {
          var products = new List<Product>();
          var con = new SqlConnection(conString);
          try
          {
              con.Open();
              SqlCommand cmd = new SqlCommand("GetProductDetails", con);
              string query = "SELECT * FROM Products where CategoryId in (Select id from Categories where CategoryName=" + CategoryName.ToString() + ")";
              cmd.CommandText = query;
              SqlDataReader dr = cmd.ExecuteReader();
              while (dr.Read())
              {
                  Product p = new Product();
                  p.ProductId = Convert.ToInt32(dr["ProductID"]);
                  p.ProductName = dr["ProductName"].ToString();
                  p.Price = Convert.ToDecimal(dr["Price"].ToString());
                  p.CategoryId = (dr["CategoryId"] != DBNull.Value) ? Convert.ToInt32(dr["CategoryId"]) : 0;
                  p.ImageUrl = (dr["Imageurl"] != DBNull.Value) ? dr["Imageurl"].ToString() : string.Empty;
                  products.Add(p);
              }
              return products;
          }
          catch (Exception ex)
          {
              //log ex
              return null;
          }
          finally
          {
              con.Close();
          }
      }

 Conclusion:

Consider Managed Code Analysis tool security rule in database coding, better use stored procedure.
If you are using inline query use parameterized sql query suggested by code analysis tool. 

 reference:

https://msdn.microsoft.com/en-us/library/ms182310.aspx