Skip to content

Instantly share code, notes, and snippets.

@wqweto
Last active March 13, 2024 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wqweto/355ec6957ef3d3c227f2b28127606df5 to your computer and use it in GitHub Desktop.
Save wqweto/355ec6957ef3d3c227f2b28127606df5 to your computer and use it in GitHub Desktop.
Signing Web Service

How to use

You can use it from command line with curl like this

c:> curl -sSL -F file=@project1.exe http://localhost:4500/sign -o project1_signed.exe --fail || echo failed
package main
import (
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
)
func uploadHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// limit upload up to 1024 MB
if err := r.ParseMultipartForm(1024 << 20); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
exFile, err := os.Executable()
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
exPath := filepath.Dir(exFile)
files := r.MultipartForm.File["file"]
for _, fileHeader := range files {
file, err := fileHeader.Open()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = os.MkdirAll(filepath.Join(exPath, "uploads"), os.ModePerm)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
uploadFile := filepath.Base(fileHeader.Filename)
uploadPath := filepath.Join(exPath, "uploads", fmt.Sprintf("%d-%s", time.Now().UnixNano(), uploadFile))
f, err := os.Create(uploadPath)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
defer f.Close()
_, err = io.Copy(f, file)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
f.Close()
batFile, err := filepath.Abs(filepath.Join(exPath, "s.bat"))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
out, err := exec.Command("cmd.exe", "/c", batFile, uploadPath).Output()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
outstr := string(out)
if !strings.Contains(outstr, "Succeed") {
http.Error(w, outstr, http.StatusInternalServerError)
return
}
w.Header().Set("Content-Disposition", "attachment; filename="+strconv.Quote(uploadFile))
w.Header().Set("Content-Type", "application/octet-stream")
http.ServeFile(w, r, uploadPath)
os.Remove(uploadPath)
}
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/sign", uploadHandler)
if err := http.ListenAndServe(":4500", mux); err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment