Java Application 의 Top 5 Secure Coding Tips 2009.6~2012.6 2011. 4. 27 소프트 4 소프트 www.soft4soft.com 02-553-9464
2 RESRT Code Analysis 목차 1. 코드검사및코딩표준 2. SW 보안취약점 2.1 코딩표준을통한보안취약점예방 2.2 전자정보표준 Framework을통한보안취약점예방 3. Java 시큐어코딩표준 3.1 코딩서식의취약점및예방 3.2 코드결함의취약점및예방 4. 결론
3 RESRT Code Analysis 1 코드검사및코딩표준 코드검사목적및활동 소스코드의결함탐지 (Prevention) 및진단 (Detection) o 코딩스타일 / 결함, 설계결함, 런-타임결함, 보안결함, 표준준수 (MISRA-C/C++) 등 o 프로그램의정확성, 안정성및보안성등보장향상 자체개발 / 운영표준코딩가이드 o 시스템 ( 업무 ) 이해및코딩수준의상향평준화 초급 / 외주개발자 o 개발단축및 QA 비용, 시간절약 Review/ 프로그램검수 고객만족도향상및향후유지보수용이 테스팅이전에 50-90% 가량의결함을제거함으로써, 개발공정의 10%~30%, 테스팅비용및공정의 5-10 배, 그리고유지보수비용의 2/3 를절감할수있다 - Software Inspection
4 RESRT Code Analysis 1 코드검사및코딩표준 코딩표준 개발명세및코딩가이드이해 Code Defect Prevention o 개발자오용, 실수, 오해최소화, 디버깅작업최소화 o Ex) API, Utility API, Framework API 사용표준화 코드구조화 Program Simple & Small o 코드이해성향상및유지보수비용절감 Code Quality
5 RESRT Code Analysis 2 SW 보안취약점 코드취약점유형 ( 가독성, 유지보수성 ) Poor Programming, ( 정확성, 안전성 ) Missing&Incorrect Programming ( 신뢰성 ) Missing Requirements Source Code Vulnerability Yes No Source Code Defects Yes No Missing & Incorrect Programming - Data & Control Flow, Interface - Type Conversion, Memory leak - Exception, Error & DB Handling - (Critical defect) Run-time Error Missing Requirements - 전자정보표준 Framework (API) - Architecture (I/) Poor Programming - Formatting - Data & Control Statement Poor Programming - Data Flow (Unused Code) - Control Flow (Unnecessary Construct) - Naming, Comment, Complexity
6 RESRT Code Analysis 2 SW 보안취약점 코드취약점심각도분류 Expressions bject rientation Methods Locking/ Concurrency Thread APIs Input utput Application Programming Interfaces Platform Security Runtime Environment Serialization Miscellaneous Java Syntax Declarations and Initialization Numeric Types and perations Exceptions and Error Handling Input Validation and Data Sanitization Low Severity: (1) low (denial-of-service attack, abnormal termination) (2) medium (data integrity violation, unintentional information disclosure) (3) high (run arbitrary code, privilege escalation) Severity Medium High
7 RESRT Code Analysis 2.1 코딩표준을통한보안취약점예방 Try-catch-finally Coding Standards ( 정의 ) try, catch 문에서예외의발생유무에관계없이반드시 finally 문이실행함 Java Syntax Rules Empty Block Catch Block Finally Block try { body-code; catch (exception-classname variable-name){ error-handler-code; finally { close-code; (1)Format try-catchfinally Syntax (2)Format try-catchfinally Statement (1)Don t use different Exception type (2)Checked Exception type SQLException(DataAc cessexception), Exception (3)Log type compliance by standard(framework API or Architecture) (1)Do not use return/throw syntax (2)Resource release type by standard : (API, Utility API, or Framework API) (3)Reuse after nonfree resource Code Defect Formatting Convention Control Error, Architecture Compliance Control Flow Error, Resource leak, Architecture Compliance Security Cause Ignore Exception (=Empty Catch) Unhandled Exception, Nullpointer Exception Exception loss (=Return Inside Finally) Security Vulnerability Denial of service attack Data integrity Violation Denial of service attack
8 RESRT Code Analysis 2.2 전자정부표준 Framework 을통한보안취약점예방 Architecture(Framework) 의 Component 및 Pattern 준수검증 각 Component 들의동작분배및개념적통일성등가이드활용 o (Java) Component I/F, Hierarchy Layer, DB(SQL)/Exception/Error(Log) Handling 등준수 결함예방 o 성능, 보안성, 계산오류, API 등의치명적인결함예방 ( 프로그램오류최소화 ) o SW 시스템의신뢰성및유지보수성효과 ( 코드일관성 ) Component I/F Examples: MVC Model 준수검사 코딩표준부재 ( 미준수 ) 코딩표준준수
2.2 전자정부표준 Framework 을통한보안취약점예방 전자정부표준개발 Framework 기능의보안취약점예방효과 실행환경의서비스그룹 ( 서비스 ) 화면처리 Layer (Security) 업무처리 Layer (Exception Handling) 데이터처리 Layer (Data Access/Source) 공통기반 Layer (File Handling, Server Security, Encryption/Decryption) 보안취약점예방종류 SQL/Command Injection, Cross Site Scripting (XSS), Cross-Site Request Forgery (CSRF) Information Exposure Through an Error Message SQL Injection, DB information Exposure, DB Resource Leak File Resource Leak, Broken Authentication and Session Management, Encryption of Sensitive Data < 전자정부개발 Framework 환경중실행환경 : 4 환경, 13 서비스그룹, 54 서비스 > 9 RESRT Code Analysis
10 RESRT Code Analysis 3.1 코딩서식의취약점및예방 Coding Formatting - Declaration 정의위험예방결과 하나의선언에서여러변수들을선언하지말것 (1) 다른유형의변수들, (2) 초기화및초기화되지않은변수의혼합 변수들의초기값들의혼란을초래 하나의선언에하나의변수선언 denial-of-service attack Noncompliant Code Compliant Code int i, J = 1; int i = 1; int J = 1; or int I=1, J = 1; 프로그래머또는검토자가 i 와 j 모두 1 로초기화됐다는실수를범할수있음
11 RESRT Code Analysis 3.1 코딩서식의취약점및예방 Coding Formatting Expression 정의위험예방결과 int privileges; 제어문장에중괄호 ({) 사용로직오류항상중괄호 ({) 사용하여애매성제거 denial-of-service attack Noncompliant Code int privileges; Compliant Code if (invalid_login()) if (allow_guests()) privileges = GUEST; else privileges = ADMINISTRATR; or if (invalid_login()) login = 0; else System.out.println("Login is valid\n"); // debugging line added login = 1; // this line always gets executed, regardless of a valid login! 권한이없는사용자가권리자권한을얻을수있는취약점 if (invalid_login()) { if (allow_guests()) { privileges = GUEST; else { privileges = ADMINISTRATR;
12 RESRT Code Analysis 3.2 코드결함의취약점및예방 Code Defects Exception Behavior 정의 위험 예방 결과 finally 블록에서종료하지말것 로직오류 finally 블록에서 return, break, continue, throw 의키워드를사용하지말것 denial-of-service attack Noncompliant Code class TryFinally { private static boolean dologic() { try { throw new IllegalStateException(); finally { System.out.println("Uncaught Exception"); return true; public static void main(string[] args) { dologic(); Compliant Code class TryFinally { private static boolean dologic() { try { throw new IllegalStateException(); finally { System.out.println("Caught Exception"); // Any return statements must go here; applicable only when exception is thrown conditionally public static void main(string[] args) { dologic(); (1) try 블록에서발생되는예외가무시됨, (2) Method 의 return 값이 finally 블록의 return 값으로대체됨
13 RESRT Code Analysis 3.2 코드결함의취약점및예방 Code Defects Return Value Check 정의위험예방결과 Method return 값무시하지말것 Method return 값무시는예기치않은프로그램동작발생 Method return 값 ( 또는에러조건 ) 검사 data integrity violation Noncompliant Code Compliant Code public class Ignore { public static void main(string[] args) { String original = "insecure"; original.replace( 'i', '9' ); System.out.println(original); public class DoNotIgnore { public static void main(string[] args) { String original = "insecure"; original = original.replace( 'i', '9' ); System.out.println(original); String.replace() method 의 return 값무시로, original string 의 Update 실패
14 RESRT Code Analysis 3.2 코드결함의취약점및예방 Code Defects Null Pointer Dereference 정의 위험 예방 결과 Null pointer dereference 하지말것 ( 역참조는 Function call, 변수읽기 / 쓰기, 배열접근에서가능 ) 프로그램종료 return 값검사, 변수또는객체가 non-null 인지확인 denial-of-service attack Noncompliant Code public static int cardinality(bject obj, final Collection col) { int count = 0; Iterator it = col.iterator(); while (it.hasnext()) { bject elt = it.next(); if ((null == obj && null == elt) obj.equals(elt)) { // null pointer dereference count++; return count; or String cmd = System.getProperty("cmd"); cmd = cmd.trim(); // null point dereference Compliant Code public static int cardinality(bject obj, final Collection col) { int count = 0; Iterator it = col.iterator(); while (it.hasnext()) { bject elt = it.next(); if ((null == obj && null == elt) (null!= obj && obj.equals(elt))) { count++; return count; 만약공격자가프로그램환경을제어하여 cmd 를미정의한다면, trim() 호출시 NULL pointer exception 발생
15 RESRT Code Analysis 3.2 코드결함의취약점및예방 Code Defects Resource Leak 정의 위험 예방 결과 Stream, Connection 과같은자원은사용후반드시종료 많은파일또는 DB 연결이 pen 되어자원고갈, 성능저하, 정보노출등의문제점발생 (Garbage Collection 시작되기전에 ) Close Method 로모든자원을해제 (API, Utility API, Framework API ) denial-of-service attack, unintentional information disclosure Noncompliant Code try { con = con.getconnection; catch (Exception e) { log(e) finally { Compliant Code try { con = con.getconnection; catch (SQLException sqle) { log(e) finally { if (con!= null) try { rs.close(); catch (Exception e) { 프로그램규모와사용가능한메모리에따라, Heap Space 가고갈될때 utfmemoryerror 발생하여, 프로그램정지결과를초래
16 RESRT Code Analysis 4 결론 A coding standard helps you: avoid undefined usage avoid unspecified usage avoid implementation-defined usage guard against compiler errors guard against common programmer error limit program complexity establish an objective basis for code review
17 RESRT Code Analysis You can t manage what you can t measure Q & A