Debian Codegraph @

internal/oauth2/utils.go

raw
1 package oauth2
2
3 import (
4 "crypto/sha256"
5 "encoding/hex"
6 "fmt"
7 "net"
8 "net/http"
9 "net/netip"
10 "net/url"
11 "slices"
12 "strings"
13
14 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/config"
15 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/state"
16 "github.com/zitadel/oidc/v3/pkg/client/rp"
17 "golang.org/x/oauth2"
18 )
19
20 // checkClientIPAddr verifies that the HTTP client address matches the VPN client address from the OAuth2 state.
21 func checkClientIPAddr(r *http.Request, conf *config.Config, session state.State) error {
22 clientIP, _, err := net.SplitHostPort(r.RemoteAddr)
23 if err != nil {
24 return fmt.Errorf("unable to split remote address %s: %w", r.RemoteAddr, err)
25 }
26
27 if conf.HTTP.EnableProxyHeaders && addrTrustedProxy(clientIP, conf.HTTP.TrustedProxies) {
28 if forwardedFor := r.Header.Values("X-Forwarded-For"); len(forwardedFor) != 0 {
29 clientIP = clientIPFromForwardedChain(clientIP, forwardedFor, conf.HTTP.TrustedProxies)
30 }
31 }
32
33 if clientIP != session.IPAddr {
34 return fmt.Errorf("%w: http client ip %s and vpn ip %s is different", ErrClientRejected, clientIP, session.IPAddr)
35 }
36
37 return nil
38 }
39
40 func clientIPFromForwardedChain(remoteAddr string, forwardedForHeaders, trustedProxies []string) string {
41 currentAddr := remoteAddr
42
43 for _, forwardedFor := range slices.Backward(forwardedForHeaders) {
44 for {
45 if !addrTrustedProxy(currentAddr, trustedProxies) {
46 return currentAddr
47 }
48
49 comma := strings.LastIndexByte(forwardedFor, ',')
50 forwardedAddr := forwardedFor[comma+1:]
51 forwardedAddr = strings.TrimSpace(forwardedAddr)
52
53 if forwardedAddr != "" {
54 currentAddr = forwardedAddr
55 }
56
57 if comma < 0 {
58 break
59 }
60
61 forwardedFor = forwardedFor[:comma]
62 }
63 }
64
65 return currentAddr
66 }
67
68 func addrTrustedProxy(addrText string, trustedProxies []string) bool {
69 addr, err := netip.ParseAddr(addrText)
70 if err != nil {
71 return false
72 }
73
74 addr = addr.Unmap()
75
76 for _, trustedProxy := range trustedProxies {
77 trustedProxy = strings.TrimSpace(trustedProxy)
78
79 prefix, err := netip.ParsePrefix(trustedProxy)
80 if err != nil {
81 continue
82 }
83
84 if prefix.Contains(addr) {
85 return true
86 }
87 }
88
89 return false
90 }
91
92 // getAuthorizeParams parses the authorizeParams string and returns a slice of rp.URLParamOpt.
93 func getAuthorizeParams(authorizeParams string) ([]rp.URLParamOpt, error) {
94 authorizeParamsQuery, err := url.ParseQuery(authorizeParams)
95 if err != nil {
96 return nil, fmt.Errorf("unable to parse '%s': %w", authorizeParams, err)
97 }
98
99 params := make([]rp.URLParamOpt, 0, len(authorizeParamsQuery))
100
101 for key, value := range authorizeParamsQuery {
102 if len(value) == 0 {
103 return nil, fmt.Errorf("authorize param %s does not have values", key)
104 }
105
106 params = append(params, rp.WithURLParam(key, value[0]))
107 }
108
109 return params, nil
110 }
111
112 // getNonce returns OAuth2 nonce for the given client ID.
113 func (c *Client) getNonce(id string) string {
114 nonce := sha256.New()
115 nonce.Write([]byte(id))
116 nonce.Write([]byte(c.conf.HTTP.Secret.String()))
117
118 return hex.EncodeToString(nonce.Sum(nil))
119 }
120
121 // OAuthConfig returns the underlying [oauth2.Config] used by the relying party.
122 // It is primarily exposed for tests that need direct access to the client
123 // configuration.
124 func (c *Client) OAuthConfig() *oauth2.Config {
125 return c.relyingParty.OAuthConfig()
126 }
127
128 // EncryptState encrypts an OAuth2 state payload for use in authorization redirects.
129 func (c *Client) EncryptState(oidcState state.State) (state.EncryptedState, error) {
130 encryptedState, err := state.Encrypt(c.stateCrypto, oidcState)
131 if err != nil {
132 return "", fmt.Errorf("encrypt state: %w", err)
133 }
134
135 return encryptedState, nil
136 }