Debian Codegraph @

server/auth_callout.go

raw
1 // Copyright 2022-2025 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package server
15
16 import (
17 "bytes"
18 "crypto/tls"
19 "encoding/pem"
20 "errors"
21 "fmt"
22 "time"
23 "unicode"
24
25 "github.com/nats-io/jwt/v2"
26 "github.com/nats-io/nkeys"
27 )
28
29 const (
30 AuthCalloutSubject = "$SYS.REQ.USER.AUTH"
31 AuthRequestSubject = "nats-authorization-request"
32 AuthRequestXKeyHeader = "Nats-Server-Xkey"
33 )
34
35 func titleCase(m string) string {
36 r := []rune(m)
37 if len(r) == 0 {
38 return _EMPTY_
39 }
40 return string(append([]rune{unicode.ToUpper(r[0])}, r[1:]...))
41 }
42
43 // Process a callout on this client's behalf.
44 func (s *Server) processClientOrLeafCallout(c *client, opts *Options, proxyRequired, trustedProxy bool, ujwt string) (authorized bool, errStr string) {
45 isOperatorMode := len(opts.TrustedKeys) > 0
46
47 // this is the account the user connected in, or the one running the callout
48 var acc *Account
49 if !isOperatorMode && opts.AuthCallout != nil && opts.AuthCallout.Account != _EMPTY_ {
50 aname := opts.AuthCallout.Account
51 var err error
52 acc, err = s.LookupAccount(aname)
53 if err != nil {
54 errStr = fmt.Sprintf("No valid account %q for auth callout request: %v", aname, err)
55 s.Warnf(errStr)
56 return false, errStr
57 }
58 } else {
59 acc = c.acc
60 }
61 if acc == nil {
62 // FIX for https://github.com/nats-io/nats-server/issues/7841
63 // hand rolled creds on leafnode became crasher here
64 errStr = fmt.Sprintf("%s not mapped to a callout account", c.kindString())
65 s.Warnf(errStr)
66 return false, errStr
67 }
68
69 // Check if we have been requested to encrypt.
70 var xkp nkeys.KeyPair
71 var xkey string
72 var pubAccXKey string
73 if !isOperatorMode && opts.AuthCallout != nil && opts.AuthCallout.XKey != _EMPTY_ {
74 pubAccXKey = opts.AuthCallout.XKey
75 } else if isOperatorMode {
76 pubAccXKey = acc.externalAuthXKey()
77 }
78 // If set grab server's xkey keypair and public key.
79 if pubAccXKey != _EMPTY_ {
80 // These are only set on creation, so lock not needed.
81 xkp, xkey = s.xkp, s.info.XKey
82 }
83
84 // Create a keypair for the user. We will expect this public user to be in the signed response.
85 // This prevents replay attacks.
86 ukp, _ := nkeys.CreateUser()
87 pub, _ := ukp.PublicKey()
88
89 reply := s.newRespInbox()
90 respCh := make(chan string, 1)
91
92 decodeResponse := func(rc *client, rmsg []byte, acc *Account) (*jwt.UserClaims, error) {
93 account := acc.Name
94 _, msg := rc.msgParts(rmsg)
95
96 // This signals not authorized.
97 // Since this is an account subscription will always have "\r\n".
98 if len(msg) <= LEN_CR_LF {
99 return nil, fmt.Errorf("auth callout violation: %q on account %q", "no reason supplied", account)
100 }
101 // Strip trailing CRLF.
102 msg = msg[:len(msg)-LEN_CR_LF]
103 encrypted := false
104 // If we sent an encrypted request the response could be encrypted as well.
105 // we are expecting the input to be `eyJ` if it is a JWT
106 if xkp != nil && len(msg) > 0 && !bytes.HasPrefix(msg, []byte(jwtPrefix)) {
107 var err error
108 msg, err = xkp.Open(msg, pubAccXKey)
109 if err != nil {
110 return nil, fmt.Errorf("error decrypting auth callout response on account %q: %v", account, err)
111 }
112 encrypted = true
113 }
114
115 cr, err := jwt.DecodeAuthorizationResponseClaims(string(msg))
116 if err != nil {
117 return nil, err
118 }
119 vr := jwt.CreateValidationResults()
120 cr.Validate(vr)
121 if len(vr.Issues) > 0 {
122 return nil, fmt.Errorf("authorization response had validation errors: %v", vr.Issues[0])
123 }
124
125 // the subject is the user id
126 if cr.Subject != pub {
127 return nil, errors.New("auth callout violation: auth callout response is not for expected user")
128 }
129
130 // check the audience to be the server ID
131 if cr.Audience != s.info.ID {
132 return nil, errors.New("auth callout violation: auth callout response is not for server")
133 }
134
135 // check if had an error message from the auth account
136 if cr.Error != _EMPTY_ {
137 return nil, fmt.Errorf("auth callout service returned an error: %v", cr.Error)
138 }
139
140 // if response is encrypted none of this is needed
141 if isOperatorMode && !encrypted {
142 pkStr := cr.Issuer
143 if cr.IssuerAccount != _EMPTY_ {
144 pkStr = cr.IssuerAccount
145 }
146 if pkStr != account {
147 if _, ok := acc.hasIssuer(pkStr); !ok {
148 return nil, errors.New("auth callout signing key is unknown")
149 }
150 }
151 }
152
153 return jwt.DecodeUserClaims(cr.Jwt)
154 }
155
156 // getIssuerAccount returns the issuer (as per JWT) - it also asserts that
157 // only in operator mode we expect to receive `issuer_account`.
158 getIssuerAccount := func(arc *jwt.UserClaims, account string) (string, error) {
159 // Make sure correct issuer.
160 var issuer string
161 if opts.AuthCallout != nil {
162 issuer = opts.AuthCallout.Issuer
163 } else {
164 // Operator mode is who we send the request on unless switching accounts.
165 issuer = acc.Name
166 }
167
168 // the jwt issuer can be a signing key
169 jwtIssuer := arc.Issuer
170 if arc.IssuerAccount != _EMPTY_ {
171 if !isOperatorMode {
172 // this should be invalid - effectively it would allow the auth callout
173 // to issue on another account which may be allowed given the configuration
174 // where the auth callout account can handle multiple different ones..
175 return _EMPTY_, fmt.Errorf("error non operator mode account %q: attempted to use issuer_account", account)
176 }
177 jwtIssuer = arc.IssuerAccount
178 }
179
180 if jwtIssuer != issuer {
181 if !isOperatorMode {
182 return _EMPTY_, fmt.Errorf("wrong issuer for auth callout response on account %q, expected %q got %q", account, issuer, jwtIssuer)
183 } else if !acc.isAllowedAcount(jwtIssuer) {
184 return _EMPTY_, fmt.Errorf("account %q not permitted as valid account option for auth callout for account %q",
185 arc.Issuer, account)
186 }
187 }
188 return jwtIssuer, nil
189 }
190
191 getExpirationAndAllowedConnections := func(arc *jwt.UserClaims, account string) (time.Duration, map[string]struct{}, error) {
192 allowNow, expiration := validateTimes(arc)
193 if !allowNow {
194 c.Errorf("Outside connect times")
195 return 0, nil, fmt.Errorf("authorized user on account %q outside of valid connect times", account)
196 }
197
198 allowedConnTypes, err := convertAllowedConnectionTypes(arc.User.AllowedConnectionTypes)
199 if err != nil {
200 c.Debugf("%v", err)
201 if len(allowedConnTypes) == 0 {
202 return 0, nil, fmt.Errorf("authorized user on account %q using invalid connection type", account)
203 }
204 }
205 return expiration, allowedConnTypes, nil
206 }
207
208 assignAccountAndPermissions := func(arc *jwt.UserClaims, account string) (*Account, error) {
209 // Apply to this client.
210 var err error
211 issuerAccount, err := getIssuerAccount(arc, account)
212 if err != nil {
213 return nil, err
214 }
215
216 // if we are not in operator mode, they can specify placement as a tag
217 var placement string
218 if !isOperatorMode {
219 // only allow placement if we are not in operator mode
220 placement = arc.Audience
221 } else {
222 placement = issuerAccount
223 }
224
225 targetAcc, err := s.LookupAccount(placement)
226 if err != nil {
227 return nil, fmt.Errorf("no valid account %q for auth callout response on account %q: %v", placement, account, err)
228 }
229 if isOperatorMode {
230 // this will validate the signing key that emitted the user, and if it is a signing
231 // key it assigns the permissions from the target account
232 if scope, ok := targetAcc.hasIssuer(arc.Issuer); !ok {
233 return nil, fmt.Errorf("user JWT issuer %q is not known", arc.Issuer)
234 } else if scope != nil {
235 // this possibly has to be different because it could just be a plain issued by a non-scoped signing key
236 if err := scope.ValidateScopedSigner(arc); err != nil {
237 return nil, fmt.Errorf("user JWT is not valid: %v", err)
238 } else if uSc, ok := scope.(*jwt.UserScope); !ok {
239 return nil, fmt.Errorf("user JWT is not a valid scoped user")
240 } else if arc.User.UserPermissionLimits, err = processUserPermissionsTemplate(uSc.Template, arc, targetAcc); err != nil {
241 return nil, fmt.Errorf("user JWT generated invalid permissions: %v", err)
242 }
243 }
244 }
245 return targetAcc, nil
246 }
247
248 processReply := func(_ *subscription, rc *client, racc *Account, subject, reply string, rmsg []byte) {
249 arc, err := decodeResponse(rc, rmsg, racc)
250 if err != nil {
251 c.authViolation()
252 respCh <- titleCase(err.Error())
253 return
254 }
255 // If the caller had established that the user should go through a proxy,
256 // or if the `arc` JWT requires it, and we don't have a trusted proxy,
257 // reject the connection.
258 if (proxyRequired || arc.ProxyRequired) && !trustedProxy {
259 err = ErrAuthProxyRequired
260 c.setAuthError(err)
261 c.authViolation()
262 respCh <- titleCase(err.Error())
263 return
264 }
265 vr := jwt.CreateValidationResults()
266 arc.Validate(vr)
267 if len(vr.Issues) > 0 {
268 c.authViolation()
269 respCh <- fmt.Sprintf("Error validating user JWT: %v", vr.Issues[0])
270 return
271 }
272
273 // Make sure that the user is what we requested.
274 if arc.Subject != pub {
275 c.authViolation()
276 respCh <- fmt.Sprintf("Expected authorized user of %q but got %q on account %q", pub, arc.Subject, racc.Name)
277 return
278 }
279
280 expiration, allowedConnTypes, err := getExpirationAndAllowedConnections(arc, racc.Name)
281 if err != nil {
282 c.authViolation()
283 respCh <- titleCase(err.Error())
284 return
285 }
286
287 targetAcc, err := assignAccountAndPermissions(arc, racc.Name)
288 if err != nil {
289 c.authViolation()
290 respCh <- titleCase(err.Error())
291 return
292 }
293
294 // the JWT is cleared, because if in operator mode it may hold the JWT
295 // for the bearer token that connected to the callout if in operator mode
296 // the permissions are already set on the client, this prevents a decode
297 // on c.RegisterNKeyUser which would have wrong values
298 c.mu.Lock()
299 c.opts.JWT = _EMPTY_
300 c.mu.Unlock()
301
302 // Build internal user and bind to the targeted account.
303 nkuser := buildInternalNkeyUser(arc, allowedConnTypes, targetAcc)
304 if err := c.RegisterNkeyUser(nkuser); err != nil {
305 c.authViolation()
306 respCh <- fmt.Sprintf("Could not register auth callout user: %v", err)
307 return
308 }
309
310 // See if the response wants to override the username.
311 if arc.Name != _EMPTY_ {
312 c.mu.Lock()
313 c.opts.Username = arc.Name
314 // Clear any others.
315 c.opts.Nkey = _EMPTY_
316 c.pubKey = _EMPTY_
317 c.opts.Token = _EMPTY_
318 c.mu.Unlock()
319 }
320
321 // Check if we need to set an auth timer if the user jwt expires.
322 c.setExpiration(arc.Claims(), expiration)
323
324 respCh <- _EMPTY_
325 }
326
327 // create a subscription to receive a response from the authcallout
328 sub, err := acc.subscribeInternal(reply, processReply)
329 if err != nil {
330 errStr = fmt.Sprintf("Error setting up reply subscription for auth request: %v", err)
331 s.Warnf(errStr)
332 return false, errStr
333 }
334 defer acc.unsubscribeInternal(sub)
335
336 // Build our request claims - jwt subject should be nkey
337 jwtSub := acc.Name
338 if opts.AuthCallout != nil {
339 jwtSub = opts.AuthCallout.Issuer
340 }
341
342 // The public key of the server, if set is available on Varz.Key
343 // This means that when a service connects, it can now peer
344 // authenticate if it wants to - but that also means that it needs to be
345 // listening to cluster changes
346 claim := jwt.NewAuthorizationRequestClaims(jwtSub)
347 claim.Audience = AuthRequestSubject
348 // Set expected public user nkey.
349 claim.UserNkey = pub
350
351 s.mu.RLock()
352 claim.Server = jwt.ServerID{
353 Name: s.info.Name,
354 Host: s.info.Host,
355 ID: s.info.ID,
356 Version: s.info.Version,
357 Cluster: s.info.Cluster,
358 }
359 s.mu.RUnlock()
360
361 // Tags
362 claim.Server.Tags = s.getOpts().Tags
363
364 // Check if we have been requested to encrypt.
365 // FIXME: possibly this public key also needs to be on the
366 // Varz, because then it can be peer verified?
367 if xkp != nil {
368 claim.Server.XKey = xkey
369 }
370
371 authTimeout := secondsToDuration(s.getOpts().AuthTimeout)
372 claim.Expires = time.Now().Add(time.Duration(authTimeout)).UTC().Unix()
373
374 // Grab client info for the request.
375 c.mu.Lock()
376 c.fillClientInfo(&claim.ClientInformation)
377 c.fillConnectOpts(&claim.ConnectOptions, ujwt)
378 // If we have a sig in the client opts, fill in nonce.
379 if claim.ConnectOptions.SignedNonce != _EMPTY_ {
380 claim.ClientInformation.Nonce = string(c.nonce)
381 }
382
383 // TLS
384 if c.flags.isSet(handshakeComplete) && c.nc != nil {
385 var ct jwt.ClientTLS
386 conn := c.nc.(*tls.Conn)
387 cs := conn.ConnectionState()
388 ct.Version = tlsVersion(cs.Version)
389 ct.Cipher = tls.CipherSuiteName(cs.CipherSuite)
390 // Check verified chains.
391 for _, vs := range cs.VerifiedChains {
392 var certs []string
393 for _, c := range vs {
394 blk := &pem.Block{
395 Type: "CERTIFICATE",
396 Bytes: c.Raw,
397 }
398 certs = append(certs, string(pem.EncodeToMemory(blk)))
399 }
400 ct.VerifiedChains = append(ct.VerifiedChains, certs)
401 }
402 // If we do not have verified chains put in peer certs.
403 if len(ct.VerifiedChains) == 0 {
404 for _, c := range cs.PeerCertificates {
405 blk := &pem.Block{
406 Type: "CERTIFICATE",
407 Bytes: c.Raw,
408 }
409 ct.Certs = append(ct.Certs, string(pem.EncodeToMemory(blk)))
410 }
411 }
412 claim.TLS = &ct
413 }
414 c.mu.Unlock()
415
416 b, err := claim.Encode(s.kp)
417 if err != nil {
418 errStr = fmt.Sprintf("Error encoding auth request claim on account %q: %v", acc.Name, err)
419 s.Warnf(errStr)
420 return false, errStr
421 }
422 req := []byte(b)
423 var hdr []byte
424
425 // Check if we have been asked to encrypt.
426 if xkp != nil {
427 req, err = xkp.Seal([]byte(req), pubAccXKey)
428 if err != nil {
429 errStr = fmt.Sprintf("Error encrypting auth request claim on account %q: %v", acc.Name, err)
430 s.Warnf(errStr)
431 return false, errStr
432 }
433 hdr = genHeader(hdr, AuthRequestXKeyHeader, xkey)
434 }
435
436 // Send out our request.
437 if err := s.sendInternalAccountMsgWithReply(acc, AuthCalloutSubject, reply, hdr, req, false); err != nil {
438 errStr = fmt.Sprintf("Error sending authorization request: %v", err)
439 s.Debugf(errStr)
440 return false, errStr
441 }
442 select {
443 case errStr = <-respCh:
444 if authorized = errStr == _EMPTY_; !authorized {
445 s.Warnf(errStr)
446 }
447 case <-time.After(authTimeout):
448 s.Debugf(fmt.Sprintf("Authorization callout response not received in time on account %q", acc.Name))
449 }
450
451 return authorized, errStr
452 }
453
454 // Fill in client information for the request.
455 // Lock should be held.
456 func (c *client) fillClientInfo(ci *jwt.ClientInformation) {
457 if c == nil || (c.kind != CLIENT && c.kind != LEAF && c.kind != JETSTREAM && c.kind != ACCOUNT) {
458 return
459 }
460
461 // Do it this way to fail to compile if fields are added to jwt.ClientInformation.
462 *ci = jwt.ClientInformation{
463 Host: c.host,
464 ID: c.cid,
465 User: c.getRawAuthUser(),
466 Name: c.opts.Name,
467 Tags: c.tags,
468 NameTag: c.nameTag,
469 Kind: c.kindString(),
470 Type: c.clientTypeString(),
471 MQTT: c.getMQTTClientID(),
472 }
473 }
474
475 // Fill in client options.
476 // Lock should be held.
477 func (c *client) fillConnectOpts(opts *jwt.ConnectOptions, ujwt string) {
478 if c == nil || (c.kind != CLIENT && c.kind != LEAF && c.kind != JETSTREAM && c.kind != ACCOUNT) {
479 return
480 }
481
482 o := c.opts
483 if ujwt == _EMPTY_ {
484 // The caller may supply a reconstructed JWT that should be sent to auth
485 // callout without storing it in c.opts.JWT. If not, fall back to the client
486 // option as before.
487 ujwt = o.JWT
488 }
489
490 // Do it this way to fail to compile if fields are added to jwt.ClientInformation.
491 *opts = jwt.ConnectOptions{
492 JWT: ujwt,
493 Nkey: o.Nkey,
494 SignedNonce: o.Sig,
495 Token: o.Token,
496 Username: o.Username,
497 Password: o.Password,
498 Name: o.Name,
499 Lang: o.Lang,
500 Version: o.Version,
501 Protocol: o.Protocol,
502 }
503 }