Develop File Filter

Prev Next

Available in Classic and VPC

You can write File Filter codes using File Filter REST API.

Note

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

File Filter implementation scenario

Here is the scenario for applying File Filter:

filesafer-programming-file_scenario_ko

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

2. Check scan results (getInputFileLog)
2-1. Identify the hash value to check scan results
2-2. Create authentication value
2-3. Add request parameter
2-4. Request API
2-5. Check response value and determine whether to block

Note

When a file is identified as malware in File Filter, the hash value of Hash Filter is updated. So you can get the same result when you view the scan results in Hash Filter.

Write File Filter codes

Write codes according to the File Filter implementation scenario.

1. Request file scan (inputFile)

Use the inputFile API from File Filter API to request a file scan.

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 malware. File restrictions are as follows:

  • File limit: When calling the inputFile API, only 1 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 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: Issue Access Key from the My Account > Account and security management > Security management > Access management menu on the console.
  • x-ncp-apigw-signature-v2 : Create a signature value by HmacSHA256-encrypting the Secret Key mapped with the Access Key (use \n for a new-line character).
  • x-ncp-apigw-api-key : Issue API Key through API Gateway.
  • x-ncp-apigw-timestamp : Not an authentication value, but 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 > Basic API > Ncloud API > 2. Create header.

1-3. Create request body

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

  • Key: file
  • Value: binary

1-4. Add request parameter

If the file to be transmitted is a zipped file with a password, add the following parameters to the request:

  • Key: archivePassword
  • Value: Zipped 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 scan results (getInputFileLog)

Use the getInputFileLog API from File Filter API to check malware inspection results.

Note

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

2-1. Identify the hash value to check scan results

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

2-2. Create 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: Issue Access Key from the My Account > Account and security management > Security management > Access management menu on the console.
  • x-ncp-apigw-signature-v2: Create a signature value by HmacSHA256-encrypting the Secret Key mapped with the Access Key (use \n for a new-line character).
  • x-ncp-apigw-api-key: Issue API Key through API Gateway.
  • x-ncp-apigw-timestamp: Not an authentication value, but 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 > Basic API > Ncloud API > 2. Create header.

2-3. Add 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 the 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 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, no results were found for the request. Two or more inputFileLogList indicate that the analysis was performed more than once. Read inputFileLogList's analysisStatusCode field value, and check the progress of inspection.

analysisStatusCode code Value Description
IPRG Analyzing Analyzing
CMPL Analysis completed Analysis complete
RDY Ready Ready
ERR Analysis error Analysis error
EXCN Exclude analysis Exclude analysis

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

analysisResultCode Value Description
M Malware detected Malware detected
N Malware not detected Malware not detected
E Detection error Detection error

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