Skip to content
Snippets Groups Projects
akms-simulator.go 4.07 KiB
Newer Older
  • Learn to ignore specific revisions
  • package main
    
    import (
    
    	"crypto/tls"
    	"crypto/x509"
    
    	"net/http"
    
    
    	"github.com/sirupsen/logrus"
    
    const (
    	// LogFile is the file where the log is stored.
    	LogFilePath = "/logs/akms-simulator.log"
    )
    
    
    type LogFile struct {
    	Source string            `json:"source"`
    	Body   PushKSAKeyRequest `json:"body"`
    }
    type PushKSAKeyRequest struct {
    	RequestID string   `json:"request_ID"`
    	ProcessID string   `json:"process_ID"`
    	KSAKeys   []KSAKey `json:"ksa_keys"`
    }
    
    type KSAKey struct {
    	KeyID string `json:"key_ID"`
    	Key   string `json:"key"`
    }
    
    
    func main() {
    
    	tlsCAFile := flag.String("ca", "", "Path to CA certificate file")
    	tlsCertFile := flag.String("cert", "", "Path to certificate file")
    	tlsKeyFile := flag.String("key", "", "Path to key file")
    	flag.Parse()
    
    
    	logrus.Info("Starting AKMS Simulator...")
    
    
    	router := http.NewServeMux()
    
    	router.HandleFunc("/api/v1/keys/push_ksa_key", handlePushKsaKey)
    
    	router.HandleFunc("/debug/get_log_file", logFileRequest)
    
    
    	server := &http.Server{
    		Addr:    ":4444",
    		Handler: router,
    	}
    
    	if *tlsCAFile != "" && *tlsCertFile != "" && *tlsKeyFile != "" {
    		logrus.Info("TLS enabled")
    		cp := x509.NewCertPool()
    		b, err := os.ReadFile(*tlsCAFile)
    		if err != nil {
    			logrus.Fatalf("Error reading CA file: %s", err)
    		}
    
    		if !cp.AppendCertsFromPEM(b) {
    			logrus.Fatalf("Error appending certs from PEM")
    		}
    
    		cert, err := tls.LoadX509KeyPair(*tlsCertFile, *tlsKeyFile)
    		if err != nil {
    			logrus.Fatalf("Error loading X509 key pair: %s", err)
    		}
    
    		tlsConfig := &tls.Config{
    			MinVersion:   tls.VersionTLS13,
    			ClientCAs:    cp,
    			Certificates: []tls.Certificate{cert},
    			ClientAuth:   tls.RequireAndVerifyClientCert,
    		}
    
    		server.TLSConfig = tlsConfig
    
    		logrus.Fatal(server.ListenAndServeTLS("", ""))
    	} else {
    		logrus.Fatal(server.ListenAndServe())
    	}
    
    func logFileRequest(w http.ResponseWriter, r *http.Request) {
    	if r.Method == http.MethodDelete {
    
    		if _, err := os.Stat(LogFilePath); err == nil {
    			err := os.Remove(LogFilePath)
    
    			if err != nil {
    				logrus.Errorf("Error deleting log file: %s", err)
    				w.WriteHeader(http.StatusInternalServerError)
    				return
    			}
    		}
    		logrus.Info("Log file deleted or never existed in the first place")
    		w.WriteHeader(http.StatusNoContent)
    		return
    	} else if r.Method != http.MethodGet {
    		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
    		logrus.Errorf("Method not allowed: %s", r.Method)
    		return
    	}
    
    
    	logrus.Info("Log file requested")
    
    	http.ServeFile(w, r, LogFilePath)
    
    func handlePushKsaKey(w http.ResponseWriter, r *http.Request) {
    	if r.Method != http.MethodPost {
    		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
    
    		logrus.Errorf("Method not allowed: %s", r.Method)
    
    	body, err := io.ReadAll(r.Body)
    
    	if err != nil {
    		http.Error(w, "Failed to read request body", http.StatusInternalServerError)
    
    		logrus.Errorf("Failed to read request body: %s", err)
    
    		return
    	}
    
    	ip := r.RemoteAddr
    
    	logstring := "Request came from: " + ip + "; Body: " + string(body)
    	logrus.Info(logstring)
    
    	var bodyObject PushKSAKeyRequest
    	err = json.Unmarshal(body, &bodyObject)
    	if err != nil {
    		logrus.Errorf("Error parsing body into PushKSAKeyRequest: %s", err)
    		return
    	}
    
    	logFile := LogFile{Source: ip, Body: bodyObject}
    	jsonLogFile, err := json.Marshal(logFile)
    	if err != nil {
    		logrus.Errorf("Error marshaling logFile: %s", err)
    		w.WriteHeader(http.StatusInternalServerError)
    		return
    	}
    
    	// Append jsonLogFile to akms-logfile.log
    
    	f, err := os.OpenFile(LogFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
    
    	if err != nil {
    		logrus.Errorf("Error opening log file: %s", err)
    		w.WriteHeader(http.StatusInternalServerError)
    		return
    	}
    	defer f.Close() //nolint:errcheck
    	if _, err := f.Write(jsonLogFile); err != nil {
    		logrus.Errorf("Error writing to log file: %s", err)
    		w.WriteHeader(http.StatusInternalServerError)
    		return
    	}
    
    	// Write the newline character
    	if _, err := f.Write([]byte("\n")); err != nil {
    		logrus.Errorf("Error writing newline to log file: %s", err)
    		w.WriteHeader(http.StatusInternalServerError)
    		return
    	}
    
    	w.WriteHeader(http.StatusNoContent)