Handlebars.java: Arbitrary file read in `SpringTemplateLoader` via URL-fragment suffix bypass
위협 신호 · CVSS · EPSS · KEV
이론적 심각도 점수
30일 내 악용 확률 예측
실측 악용 기록 없음
2주 이내 패치 — 우선 조치 대상
CVSS 벡터 · 메트릭
CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N상세 설명
Summary
com.github.jknack.handlebars.springmvc.SpringTemplateLoader resolves Spring MVC view names into URLs via Spring's ResourceLoader without applying the path-containment check that protects every other URL-based loader in the project (ClassPathTemplateLoader, FileTemplateLoader, ServletContextTemplateLoader - all hardened by commit d177cdee).
The only remaining defense for file: / classpath: view names is the unconditional .hbs suffix appended by AbstractTemplateLoader.resolve(...). This suffix is the load-bearing security boundary that prevents a request like view=file:/etc/passwd from reading /etc/passwd instead of /etc/passwd.hbs.
This boundary is bypassed by a single character: # (the URL fragment delimiter).
When the view name ends with #, the appended .hbs lands inside the URL fragment. Both Spring's FileUrlResource.exists() (via URI.getSchemeSpecificPart()) and the JDK's URL.openStream() (via URL.getFile()) silently discard the fragment, so the file actually opened is the bare path the attacker specified - for example /etc/passwd rather than /etc/passwd.hbs. The compiled "template" is then parsed and rendered into the HTTP response body.
Result: unauthenticated, network-reachable, arbitrary file read of any file readable by the JVM process on any Spring MVC application that uses a default-configured HandlebarsViewResolver and exposes a controller that returns a (fully or partly) user-influenced view name.
Vulnerable Code
SpringTemplateLoader.resolve - preserves file: / classpath: and applies suffix to the path portion
1// handlebars-springmvc/.../SpringTemplateLoader.java:66-77 2@Override 3public String resolve(final String location) { 4 String protocol = null; 5 if (location.startsWith(ResourceUtils.CLASSPATH_URL_PREFIX)) { 6 protocol = ResourceUtils.CLASSPATH_URL_PREFIX; 7 } else if (location.startsWith(ResourceUtils.FILE_URL_PREFIX)) { 8 protocol = ResourceUtils.FILE_URL_PREFIX; // matches "file:" 9 }10 if (protocol == null) {11 return super.resolve(location);12 }13 return protocol + super.resolve(location.substring(protocol.length()));14}SpringTemplateLoader.getResource - no containment check
1// handlebars-springmvc/.../SpringTemplateLoader.java:57-63 2@Override 3protected URL getResource(final String location) throws IOException { 4 Resource resource = loader.getResource(location); // trust Spring blindly 5 if (!resource.exists()) { 6 return null; 7 } 8 return resource.getURL(); 9}Contrast with the hardened sibling ClassPathTemplateLoader.getResource, which delegates to URLTemplateLoader.classpathResource(...) - the containment helper added by commit d177cdee:
1// handlebars/.../io/URLTemplateLoader.java:75-93 (the d177cdee hardening) 2protected final String classpathResource(String location) { 3 String resolvedPath = 4 Paths.get(location).normalize().toString().replace(java.io.File.separatorChar, '/'); 5 if (location.startsWith("/") && !resolvedPath.startsWith("/")) { 6 resolvedPath = "/" + resolvedPath; 7 } 8 String prefix = getPrefix(); 9 if (!prefix.equals("/") && !resolvedPath.startsWith(prefix)) {10 throw new IllegalArgumentException(11 "Path traversal attempt detected. Resolved path escapes base prefix: " + location);12 }13 return resolvedPath;14}SpringTemplateLoader.getResource never calls this helper.
HandlebarsViewResolver - strips the outer prefix/suffix and forwards to compile, no validation
1// handlebars-springmvc/.../HandlebarsViewResolver.java:112-117 2public HandlebarsViewResolver(final Class<? extends HandlebarsView> viewClass) { 3 setViewClass(viewClass); 4 setContentType(DEFAULT_CONTENT_TYPE); 5 setPrefix(TemplateLoader.DEFAULT_PREFIX); // "/" 6 setSuffix(TemplateLoader.DEFAULT_SUFFIX); // ".hbs" 7} 8 9// handlebars-springmvc/.../HandlebarsViewResolver.java:163-17810protected AbstractUrlBasedView configure(final HandlebarsView view) throws IOException {11 String url = view.getUrl();12 url = url.substring(getPrefix().length(), url.length() - getSuffix().length());13 try {14 view.setTemplate(handlebars.compile(url)); // ← attacker-controlled url15 view.setValueResolver(valueResolvers.toArray(new ValueResolver[0]));16 } catch (IOException ex) {17 if (failOnMissingFile) throw ex;18 logger.debug("File not found: " + url);19 }20 return view;21}AbstractTemplateLoader.resolve - the load-bearing .hbs gate
1// handlebars/.../io/AbstractTemplateLoader.java:47-50 2@Override 3public String resolve(final String uri) { 4 return prefix + normalize(uri) + suffix; // "/" + path + ".hbs" 5}The suffix string is concatenated as a string. Whether that string lands in the path component, query component, or fragment component of the resulting URL is decided by Spring's URL parsing - not by Handlebars.
Impact
Direct primitive
Unauthenticated arbitrary file read of any file readable by the JVM process UID.
Real-world attack chains (downstream impact)
- Read
application.yml-> extractjwt.secret/spring.datasource.password-> forge admin JWT or directly connect to the database. Common Spring Boot deployment pattern; one request to game-over. - Read AWS / GCP credentials -> assume role -> exfiltrate buckets, modify infrastructure.
- Read K8s service-account token -> API-server access scoped to the pod's role -> namespace lateral movement, secret exfiltration.
- Read
/proc/self/environ-> harvest CI/CD-injected secrets that never appear on disk. - Read private keys (
id_rsa, TLS keys) -> impersonate host / decrypt MITM'd traffic / sign commits. - Read the application's source-code-on-disk to discover further server-side endpoints, hardcoded credentials, or chains.
Indirect
- Confirmed reachable from any controller that returns user-influenced view names - a documented Spring anti-pattern that nevertheless appears in production (CMS preview endpoints, theme switchers, multi-tenant view routing,
@RequestMapping("/{view}")patterns,DefaultRequestToViewNameTranslator-driven URL->view mappings). - No authentication, no privilege, no clicks - a single Internet HTTP GET.
Remediation
Any of the following independently closes the bypass. We recommend implementing #1 and #2 for defense in depth.
Apply the containment helper to SpringTemplateLoader.getResource (parity with d177cdee)
1// handlebars-springmvc/.../SpringTemplateLoader.java 2@Override 3protected URL getResource(final String location) throws IOException { 4 // For classpath: locations, delegate to the hardened helper as ClassPathTemplateLoader does. 5 // For file: locations, perform an explicit canonical-path containment check. 6 Resource resource = loader.getResource(location); 7 if (!resource.exists()) { 8 return null; 9 }10 URL url = resource.getURL();11 validateNoUnsafeUrlComponents(url); // see 9.312 return url;13}Validate the resolved URL components
1private static void validateNoUnsafeUrlComponents(URL url) { 2 if (url.getRef() != null) { 3 throw new IllegalArgumentException( 4 "Template URL must not contain a fragment: " + url); 5 } 6 if (url.getQuery() != null) { 7 throw new IllegalArgumentException( 8 "Template URL must not contain a query: " + url); 9 }10}This is the structural fix - it ensures the textual .hbs check matches the resolved-file behavior regardless of input shape.
Remove the protocol short-circuit entirely
If the supported deployment model is "templates live in one well-known prefix", SpringTemplateLoader.resolve should not preserve file: / classpath: prefixes from user input at all. Either remove that branch, or require an explicit allow-list in the constructor:
1public SpringTemplateLoader(ResourceLoader loader, boolean allowProtocolPrefixes) { ... }with the default being false.
Validate the stripped view name in HandlebarsViewResolver.configure
1// handlebars-springmvc/.../HandlebarsViewResolver.java:163-178 2protected AbstractUrlBasedView configure(final HandlebarsView view) throws IOException { 3 String url = view.getUrl(); 4 url = url.substring(getPrefix().length(), url.length() - getSuffix().length()); 5 if (url.contains(":") || url.contains("#") || url.contains("..")) { 6 throw new IllegalArgumentException("Unsafe view name: " + url); 7 } 8 // ... 9}This is a defense-in-depth check that rejects view names containing protocols, fragments, or traversal sequences. It does not by itself remove the SpringTemplateLoader weakness (developers calling handlebars.compile(...) directly still bypass it), but it eliminates the most common reach pattern.
AI 심층 분석
공격 시나리오 · 재현 가능한 PoC 페이로드 · 즉시 적용 가능한 차단 패치를 한 번에 받아 보세요. 보안 운영팀이 그대로 점검·티켓팅에 쓸 수 있는 형태로 정리해 드립니다.
참고 자료 5
링크 내용 불러오는 중…