Path traversal remediation function examples in multiple languages: Java, Python, .Net, JavaScript, Go, Rust, Ruby, PHP, and C++

Path Traversal Remediation

Here are some examples of functions in Java, Python 3, JavaScript, C#, Go, Ruby, PHP, Rust, and C++ that sanitize an input string for path traversal:

**Java:**

```java

import java.nio.file.Path;

import java.nio.file.Paths;

public class PathTraversalSanitizer {

    public static String sanitizePath(String input) {

        Path basePath = Paths.get("/base/path"); // Replace with your actual base path

        Path resolvedPath = basePath.resolve(input).normalize();

        if (resolvedPath.startsWith(basePath)) {

            return resolvedPath.toString();

        } else {

            return null; // Path traversal attempt detected

        }

    }

    public static void main(String[] args) {

        String userInput = "../secret/file.txt";

        String sanitizedPath = sanitizePath(userInput);

        if (sanitizedPath != null) {

            System.out.println("Sanitized Path: " + sanitizedPath);

        } else {

            System.out.println("Path traversal attempt detected.");

        }

    }

}

```

**Python 3:**

```python

import os

def sanitize_path(input_path, base_path):

    sanitized_path = os.path.abspath(os.path.join(base_path, input_path))

    if sanitized_path.startswith(base_path):

        return sanitized_path

    else:

        return None  # Path traversal attempt detected

# Example usage

user_input = "../secret/file.txt"

base_path = "/base/path"  # Replace with your actual base path

sanitized_path = sanitize_path(user_input, base_path)

if sanitized_path is not None:

    print(f"Sanitized Path: {sanitized_path}")

else:

    print("Path traversal attempt detected.")

```

**JavaScript:**

```javascript

const path = require('path');

function sanitizePath(input, basePath) {

    const sanitizedPath = path.resolve(basePath, input);

    if (sanitizedPath.startsWith(basePath)) {

        return sanitizedPath;

    } else {

        return null; // Path traversal attempt detected

    }

}

// Example usage

const userInput = "../secret/file.txt";

const basePath = "/base/path"; // Replace with your actual base path

const sanitizedPath = sanitizePath(userInput, basePath);

if (sanitizedPath !== null) {

    console.log(`Sanitized Path: ${sanitizedPath}`);

} else {

    console.log("Path traversal attempt detected.");

}

```

**C#:**

```csharp

using System;

using System.IO;

public class PathTraversalSanitizer

{

    public static string SanitizePath(string input, string basePath)

    {

        string sanitizedPath = Path.GetFullPath(Path.Combine(basePath, input));

        if (sanitizedPath.StartsWith(basePath, StringComparison.OrdinalIgnoreCase))

        {

            return sanitizedPath;

        }

        else

        {

            return null; // Path traversal attempt detected

        }

    }

    public static void Main(string[] args)

    {

        string userInput = "../secret/file.txt";

        string basePath = @"C:\base\path"; // Replace with your actual base path

        string sanitizedPath = SanitizePath(userInput, basePath);

        if (sanitizedPath != null)

        {

            Console.WriteLine($"Sanitized Path: {sanitizedPath}");

        }

        else

        {

            Console.WriteLine("Path traversal attempt detected.");

        }

    }

}

```

**Go (Golang):**

```go

package main

import (

"fmt"

"path/filepath"

)

func sanitizePath(input, basePath string) string {

absPath, err := filepath.Abs(filepath.Join(basePath, input))

if err != nil || !filepath.HasPrefix(absPath, basePath) {

return "" // Path traversal attempt detected

}

return absPath

}

func main() {

userInput := "../secret/file.txt"

basePath := "/base/path" // Replace with your actual base path

sanitizedPath := sanitizePath(userInput, basePath)

if sanitizedPath != "" {

fmt.Printf("Sanitized Path: %s\n", sanitizedPath)

} else {

fmt.Println("Path traversal attempt detected.")

}

}

```

**Ruby:**

```ruby

require 'pathname'

def sanitize_path(input, base_path)

  absolute_path = File.expand_path(File.join(base_path, input))

  if absolute_path.start_with?(base_path)

    return absolute_path

  else

    return nil # Path traversal attempt detected

  end

end

# Example usage

user_input = "../secret/file.txt"

base_path = "/base/path" # Replace with your actual base path

sanitized_path = sanitize_path(user_input, base_path)

if sanitized_path

  puts "Sanitized Path: #{sanitized_path}"

else

  puts "Path traversal attempt detected."

end

```

**PHP:**

```php

function sanitizePath($input, $basePath) {

    $absolutePath = realpath($basePath . '/' . $input);

    if (strpos($absolutePath, $basePath) === 0) {

        return $absolutePath;

    } else {

        return null; // Path traversal attempt detected

    }

}

// Example usage

$userInput = "../secret/file.txt";

$basePath = "/base/path"; // Replace with your actual base path

$sanitizedPath = sanitizePath($userInput, $basePath);

if ($sanitizedPath !== null) {

    echo "Sanitized Path: " . $sanitizedPath . PHP_EOL;

} else {

    echo "Path traversal attempt detected." . PHP_EOL;

}

```

**Rust:**

```rust

use std::path::{Path, PathBuf};

fn sanitize_path(input: &str, base_path: &str) -> Option<PathBuf> {

    let combined_path = Path::new(base_path).join(input);

    let absolute_path = combined_path.canonicalize().ok()?;

    if absolute_path.starts_with(Path::new(base_path)) {

        Some(absolute_path)

    } else {

        None // Path traversal attempt detected

    }

}

fn main() {

    let user_input = "../secret/file.txt";

    let base_path = "/base/path"; // Replace with your actual base path

    if let Some(sanitized_path) = sanitize_path(user_input, base_path) {

        println!("Sanitized Path: {:?}", sanitized_path);

    } else {

        println!("Path traversal attempt detected.");

    }

}

```

**C++:**

```cpp

#include <iostream>

#include <filesystem>

std::string sanitizePath(const std::string& input, const std::string& basePath) {

    std::filesystem::path absolutePath = std::filesystem::canonical(std::filesystem::path(basePath) / input);

    std::filesystem::path basePathPath = std::filesystem::path(basePath);

    if (absolutePath.has_parent_path() && absolutePath.has_root_path() &&

        absolutePath.parent_path() == basePathPath && absolutePath.has_filename()) {

        return absolutePath.string();

    } else {

        return ""; // Path traversal attempt detected

    }

}

int main() {

    std::string userInput = "../secret/file.txt";

    std::string basePath = "/base/path"; // Replace with your actual base path

    std::string sanitizedPath = sanitizePath(userInput, basePath);

    if (!sanitizedPath.empty()) {

        std::cout << "Sanitized Path: " << sanitizedPath << std::endl;

    } else {

        std::cout << "Path traversal attempt detected." << std::endl;

    }

    return 0

Previous
Previous

Remediating SQL Injection

Next
Next

Cross Site Scripting (XSS) Sanitization/Validation process concepts in multiple languages including Java, Python, JavaScript, C#.NET, GoLang or GO, RUST, PHP, and C++