package main
import (
"fmt"
"net/http"
"os/exec"
"regexp"
)
// Allowlist of valid hosts
var allowedHosts = map[string]bool{
"localhost": true,
"google.com": true,
"example.com": true,
}
var hostnamePattern = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9.-]{0,61}[a-zA-Z0-9]$`)
func pingHandler(w http.ResponseWriter, r *http.Request) {
host := r.URL.Query().Get("host")
// SECURE: Validate against allowlist
if !allowedHosts[host] || !hostnamePattern.MatchString(host) {
http.Error(w, "Invalid host", 400)
return
}
// SECURE: Use argument array, no shell
cmd := exec.Command("ping", "-c", "4", host)
output, err := cmd.CombinedOutput()
if err != nil {
http.Error(w, "Ping failed", 500)
return
}
w.Write(output)
}
var allowedFiles = map[string]bool{
"readme.txt": true,
"config.json": true,
"log.txt": true,
}
func fileHandler(w http.ResponseWriter, r *http.Request) {
filename := r.URL.Query().Get("file")
// SECURE: Validate against allowlist
if !allowedFiles[filename] {
http.Error(w, "File not allowed", 400)
return
}
// SECURE: Use argument array, no shell
cmd := exec.Command("cat", filename)
output, err := cmd.CombinedOutput()
if err != nil {
http.Error(w, "File read failed", 500)
return
}
w.Write(output)
}
func main() {
http.HandleFunc("/ping", pingHandler)
http.HandleFunc("/file", fileHandler)
http.ListenAndServe(":8080", nil)
}