어제저녁부터 시끌시끌한 주제인 Spring4 Shell에 대해서 찾아 정리한 글입니다. 짧은 시간 동안, 얕은 이해도를 가지고 대략적인 부분만 작성하였기에 이 부분을 유의해주시고 피드백해주시면 감사드리겠습니다.

해당 문제가 발생하기 위한 조건

  • Java 9+
  • Spring Core 5.3.17 또는 5.2.19 버전 이하를 사용
  • Post Mapping end-point
  • JSON / XML Converting을 사용하지 않는 API (application/x-www-form-urlencoded 사용)
    • 즉 @ModelAttribute - ModelAttributeMethodProcessor이나 Key=Value Format의 Binding을 사용할 때
  • 외장 Tomcat 9 사용
    • WebAppClassLoaderBase + WebAppClassLoader(. 경로를 구분자로 이용) 기능을 악용합니다.
    • 내장 Tomcat에서 사용하는 LaunchedURLClassLoader (URLClassLoader 구현체)는 위에서 언급한. class를 접근하기 위해서 . 대신 /를 구분자로 사용한 전체 디랙터리 경로를 전달하여야 하기 때문에 현재 공개된 POC 방법을 활용한 접근이 어렵습니다. (그래서 제한적이다 라고 표현하는 것 같습니다.)
  • DataBinder에서 허용하는 패턴을 설정하지 않은 경우 (allow all)

 

 

해당 문제가 발생한 이유.

Java 9에서는 Java Module System이 추가됨에 따라 3계층 Class Loader 중 Application Class Loader(사용자 클래스를 로딩하는 주체)가 Module Path를 통해 Class를 접근, 생성 및 수정하는 것이 가능해졌습니다.

  • 이로 인하여서 빈 정보가 저장되는 객체와 이를 캐싱되는 CachedIntrospectionResults의 초기화 로직에서 getClassLoader(), getProtectDomain() 조건 검증을 통해 ClassLoader에 대한 method를 등록하지 않도록 한 기존 로직을 우회할 방법이 생겼다고 합니다. (이를 통해 ClassLoader에 접근하여 임의 코드를 실행할 수 있습니다.)
    • 우회 가능 형식 ex) class.module.classLoader.~



관련한 매커니즘으로 cve-2010-1622와 cve-2014-0094-apache-struts-security-bypass-vulnerability을 참고하시면 좋을 것 같습니다.

 

 

취약점을 공격하는 방법

Post 요청으로 Query Parameter를 보낼 때 악의적으로 조작된 값을 포함하여 전달합니다.

  • 이때 전달되는 Parameter Value가 Databinder로 넘어갔을 때 사용하는 ClassLoader에 의해 Pipeline mechanism을 수행할 수 있으며 디스크에 존재하는 특정 파일을 접근하거나 생성 및 수정할 수 있게 됩니다.
    • ServletRequestDataBinder.bind() 참조
// AbstractNestablePropertyAccessor 
@Override 
@Nullable 
public Class<?> getPropertyType(String propertyName) throws BeansException {
	try { 
    	PropertyHandler ph = getPropertyHandler(propertyName); 
        if (ph != null) { 
        	return ph.getPropertyType(); 
        } else { 
        	// Maybe an indexed/mapped property... 
            Object value = getPropertyValue(propertyName); 
            if (value != null) { 
            	return value.getClass(); 
            } 
            // Check to see if there is a custom editor, 
            // which might give an indication on the desired target type. 
            Class<?> editorType = guessPropertyTypeFromEditors(propertyName); 
            if (editorType != null) { 
            	return editorType; 
            } 
        } 
    } catch (InvalidPropertyException ex) { 
    	// Consider as not determinable. 
    } 
    return null; 
} 

// BeanWrapperImpl 
@Override 
@Nullable 
protected BeanPropertyHandler getLocalPropertyHandler(String propertyName) { 
	PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(propertyName); 
    return (pd != null ? new BeanPropertyHandler(pd) : null); 
}

 

 

 

해당 문제를 회피하는 방법.

  • Java 9 또는 외장 Tomcat을 사용하지 않습니다.
  • @ModelAttribute를 사용하지 않습니다. (DataBinder)
  • @InitBinder를 정의할 때 setDisallowedFields() 메서드를 이용해 class가 들어가는 패턴을 제외하도록 설정하거나 또는 setAllowedFields() 메서드를 이용해 허용하는 패턴을 정의합니다.
    • 권고) String [] denylist = new String[]{"class.*", "Class.*", ".class.", ".Class."};
  • RequestMappingHandler를 확장하여 createDataBinderInstance를 재정의합니다. (처리는 위 방법과 동일)
  • 취약점이 해결된 버전으로 업데이트 합니다.

 

 

(04-01 추가) Spring4Shell 취약점 해결 버전 배포

Spring4Shell 취약점을 해결하는 버전이 배포되었습니다. ( Spring Core 5.3.18, 5.2.20, Spring Boot 2.6.6, 2.5.12 )

 

 

 

참고 링크

 

+ Recent posts