Debian Codegraph @

internal/openvpn/passthrough_test.go

raw
1 package openvpn_test
2
3 import (
4 "context"
5 "log/slog"
6 "net"
7 "net/url"
8 "os"
9 "regexp"
10 "runtime"
11 "strconv"
12 "strings"
13 "testing"
14 "time"
15
16 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/config"
17 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/config/types"
18 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/openvpn"
19 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/test/testsuite"
20 "github.com/stretchr/testify/assert"
21 "github.com/stretchr/testify/require"
22 "golang.org/x/net/nettest"
23 )
24
25 var rePassThroughLogListen = regexp.MustCompile(`"start pass-through listener on (?:tcp|unix)://(\S+)"`)
26
27 const OpenVPNManagementInterfaceCommandResultStatus = `OpenVPN CLIENT LIST
28 Updated,2024-02-17 10:55:19
29 Common Name,Real Address,Bytes Received,Bytes Sent,Connected Since
30 ROUTING TABLE
31 Virtual Address,Common Name,Real Address,Last Ref
32 GLOBAL STATS
33 Max bcast/mcast queue length,0
34 END`
35
36 const OpenVPNManagementInterfaceCommandResultHelp = `Management Interface for OpenVPN 2.6.9 [git:release/2.6/6640a10bf6d84eee] x86_64-pc-linux-gnu [SSL (OpenSSL)] [LZO] [LZ4] [EPOLL] [MH/PKTINFO] [AEAD] [DCO] built on Feb 17 2024
37 Commands:
38 auth-retry t : Auth failure retry mode (none,interact,nointeract).
39 bytecount n : Show bytes in/out, update every n secs (0=off).
40 echo [on|off] [N|all] : Like log, but only show messages in echo buffer.
41 cr-response response : Send a challenge response answer via CR_RESPONSE to server
42 exit|quit : Close management session.
43 forget-passwords : Forget passwords entered so far.
44 help : Print this message.
45 hold [on|off|release] : Set/show hold flag to on/off state, or
46 release current hold and start tunnel.
47 kill cn : Kill the client instance(s) having common name cn.
48 kill IP:port : Kill the client instance connecting from IP:port.
49 load-stats : Show global server load stats.
50 log [on|off] [N|all] : Turn on/off realtime log display
51 + show last N lines or 'all' for entire history.
52 mute [n] : Set log mute level to n, or show level if n is absent.
53 needok type action : Enter confirmation for NEED-OK request of 'type',
54 where action = 'ok' or 'cancel'.
55 needstr type action : Enter confirmation for NEED-STR request of 'type',
56 where action is reply string.
57 net : (Windows only) Show network info and routing table.
58 password type p : Enter password p for a queried OpenVPN password.
59 remote type [host port] : Override remote directive, type=ACCEPT|MOD|SKIP.
60 remote-entry-count : Get number of available remote entries.
61 remote-entry-get i|all [j]: Get remote entry at index = i to to j-1 or all.
62 proxy type [host port flags] : Enter dynamic proxy server info.
63 pid : Show process ID of the current OpenVPN process.
64 client-auth CID KID : Authenticate client-id/key-id CID/KID (MULTILINE)
65 client-auth-nt CID KID : Authenticate client-id/key-id CID/KID
66 client-deny CID KID R [CR] : Deny auth client-id/key-id CID/KID with log reason
67 text R and optional client reason text CR
68 client-pending-auth CID KID MSG timeout : Instruct OpenVPN to send AUTH_PENDING and INFO_PRE msg
69 to the client and wait for a final client-auth/client-deny
70 client-kill CID [M] : Kill client instance CID with message M (def=RESTART)
71 env-filter [level] : Set env-var filter level
72 rsa-sig : Enter a signature in response to >RSA_SIGN challenge
73 Enter signature base64 on subsequent lines followed by END
74 pk-sig : Enter a signature in response to >PK_SIGN challenge
75 Enter signature base64 on subsequent lines followed by END
76 certificate : Enter a client certificate in response to >NEED-CERT challenge
77 Enter certificate base64 on subsequent lines followed by END
78 signal s : Send signal s to daemon,
79 s = SIGHUP|SIGTERM|SIGUSR1|SIGUSR2.
80 state [on|off] [N|all] : Like log, but show state history.
81 status [n] : Show current daemon status info using format #n.
82 test n : Produce n lines of output for testing/debugging.
83 username type u : Enter username u for a queried OpenVPN username.
84 verb [n] : Set log verbosity level to n, or show if n is absent.
85 version [n] : Set client's version to n or show current version of daemon.
86 END
87 `
88
89 const OpenVPNManagementInterfaceCommandResultStatus2 = `TITLE,OpenVPN 2.6.9 [git:release/2.6/6640a10bf6d84eee] x86_64-pc-linux-gnu [SSL (OpenSSL)] [LZO] [LZ4] [EPOLL] [MH/PKTINFO] [AEAD] [DCO] built on Mar 16 2024
90 TIME,2024-03-23 16:00:26,1711209626
91 HEADER,CLIENT_LIST,Common Name,Real Address,Virtual Address,Virtual IPv6 Address,Bytes Received,Bytes Sent,Connected Since,Connected Since (time_t),Username,Client ID,Peer ID,Data Channel Cipher
92 HEADER,ROUTING_TABLE,Virtual Address,Common Name,Real Address,Last Ref,Last Ref (time_t)
93 GLOBAL_STATS,Max bcast/mcast queue length,0
94 GLOBAL_STATS,dco_enabled,0
95 END
96 `
97
98 const OpenVPNManagementInterfaceCommandResultStatus3 = `TITLE OpenVPN 2.6.9 [git:release/2.6/6640a10bf6d84eee] x86_64-pc-linux-gnu [SSL (OpenSSL)] [LZO] [LZ4] [EPOLL] [MH/PKTINFO] [AEAD] [DCO] built on Mar 16 2024
99 TIME 2024-03-23 16:00:26 1711209626
100 HEADER CLIENT_LIST Common Name Real Address Virtual Address Virtual IPv6 Address Bytes Received Bytes Sent Connected Since Connected Since (time_t) Username Client ID Peer ID Data Channel Cipher
101 HEADER ROUTING_TABLE Virtual Address Common Name Real Address Last Ref Last Ref (time_t)
102 GLOBAL_STATS Max bcast/mcast queue length 0
103 GLOBAL_STATS dco_enabled 0
104 END
105 `
106
107 func TestPassThroughFull(t *testing.T) {
108 t.Parallel()
109
110 configs := []struct {
111 name string
112 scheme string
113 conf config.Config
114 invalidPassword bool
115 }{
116 {
117 name: "tcp without password",
118 scheme: openvpn.SchemeTCP,
119 conf: newPassThroughTestConfig(""),
120 },
121 {
122 name: "unix with password",
123 scheme: openvpn.SchemeUnix,
124 conf: func() config.Config {
125 conf := newPassThroughTestConfig(testsuite.Secret)
126 conf.OpenVPN.Passthrough.SocketGroup = strconv.Itoa(os.Getgid())
127
128 return conf
129 }(),
130 },
131 {
132 name: "tcp with password",
133 scheme: openvpn.SchemeTCP,
134 conf: newPassThroughTestConfig(testsuite.Secret),
135 },
136 {
137 name: "tcp with invalid password",
138 scheme: openvpn.SchemeTCP,
139 conf: newPassThroughTestConfig(testsuite.Secret),
140 invalidPassword: true,
141 },
142 }
143
144 for _, tc := range configs {
145 t.Run(tc.name, func(t *testing.T) {
146 t.Parallel()
147
148 ctx, cancel := context.WithCancel(t.Context())
149 t.Cleanup(cancel)
150
151 suite, passThroughConn, passThroughNetConn := setupPassThroughConnection(ctx, t, tc.scheme, &tc.conf)
152 if !authenticatePassThroughConnection(t, tc.conf, passThroughNetConn, passThroughConn, tc.invalidPassword) {
153 return
154 }
155
156 passThroughConn.ExpectMessage(t, openvpn.WelcomeBanner)
157
158 for range 10 {
159 passThroughConn.SendMessagef(t, "")
160 passThroughConn.SendMessagef(t, "\n")
161 passThroughConn.SendMessagef(t, "\r\n")
162
163 passThroughConn.SendAndExpectMessage(t, "hold", "SUCCESS: hold release succeeded")
164
165 // PID
166 forwardPassThroughCommand(t, suite, passThroughConn, "pid", "SUCCESS: pid=7")
167
168 // unknown command
169 forwardPassThroughCommand(t, suite, passThroughConn, "foo", "ERROR: unknown command, enter 'help' for more options")
170
171 // kill 1
172 forwardPassThroughCommand(t, suite, passThroughConn, "kill 1", "SUCCESS: common name '1' killed")
173
174 // auth decision commands are owned by openvpn-auth-oauth2.
175 passThroughConn.SendAndExpectMessage(t, "client-auth 1 2", "ERROR: command not allowed")
176 passThroughConn.SendAndExpectMessage(t, "client-auth-nt 1", "ERROR: command not allowed")
177 passThroughConn.SendAndExpectMessage(t, "client-deny 1 2 reason", "ERROR: command not allowed")
178 passThroughConn.SendAndExpectMessage(t, "client-pending-auth 1 2 msg 10", "ERROR: command not allowed")
179
180 // client-kill 1
181 forwardPassThroughCommand(t, suite, passThroughConn, "client-kill 1", "ERROR: client-kill command failed")
182
183 // version with argument changes client version
184 forwardPassThroughCommand(t, suite, passThroughConn, "version 3", "SUCCESS: version=3")
185
186 // Forwarded secret-bearing commands must not log the secret value.
187 forwardPassThroughCommand(t, suite, passThroughConn, "password Auth super-secret-value", "SUCCESS: password is correct")
188 require.NotContains(t, suite.Logs(), "super-secret-value")
189
190 // version
191 forwardPassThroughCommand(t, suite, passThroughConn, "version", "OpenVPN Version: openvpn-auth-oauth2\r\nManagement Version: 5\r\nEND")
192
193 // status
194 forwardPassThroughCommand(t, suite, passThroughConn, "status", OpenVPNManagementInterfaceCommandResultStatus)
195
196 // status 2
197 forwardPassThroughCommand(t, suite, passThroughConn, "status 2", OpenVPNManagementInterfaceCommandResultStatus2)
198
199 // status 3
200 forwardPassThroughCommand(t, suite, passThroughConn, "status 3", OpenVPNManagementInterfaceCommandResultStatus3)
201 }
202
203 // help
204 for range 10 {
205 forwardPassThroughCommand(t, suite, passThroughConn, "help", OpenVPNManagementInterfaceCommandResultHelp)
206 }
207
208 if tc.scheme == openvpn.SchemeUnix {
209 passThroughConn.SendMessagef(t, " exit ")
210 require.NoError(t, passThroughNetConn.Close())
211
212 gid, err := testsuite.GetGIDOfFile(tc.conf.OpenVPN.Passthrough.Address.Path)
213 require.NoError(t, err)
214
215 assert.Equal(t, tc.conf.OpenVPN.Passthrough.SocketGroup, strconv.Itoa(gid))
216
217 permission, err := testsuite.GetPermissionsOfFile(tc.conf.OpenVPN.Passthrough.Address.Path)
218 require.NoError(t, err)
219
220 assert.Equal(t, os.FileMode(0o660).String(), permission)
221 } else {
222 passThroughConn.SendMessagef(t, " quit ")
223 require.NoError(t, passThroughNetConn.Close())
224 }
225 })
226 }
227 }
228
229 func TestPassThroughCommandTimeoutSanitizesLogs(t *testing.T) {
230 t.Parallel()
231
232 ctx, cancel := context.WithCancel(t.Context())
233 t.Cleanup(cancel)
234
235 conf := newPassThroughTestConfig(testsuite.Secret)
236 conf.OpenVPN.CommandTimeout = 100 * time.Millisecond
237
238 suite, passThroughConn, passThroughNetConn := setupPassThroughConnection(ctx, t, openvpn.SchemeTCP, &conf)
239 require.True(t, authenticatePassThroughConnection(t, conf, passThroughNetConn, passThroughConn, false))
240 passThroughConn.ExpectMessage(t, openvpn.WelcomeBanner)
241
242 passThroughConn.SendMessagef(t, "password Auth super-secret-value")
243 suite.ExpectMessage(t, "password Auth super-secret-value")
244
245 require.Eventually(t, func() bool {
246 logs := suite.Logs()
247
248 return strings.Contains(logs, "pass-through: command failed") &&
249 strings.Contains(logs, "command error 'password'")
250 }, time.Second, 10*time.Millisecond, suite.Logs())
251
252 require.NotContains(t, suite.Logs(), "super-secret-value")
253 }
254
255 func newPassThroughTestConfig(password string) config.Config {
256 conf := config.Defaults
257 conf.HTTP.Secret = testsuite.Secret
258 conf.Log.Level = slog.LevelDebug
259 conf.OpenVPN.Passthrough.Enabled = true
260 conf.OpenVPN.Passthrough.Password = types.Secret(password)
261
262 return conf
263 }
264
265 func setupPassThroughConnection(
266 ctx context.Context,
267 t *testing.T,
268 scheme string,
269 conf *config.Config,
270 ) (*testsuite.Suite, *testsuite.Conn, net.Conn) {
271 t.Helper()
272
273 if scheme == openvpn.SchemeUnix && runtime.GOOS == "windows" {
274 t.Skip("skipping test on windows")
275 }
276
277 switch scheme {
278 case openvpn.SchemeTCP:
279 conf.OpenVPN.Passthrough.Address = types.URL{URL: &url.URL{Scheme: scheme, Host: "127.0.0.1:0"}}
280 case openvpn.SchemeUnix:
281 temp, err := nettest.LocalPath()
282 require.NoError(t, err)
283
284 conf.OpenVPN.Passthrough.Address = types.URL{URL: &url.URL{Scheme: scheme, Path: temp}}
285 }
286
287 suite := testsuite.New(conf)
288 errOpenVPNClientCh := suite.SetupManagementEnvironment(ctx, t, nil)
289 openVPNClient := suite.GetOpenVPNClient()
290
291 var passThroughNetConn net.Conn
292
293 t.Cleanup(func() {
294 if passThroughNetConn != nil {
295 _ = passThroughNetConn.Close()
296 }
297
298 openVPNClient.Shutdown(t.Context())
299
300 select {
301 case err := <-errOpenVPNClientCh:
302 require.NoError(t, err, suite.Logs())
303 case <-time.After(1 * time.Second):
304 t.Fatalf("timeout waiting for connection to close. Logs:\n\n%s", suite.Logs())
305 }
306 })
307
308 if conf.OpenVPN.Password != "" {
309 suite.SendMessagef(t, "ENTER PASSWORD:")
310 suite.ExpectMessage(t, conf.OpenVPN.Password.String())
311 suite.SendMessagef(t, "SUCCESS: password is correct")
312 }
313
314 suite.ExpectVersionAndReleaseHold(t)
315 suite.SendMessagef(t, "")
316 suite.SendMessagef(t, "\r\n")
317
318 passThroughNetConn = dialPassThroughConnection(ctx, t, suite, scheme)
319
320 return suite, testsuite.NewConn(passThroughNetConn).WithLogs(suite.Logs), passThroughNetConn
321 }
322
323 func dialPassThroughConnection(ctx context.Context, t *testing.T, suite *testsuite.Suite, scheme string) net.Conn {
324 t.Helper()
325
326 var passThroughAddr []string
327
328 require.Eventually(t, func() bool {
329 passThroughAddr = rePassThroughLogListen.FindStringSubmatch(suite.Logs())
330
331 return passThroughAddr != nil
332 }, time.Second, 50*time.Millisecond)
333
334 require.Len(t, passThroughAddr, 2, "unexpected log output: %s", suite.Logs())
335
336 passThroughNetConn, err := testsuite.WaitUntilListening(ctx, t, scheme, passThroughAddr[1])
337 require.NoError(t, err)
338
339 return passThroughNetConn
340 }
341
342 func authenticatePassThroughConnection(
343 t *testing.T,
344 conf config.Config,
345 passThroughNetConn net.Conn,
346 passThroughConn *testsuite.Conn,
347 invalidPassword bool,
348 ) bool {
349 t.Helper()
350
351 if conf.OpenVPN.Passthrough.Password.String() == "" {
352 return true
353 }
354
355 buf := make([]byte, 15)
356 _, err := passThroughNetConn.Read(buf)
357 require.NoError(t, err)
358 require.Equal(t, "ENTER PASSWORD:", string(buf))
359
360 if invalidPassword {
361 passThroughConn.SendAndExpectMessage(t, "invalid", "ERROR: bad password")
362
363 return false
364 }
365
366 passThroughConn.SendAndExpectMessage(t, conf.OpenVPN.Passthrough.Password.String(), "SUCCESS: password is correct")
367
368 return true
369 }
370
371 func forwardPassThroughCommand(t *testing.T, suite *testsuite.Suite, passThroughConn *testsuite.Conn, command, response string) {
372 t.Helper()
373
374 passThroughConn.SendMessagef(t, command)
375 suite.ExpectMessage(t, command)
376 suite.SendMessagef(t, response)
377 passThroughConn.ExpectMessage(t, response)
378 }