add run-as to run hook in other user context

This commit is contained in:
Stefan Schubert 2023-07-05 19:50:07 +02:00
parent f187592147
commit af3ceffdac
No known key found for this signature in database
GPG key ID: B88EC486BDF3E5AD
5 changed files with 47 additions and 0 deletions

View file

@ -6,6 +6,7 @@ Hooks are defined as objects in the JSON or YAML hooks configuration file. Pleas
* `id` - specifies the ID of your hook. This value is used to create the HTTP endpoint (http://yourserver:port/hooks/your-hook-id)
* `execute-command` - specifies the command that should be executed when the hook is triggered
* `run-as` - specifies a different user to run the command with
* `command-working-directory` - specifies the working directory that will be used for the script when it's executed
* `response-message` - specifies the string that will be returned to the hook initiator
* `response-headers` - specifies the list of headers in format `{"name": "X-Example-Header", "value": "it works"}` that will be returned in HTTP response for the hook

View file

@ -566,6 +566,7 @@ func (h *HooksFiles) Set(value string) error {
type Hook struct {
ID string `json:"id,omitempty"`
ExecuteCommand string `json:"execute-command,omitempty"`
RunAs string `json:"run-as,omitempty"`
CommandWorkingDirectory string `json:"command-working-directory,omitempty"`
ResponseMessage string `json:"response-message,omitempty"`
ResponseHeaders ResponseHeaders `json:"response-headers,omitempty"`

32
setuser.go Normal file
View file

@ -0,0 +1,32 @@
//go:build !windows
// +build !windows
package main
import (
"log"
"os/exec"
"os/user"
"strconv"
"syscall"
)
// sets user for the command to execute
func setUser(cmd *exec.Cmd, username string) {
user, err := user.Lookup(username)
if err != nil {
log.Printf("[%s] error lookup user: %s\n", username, err)
return
}
uid, err := strconv.ParseUint(user.Uid, 10, 32)
if err != nil {
log.Printf("Uid [%s] is not an decimal value: %s\n", user.Uid, err)
return
}
gid, err := strconv.ParseUint(user.Gid, 10, 32)
if err != nil {
log.Printf("Uid [%s] is not an decimal value: %s\n", user.Uid, err)
return
}
cmd.SysProcAttr = &syscall.SysProcAttr{Credential: &syscall.Credential{Uid: uint32(uid), Gid: uint32(gid)}}
}

10
setuser_windows.go Normal file
View file

@ -0,0 +1,10 @@
//go:build windows
// +build windows
package main
import "os/exec"
func setUser(cmd *exec.Cmd, username string) {
// NOOP: Windows doesn't have setuid setgid equivalent to the Unix world.
}

View file

@ -575,6 +575,9 @@ func handleHook(h *hook.Hook, r *hook.Request) (string, error) {
}
cmd := exec.Command(cmdPath)
if h.RunAs != "" {
setUser(cmd, h.RunAs)
}
cmd.Dir = h.CommandWorkingDirectory
cmd.Args, errors = h.ExtractCommandArguments(r)