File Filter 개발
    • PDF

    File Filter 개발

    • PDF

    Article Summary

    Classic/VPC 환경에서 이용 가능합니다.

    File Filter REST API를 사용하여 File Filter 코드를 작성하는 방법을 설명합니다.

    참고

    File Filter 개발에 앞서 File Safer 이용 신청, API Gateway 이용 신청 및 API Key 생성을 해야 합니다. 자세한 내용은 File Safer 시작을 참조해 주십시오.

    File Filter 구현 시나리오

    File Filter를 적용하는 시나리오는 다음과 같습니다.

    filesafer-programming-file_scenario_ko

    1. 파일 검사 요청(inputFile)
    1-1. 악성 코드로 의심되는 파일을 구분
    1-2. 인증값 생성
    1-3. 요청 Body 생성
    1-4. 요청 파라미터 추가
    1-5. API 요청

    2. 검사 결과 확인(getInputFileLog)
    2-1. 검사 결과를 확인할 Hash 값 구분
    2-2. 인증값 생성
    2-3. 요청 파라미터 추가
    2-4. API 요청
    2-5. 응답 값 확인 및 차단 여부 판단

    참고

    File Filter에서 악성 코드로 확인되는 경우 Hash Filter의 Hash 값을 업데이트하기 때문에 검사 결과를 Hash Filter에서 조회하여도 동일한 결과를 얻을 수 있습니다.

    File Filter 코드 작성

    File Filter 구현 시나리오에 따라 코드를 작성해 주십시오.

    1. 파일 검사 요청(inputFile)

    File Filter API 중 inputFile을 사용하여 파일 검사를 요청합니다.

    참고

    inputFile API 사양은 inputFile (File Filter)를 참조해 주십시오.

    1-1. 악성 코드로 의심되는 파일을 구분

    Hash Filter로 확인이 안되는 파일이거나 악성 여부 확인이 필요한 파일을 구분해 주십시오. 파일 제약 사항은 다음과 같습니다.

    • 파일 개수 제한: inputFile API 호출 시 요청당 파일 한 개만 처리. 파일이 2개 이상 전송되는 경우 파일 한 개만 임의로 선택되어 처리.
    • 파일 크기 제한: API 호출당 파일 용량 10 MB로 제한

    1-2. 인증값 생성

    네이버 클라우드 플랫폼 API 사용 인증에 필요한 IAM 인증값을 생성해 주십시오. 인증에 필요한 헤더는 다음과 같습니다.

    • x-ncp-iam-access-key: 네이버 클라우드 플랫폼 포털의 마이페이지 > API 인증키 관리 메뉴에서 Access Key 발급
    • x-ncp-apigw-signature-v2 : Access Key와 매핑되는 Secret Key를 HmacSHA256 암호화하여 signature 값 생성(개행 문자는 \n 사용)
    • x-ncp-apigw-api-key : API Gateway를 통해 API Key 발급
    • x-ncp-apigw-timestamp : 인증값은 아니지만 요청 헤더에 포함. API 명세 참고
    참고

    signature 값을 생성하는 방법과 예제 코드는 네이버 클라우드 플랫폼 API 가이드 > API 개요 > 기본 API > Ncloud API > 2.헤더 생성을 참조해 주십시오.

    1-3. 요청 Body 생성

    Multipart로 Body에 파일을 포함한 요청을 생성해 주십시오.

    • Key: file
    • Value: binary

    1-4. 요청 파라미터 추가

    전송하려는 파일이 패스워드가 설정된 압축 파일인 경우 아래의 파라미터를 요청에 추가해 주십시오.

    • Key: archivePassword
    • Value: 압축파일 패스워드 String

    다음은 파라미터가 추가된 POST 요청 Body의 포맷입니다. boundary 값은 엔티티 구분자로 사용하며 boundary 설정 값 앞에는 '--'을 넣어야 합니다. 각 엔티티 끝에는 crlf('\r\n')를 사용해야 합니다.

    Content-Type: multipart/form-data; boundary=----AAAAAAAAAAAAAAAAAAAAAAAAAAAAA
    
    ------AAAAAAAAAAAAAAAAAAAAAAAAAAAAA
    Content-Disposition: form-data; name="file"; filename="suspicious-file.zip"
    Content-Type: application/x-zip-compressed
    
    ... contents of 'suspicious-file.zip'
    ------AAAAAAAAAAAAAAAAAAAAAAAAAAAAA
    Content-Disposition: form-data; name="archivePassword"
    
    password
    ------AAAAAAAAAAAAAAAAAAAAAAAAAAAAA--
    

    1-5. API 요청

    File Filter inputFile URI로 요청을 전송해 주십시오. 다음은 inputFile 요청 예제 코드입니다.

    public static void request(String fileName, String password) throws Exception 
    {
    	String boundary = "----AAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
    	String crlf = "\r\n";
    	
    	String apiDomain = "https://filesafer.apigw.ntruss.com";
    	String apiURL = "/filefilter/v1/inputFile";
    	String method = "POST";
    	long timestamp = System.currentTimeMillis();
    		
    	// step 2: Create Authentication Value
    	String signature = makeSignature(method, apiURL, timestamp);
    
    	// step 3: Create request with the identified file added
    	var path = (Path) Paths.get(fileName);
    	byte[] separator = ("--" + boundary + "\r\nContent-Disposition: form-data; name=").getBytes(StandardCharsets.UTF_8);
    		
    	var byteArrays = new ArrayList<byte[]>();
    	byteArrays.add(separator);
    	byteArrays.add(("\"file\"; filename=\"" + path.getFileName() + crlf).getBytes(StandardCharsets.UTF_8));
    	byteArrays.add(("Content-Type: " + Files.probeContentType(path) + crlf + crlf).getBytes(StandardCharsets.UTF_8));
    	byteArrays.add(Files.readAllBytes(path));
    	byteArrays.add(crlf.getBytes(StandardCharsets.UTF_8));
    		
    	// step 4: If the file you want to transfer is a zip file with a password, add the following parameters to the request
    	if (password != null && !password.isEmpty()) { 
    		byteArrays.add(separator);
    		byteArrays.add(("\"archivePassword\"\r\n\r\n" + password + "\r\n").getBytes(StandardCharsets.UTF_8));
    	}
    		
    	byteArrays.add(("--" + boundary + "--").getBytes(StandardCharsets.UTF_8));
    
    	// step5: Request API
    	HttpRequest request = HttpRequest.newBuilder()
    			.POST(BodyPublishers.ofByteArrays(byteArrays))
    			.uri(URI.create(apiDomain + apiURL))
    			.setHeader("x-ncp-apigw-timestamp", Long.toString(timestamp))
    			.setHeader("x-ncp-iam-access-key", ACCESSKEY)
    			.setHeader("x-ncp-apigw-signature-v2", signature)
    			.setHeader("x-ncp-apigw-api-key", APIKEY)				
    			.headers("Content-Type", "multipart/form-data; boundary=" + boundary)
    			.build();
    
    	HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
    
    	// Check the response value
    	int responseCode = response.statusCode();
    	String responseBody = response.body().toString();
    	
    	// do next step (ex, check to transfer succeeded)
    	...		
    }
    

    2. 검사 결과 확인(getInputFileLog)

    File Filter API 중 getInputFileLog를 사용하여 악성 코드 검사 결과를 확인합니다.

    참고

    getInputFileLog API 사양은 getInputFileLog (File Filter)를 참조해 주십시오.

    2-1. 검사 결과를 확인할 Hash 값 구분

    파일 검사 요청 시나리오를 통해 File Filter에 검사를 요청했던 파일의 Hash 값을 구분해 주십시오.

    2-2. 인증값 생성

    네이버 클라우드 플랫폼 API 사용 인증에 필요한 IAM 인증값을 생성해 주십시오. 인증에 필요한 헤더는 다음과 같습니다.

    • x-ncp-iam-access-key: 네이버 클라우드 플랫폼 포털의 마이페이지 > API 인증키 관리 메뉴에서 Access Key 발급
    • x-ncp-apigw-signature-v2 : Access Key와 매핑되는 Secret Key를 HmacSHA256 암호화하여 signature 값 생성(개행 문자는 \n 사용)
    • x-ncp-apigw-api-key : API Gateway를 통해 API Key 발급
    • x-ncp-apigw-timestamp : 인증값은 아니지만 요청 헤더에 포함. API 명세 참고
    참고

    signature 값을 생성하는 방법과 예제 코드는 네이버 클라우드 플랫폼 API 가이드 > API 개요 > 기본 API > Ncloud API > 2.헤더 생성을 참조해 주십시오.

    2-3. 요청 파라미터 추가

    getInputFileLog API 요청 파라미터 값을 추가해 주십시오. 요청 파라미터는 다음과 같습니다.

    • hashCode: Hash 값을 스트링으로 추가
    • hashType: Hash 값의 알고리즘을 표기(MD5 또는 SHA-1)

    다음은 생성된 파라미터 예시입니다.

    hashCode=00010efc49b7174d18400710eed1642a7d4b12db&hashType=sha1
    

    2-4. API 요청

    File Filter getInputFileLog URI로 요청을 전송해 주십시오. 다음은 getInputFileLog 요청 예제 코드입니다.

    public static void main(String[] args)
    {
    	String apiDomain = "https://filesafer.apigw.ntruss.com";
    	String method = "GET";
    	String apiURL = "/filefilter/v1/getInputFileLog?hashCode=FILE_HASH&hashType=sha1"; // step 3: add required parameter 
    
    	long timestamp = System.currentTimeMillis();
    
    	// step 2: Create Authentication Value
    	String signature = makeSignature(method, apiURL, timestamp);
    	
    	// step 4: Request API
    	URL url = new URL(apiDomain + apiURL);
    	HttpURLConnection con = (HttpURLConnection)url.openConnection();
    	con.setRequestMethod(method);
    	con.setRequestProperty("x-ncp-apigw-timestamp", Long.toString(timestamp));
    	con.setRequestProperty("x-ncp-iam-access-key", ACCESSKEY); // access key (from portal or sub account)
    	con.setRequestProperty("x-ncp-apigw-signature-v2", signature);
    
    			
    	// step5: Check the response value and determine whether to block
    	int responseCode = con.getResponseCode();
    	BufferedReader br = null;
    	
    	if(responseCode == 200) {
    		br = new BufferedReader(new InputStreamReader(con.getInputStream()));
    
    		String inputLine;
    		StringBuffer response = new StringBuffer();
    		while ((inputLine = br.readLine()) != null) {
    			response.append(inputLine);
    		}
    	
    		// do next step (ex, determine whether to block)
    		...
    
    		br.close();
    	}
    }
    

    2-5. 응답 값 확인 및 차단 여부 판단

    getInputFileLog 응답에 따라서 차단 또는 허용 여부를 판단해 주십시오.

    inputFileLogList의 개수가 0이면 요청한 결과가 없는 경우이고, inputFileLogList가 2개 이상일 경우는 2번 이상 분석된 경우입니다. inputFileLogListanalysisStatusCode 필드 값을 읽어서 검사 진행 상황을 확인해 주십시오.

    analysisStatusCode 코드설명
    IPRGAnalyzing분석 중
    CMPLAnalysis completed분석 완료
    RDYReady분석 대기
    ERRAnalysis error오류
    EXCNExclude analysis예외

    inputFileLogListanalysisResultCode 필드 값을 읽어서 검사 결과를 확인해 주십시오.

    analysisResultCode설명
    MMalware detected악성 코드 탐지
    NMalware not detected정상 파일
    EDetection error오류

    악성 코드가 검출된 경우에는 파일을 시스템에서 삭제하거나 안전하게 격리해 주십시오.
    다음은 검사 분석 완료 상태이면서 악성 코드가 검출된 경우의 응답 예시입니다.

    {
      "returnCode": "0",
      "returnMessage": "success",
      "inputFileLogList": [
        {
          "fileType": "application/x-msdownload; format=pe32",
          "fileSize": 740544,
          "md5": "a69acb01b99959efec7c0a2a8caa7545",
          "sha1": "f093e7767bb63ac973b697d3fd1d40a78b87b8bf",
          "sha256": "470a75fe3da2ddf9d27fb3f9c96e6c665506ea7ba26ab89f0c89606f678ae4a2",
          "analysisStatusCode": "CMPL",
          "analysisResultCode": "M",
          "notifyYmdt": 1544005507000,
          "registrationYmdt": 1544005472000,
          "serviceCode": null,
          "applicationCode": null
        },
        {
          "fileType": "application/x-msdownload; format=pe32",
          "fileSize": 740544,
          "md5": "a69acb01b99959efec7c0a2a8caa7545",
          "sha1": "f093e7767bb63ac973b697d3fd1d40a78b87b8bf",
          "sha256": "470a75fe3da2ddf9d27fb3f9c96e6c665506ea7ba26ab89f0c89606f678ae4a2",
          "analysisStatusCode": "CMPL",
          "analysisResultCode": "M",
          "notifyYmdt": 1544006407000,
          "registrationYmdt": 1544006150000,
          "serviceCode": null,
          "applicationCode": null
        },
      ]
    }
    

    이 문서가 도움이 되었습니까?

    Changing your password will log you out immediately. Use the new password to log back in.
    First name must have atleast 2 characters. Numbers and special characters are not allowed.
    Last name must have atleast 1 characters. Numbers and special characters are not allowed.
    Enter a valid email
    Enter a valid password
    Your profile has been successfully updated.