본문 바로가기

Java

[시큐어코딩] 부적절한 자원 해제(IO)

* 시큐어 코딩이란?

    - 소프트웨어 개발 과정에서 개발자의 실수, 논리적 오류 등으로 인한 보안약점을 최소화하기 위한 개발 기법이다.

 

보통 개발 후 code-ray와 같은 보안 프로그램을 돌리는데

이 때 행정안전부의 'JAVA 시큐어 코딩 가이드' 를 참고하면 큰 도움을 받을 수 있다!

https://www.kisa.or.kr/2060204/form?postSeq=6&page=1#fnPostAttachDownload

개발한 코드가 어떠한 경우에 보안약점이 될 수 있는지와 안전하지 않은 코드, 안전한 코드 예시까지 들어주기 때문이다.

(유료 보안 프로그램의 경우 결과 보고서에 쓰여있긴 하다.)

 

이번에 내가 처리한 부분은 아래와 같다.

 

5.2 부적절한 자원 해제(IO)

    - 발생하는 경우

        (1) Reader/Writer, BufferReader/BufferWriter, PipedReader/PipedWriter 객체를 사용한 후

            정상적으로 해제하지 않았을 경우

        (2) FileInputSteram/FileOutputStream, DataInputStream/DataOutputStream,

            BufferedInputStream/BufferedOutputStream, ByteArrayInputStream/ByteArrayOutputStream,

            SequenceInputStream, PrintStream 객체를 사용한 후 정상적으로 해제하지 않았을 경우

    - 수정 방법

        try-catch 문의 finally 블럭에서 자원을 해제한다. (예외 발생시 자원 해제가 되지 않을 수 있기 때문이다.)

 

 

public class ListController {

	public static void test(String path, String text) {
    	
        	// 취약한 코드
		try {
        		FileWriter fw = new FileWriter(path);
			PrintWriter pw = new PrintWriter(fw);
			pw.println(text);
            
            		fw.close();
            		pw.close()
		} catch (IOException e) {
			logger.error("ERROR:{}", "IOException Occured!");
		}
    
    		// 올바른 코드
		FileWriter fw = null;
        	PrintWriter pw = null;
		try {
			fw = new FileWriter(path);
            		pw = new PrintWriter(fw);
			pw.println(text);
		} catch (IOException e) {
			logger.error("ERROR:{}", "IOException Occured!");
		} finally {
        		try {
                            if (fw != null) {
                               fw.close();
                            }
                            if (pw != null) {
                                pw.close();
                            }
            		} catch (IOException e) {
				logger.error("IOException Occured");
			}
		}
	}
	
}

 

/* 출처 : 행정안전부 */

728x90