Skip to content

Instantly share code, notes, and snippets.

@jellis
Created September 7, 2016 05:02
Show Gist options
  • Save jellis/e2fcbb7ac50146599d3e441f53124477 to your computer and use it in GitHub Desktop.
Save jellis/e2fcbb7ac50146599d3e441f53124477 to your computer and use it in GitHub Desktop.
package main
import (
"net/http"
"os"
"strings"
)
var token = "ABC123"
func main() {
http.HandleFunc("/file", writeFile)
http.ListenAndServeTLS(":8000", "server.pem", "server.key", nil)
}
func writeFile(w http.ResponseWriter, r *http.Request) {
if AuthHeader(r) != token {
// Jump ship
}
// The endpoint we're writing to
var path = "/home/deploy/.ssh/authorized_keys"
r.ParseForm()
if r.Method != "POST" || r.Form.Get("authorized_keys") == "" {
// Throw a 404
}
// Open the file to write to it
f, err := os.Create(path)
if err != nil {
w.WriteHeader(500)
}
// Close the file when we're done
defer f.Close()
// Write the new authorized_keys value
f.WriteString(r.Form.Get("authorized_keys"))
f.Sync()
// Send a response
w.WriteHeader(200)
}
func AuthHeader(r *http.Request) (string) {
authHeader := r.Header.Get("Authorization");
if authHeader == "" {
return ""
}
authHeaderParts := strings.Split(authHeader, " ")
if len(authHeaderParts) != 2 || strings.ToLower(authHeaderParts[0]) != "bearer" {
return ""
}
return authHeaderParts[1]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment