-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathconnect.go
332 lines (279 loc) · 7.42 KB
/
connect.go
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
package ocrunner
import (
"bytes"
"fmt"
"os"
"os/exec"
"os/user"
"strconv"
"strings"
log "github.com/sirupsen/logrus"
"github.com/telekom-mms/oc-daemon/pkg/logininfo"
)
// ConnectEvent is a connect runner event
type ConnectEvent struct {
// Connect indicates connect and disconnect
// TODO: use a Type with more values?
Connect bool
// login info for connect
login *logininfo.LoginInfo
// Env are extra environment variables set during execution
env []string
}
// Connect is a openconnect connection runner
type Connect struct {
// connection runner configuration
config *Config
// openconnect command
command *exec.Cmd
// channel for openconnect exits
exits chan struct{}
// channels for commands from user
commands chan *ConnectEvent
done chan struct{}
// channel for user facing events
events chan *ConnectEvent
}
// setPIDOwner sets the owner of the pid file
func (c *Connect) setPIDOwner() {
if c.config.PIDOwner == "" {
// do not change owner
return
}
user, err := user.Lookup(c.config.PIDOwner)
if err != nil {
log.WithError(err).Error("OC-Runner could not get UID of pid file owner")
return
}
uid, err := strconv.Atoi(user.Uid)
if err != nil {
log.WithError(err).Error("OC-Runner could not convert UID of pid file owner to int")
return
}
if err := os.Chown(c.config.PIDFile, uid, -1); err != nil {
log.WithError(err).Error("OC-Runner could not change owner of pid file")
}
}
// setPIDGroup sets the group of the pid file
func (c *Connect) setPIDGroup() {
if c.config.PIDGroup == "" {
// do not change group
return
}
group, err := user.LookupGroup(c.config.PIDGroup)
if err != nil {
log.WithError(err).Error("OC-Runner could not get GID of pid file group")
return
}
gid, err := strconv.Atoi(group.Gid)
if err != nil {
log.WithError(err).Error("OC-Runner could not convert GID of pid file group to int")
return
}
if err := os.Chown(c.config.PIDFile, -1, gid); err != nil {
log.WithError(err).Error("OC-Runner could not change group of pid file")
}
}
// savePidFile saves the running command to pid file
func (c *Connect) savePidFile() {
if c.command == nil || c.command.Process == nil {
return
}
// get pid
pid := fmt.Sprintf("%d\n", c.command.Process.Pid)
// convert permissions
perm, err := strconv.ParseUint(c.config.PIDPermissions, 8, 32)
if err != nil {
log.WithError(err).Error("OC-Runner could not convert permissions of pid file to uint")
return
}
// write pid to file with permissions
err = os.WriteFile(c.config.PIDFile, []byte(pid), os.FileMode(perm))
if err != nil {
log.WithError(err).Error("OC-Runner writing pid error")
}
// set owner and group
c.setPIDOwner()
c.setPIDGroup()
}
// handleConnect establishes the connection by starting openconnect
func (c *Connect) handleConnect(e *ConnectEvent) {
if c.command != nil {
// command seems to be running, stop here
log.WithField("error", "openconnect process already running").
Error("OC-Runner connect error")
return
}
// create openconnect command and
// use login information from Authenticate():
//
// openconnect --cookie-on-stdin $HOST --servercert $FINGERPRINT
//
serverCert := fmt.Sprintf("--servercert=%s", e.login.Fingerprint)
xmlConfig := fmt.Sprintf("--xmlconfig=%s", c.config.XMLProfile)
script := fmt.Sprintf("--script=%s", c.config.VPNCScript)
host := e.login.Host
if e.login.ConnectURL != "" {
host = e.login.ConnectURL
}
parameters := []string{
xmlConfig,
script,
"--cookie-on-stdin",
host,
serverCert,
}
if c.config.NoProxy {
parameters = append(parameters, "--no-proxy")
}
if e.login.Resolve != "" {
resolve := fmt.Sprintf("--resolve=%s", e.login.Resolve)
parameters = append(parameters, resolve)
}
if c.config.VPNDevice != "" {
device := fmt.Sprintf("--interface=%s", c.config.VPNDevice)
parameters = append(parameters, device)
}
parameters = append(parameters, c.config.ExtraArgs...)
c.command = exec.Command(c.config.OpenConnect, parameters...)
// run command, pass login info to stdin
b := bytes.NewBufferString(e.login.Cookie)
c.command.Stdin = b
c.command.Stdout = os.Stdout
c.command.Stderr = os.Stderr
c.command.Env = append(os.Environ(), c.config.ExtraEnv...)
c.command.Env = append(c.command.Env, e.env...)
if err := c.command.Start(); err != nil {
log.WithError(err).Error("OC-Runner executing connect error")
c.exits <- struct{}{}
return
}
// save pid and cmd line
c.savePidFile()
// signal connect to user
c.events <- &ConnectEvent{
Connect: true,
}
// wait for program termination and signal disconnect
go func() {
if err := c.command.Wait(); err != nil {
log.WithError(err).
Error("OC-Runner waiting for connect termination error")
}
c.exits <- struct{}{}
}()
}
// handleDisconnect tears down the connection by stopping openconnect
func (c *Connect) handleDisconnect() {
if c.command == nil || c.command.Process == nil {
log.WithField("error", "no openconnect process running").
Error("OC-Runner disconnect error")
return
}
if err := c.command.Process.Signal(os.Interrupt); err != nil {
// TODO: handle failed signal?
log.WithError(err).Error("OC-Runner sending interrupt for disconnect error")
}
}
// handleOCExit handles openconnect program terminations
func (c *Connect) handleOCExit() {
// clear command
c.command = nil
// signal disconnect to user
c.events <- &ConnectEvent{}
}
// handleStop handles stopping the runner
func (c *Connect) handleStop() {
if c.command != nil {
// TODO: is this ok or ugly?
c.handleDisconnect()
<-c.exits
c.handleOCExit()
}
}
// start starts the connect runner
func (c *Connect) start() {
defer close(c.events)
for {
select {
case cmd := <-c.commands:
if cmd.Connect {
c.handleConnect(cmd)
break
}
c.handleDisconnect()
case <-c.exits:
c.handleOCExit()
case <-c.done:
c.handleStop()
return
}
}
}
// Start starts the connect runner
func (c *Connect) Start() {
go c.start()
}
// Stop stops the connect runner
func (c *Connect) Stop() {
close(c.done)
for range c.events {
// wait for event channel close
}
}
// Connect connects the vpn by starting openconnect
func (c *Connect) Connect(login *logininfo.LoginInfo, env []string) {
e := &ConnectEvent{
Connect: true,
login: login,
env: env,
}
c.commands <- e
}
// Disconnect disconnects the vpn by stopping openconnect
func (c *Connect) Disconnect() {
e := &ConnectEvent{}
c.commands <- e
}
// Events returns the connect events channel
func (c *Connect) Events() chan *ConnectEvent {
return c.events
}
// NewConnect returns a new Connect
func NewConnect(config *Config) *Connect {
return &Connect{
config: config,
exits: make(chan struct{}),
commands: make(chan *ConnectEvent),
done: make(chan struct{}),
events: make(chan *ConnectEvent),
}
}
// CleanupConnect cleans up connect after a failed shutdown
func CleanupConnect(config *Config) {
// get pid from file
b, err := os.ReadFile(config.PIDFile)
if err != nil {
return
}
pid, err := strconv.Atoi(strings.TrimSpace(string(b)))
if err != nil {
return
}
// check if it is running and command line starts with openconnect
cmdLine, err := os.ReadFile(fmt.Sprintf("/proc/%d/cmdline", pid))
if err != nil {
return
}
if !strings.HasPrefix(string(cmdLine), config.OpenConnect) {
return
}
// find process and send interrupt signal
process, err := os.FindProcess(pid)
if err != nil {
return
}
if err := process.Signal(os.Interrupt); err == nil {
log.Warn("OC-Runner cleaned up process")
}
}