main.go 3.77 KB
Newer Older
ale's avatar
ale committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
package main

import (
	"bufio"
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"strings"
)

var (
	configPath   = flag.String("config", "/etc/git-ssh-acl", "config directory")
	doUpdateKeys = flag.Bool("update", false, "update authorized_keys file")
)

type RepoAuth struct {
	Path    string   `json:"path"`
	Writers []string `json:"rw,omitempty"`
	Readers []string `json:"ro,omitempty"`
}

func (r *RepoAuth) CheckACL(cmd, user string) bool {
	switch cmd {
	case "git-receive-pack", "git receive-pack":
		return contains(r.Writers, user)
	case "git-upload-pack", "git upload-pack", "git-upload-archive", "git upload-archive":
		return contains(r.Writers, user) || contains(r.Readers, user)
	}
	return false
}

func contains(l []string, s string) bool {
	for _, elem := range l {
		if elem == s {
			return true
		}
	}
	return false
}

func readConfig(path string) ([]*RepoAuth, error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	var conf []*RepoAuth
	if err := json.NewDecoder(f).Decode(&conf); err != nil {
		return nil, err
	}
	return conf, nil
}

func parseCommand(s string) (string, string, error) {
	parts := strings.SplitN(s, " ", 2)
	if len(parts) < 2 {
		return "", "", errors.New("not enough arguments")
	}
	action := parts[0]
	arg := parts[1]
	if action == "git" {
		subparts := strings.SplitN(arg, " ", 2)
		if len(subparts) < 2 {
			return "", "", errors.New("not enough arguments")
		}
		action = fmt.Sprintf("%s %s", action, subparts[0])
		arg = subparts[1]
	}
	return action, arg, nil
}

var pathRx = regexp.MustCompile(`^'/*([a-zA-Z0-9][a-zA-Z0-9._-]*(/[a-zA-Z0-9][a-zA-Z0-9._-]*)*)'$`)

func runGit(s, user string, conf []*RepoAuth) error {
	cmd, arg, err := parseCommand(s)
	if err != nil {
		return err
	}

	matches := pathRx.FindStringSubmatch(arg)
	if matches == nil || matches[1] == "" {
		return errors.New("bad argument")
	}
	path := matches[1]
	found := false
	for _, repo := range conf {
		if repo.Path == path {
			if !repo.CheckACL(cmd, user) {
				return errors.New("unauthorized")
			}
			found = true
			break
		}
	}
	if !found {
		return errors.New("unknown repository")
	}

	gitCmd := exec.Command("git", "shell", "-c", fmt.Sprintf("%s %s", cmd, arg))
	gitCmd.Stdout = os.Stdout
	gitCmd.Stderr = os.Stderr
	gitCmd.Stdin = os.Stdin
	return gitCmd.Run()
}

func readSshKeys(path string) ([]string, error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	var keys []string
	for s := bufio.NewScanner(f); s.Scan(); {
		line := s.Text()
		if strings.HasPrefix(line, "ssh-") {
			keys = append(keys, line)
		}
	}
	return keys, nil
}

func updateAuthorizedKeys(outputFile string) error {
	filenames, err := filepath.Glob(fmt.Sprintf("%s/users/*.key", *configPath))
	if err != nil {
		return err
	}

	w, err := os.OpenFile(outputFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
	if err != nil {
		return err
	}
	defer w.Close()

	for _, f := range filenames {
		keys, err := readSshKeys(f)
		if err != nil {
			log.Printf("%v", err)
			continue
		}
		user := strings.TrimSuffix(filepath.Base(f), ".key")
		for _, k := range keys {
			fmt.Fprintf(w, "command=\"%s %s\" %s\n", os.Args[0], user, k)
		}
	}
	return nil
}

func main() {
	log.SetFlags(0)
	flag.Parse()

	if *doUpdateKeys {
		if flag.NArg() != 1 {
			log.Fatal("Usage: git-ssh-acl --update <AUTHORIZED_KEYS_FILE>")
		}
		updateAuthorizedKeys(flag.Arg(0))
	} else {
		if flag.NArg() != 1 {
			log.Fatal("Usage: git-ssh-acl <USER>")
		}
		user := flag.Arg(0)

		conf, err := readConfig(filepath.Join(*configPath, "config.json"))
		if err != nil {
			log.Fatal(err)
		}

		cmd := os.Getenv("SSH_ORIGINAL_COMMAND")
		if cmd == "" {
			log.Fatal("SSH_ORIGINAL_COMMAND is unset")
		}

		if err := runGit(cmd, user, conf); err != nil {
			log.Fatal(err)
		}
	}
}