| 1 |
package openvpn |
| 2 |
|
| 3 |
import ( |
| 4 |
"bufio" |
| 5 |
"bytes" |
| 6 |
"context" |
| 7 |
"errors" |
| 8 |
"fmt" |
| 9 |
"io" |
| 10 |
"log/slog" |
| 11 |
"net" |
| 12 |
"strconv" |
| 13 |
"strings" |
| 14 |
"sync" |
| 15 |
"time" |
| 16 |
|
| 17 |
"github.com/jkroepke/openvpn-auth-oauth2/v2/internal/config" |
| 18 |
"github.com/jkroepke/openvpn-auth-oauth2/v2/internal/openvpn/connection" |
| 19 |
) |
| 20 |
|
| 21 |
// minManagementInterfaceVersion defines the minimum supported version of the |
| 22 |
// OpenVPN management interface. |
| 23 |
const minManagementInterfaceVersion = 5 |
| 24 |
|
| 25 |
const ( |
| 26 |
managementVersionPrefix = "Management Version: " |
| 27 |
managementPluginVersionPrefix = "OpenVPN Version: openvpn-auth-oauth2" |
| 28 |
) |
| 29 |
|
| 30 |
const WelcomeBanner = ">INFO:OpenVPN Management Interface Version 5 -- type 'help' for more info" |
| 31 |
|
| 32 |
// New creates a new Client configured with the provided logger and |
| 33 |
// configuration. |
| 34 |
func New(logger *slog.Logger, conf *config.Config) *Client { |
| 35 |
client := &Client{ |
| 36 |
conf: conf, |
| 37 |
logger: logger, |
| 38 |
|
| 39 |
connMu: sync.Mutex{}, |
| 40 |
|
| 41 |
commandsBuffer: bytes.Buffer{}, |
| 42 |
|
| 43 |
clientsCh: make(chan connection.Client, 10), |
| 44 |
commandLock: make(chan struct{}, 1), |
| 45 |
commandResponseCh: make(chan string), |
| 46 |
commandTimer: time.NewTimer(conf.OpenVPN.CommandTimeout), |
| 47 |
commandsCh: make(chan string, 10), |
| 48 |
passThroughCh: make(chan string, 10), |
| 49 |
shutdownCh: make(chan struct{}), |
| 50 |
} |
| 51 |
|
| 52 |
client.commandsBuffer.Grow(512) |
| 53 |
|
| 54 |
client.commandLock <- struct{}{} |
| 55 |
|
| 56 |
client.commandTimer.Stop() |
| 57 |
|
| 58 |
return client |
| 59 |
} |
| 60 |
|
| 61 |
// SetOAuth2Client assigns the OAuth2 client used for token refresh and |
| 62 |
// disconnect callbacks. |
| 63 |
func (c *Client) SetOAuth2Client(client oauth2Client) { |
| 64 |
c.oauth2 = client |
| 65 |
} |
| 66 |
|
| 67 |
// Connect establishes the management interface connection and starts the |
| 68 |
// internal handlers. The call blocks until the context is cancelled or the |
| 69 |
// connection terminates. |
| 70 |
// |
| 71 |
//nolint:cyclop |
| 72 |
func (c *Client) Connect(ctx context.Context) error { |
| 73 |
var err error |
| 74 |
|
| 75 |
ctx, cancel := context.WithCancel(ctx) |
| 76 |
defer cancel() |
| 77 |
|
| 78 |
c.ctxCancel = cancel |
| 79 |
|
| 80 |
c.logger.LogAttrs(ctx, slog.LevelInfo, "connect to openvpn management interface "+c.conf.OpenVPN.Addr.String()) |
| 81 |
|
| 82 |
if err = c.setupConnection(ctx); err != nil { |
| 83 |
return fmt.Errorf("unable to connect to openvpn management interface %s: %w", c.conf.OpenVPN.Addr.String(), err) |
| 84 |
} |
| 85 |
|
| 86 |
c.scanner = bufio.NewScanner(c.conn) |
| 87 |
c.scanner.Split(bufio.ScanLines) |
| 88 |
c.scanner.Buffer(make([]byte, 0, bufio.MaxScanTokenSize), bufio.MaxScanTokenSize) |
| 89 |
|
| 90 |
if err = c.handlePassword(ctx); err != nil { |
| 91 |
_ = c.conn.Close() |
| 92 |
|
| 93 |
return fmt.Errorf("unable to authenticate with OpenVPN management interface: %w", err) |
| 94 |
} |
| 95 |
|
| 96 |
defer c.Shutdown(ctx) |
| 97 |
|
| 98 |
errChMessages := make(chan error, 1) |
| 99 |
errChClients := make(chan error, 1) |
| 100 |
errChCommands := make(chan error, 1) |
| 101 |
errChPassThrough := make(chan error, 1) |
| 102 |
|
| 103 |
go c.handleMessages(ctx, errChMessages) |
| 104 |
go c.handleClients(ctx, errChClients) |
| 105 |
go c.handleCommands(ctx, errChCommands) |
| 106 |
|
| 107 |
c.logger.LogAttrs(ctx, slog.LevelInfo, "connection to OpenVPN management interface established") |
| 108 |
|
| 109 |
if c.conf.OpenVPN.Passthrough.Enabled { |
| 110 |
go c.handlePassThrough(ctx, errChPassThrough) |
| 111 |
} |
| 112 |
|
| 113 |
if err := c.checkManagementInterfaceVersion(ctx); err != nil { |
| 114 |
if errors.Is(err, ErrConnectionTerminated) { |
| 115 |
return nil |
| 116 |
} |
| 117 |
|
| 118 |
return fmt.Errorf("unable to check OpenVPN management interface version: %w", err) |
| 119 |
} |
| 120 |
|
| 121 |
select { |
| 122 |
case <-ctx.Done(): |
| 123 |
c.Shutdown(ctx) |
| 124 |
case err = <-errChMessages: |
| 125 |
if err != nil { |
| 126 |
err = fmt.Errorf("error handling messages: %w", err) |
| 127 |
} |
| 128 |
case err = <-errChClients: |
| 129 |
if err != nil { |
| 130 |
err = fmt.Errorf("error handling clients: %w", err) |
| 131 |
} |
| 132 |
case err = <-errChCommands: |
| 133 |
if err != nil { |
| 134 |
err = fmt.Errorf("error handling commands: %w", err) |
| 135 |
} |
| 136 |
case err = <-errChPassThrough: |
| 137 |
if err != nil { |
| 138 |
err = fmt.Errorf("error handling passthrough: %w", err) |
| 139 |
} |
| 140 |
} |
| 141 |
|
| 142 |
if err != nil { |
| 143 |
return fmt.Errorf("openvpn management error: %w", err) |
| 144 |
} |
| 145 |
|
| 146 |
return nil |
| 147 |
} |
| 148 |
|
| 149 |
// setupConnection dials the OpenVPN management interface and stores the |
| 150 |
// resulting connection on the Client. |
| 151 |
func (c *Client) setupConnection(ctx context.Context) error { |
| 152 |
c.connMu.Lock() |
| 153 |
defer c.connMu.Unlock() |
| 154 |
|
| 155 |
var err error |
| 156 |
|
| 157 |
dialer := &net.Dialer{Timeout: 1 * time.Second} |
| 158 |
|
| 159 |
switch c.conf.OpenVPN.Addr.Scheme { |
| 160 |
case SchemeTCP: |
| 161 |
c.conn, err = dialer.DialContext(ctx, c.conf.OpenVPN.Addr.Scheme, c.conf.OpenVPN.Addr.Host) |
| 162 |
case SchemeUnix: |
| 163 |
c.conn, err = dialer.DialContext(ctx, c.conf.OpenVPN.Addr.Scheme, c.conf.OpenVPN.Addr.Path) |
| 164 |
default: |
| 165 |
err = fmt.Errorf("unable to connect to openvpn management interface: %w %s", ErrUnknownProtocol, c.conf.OpenVPN.Addr.Scheme) |
| 166 |
} |
| 167 |
|
| 168 |
return err |
| 169 |
} |
| 170 |
|
| 171 |
// checkManagementInterfaceVersion verifies that the management interface meets |
| 172 |
// the minimum required version. |
| 173 |
func (c *Client) checkManagementInterfaceVersion(ctx context.Context) error { |
| 174 |
resp, err := c.SendCommand(ctx, "version", false) |
| 175 |
if resp == "" { |
| 176 |
return nil |
| 177 |
} |
| 178 |
|
| 179 |
if err != nil { |
| 180 |
return fmt.Errorf("error from version command: %w", err) |
| 181 |
} |
| 182 |
|
| 183 |
if !strings.HasPrefix(resp, "OpenVPN Version: ") { |
| 184 |
return fmt.Errorf("error from version command: %w: %s", ErrErrorResponse, resp) |
| 185 |
} |
| 186 |
|
| 187 |
versionParts := strings.Split(resp, "\r\n") |
| 188 |
|
| 189 |
if len(versionParts) != 4 { |
| 190 |
return fmt.Errorf("%w: %s", ErrUnexpectedResponseFromVersionCommand, resp) |
| 191 |
} |
| 192 |
|
| 193 |
c.logger.LogAttrs(ctx, slog.LevelInfo, strings.Join(versionParts[0:1], " - ")) |
| 194 |
|
| 195 |
if c.conf.OpenVPN.EnforceUniqueUser && strings.HasPrefix(versionParts[0], managementPluginVersionPrefix) { |
| 196 |
return ErrEnforceUniqueUserUnsupported |
| 197 |
} |
| 198 |
|
| 199 |
managementInterfaceVersion, err := parseManagementInterfaceVersion(versionParts[1]) |
| 200 |
if err != nil { |
| 201 |
return err |
| 202 |
} |
| 203 |
|
| 204 |
// Management Interface Version 5 is required at minimum |
| 205 |
// ref: https://github.com/OpenVPN/openvpn/commit/a261e173341f8e68505a6ab5a413d09b0797a459 |
| 206 |
if managementInterfaceVersion < minManagementInterfaceVersion { |
| 207 |
return ErrRequireManagementInterfaceVersion5 |
| 208 |
} |
| 209 |
|
| 210 |
return nil |
| 211 |
} |
| 212 |
|
| 213 |
func parseManagementInterfaceVersion(versionLine string) (int, error) { |
| 214 |
prefix, version, found := strings.Cut(versionLine, managementVersionPrefix) |
| 215 |
if !found || prefix != "" { |
| 216 |
return 0, fmt.Errorf("%w: %s", ErrUnexpectedResponseFromVersionCommand, versionLine) |
| 217 |
} |
| 218 |
|
| 219 |
managementInterfaceVersion, err := strconv.Atoi(version) |
| 220 |
if err != nil { |
| 221 |
return 0, fmt.Errorf("unable to parse openvpn management interface version: %w", err) |
| 222 |
} |
| 223 |
|
| 224 |
return managementInterfaceVersion, nil |
| 225 |
} |
| 226 |
|
| 227 |
// checkClientSsoCapabilities reports whether the given client supports SSO via |
| 228 |
// the webauth protocol. |
| 229 |
func (c *Client) checkClientSsoCapabilities(client connection.Client) bool { |
| 230 |
return strings.Contains(client.IvSSO, "webauth") |
| 231 |
} |
| 232 |
|
| 233 |
// Shutdown closes the management connection and stops command processing. |
| 234 |
func (c *Client) Shutdown(ctx context.Context) { |
| 235 |
if !c.closed.CompareAndSwap(0, 1) { |
| 236 |
return |
| 237 |
} |
| 238 |
|
| 239 |
// commandsCh has multiple producers and is intentionally left open; |
| 240 |
// shutdownCh owns lifecycle signaling. |
| 241 |
close(c.shutdownCh) |
| 242 |
|
| 243 |
c.logger.LogAttrs(ctx, slog.LevelInfo, "shutdown OpenVPN management connection") |
| 244 |
|
| 245 |
c.connMu.Lock() |
| 246 |
defer c.connMu.Unlock() |
| 247 |
|
| 248 |
if c.conn != nil { |
| 249 |
_ = c.conn.Close() |
| 250 |
} |
| 251 |
} |
| 252 |
|
| 253 |
// SendCommand sends a command to the management interface and waits for its |
| 254 |
// response. When passthrough is true the raw response is returned without any |
| 255 |
// validation. A rejected command returns the raw response together with a |
| 256 |
// [ManagementCommandError]. |
| 257 |
func (c *Client) SendCommand(ctx context.Context, cmd string, passthrough bool) (string, error) { |
| 258 |
if cmd == "\x00" || c.closed.Load() == 1 { |
| 259 |
return "", nil |
| 260 |
} |
| 261 |
|
| 262 |
commandName := managementCommandForError(cmd, passthrough) |
| 263 |
|
| 264 |
if err := c.waitForCommandLock(ctx); err != nil { |
| 265 |
return "", fmt.Errorf("command error '%s': %w", commandName, err) |
| 266 |
} |
| 267 |
|
| 268 |
releaseCommandLock := true |
| 269 |
defer func() { |
| 270 |
if releaseCommandLock { |
| 271 |
c.commandLock <- struct{}{} |
| 272 |
} |
| 273 |
}() |
| 274 |
|
| 275 |
if c.closed.Load() == 1 { |
| 276 |
return "", ErrConnectionTerminated |
| 277 |
} |
| 278 |
|
| 279 |
if err := c.enqueueCommand(ctx, cmd); err != nil { |
| 280 |
return "", fmt.Errorf("command error '%s': %w", commandName, err) |
| 281 |
} |
| 282 |
|
| 283 |
// commandLock serializes resets and receives on the reusable timer. |
| 284 |
c.commandTimer.Reset(c.conf.OpenVPN.CommandTimeout) |
| 285 |
|
| 286 |
stopCommandTimer := true |
| 287 |
defer func() { |
| 288 |
if stopCommandTimer { |
| 289 |
c.commandTimer.Stop() |
| 290 |
} |
| 291 |
}() |
| 292 |
|
| 293 |
resp, canceled, err := c.waitForCommandResponse(ctx, commandName, passthrough) |
| 294 |
if canceled { |
| 295 |
releaseCommandLock = false |
| 296 |
stopCommandTimer = false |
| 297 |
|
| 298 |
go c.discardCommandResponse() |
| 299 |
} |
| 300 |
|
| 301 |
return resp, err |
| 302 |
} |
| 303 |
|
| 304 |
func (c *Client) waitForCommandLock(ctx context.Context) error { |
| 305 |
if err := ctx.Err(); err != nil { |
| 306 |
return fmt.Errorf("wait for command lock: %w", err) |
| 307 |
} |
| 308 |
|
| 309 |
select { |
| 310 |
case <-ctx.Done(): |
| 311 |
return fmt.Errorf("wait for command lock: %w", ctx.Err()) |
| 312 |
case <-c.shutdownCh: |
| 313 |
return ErrConnectionTerminated |
| 314 |
case <-c.commandLock: |
| 315 |
return nil |
| 316 |
} |
| 317 |
} |
| 318 |
|
| 319 |
func (c *Client) enqueueCommand(ctx context.Context, cmd string) error { |
| 320 |
if err := ctx.Err(); err != nil { |
| 321 |
return fmt.Errorf("enqueue command: %w", err) |
| 322 |
} |
| 323 |
|
| 324 |
select { |
| 325 |
case <-ctx.Done(): |
| 326 |
return fmt.Errorf("enqueue command: %w", ctx.Err()) |
| 327 |
case <-c.shutdownCh: |
| 328 |
return ErrConnectionTerminated |
| 329 |
case c.commandsCh <- cmd: |
| 330 |
return nil |
| 331 |
} |
| 332 |
} |
| 333 |
|
| 334 |
func (c *Client) waitForCommandResponse( |
| 335 |
ctx context.Context, commandName string, passthrough bool, |
| 336 |
) (string, bool, error) { |
| 337 |
select { |
| 338 |
case resp, ok := <-c.commandResponseCh: |
| 339 |
if !ok { |
| 340 |
return "", false, ErrConnectionTerminated |
| 341 |
} |
| 342 |
|
| 343 |
response, err := validateCommandResponse(commandName, resp, passthrough) |
| 344 |
|
| 345 |
return response, false, err |
| 346 |
case <-ctx.Done(): |
| 347 |
return "", true, fmt.Errorf("command error '%s': %w", commandName, ctx.Err()) |
| 348 |
case <-c.shutdownCh: |
| 349 |
return "", false, ErrConnectionTerminated |
| 350 |
case <-c.commandTimer.C: |
| 351 |
return "", false, fmt.Errorf("command error '%s': %w", commandName, ErrTimeout) |
| 352 |
} |
| 353 |
} |
| 354 |
|
| 355 |
func validateCommandResponse(commandName, resp string, passthrough bool) (string, error) { |
| 356 |
if passthrough { |
| 357 |
return resp, nil |
| 358 |
} |
| 359 |
|
| 360 |
if resp == "" { |
| 361 |
return "", fmt.Errorf("command error '%s': %w", commandName, ErrEmptyResponse) |
| 362 |
} |
| 363 |
|
| 364 |
if strings.HasPrefix(resp, "ERROR:") { |
| 365 |
return resp, &ManagementCommandError{ |
| 366 |
Command: commandName, |
| 367 |
Response: strings.TrimSpace(resp), |
| 368 |
} |
| 369 |
} |
| 370 |
|
| 371 |
return resp, nil |
| 372 |
} |
| 373 |
|
| 374 |
// discardCommandResponse preserves command-response ordering after the caller |
| 375 |
// stops waiting for a command that was already sent. |
| 376 |
func (c *Client) discardCommandResponse() { |
| 377 |
defer func() { |
| 378 |
c.commandTimer.Stop() |
| 379 |
|
| 380 |
c.commandLock <- struct{}{} |
| 381 |
}() |
| 382 |
|
| 383 |
select { |
| 384 |
case <-c.commandResponseCh: |
| 385 |
case <-c.shutdownCh: |
| 386 |
case <-c.commandTimer.C: |
| 387 |
} |
| 388 |
} |
| 389 |
|
| 390 |
// SendCommandf formats a command using fmt.Sprintf and then calls SendCommand. |
| 391 |
func (c *Client) SendCommandf(ctx context.Context, format string, a ...any) (string, error) { |
| 392 |
return c.SendCommand(ctx, fmt.Sprintf(format, a...), false) |
| 393 |
} |
| 394 |
|
| 395 |
// rawCommand writes a command followed by CRLF to the management interface. |
| 396 |
func (c *Client) rawCommand(ctx context.Context, cmd, logCommand string) error { |
| 397 |
if c.logger.Enabled(ctx, slog.LevelDebug) { |
| 398 |
c.logger.LogAttrs(ctx, slog.LevelDebug, "send command", slog.String("command", logCommand)) |
| 399 |
} |
| 400 |
|
| 401 |
c.commandsBuffer.Reset() |
| 402 |
c.commandsBuffer.WriteString(cmd) |
| 403 |
c.commandsBuffer.WriteString("\r\n") |
| 404 |
|
| 405 |
if err := c.conn.SetWriteDeadline(time.Now().Add(time.Second)); err != nil { |
| 406 |
return fmt.Errorf("unable to set read deadline: %w", err) |
| 407 |
} |
| 408 |
|
| 409 |
if _, err := c.commandsBuffer.WriteTo(c.conn); err != nil { |
| 410 |
return fmt.Errorf("unable to write into OpenVPN management connection: %w", err) |
| 411 |
} |
| 412 |
|
| 413 |
return nil |
| 414 |
} |
| 415 |
|
| 416 |
func managementCommandForError(cmd string, passthrough bool) string { |
| 417 |
if passthrough { |
| 418 |
return managementCommandName(cmd) |
| 419 |
} |
| 420 |
|
| 421 |
return strings.SplitN(cmd, "\r\n", 2)[0] |
| 422 |
} |
| 423 |
|
| 424 |
func managementCommandName(cmd string) string { |
| 425 |
cmdFirstLine, _, _ := strings.Cut(cmd, "\r\n") |
| 426 |
for field := range strings.FieldsSeq(cmdFirstLine) { |
| 427 |
return field |
| 428 |
} |
| 429 |
|
| 430 |
return "" |
| 431 |
} |
| 432 |
|
| 433 |
// readMessage . |
| 434 |
func (c *Client) readMessage(buf *bytes.Buffer) error { |
| 435 |
buf.Reset() |
| 436 |
|
| 437 |
var line []byte |
| 438 |
|
| 439 |
for c.scanner.Scan() { |
| 440 |
line = c.scanner.Bytes() |
| 441 |
|
| 442 |
if len(line) == 0 { |
| 443 |
continue |
| 444 |
} |
| 445 |
|
| 446 |
if _, err := buf.Write(line); err != nil { |
| 447 |
return fmt.Errorf("unable to write string to buffer: %w", err) |
| 448 |
} |
| 449 |
|
| 450 |
if _, err := buf.WriteString("\r\n"); err != nil { |
| 451 |
return fmt.Errorf("unable to write newline to buffer: %w", err) |
| 452 |
} |
| 453 |
|
| 454 |
if c.isMessageLineEOF(line) { |
| 455 |
return nil |
| 456 |
} |
| 457 |
} |
| 458 |
|
| 459 |
if c.closed.Load() == 0 && c.scanner.Err() != nil { |
| 460 |
return fmt.Errorf("scanner error: %w", c.scanner.Err()) |
| 461 |
} |
| 462 |
|
| 463 |
return io.EOF |
| 464 |
} |
| 465 |
|
| 466 |
func (c *Client) isMessageLineEOF(line []byte) bool { |
| 467 |
switch { |
| 468 |
// SUCCESS, ERROR, END, >HOLD, >INFO, >NOTIFY |
| 469 |
case bytes.HasPrefix(line, []byte("SU")), |
| 470 |
bytes.HasPrefix(line, []byte("ER")), |
| 471 |
bytes.HasPrefix(line, []byte("EN")), |
| 472 |
bytes.HasPrefix(line, []byte(">H")), |
| 473 |
bytes.HasPrefix(line, []byte(">I")), |
| 474 |
bytes.HasPrefix(line, []byte(">N")): |
| 475 |
return true |
| 476 |
default: |
| 477 |
return bytes.Equal(line, []byte(">CLIENT:ENV,END")) |
| 478 |
} |
| 479 |
} |