| 1 |
package openvpn |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"encoding/base64" |
| 6 |
"errors" |
| 7 |
"fmt" |
| 8 |
"io" |
| 9 |
"io/fs" |
| 10 |
"log/slog" |
| 11 |
"strings" |
| 12 |
|
| 13 |
"github.com/jkroepke/openvpn-auth-oauth2/v2/internal/config" |
| 14 |
"github.com/jkroepke/openvpn-auth-oauth2/v2/internal/state" |
| 15 |
) |
| 16 |
|
| 17 |
// AcceptClient accepts an OpenVPN client connection. |
| 18 |
// It reads the client configuration from the CCD path if enabled. |
| 19 |
func (c *Client) AcceptClient(ctx context.Context, logger *slog.Logger, client state.ClientIdentifier, username string, clientConfigNames ...string) error { |
| 20 |
logger.LogAttrs(ctx, slog.LevelInfo, "client authentication") |
| 21 |
|
| 22 |
clientConfig, err := c.loadClientConfig(ctx, logger, client, clientConfigNames, username) |
| 23 |
if err != nil { |
| 24 |
logger.LogAttrs( |
| 25 |
ctx, slog.LevelWarn, "failed to load client config", |
| 26 |
slog.Any("error", err), |
| 27 |
) |
| 28 |
c.DenyClient(ctx, logger, client, "client configuration not found") |
| 29 |
|
| 30 |
return err |
| 31 |
} |
| 32 |
|
| 33 |
if c.conf.OpenVPN.EnforceUniqueUser { |
| 34 |
c.acceptMu.Lock() |
| 35 |
defer c.acceptMu.Unlock() |
| 36 |
|
| 37 |
if err = c.enforceUniqueUser(ctx, logger, client.CID, username); err != nil { |
| 38 |
logger.LogAttrs( |
| 39 |
ctx, slog.LevelWarn, "failed to terminate existing OpenVPN sessions", |
| 40 |
slog.Any("error", err), |
| 41 |
) |
| 42 |
|
| 43 |
return err |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
err = c.sendClientAuth(ctx, client, clientConfig) |
| 48 |
if err != nil { |
| 49 |
logger.LogAttrs( |
| 50 |
ctx, slog.LevelWarn, "failed to accept client", |
| 51 |
slog.Any("error", err), |
| 52 |
) |
| 53 |
} |
| 54 |
|
| 55 |
return err |
| 56 |
} |
| 57 |
|
| 58 |
// loadClientConfig reads the client configuration from CCD and logs the result. |
| 59 |
func (c *Client) loadClientConfig( |
| 60 |
ctx context.Context, logger *slog.Logger, client state.ClientIdentifier, clientConfigNames []string, username string, |
| 61 |
) ([]string, error) { |
| 62 |
var clientConfig []string |
| 63 |
|
| 64 |
if !c.conf.OpenVPN.ClientConfig.Enabled { |
| 65 |
return c.applyUsernameConfig(clientConfig, client, username), nil |
| 66 |
} |
| 67 |
|
| 68 |
if len(clientConfigNames) == 0 { |
| 69 |
clientConfigNames = []string{"DEFAULT"} |
| 70 |
} |
| 71 |
|
| 72 |
if c.conf.OpenVPN.ClientConfig.Strategy != config.OpenVPNConfigStrategyMerge { |
| 73 |
clientConfigNames = clientConfigNames[:1] |
| 74 |
} |
| 75 |
|
| 76 |
clientConfig, err := c.readClientConfigs(ctx, logger, clientConfigNames) |
| 77 |
if err != nil { |
| 78 |
return nil, err |
| 79 |
} |
| 80 |
|
| 81 |
return c.applyUsernameConfig(clientConfig, client, username), nil |
| 82 |
} |
| 83 |
|
| 84 |
func (c *Client) applyUsernameConfig(clientConfig []string, client state.ClientIdentifier, username string) []string { |
| 85 |
if !c.conf.OAuth2.Refresh.ValidateUser && !c.conf.OpenVPN.EnforceUniqueUser { |
| 86 |
return clientConfig |
| 87 |
} |
| 88 |
|
| 89 |
if c.conf.OpenVPN.OverrideUsername { |
| 90 |
clientConfig = append(clientConfig, fmt.Sprintf(`override-username %q`, username)) |
| 91 |
} else if c.conf.OpenVPN.AuthTokenUser && client.UsernameIsDefined == 0 { |
| 92 |
if len(username) == 0 { |
| 93 |
username = "username" |
| 94 |
} |
| 95 |
|
| 96 |
clientConfig = append(clientConfig, fmt.Sprintf(`push "auth-token-user %s"`, base64.StdEncoding.EncodeToString([]byte(username)))) |
| 97 |
} |
| 98 |
|
| 99 |
return clientConfig |
| 100 |
} |
| 101 |
|
| 102 |
func (c *Client) readClientConfigs(ctx context.Context, logger *slog.Logger, clientConfigNames []string) ([]string, error) { |
| 103 |
if c.conf.OpenVPN.ClientConfig.Strategy != config.OpenVPNConfigStrategyMerge { |
| 104 |
return c.readSingleClientConfig(ctx, logger, clientConfigNames[0]) |
| 105 |
} |
| 106 |
|
| 107 |
seenConfigNames := make(map[string]struct{}, len(clientConfigNames)) |
| 108 |
seenLines := make(map[string]struct{}) |
| 109 |
clientConfig := make([]string, 0, len(clientConfigNames)) |
| 110 |
|
| 111 |
for _, clientConfigName := range clientConfigNames { |
| 112 |
if _, ok := seenConfigNames[clientConfigName]; ok { |
| 113 |
continue |
| 114 |
} |
| 115 |
|
| 116 |
seenConfigNames[clientConfigName] = struct{}{} |
| 117 |
|
| 118 |
configLines, err := c.readClientConfig(clientConfigName) |
| 119 |
if err != nil { |
| 120 |
skip, err := c.handleClientConfigReadError(ctx, logger, clientConfigName, err) |
| 121 |
if err != nil { |
| 122 |
return nil, err |
| 123 |
} |
| 124 |
|
| 125 |
if skip { |
| 126 |
continue |
| 127 |
} |
| 128 |
} else { |
| 129 |
c.logClientConfigRead(ctx, logger, clientConfigName, configLines, nil) |
| 130 |
} |
| 131 |
|
| 132 |
if len(configLines) == 0 { |
| 133 |
continue |
| 134 |
} |
| 135 |
|
| 136 |
for _, line := range configLines { |
| 137 |
if _, ok := seenLines[line]; ok { |
| 138 |
continue |
| 139 |
} |
| 140 |
|
| 141 |
seenLines[line] = struct{}{} |
| 142 |
clientConfig = append(clientConfig, line) |
| 143 |
} |
| 144 |
} |
| 145 |
|
| 146 |
return clientConfig, nil |
| 147 |
} |
| 148 |
|
| 149 |
func (c *Client) readSingleClientConfig(ctx context.Context, logger *slog.Logger, clientConfigName string) ([]string, error) { |
| 150 |
clientConfig, err := c.readClientConfig(clientConfigName) |
| 151 |
if err != nil { |
| 152 |
_, err := c.handleClientConfigReadError(ctx, logger, clientConfigName, err) |
| 153 |
if err != nil { |
| 154 |
return nil, err |
| 155 |
} |
| 156 |
|
| 157 |
return nil, nil |
| 158 |
} |
| 159 |
|
| 160 |
c.logClientConfigRead(ctx, logger, clientConfigName, clientConfig, nil) |
| 161 |
|
| 162 |
return clientConfig, nil |
| 163 |
} |
| 164 |
|
| 165 |
func (c *Client) handleClientConfigReadError(ctx context.Context, logger *slog.Logger, clientConfigName string, err error) (bool, error) { |
| 166 |
if errors.Is(err, fs.ErrNotExist) { |
| 167 |
logger.LogAttrs( |
| 168 |
ctx, slog.LevelDebug, "client config file not found", |
| 169 |
slog.String("config", clientConfigName), |
| 170 |
) |
| 171 |
|
| 172 |
if c.conf.OpenVPN.ClientConfig.IgnoreNotFound { |
| 173 |
return true, nil |
| 174 |
} |
| 175 |
} |
| 176 |
|
| 177 |
return false, fmt.Errorf("read client config %q: %w", clientConfigName, err) |
| 178 |
} |
| 179 |
|
| 180 |
func (c *Client) logClientConfigRead(ctx context.Context, logger *slog.Logger, clientConfigName string, clientConfig []string, err error) { |
| 181 |
switch { |
| 182 |
case err != nil: |
| 183 |
logger.LogAttrs( |
| 184 |
ctx, slog.LevelDebug, "failed to read client config", |
| 185 |
slog.String("config", clientConfigName), |
| 186 |
slog.Any("error", err), |
| 187 |
) |
| 188 |
case len(clientConfig) > 0: |
| 189 |
logger.LogAttrs( |
| 190 |
ctx, slog.LevelDebug, "applying client config from CCD", |
| 191 |
slog.String("config", clientConfigName), |
| 192 |
slog.Any("content", clientConfig), |
| 193 |
) |
| 194 |
default: |
| 195 |
logger.LogAttrs( |
| 196 |
ctx, slog.LevelInfo, "no client config found in CCD", |
| 197 |
slog.String("config", clientConfigName), |
| 198 |
) |
| 199 |
} |
| 200 |
} |
| 201 |
|
| 202 |
// sendClientAuth sends the appropriate client-auth or client-auth-nt command. |
| 203 |
func (c *Client) sendClientAuth(ctx context.Context, client state.ClientIdentifier, clientConfig []string) error { |
| 204 |
if len(clientConfig) == 0 { |
| 205 |
_, err := c.SendCommandf(ctx, `client-auth-nt %d %d`, client.CID, client.KID) |
| 206 |
|
| 207 |
return err |
| 208 |
} |
| 209 |
|
| 210 |
sb := strings.Builder{} |
| 211 |
_, _ = fmt.Fprintf(&sb, "client-auth %d %d\r\n", client.CID, client.KID) |
| 212 |
|
| 213 |
for _, line := range clientConfig { |
| 214 |
sb.WriteString(strings.TrimSpace(line)) |
| 215 |
sb.WriteString("\r\n") |
| 216 |
} |
| 217 |
|
| 218 |
sb.WriteString("END") |
| 219 |
|
| 220 |
_, err := c.SendCommand(ctx, sb.String(), false) |
| 221 |
|
| 222 |
return err |
| 223 |
} |
| 224 |
|
| 225 |
func (c *Client) DenyClient(ctx context.Context, logger *slog.Logger, client state.ClientIdentifier, reason string) { |
| 226 |
logger.LogAttrs(ctx, slog.LevelInfo, fmt.Sprintf("deny OpenVPN client cid %d, kid %d", client.CID, client.KID)) |
| 227 |
|
| 228 |
_, err := c.SendCommandf(ctx, `client-deny %d %d "%s"`, client.CID, client.KID, reason) |
| 229 |
if err != nil { |
| 230 |
logger.LogAttrs( |
| 231 |
ctx, slog.LevelWarn, "failed to deny client", |
| 232 |
slog.Any("error", err), |
| 233 |
) |
| 234 |
} |
| 235 |
} |
| 236 |
|
| 237 |
func (c *Client) readClientConfig(username string) ([]string, error) { |
| 238 |
if !c.conf.OpenVPN.ClientConfig.Enabled || c.conf.OpenVPN.ClientConfig.Path.IsEmpty() || len(username) == 0 { |
| 239 |
return make([]string, 0, 1), nil |
| 240 |
} |
| 241 |
|
| 242 |
clientConfigPath := username + ".conf" |
| 243 |
if !fs.ValidPath(clientConfigPath) { |
| 244 |
return nil, fmt.Errorf("invalid client config path %q", clientConfigPath) |
| 245 |
} |
| 246 |
|
| 247 |
clientConfigFile, err := c.conf.OpenVPN.ClientConfig.Path.Open(clientConfigPath) |
| 248 |
if err != nil { |
| 249 |
return nil, fmt.Errorf("failed to open client config file: %w", err) |
| 250 |
} |
| 251 |
defer clientConfigFile.Close() |
| 252 |
|
| 253 |
clientConfigBytes, err := io.ReadAll(clientConfigFile) |
| 254 |
if err != nil { |
| 255 |
return nil, fmt.Errorf("failed to read client config file: %w", err) |
| 256 |
} |
| 257 |
|
| 258 |
content := strings.TrimSpace(strings.ReplaceAll(string(clientConfigBytes), "\r", "")) |
| 259 |
|
| 260 |
// Pre-allocate with exact line count + 1 spare capacity for applyUsernameConfig. |
| 261 |
n := strings.Count(content, "\n") + 1 |
| 262 |
result := make([]string, 0, n+1) |
| 263 |
|
| 264 |
for { |
| 265 |
i := strings.IndexByte(content, '\n') |
| 266 |
if i < 0 { |
| 267 |
result = append(result, content) |
| 268 |
|
| 269 |
break |
| 270 |
} |
| 271 |
|
| 272 |
result = append(result, content[:i]) |
| 273 |
content = content[i+1:] |
| 274 |
} |
| 275 |
|
| 276 |
return result, nil |
| 277 |
} |