-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
handler.go
287 lines (228 loc) · 8.25 KB
/
handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
package oauth2
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"io/fs"
"log/slog"
"net"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/jkroepke/openvpn-auth-oauth2/internal/config"
"github.com/jkroepke/openvpn-auth-oauth2/internal/oauth2/idtoken"
"github.com/jkroepke/openvpn-auth-oauth2/internal/oauth2/types"
"github.com/jkroepke/openvpn-auth-oauth2/internal/state"
"github.com/jkroepke/openvpn-auth-oauth2/internal/ui"
"github.com/jkroepke/openvpn-auth-oauth2/internal/utils"
"github.com/zitadel/logging"
"github.com/zitadel/oidc/v3/pkg/client/rp"
"github.com/zitadel/oidc/v3/pkg/oidc"
)
type OpenVPN interface {
AcceptClient(logger *slog.Logger, client state.ClientIdentifier, username string)
DenyClient(logger *slog.Logger, client state.ClientIdentifier, reason string)
}
func (p *Provider) Handler() *http.ServeMux {
staticFs, err := fs.Sub(ui.Static, "assets")
if err != nil {
panic(err)
}
if p.conf.HTTP.AssetPath != "" {
staticFs = utils.NewOverlayFS(staticFs, os.DirFS(p.conf.HTTP.AssetPath))
}
basePath := strings.TrimSuffix(p.conf.HTTP.BaseURL.Path, "/")
mux := http.NewServeMux()
mux.Handle("/", http.NotFoundHandler())
mux.Handle(fmt.Sprintf("GET %s/assets/", basePath), http.StripPrefix(utils.StringConcat(basePath, "/assets/"), http.FileServerFS(staticFs)))
mux.Handle(fmt.Sprintf("GET %s/oauth2/start", basePath), p.oauth2Start())
mux.Handle(fmt.Sprintf("GET %s/oauth2/callback", basePath), p.oauth2Callback())
return mux
}
func (p *Provider) oauth2Start() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sendCacheHeaders(w)
sessionState := r.URL.Query().Get("state")
if sessionState == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
session, err := state.NewWithEncodedToken(sessionState, p.conf.HTTP.Secret.String())
if err != nil {
p.logger.Warn(utils.StringConcat("invalid state: ", err.Error()))
w.WriteHeader(http.StatusBadRequest)
return
}
logger := p.logger.With(
slog.String("ip", fmt.Sprintf("%s:%s", session.IPAddr, session.IPPort)),
slog.Uint64("cid", session.Client.CID),
slog.Uint64("kid", session.Client.KID),
slog.String("common_name", session.CommonName),
)
if p.conf.HTTP.Check.IPAddr {
ok, httpStatusCode, denyReason := checkClientIPAddr(r, logger, session, p.conf)
if !ok {
p.openvpn.DenyClient(logger, session.Client, denyReason)
w.WriteHeader(httpStatusCode)
return
}
}
logger.Info("initialize authorization via oauth2")
authorizeParams := p.authorizeParams
if p.conf.OAuth2.Nonce {
id := strconv.FormatUint(session.Client.CID, 10)
if p.conf.OAuth2.Refresh.UseSessionID && session.Client.SessionID != "" {
id = session.Client.SessionID
}
authorizeParams = append(authorizeParams, rp.WithURLParam("nonce", p.GetNonce(id)))
}
rp.AuthURLHandler(func() string {
return sessionState
}, p.RelyingParty, authorizeParams...).ServeHTTP(w, r)
})
}
func sendCacheHeaders(w http.ResponseWriter) {
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
w.Header().Set("Pragma", "no-cache")
w.Header().Set("Expires", "0")
}
func checkClientIPAddr(r *http.Request, logger *slog.Logger, session state.State, conf config.Config) (bool, int, string) {
clientIP, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
logger.Warn(err.Error())
return false, http.StatusInternalServerError, "client rejected"
}
if strings.HasPrefix(r.RemoteAddr, "[") {
clientIP = utils.StringConcat("[", clientIP, "]")
}
if conf.HTTP.EnableProxyHeaders {
if fwdAddress := r.Header.Get("X-Forwarded-For"); fwdAddress != "" {
clientIP = strings.Split(fwdAddress, ", ")[0]
}
}
if clientIP != session.IPAddr {
reason := utils.StringConcat("http client ip ", clientIP, " and vpn ip ", session.IPAddr, " is different.")
logger.Warn(reason)
return false, http.StatusForbidden, reason
}
return true, 0, ""
}
//nolint:cyclop
func (p *Provider) oauth2Callback() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sendCacheHeaders(w)
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
encryptedState := r.URL.Query().Get("state")
if encryptedState == "" {
writeError(w, p.logger, p.conf, http.StatusBadRequest, "Bad Request", "state is empty")
return
}
session, err := state.NewWithEncodedToken(encryptedState, p.conf.HTTP.Secret.String())
if err != nil {
writeError(w, p.logger, p.conf, http.StatusBadRequest, "Invalid State", err.Error())
return
}
logger := p.logger.With(
slog.String("ip", fmt.Sprintf("%s:%s", session.IPAddr, session.IPPort)),
slog.Uint64("cid", session.Client.CID),
slog.Uint64("kid", session.Client.KID),
slog.String("session_id", session.Client.SessionID),
slog.String("common_name", session.CommonName),
)
ctx = logging.ToContext(ctx, logger)
id := strconv.FormatUint(session.Client.CID, 10)
if p.conf.OAuth2.Refresh.UseSessionID && session.Client.SessionID != "" {
id = session.Client.SessionID
}
if p.conf.OAuth2.Nonce {
ctx = context.WithValue(ctx, types.CtxNonce{}, p.GetNonce(id))
r = r.WithContext(ctx)
}
rp.CodeExchangeHandler(func(
w http.ResponseWriter, _ *http.Request, tokens *oidc.Tokens[*idtoken.Claims], _ string,
_ rp.RelyingParty,
) {
if tokens.IDTokenClaims != nil {
logger = logger.With(
slog.String("idtoken.subject", tokens.IDTokenClaims.Subject),
slog.String("idtoken.email", tokens.IDTokenClaims.EMail),
slog.String("idtoken.preferred_username", tokens.IDTokenClaims.PreferredUsername),
)
logger.Debug("claims", "claims", tokens.IDTokenClaims.Claims)
}
user, err := p.Provider.GetUser(ctx, logger, tokens)
if err != nil {
p.openvpn.DenyClient(logger, session.Client, "unable to fetch user data")
writeError(w, logger, p.conf, http.StatusInternalServerError, "fetchUser", err.Error())
return
}
logger = logger.With(
slog.String("user.subject", user.Subject),
slog.String("user.preferred_username", user.PreferredUsername),
)
err = p.Provider.CheckUser(ctx, session, user, tokens)
if err != nil {
p.openvpn.DenyClient(logger, session.Client, "client rejected")
writeError(w, logger, p.conf, http.StatusInternalServerError, "user validation", err.Error())
return
}
logger.Info("successful authorization via oauth2")
p.openvpn.AcceptClient(logger, session.Client, getAuthTokenUsername(session, user))
if p.conf.OAuth2.Refresh.Enabled {
refreshToken := types.EmptyToken
if p.conf.OAuth2.Refresh.ValidateUser {
refreshToken = p.Provider.GetRefreshToken(tokens)
}
if refreshToken == "" {
p.logger.Warn("oauth2.refresh is enabled, but provider does not return refresh token")
} else if err = p.storage.Set(id, refreshToken); err != nil {
logger.Warn(err.Error())
}
}
writeSuccess(w, p.conf, logger)
}, p.RelyingParty).ServeHTTP(w, r)
})
}
func getAuthTokenUsername(session state.State, user types.UserData) string {
username := session.CommonName
if user.PreferredUsername != "" {
username = user.PreferredUsername
} else if user.Subject != "" {
username = user.Subject
}
return username
}
func writeError(w http.ResponseWriter, logger *slog.Logger, conf config.Config, httpCode int, errorType, errorDesc string) {
if httpCode == http.StatusUnauthorized {
httpCode = http.StatusForbidden
}
h := sha256.New()
h.Write([]byte(time.Now().String()))
errorID := hex.EncodeToString(h.Sum(nil))
logger.Warn(fmt.Sprintf("%s: %s", errorType, errorDesc), slog.String("error_id", errorID))
w.WriteHeader(httpCode)
err := conf.HTTP.CallbackTemplate.Execute(w, map[string]string{
"title": "Access denied",
"message": "Please contact your administrator.",
"errorID": errorID,
})
if err != nil {
logger.Error(fmt.Errorf("executing template: %w", err).Error())
w.WriteHeader(http.StatusInternalServerError)
}
}
func writeSuccess(w http.ResponseWriter, conf config.Config, logger *slog.Logger) {
err := conf.HTTP.CallbackTemplate.Execute(w, map[string]string{
"title": "Access granted",
"message": "You can close this window now.",
"errorID": "",
})
if err != nil {
logger.Error(fmt.Errorf("executing template: %w", err).Error())
w.WriteHeader(http.StatusInternalServerError)
}
}