삽질 하자! 파는만큼 보인다

[JAVA] 첨부파일 등록시 확장자를 변조하여 등록했을때 체크방법 본문

JAVA

[JAVA] 첨부파일 등록시 확장자를 변조하여 등록했을때 체크방법

주니꾸주니 2024. 4. 12. 20:55

보안성검토에서 체크가 된 내역중 파일 확장자를 변조하여 등록 할 수 있는 보안성 문제가 발생하였다.

예를 들어 bat파일을 png파일로 확장자를 변형하여 파일 등록처리를 하는 문제였다.

 

if ("xls".equalsIgnoreCase(fileExt)
					|| "xlsx".equalsIgnoreCase(fileExt)
					|| "doc".equalsIgnoreCase(fileExt)
					|| "docx".equalsIgnoreCase(fileExt)
					|| "hwp".equalsIgnoreCase(fileExt)
					|| "hwpx".equalsIgnoreCase(fileExt)
					|| "ppt".equalsIgnoreCase(fileExt)
					|| "pptx".equalsIgnoreCase(fileExt)
					|| "txt".equalsIgnoreCase(fileExt)
					|| "gif".equalsIgnoreCase(fileExt)
					|| "jpg".equalsIgnoreCase(fileExt)
					|| "jpeg".equalsIgnoreCase(fileExt)
					|| "png".equalsIgnoreCase(fileExt)
					|| "zip".equalsIgnoreCase(fileExt)
					|| "bmp".equalsIgnoreCase(fileExt)
					|| "pdf".equalsIgnoreCase(fileExt)) {

				//확장자가 이미지 파일일경우 
				if(fileExt.equalsIgnoreCase("jpg") || fileExt.equalsIgnoreCase("jpeg") || fileExt.equalsIgnoreCase("png") 
						|| fileExt.equalsIgnoreCase("gif") || fileExt.equalsIgnoreCase("bmp")) {
					Boolean checkResult = imageCheck(file,fileExt);
					if(checkResult==false) {
						continue;
					}
				}

 

 

위의 이미지는 파일 등록시 코드의 일부이다.

등록가능한 확장자를 if문으로 체크하고 

다음 if문으로 이미지 파일인 경우에만 파일을 추가하는 로직을 구성했다.

 

imageCheck라는 메서드를 구현하여  이미지인지 확인하는 처리를 했다.

imageCheck 메서드는 해당 파일이 이미지일 경우 true를 반환하고 아닐경우는 false를 반환한다.

키포인트는 이미지파일에는 width, height 길이가 존재하기 때문에 해당 값을 체크하여 

온전한 이미지 파일인지 파악이 가능하다.

 

public boolean imageCheck(MultipartFile file, String fileExt) throws Exception{
		// 이미지 파일의 InputStream 가져오기
		InputStream inputStream = file.getInputStream();		
	    BufferedImage image = null;
	    
		 try {
		       image = ImageIO.read(inputStream);
		    } catch (Exception e) {
		        // 이미지 파일이 아닌 경우 처리
		        e.printStackTrace();
		        return false;
		    }
		 
		 if (image == null) {
		     return false;
		 }
		 
		int width = image.getWidth();
		int height = image.getHeight();
		
		 if (width != 0 && height != 0) {
		        // 이미지 파일인 경우
		        return true;
		 }else {
			 	// 이미지 파일이 아닌 경우
		        return false;
		 }
	}