Develop File Filter
    • PDF

    Develop File Filter

    • PDF

    Article Summary

    Available in Classic and VPC

    It describes how to use File Filter REST API to create the File Filter code.

    Note

    Before developing File Filter, you need to subscribe to File Safer, subscribe to API Gateway, and create an API Key. For more information, see Getting started with File Safer.

    File Filter implementation scenario

    The following describes the scenario for applying File Filter.

    filesafer-programming-file_scenario_ko

    1. Request file inspection (inputFile)
    1-1. Identify files suspected of being malware
    1-2. Create an authentication value
    1-3. Create request body
    1-4. Add a request parameter
    1-5. Request API

    2. Check inspection results (getInputFileLog)
    2-1. Identify the hash value for checking inspection results
    2-2. Create an authentication value
    2-3. Add a request parameter
    2-4. Request API
    2-5. Check the response value and decide whether to block

    Note

    If the File Filter is identified as malware, the hash value of the hash filter is updated. So you can get the same result even if you look up the inspection results in Hash Filter.

    Write File Filter codes

    Write codes according to the File Filter implementation scenario.

    1. Request file inspection (inputFile)

    Use inputFile among File Filter APIs to request file inspection.

    Note

    For information on inputFile API specifications, see inputFile (File Filter).

    1-1. Identify files suspected of being malware

    Identify files that cannot be verified by Hash Filter or files that need to be checked for maliciousness. File restrictions are as follows:

    • Limitation on the number of files: when calling the inputFile API, only one file is processed per request. If 2 or more files are transmitted, only 1 file is randomly selected and processed.
    • File size limit: file size per API call is limited to 10 MB

    1-2. Create an authentication value

    Create an IAM authentication value required for the NAVER Cloud Platform API use authentication. The headers required for authentication are as follows:

    • x-ncp-iam-access-key: get the access key issued in the My page> Manage API authentication key menu of the NAVER Cloud Platform portal
    • x-ncp-apigw-signature-v2: create a signature value by HmacSHA256-encrypting the Secret Key mapped with the Access Key (Use \n for the newline character)
    • x-ncp-apigw-api-key: get the API Key issued through the API Gateway
    • x-ncp-apigw-timestamp: it is not an authentication value, but it is included in the request header. See API specifications.
    Note

    For information on how to create a signature value and example codes, see NAVER Cloud Platform API guide > API overview > Default API > Ncloud API > 2. Create headers.

    1-3. Create request body

    Create a request that includes a file in the body as a multipart.

    • Key: file
    • Value: binary

    1-4. Add a request parameter

    If the file to be transmitted is a compression file with a password, add the following parameters to the request.

    • Key: archivePassword
    • Value: compression file password string

    The following is the format of the POST request body with parameters added. The boundary value is used as an entity identifier, and '--' must be put in front of the boundary setting value. You must use crlf('\r\n') at the end of each entity.

    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. Request API

    Send the request to the File Filter inputFile URI. The following is an example code of the inputFile request.

    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. Check inspection results (getInputFileLog)

    Use getInputFileLog among the File Filter APIs to check malware inspection results.

    Note

    For information on the getInputFileLog API specifications, see getInputFileLog (File Filter).

    2-1. Identify the hash value for checking inspection results

    Identify the hash value of the file you requested File Filter to inspect through the file inspection request scenario.

    2-2. Create an authentication value

    Create an IAM authentication value required for the NAVER Cloud Platform API use authentication. The headers required for authentication are as follows:

    • x-ncp-iam-access-key: get the access key issued in the My page> Manage API authentication key menu of the NAVER Cloud Platform portal
    • x-ncp-apigw-signature-v2: create a signature value by HmacSHA256-encrypting the Secret Key mapped with the Access Key (Use \n for the newline character)
    • x-ncp-apigw-api-key: get the API Key issued through the API Gateway
    • x-ncp-apigw-timestamp: it is not an authentication value, but it is included in the request header. See API specifications.
    Note

    For information on how to create a signature value and example codes, see NAVER Cloud Platform API guide > API overview > Default API > Ncloud API > 2. Create headers.

    2-3. Add a request parameter

    Add the getInputFileLog API request parameter value. The request parameters are as follows:

    • hashCode: add a hash value as a string
    • hashType: indicate the algorithm of the hash value (MD5 or SHA-1)

    The following is an example of a created parameter.

    hashCode=00010efc49b7174d18400710eed1642a7d4b12db&hashType=sha1
    

    2-4. Request API

    Send a request to the File Filter getInputFileLog URI. The following is an example code of the getInputFileLog request.

    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. Check the response value and determine whether to block

    Determine whether to block or allow according to the getInputFileLog response.

    If the number of inputFileLogList is 0, there is no requested result, and if there are more than 2 inputFileLogList, it is analyzed more than twice. Read the analysisStatusCode field value of inputFileLogList, and check the progress of inspection.

    analysisStatusCode codeValueDescription
    IPRGAnalyzingAnalyzing
    CMPLAnalysis completedAnalysis completed
    RDYReadyWaiting for analysis
    ERRAnalysis errorError
    EXCNExclude analysisException

    Read the analysisResultCode field value of inputFileLogList, and check the inspection result.

    analysisResultCodeValueDescription
    MMalware detectedDetect malware
    NMalware not detectedNormal file
    EDetection errorError

    If malware is detected, delete the file from the system or quarantine it safely.
    The following is an example of a response when inspection analysis is complete and malware is detected.

    {
      "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
        },
      ]
    }
    

    Was this article helpful?

    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.