Debian Codegraph @

internal/openvpn/client.go

raw
1 package openvpn
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7 "log/slog"
8 "slices"
9 "strconv"
10 "strings"
11 "time"
12
13 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/oauth2/idtoken"
14 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/oauth2/types"
15 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/openvpn/connection"
16 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/state"
17 )
18
19 const openVPNManagementCommandBodyLimit = 1023
20
21 func (c *Client) processClient(ctx context.Context, client connection.Client) error {
22 logger := slog.New(c.logger.Handler().WithAttrs([]slog.Attr{
23 slog.String("ip", client.IPAddr+":"+client.IPPort),
24 slog.Uint64("cid", client.CID),
25 slog.Uint64("kid", client.KID),
26 slog.String("common_name", client.CommonName),
27 slog.String("reason", client.Reason),
28 slog.String("session_id", client.SessionID),
29 slog.String("session_state", client.SessionState),
30 }))
31
32 ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
33 defer cancel()
34
35 switch client.Reason {
36 case "REAUTH":
37 if !c.conf.OpenVPN.ReAuthentication {
38 logger.LogAttrs(ctx, slog.LevelInfo, "client re-authentication not enabled")
39 c.DenyClient(ctx, logger, state.ClientIdentifier{CID: client.CID, KID: client.KID}, "client re-authentication not enabled")
40
41 return nil
42 }
43
44 fallthrough
45 case "CONNECT":
46 c.handleClientAuthentication(ctx, logger, client)
47 case "ESTABLISHED":
48 c.clientEstablished(ctx, logger, client)
49 case "DISCONNECT":
50 c.clientDisconnect(ctx, logger, client)
51 default:
52 return fmt.Errorf("%w: %s", ErrUnknownClientReason, client.Reason)
53 }
54
55 return nil
56 }
57
58 // handleClientAuthentication holds the shared authentication logic for CONNECT and REAUTH events.
59 func (c *Client) handleClientAuthentication(ctx context.Context, logger *slog.Logger, client connection.Client) {
60 logger.LogAttrs(ctx, slog.LevelInfo, "new client authentication")
61
62 // Check if the client is allowed to bypass authentication. If so, accept the client.
63 if c.checkAuthBypass(client) {
64 c.acceptBypassedClient(ctx, logger, client)
65
66 return
67 }
68
69 // Check if the client supports SSO authentication via webauth.
70 if !c.checkClientSsoCapabilities(client) {
71 errorSsoNotSupported := "OpenVPN Client does not support SSO authentication via webauth"
72 logger.LogAttrs(ctx, slog.LevelWarn, errorSsoNotSupported)
73 c.DenyClient(ctx, logger, state.ClientIdentifier{CID: client.CID, KID: client.KID}, errorSsoNotSupported)
74
75 return
76 }
77
78 // Check if the client is already authenticated and refresh the client's authentication if enabled.
79 // If the client is successfully re-authenticated, accept the client.
80 user, tokens, clientConfigNames, ok, err := c.silentReAuthentication(ctx, logger, client)
81 if err != nil {
82 c.DenyClient(ctx, logger, state.ClientIdentifier{CID: client.CID, KID: client.KID}, ReasonStateExpiredOrInvalid)
83
84 logger.LogAttrs(
85 ctx, slog.LevelError, "error refreshing client auth",
86 slog.Any("err", err),
87 )
88
89 return
90 }
91
92 if ok {
93 c.acceptSilentlyReAuthenticatedClient(ctx, logger, client, user, tokens, clientConfigNames)
94
95 return
96 }
97
98 // Start the authentication process for the client.
99 if err := c.startClientAuth(ctx, logger, client); err != nil {
100 // Deny the client if an error occurred during the authentication process.
101 logger.LogAttrs(
102 ctx, slog.LevelError, "error starting client auth",
103 slog.Any("err", err),
104 )
105
106 c.DenyClient(ctx, logger, state.ClientIdentifier{CID: client.CID, KID: client.KID}, "internal error")
107 }
108 }
109
110 func (c *Client) acceptBypassedClient(ctx context.Context, logger *slog.Logger, client connection.Client) {
111 logger.LogAttrs(ctx, slog.LevelInfo, "client bypass authentication")
112
113 clientIdentifier := stateClientIdentifier(client)
114 if err := c.AcceptClient(ctx, logger, clientIdentifier, client.CommonName, ""); err != nil {
115 logger.LogAttrs(ctx, slog.LevelWarn, "failed to accept bypassed client", slog.Any("err", err))
116 c.DenyClient(ctx, logger, clientIdentifier, "authentication acceptance failed")
117 }
118 }
119
120 func (c *Client) acceptSilentlyReAuthenticatedClient(
121 ctx context.Context,
122 logger *slog.Logger,
123 client connection.Client,
124 user types.UserInfo,
125 tokens *idtoken.IDToken,
126 clientConfigNames []string,
127 ) {
128 if tokens != nil && len(clientConfigNames) == 0 {
129 var err error
130
131 clientConfigNames, err = c.oauth2.ResolveClientConfigNames(
132 types.AuthModeNonInteractive,
133 state.State{
134 Client: stateClientIdentifier(client),
135 IPAddr: client.IPAddr,
136 IPPort: client.IPPort,
137 SessionState: client.SessionState,
138 },
139 tokens,
140 user,
141 )
142 if err != nil {
143 logger.LogAttrs(ctx, slog.LevelWarn, "failed to resolve client config", slog.Any("err", err))
144 c.DenyClient(ctx, logger, stateClientIdentifier(client), "invalid client config")
145
146 return
147 }
148 }
149
150 clientIdentifier := stateClientIdentifier(client)
151 if err := c.AcceptClient(ctx, logger, clientIdentifier, user.Username, clientConfigNames...); err != nil {
152 logger.LogAttrs(ctx, slog.LevelWarn, "failed to accept silently re-authenticated client", slog.Any("err", err))
153 c.DenyClient(ctx, logger, clientIdentifier, "authentication acceptance failed")
154 }
155 }
156
157 func stateClientIdentifier(client connection.Client) state.ClientIdentifier {
158 return state.ClientIdentifier{
159 SessionID: client.SessionID,
160 CommonName: client.CommonName,
161 CID: client.CID,
162 KID: client.KID,
163 UsernameIsDefined: client.UsernameIsDefined,
164 }
165 }
166
167 // startClientAuth initiates the authentication process for the client.
168 // The openvpn-auth-oauth2 plugin will send a client-pending-auth command to the OpenVPN management interface.
169 func (c *Client) startClientAuth(ctx context.Context, logger *slog.Logger, client connection.Client) error {
170 clientIdentifier := state.ClientIdentifier{
171 CID: client.CID,
172 KID: client.KID,
173 CommonName: client.CommonName,
174 }
175
176 if c.conf.OAuth2.Refresh.UseSessionID {
177 clientIdentifier.SessionID = client.SessionID
178 }
179
180 var (
181 ipAddr string
182 ipPort string
183 )
184
185 if c.conf.Log.VPNClientIP || c.conf.HTTP.Check.IPAddr || c.conf.OAuth2.Validate.Expression != "" {
186 ipAddr = client.IPAddr
187 }
188
189 if c.conf.Log.VPNClientIP {
190 ipPort = client.IPPort
191 }
192
193 encryptedOIDCState, err := c.oauth2.EncryptState(state.State{
194 Client: clientIdentifier,
195 IPAddr: ipAddr,
196 IPPort: ipPort,
197 SessionState: client.SessionState,
198 })
199 if err != nil {
200 return fmt.Errorf("error encoding state: %w", err)
201 }
202
203 startURL := buildOAuth2StartURL(c.conf.HTTP.BaseURL.String(), encryptedOIDCState)
204
205 command, err := buildClientPendingAuthCommand(client, startURL, c.conf.OpenVPN.AuthPendingTimeout)
206 if err != nil {
207 return err
208 }
209
210 logger.LogAttrs(ctx, slog.LevelInfo, "sent client-pending-auth command")
211
212 _, err = c.SendCommand(ctx, command, false)
213 if err != nil {
214 return fmt.Errorf("error sending client-pending-auth command: %w", err)
215 }
216
217 return nil
218 }
219
220 func buildOAuth2StartURL(baseURL string, encryptedOIDCState state.EncryptedState) string {
221 return strings.TrimSuffix(baseURL, "/") + "/oauth2/start?state=" + encryptedOIDCState
222 }
223
224 func buildClientPendingAuthCommand(client connection.Client, startURL string, timeout time.Duration) (string, error) {
225 const (
226 commandPrefix = "client-pending-auth "
227 webAuthPrefix = ` "WEB_AUTH::`
228 commandSuffix = `" `
229 )
230
231 // Keep the numeric fields in stack-backed scratch buffers so building a valid
232 // command requires only the returned string's allocation.
233 var (
234 cidBuffer [20]byte
235 kidBuffer [20]byte
236 timeoutBuffer [20]byte
237 )
238
239 cid := strconv.AppendUint(cidBuffer[:0], client.CID, 10)
240 kid := strconv.AppendUint(kidBuffer[:0], client.KID, 10)
241 timeoutSeconds := strconv.AppendFloat(timeoutBuffer[:0], timeout.Seconds(), 'f', 0, 64)
242 commandSize := len(commandPrefix) + len(cid) + 1 + len(kid) + len(webAuthPrefix) +
243 len(startURL) + len(commandSuffix) + len(timeoutSeconds)
244
245 if commandSize > openVPNManagementCommandBodyLimit {
246 return "", fmt.Errorf(
247 "client-pending-auth command is %d bytes; OpenVPN accepts at most %d bytes",
248 commandSize,
249 openVPNManagementCommandBodyLimit,
250 )
251 }
252
253 var command strings.Builder
254 command.Grow(commandSize)
255 command.WriteString(commandPrefix)
256 _, _ = command.Write(cid)
257 _ = command.WriteByte(' ')
258 _, _ = command.Write(kid)
259 command.WriteString(webAuthPrefix)
260 command.WriteString(startURL)
261 command.WriteString(commandSuffix)
262 _, _ = command.Write(timeoutSeconds)
263
264 return command.String(), nil
265 }
266
267 // checkAuthBypass checks if the client is allowed to bypass authentication based on its common name.
268 // It returns true if the client is allowed to bypass authentication, false otherwise.
269 func (c *Client) checkAuthBypass(client connection.Client) bool {
270 for _, pattern := range c.conf.OpenVPN.Bypass.CommonNames {
271 if pattern.MatchString(client.CommonName) {
272 return true
273 }
274 }
275
276 return false
277 }
278
279 // silentReAuthentication attempts to silently re-authenticate the client using a refresh token if available.
280 // It returns true if the client was successfully re-authenticated, false otherwise.
281 func (c *Client) silentReAuthentication(
282 ctx context.Context, logger *slog.Logger, client connection.Client,
283 ) (types.UserInfo, *idtoken.IDToken, []string, bool, error) {
284 if !c.conf.OAuth2.Refresh.Enabled {
285 logger.LogAttrs(ctx, slog.LevelDebug, "silent re-authentication disabled by configuration")
286
287 return types.UserInfo{}, nil, nil, false, nil
288 }
289
290 if c.conf.OAuth2.Refresh.UseSessionID {
291 if client.SessionID == "" || !slices.Contains([]string{"Initial", "AuthenticatedEmptyUser", "Authenticated"}, client.SessionState) {
292 return types.UserInfo{}, nil, nil, false, ErrClientSessionStateInvalidOrExpired
293 }
294 } else if client.SessionID != "" {
295 logger.LogAttrs(ctx, slog.LevelWarn, "detected client session ID but not configured to use it. Please enable --oauth2.refresh.use-session-id")
296 }
297
298 if c.oauth2 == nil {
299 return types.UserInfo{}, nil, nil, false, errors.New("oauth2 client not set")
300 }
301
302 user, token, clientConfigNames, ok, err := c.oauth2.RefreshClientAuth(ctx, logger, client)
303 if err != nil {
304 logger.LogAttrs(ctx, slog.LevelWarn, "error refreshing client auth", slog.Any("err", err))
305 }
306
307 logger.LogAttrs(ctx, slog.LevelDebug, "silent re-authentication", slog.Bool("result", ok))
308
309 return user, token, clientConfigNames, ok, nil
310 }
311
312 func (c *Client) clientEstablished(ctx context.Context, logger *slog.Logger, client connection.Client) {
313 logger.LogAttrs(
314 ctx, slog.LevelInfo, "client established",
315 slog.String("vpn_ip", client.VPNAddress),
316 )
317 }
318
319 func (c *Client) clientDisconnect(ctx context.Context, logger *slog.Logger, client connection.Client) {
320 logger.LogAttrs(ctx, slog.LevelInfo, "client disconnected")
321
322 c.oauth2.ClientDisconnect(ctx, logger, client)
323 }