57 lines
1.4 KiB
Go
57 lines
1.4 KiB
Go
|
|
// Copyright 2025 Patial Tech (Ankit Patial).
|
||
|
|
//
|
||
|
|
// This file is part of code.patial.tech/go/appcore, which is MIT licensed.
|
||
|
|
// See http://opensource.org/licenses/MIT
|
||
|
|
|
||
|
|
package open
|
||
|
|
|
||
|
|
import (
|
||
|
|
"errors"
|
||
|
|
"fmt"
|
||
|
|
"os"
|
||
|
|
"path/filepath"
|
||
|
|
"strings"
|
||
|
|
)
|
||
|
|
|
||
|
|
// validateInput checks for common security issues in file paths
|
||
|
|
func validateInput(input string) error {
|
||
|
|
if input == "" {
|
||
|
|
return errors.New("input path cannot be empty")
|
||
|
|
}
|
||
|
|
|
||
|
|
// Clean the path to resolve . and .. references
|
||
|
|
clean := filepath.Clean(input)
|
||
|
|
|
||
|
|
// Check for suspicious characters that could be used for injection
|
||
|
|
// Allow URIs (http://, https://, etc.) but validate file paths
|
||
|
|
if !strings.Contains(clean, "://") {
|
||
|
|
// For file paths, check for path traversal attempts
|
||
|
|
if strings.Contains(clean, "..") {
|
||
|
|
return errors.New("path traversal detected in input")
|
||
|
|
}
|
||
|
|
|
||
|
|
// Check if path exists (for file paths)
|
||
|
|
if _, err := os.Stat(clean); err != nil {
|
||
|
|
if os.IsNotExist(err) {
|
||
|
|
return fmt.Errorf("path does not exist: %s", clean)
|
||
|
|
}
|
||
|
|
return fmt.Errorf("cannot access path: %w", err)
|
||
|
|
}
|
||
|
|
} else {
|
||
|
|
// For URIs, validate scheme
|
||
|
|
allowedSchemes := []string{"http://", "https://", "file://", "ftp://", "mailto:"}
|
||
|
|
valid := false
|
||
|
|
for _, scheme := range allowedSchemes {
|
||
|
|
if strings.HasPrefix(strings.ToLower(clean), scheme) {
|
||
|
|
valid = true
|
||
|
|
break
|
||
|
|
}
|
||
|
|
}
|
||
|
|
if !valid {
|
||
|
|
return fmt.Errorf("URI scheme not allowed: %s", clean)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
return nil
|
||
|
|
}
|