Skip to content

Instantly share code, notes, and snippets.

@hkneptune
Last active January 31, 2022 20:21
Show Gist options
  • Save hkneptune/aed0fa3fc42cb9b84eb40579eaefc95a to your computer and use it in GitHub Desktop.
Save hkneptune/aed0fa3fc42cb9b84eb40579eaefc95a to your computer and use it in GitHub Desktop.
The utility class to solve the Path Manipulation issue found by the Fortify Static Code Analyzer.
/**
* Path Manipulation (Input Validation and Representation, Data Flow)
*
* **Abstract:**
*
* Attackers are able to control the file system path argument, which allows them to access or
* modify otherwise protected files.
*
* **Explanation:**
*
* Path manipulation errors occur when the following two conditions are met:
*
* 1. An attacker is able to specify a path used in an operation on the file system.
*
* 2. By specifying the resource, the attacker gains a capability that would not otherwise be
* permitted.
*
* For example, the program may give the attacker the ability to overwrite the specified file or run
* with a configuration controlled by the attacker.
*/
// https://gist.github.com/hkneptune/aed0fa3fc42cb9b84eb40579eaefc95a
package com.neptuneli.util;
public class Normalize {
private Normalize() {
}
/**
* Remove invalid characters in the string
*
* @param input The string with variables entered by users
* @return The clean string
*/
public static String parse(final String input) {
final StringBuilder output = new StringBuilder();
if (input != null) {
for (int i = 0; i < input.length(); ++i) {
output.append(Normalize.parse(input.charAt(i)));
}
}
return output.toString();
}
/**
* Replace the character with a valid character
*
* @param input The character for checking
* @return The clean character
*/
public static char parse(final char input) {
final int digit = (int) input;
char output = '\0';
// All
// for (int i = 32; i <= 126; ++i) {
// if (digit == i) {
// output = (char) i;
// }
// }
// From 0 to 9 and :
for (int i = 48; i <= 58; ++i) {
if (digit == i) {
output = (char) i;
}
}
// @ and From A to Z
for (int i = 64; i <= 90; ++i) {
if (digit == i) {
output = (char) i;
}
}
// From a to z
for (int i = 97; i <= 122; ++i) {
if (digit == i) {
output = (char) i;
}
}
// - . /
for (int i = 45; i <= 47; ++i) {
if (digit == i) {
output = (char) i;
}
}
// \
if (digit == 92) {
output = (char) 92;
}
// _
if (digit == 95) {
output = (char) 95;
}
// space
if (digit == 32) {
output = (char) 32;
}
return output;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment