-
item 85 자바 직렬화의 대안을 찾으라책/이펙티브 자바 2022. 4. 26. 10:41
ITEM 85 자바 직렬화의 대안을 찾으라
직렬화 위험을 회피하는 가장 좋은 방법은 아무것도 역직렬화하지 않는것이다
- 신뢰할 수 없는 바이트 스트림을 역직렬화 하는게 스스로를 공격에 노출하는 행위다
- 객체와 바이트 시퀀스를 변환해주는 다른 메커니즘이 많이 있기 때문에 우리가 작성하는 코드에 자바 직렬화를 써야 할 이유가 없다
- 이 방식들은 자바 직렬화의 여러 위험을 회피하면서 다양한 플랫폼 지원, 우수한 성능, 풍부한 지원 도구, 활발한 커뮤니티와 전문가 집단 등 수많은 이점을 제공한다
- 이 표현들은 자바 직렬화보다 훨씬 간단하며 임의 객체 그래프를 자동으로 직렬화,역직렬화 하지 않는다
- 대신 속성-값 쌍의 집합으로 구성된 간단하고 구조화된 데이터 객체를 사용하며 기본타입 몇개와 배열타입만 제공할 뿐이다
- 위와 같이 간단한 추상화로도 강력한 분산 시스템 구축이 가능하며 자바 직렬화의 문제를 피할 수 있다
- 대표적인 예로 json, 프로토콜 버퍼(protocol buffers 또는 protobuf)가 있다
레거시 시스템 때문에 자바 직렬화를 완전히 배제할 수 없을 때의 차선책은 신뢰할 수 없는 데이터는 절대 역직렬화 하지 않는 것이다
- 신뢰할 수 없는 발신원의 RMI는 절대 수용해선 안된다
- 자바 공식 보안 코딩 지침에 "신뢰할 수 없는 데이터의 역직렬화는 본질적으로 위험하므로 절대로 피해야 한다"고 적혀있다
직렬화를 피할 수 없으며 역직렬화한 데이터가 안전한지 확신하려면 객체 역직렬화 필터링을 사용하자
- java9에 추가되었지만 예전 버전도 쓸 수 있으며 데이터 스트림이 역직렬화되기 전에 필터를 설치하는 기능이다
- 클래스 단위로 특정 클래스를 받아들이거나 거부할 수 있다
- 기본 수용 모드에서는 블랙리스트에 기록된 잠재적으로 위험한 클래스들을 거부한다
- 기본 모드에서는 화이트리스트에 기록된 안전하다고 알려진 클래스들만 수용한다
- 블랙리스트 방식보다는 화이트리스트 방식을 추천한다
- 블랙리스트 방식은 이미 알려진 위험으로부터만 보호할 수 있기 때문이다
- 스왓(SWAT)이라는 도구를 사용하면 화이트리스트를 자동으로 생성해준다
- 필터링 기능은 메모리를 과하게 사용하거나 객체 그래프가 너무 깊어지는걸 보호해주지만 직렬화 폭탄은 걸러내지 못한다
자바 직렬화는 여전히 사용되고 있는 코드이다
- 자바 직렬화를 사용하는 시스템을 관리해야 한다면 시간과 노력을 들여 json, 프로토콜 버퍼 등으로 마이그레이션 하는 것을 고려해보자
직렬화는 위험하니 피해야 하며 시스템을 밑바닥부터 설계한다면 json이나 프로토콜버퍼 같은 대안을 사용하자
신뢰할 수 없는 데이터는 역직렬화하지 말자
꼭 해야 한다면 객체 역직렬화 필터링을 사용하되 이마저도 모든 공격을 막아줄 수는 없음을 기억하자
클래스가 직렬화를 지원하도록 만들지 말고, 만들어야 한다면 정말 신경써서 작성해야 한다
'책 > 이펙티브 자바' 카테고리의 다른 글
item 87 커스텀 직렬화 형태를 고려해보라 (0) 2022.04.28 item 86 Serializable을 구현할지는 신중히 결정하라 (0) 2022.04.26 item 84 프로그램의 동작을 스레드 스케줄러에 기대지 말라 (0) 2022.04.25 item 83 지연 초기화는 신중히 사용하라 (0) 2022.04.25 item 82 스레드 안정성 수준을 문서화하라 (0) 2022.04.25