summaryrefslogtreecommitdiff
path: root/tlsserver.go
blob: 0c75d379ae5f2c221c10f666db65ef3d3f559cb1 (plain)
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
package main

import (
	"crypto/tls"
	"flag"
	"fmt"
	"log"
	"net"
	"os"
	"os/exec"
	"os/user"
	"strconv"
	"sync"
	"syscall"
)

var (
	cfile = flag.String("cert", "cert.pem", "Certificate file in PEM format")
	kfile = flag.String("key", "key.pem", "Key file in PEM format")
	port  = flag.String("port", ":1234", "Port to bind to")
	max   = flag.Int("max", 5, "Maximum allowed failed attempts from IP")
	uid   = flag.Int("uid", -1, "UID to run under")
	args  []string
)

const TLSSERVER = "[tlsserver]"

func main() {
	flag.Parse()

	if flag.NArg() < 1 {
		fmt.Println("Usage: tlsserver [options] cmd [flags for cmd]")
		fmt.Println("options:")
		flag.PrintDefaults()
		os.Exit(1)
	}

	if os.Args[0] == TLSSERVER {
		log.Fatal(serve())
	} else {
		log.Fatal(exc())
	}
}

func exc() error {
	if *uid < 0 {
		return serve()
	}

	// Collect information about the user
	user, err := user.LookupId(strconv.Itoa(*uid))
	if err != nil {
		return err
	}

	// Get the primary and secondary groups
	gids := []int{}

	gid, err := strconv.Atoi(user.Gid)
	if err != nil {
		return fmt.Errorf("couldn't parse user.Gid, strconv.Atoi(%s): %v", user.Gid, err)
	}

	if sgids, err := user.GroupIds(); err != nil {
		log.Printf("weird, couldn't get supplimentary groups: %v", err)
	} else {
		for _, s := range sgids {
			v, e := strconv.Atoi(s)
			if e != nil {
				log.Printf("weird, strconv.Atoi(%s): %v", s, e)
				continue
			} else if v != gid {
				gids = append(gids, v)
			}
		}
	}

	if err := setgid(gid); err != nil {
		return err
	}

	if len(gids) > 0 {
		if err = syscall.Setgroups(gids); err != nil {
			return fmt.Errorf("syscall.Setgroups: %w", err)
		}
	}

	if err = setuid(*uid); err != nil {
		return err
	}

	// Setup the arguments that are needed
	args := []string{TLSSERVER} // name of the command

	for _, arg := range []string{"cert", "key", "port"} {
		fl := flag.Lookup(arg)
		// Only set the flag if it's value are different from the default
		if fl != nil && fl.Value.String() != fl.DefValue {
			args = append(args, "-"+arg, fl.Value.String())
		}
	}
	args = append(args, flag.Args()...)

	return syscall.Exec(os.Args[0], args, os.Environ())
}

func serve() error {
	args = flag.Args()

	// setup certs etc. for TLS-socket
	tconf := new(tls.Config)
	cert, err := tls.LoadX509KeyPair(*cfile, *kfile)
	if err != nil {
		fmt.Println("error with certs:", err)
		os.Exit(2)
	}

	tconf.Certificates = append(tconf.Certificates, cert)
	tconf.BuildNameToCertificate()

	// start listening
	sock, err := tls.Listen("tcp", *port, tconf)
	if err != nil {
		fmt.Println("error with tcp-socket:", err)
		os.Exit(3)
	}
	defer sock.Close()

	// accept-loop
	for {
		conn, err := sock.Accept()
		if err != nil {
			log.Println("error during Accept()", err)
			continue
		}
		log.Println("Got connection:", conn.RemoteAddr())
		go handleConnection(conn, args...)
	}
}

// Track the number of bad attempts.

var mux sync.RWMutex
var badActors = map[string]int{}

func isBadActor(host string) bool {
	mux.RLock()
	defer mux.RUnlock()
	if n, ok := badActors[host]; ok && n >= *max {
		return true
	}
	return false
}

func markBadActor(host string) {
	mux.Lock()
	defer mux.Unlock()
	n, _ := badActors[host]
	badActors[host] = n + 1
}

func markGoodActor(host string) {
	mux.Lock()
	defer mux.Unlock()
	n, _ := badActors[host]
	if n > 0 {
		n -= 1
	}
	badActors[host] = n
}

func handleConnection(conn net.Conn, args ...string) {
	defer conn.Close()

	// prepare environment according to tcp-environ(5)
	rh, rp, err := net.SplitHostPort(conn.RemoteAddr().String())
	if err != nil {
		log.Println("net.SplitHostPort(conn.RemoteAddr()):", err)
		return
	}

	if isBadActor(rh) {
		log.Printf("Too many bad attempts from %s, dropping connection\n", rh)
		return
	}

	lh, lp, err := net.SplitHostPort(conn.LocalAddr().String())
	if err != nil {
		log.Println("net.SplitHostPort(conn.LocalAddr()):", err)
		return
	}

	// setup cmd
	cmd := exec.Command(args[0])
	cmd.Args = args
	cmd.Stdin = conn
	cmd.Stdout = conn
	cmd.Stderr = os.Stderr
	cmd.Env = []string{
		"PATH=" + os.Getenv("PATH"),
		"PROTO=TCP",
		"TCPLOCALIP=" + lh,
		"TCPLOCALPORT=" + lp,
		"TCPREMOTEIP=" + rh,
		"TCPREMOTEPORT=" + rp,
	}

	err = cmd.Run()
	if err != nil {
		log.Println("Cmd error return: ", err)
		markBadActor(rh)
	} else {
		markGoodActor(rh)
	}
	log.Println("Done with connection", conn.RemoteAddr())
}

// Since go1.4 the setgid syscall is deliberatelly not supported anymore, as it
// only applies to the calling thread.  So we try this here:
func setgid(gid int) error {
	// RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err Errno)
	_, _, e := syscall.RawSyscall(syscall.SYS_SETGID, uintptr(gid), 0, 0)
	if e != 0 {
		return fmt.Errorf("setgid: %w", e)
	}
	return nil
}

func setuid(uid int) error {
	// RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err Errno)
	_, _, e := syscall.RawSyscall(syscall.SYS_SETUID, uintptr(uid), 0, 0)
	if e != 0 {
		return fmt.Errorf("setuid: %w", e)
	}
	return nil
}