Debian Codegraph @

server/auth.go

raw
1 // Copyright 2012-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 "crypto/sha256"
18 "crypto/subtle"
19 "crypto/tls"
20 "crypto/x509/pkix"
21 "encoding/asn1"
22 "encoding/base64"
23 "encoding/hex"
24 "fmt"
25 "net"
26 "net/url"
27 "regexp"
28 "slices"
29 "strings"
30 "sync/atomic"
31 "time"
32
33 "github.com/nats-io/jwt/v2"
34 "github.com/nats-io/nats-server/v2/internal/ldap"
35 "github.com/nats-io/nkeys"
36 "golang.org/x/crypto/bcrypt"
37 )
38
39 // Authentication is an interface for implementing authentication
40 type Authentication interface {
41 // Check if a client is authorized to connect
42 Check(c ClientAuthentication) bool
43 }
44
45 // ClientAuthentication is an interface for client authentication
46 type ClientAuthentication interface {
47 // GetOpts gets options associated with a client
48 GetOpts() *ClientOpts
49 // GetTLSConnectionState if TLS is enabled, TLS ConnectionState, nil otherwise
50 GetTLSConnectionState() *tls.ConnectionState
51 // RegisterUser optionally map a user after auth.
52 RegisterUser(*User)
53 // RemoteAddress expose the connection information of the client
54 RemoteAddress() net.Addr
55 // GetNonce is the nonce presented to the user in the INFO line
56 GetNonce() []byte
57 // Kind indicates what type of connection this is matching defined constants like CLIENT, ROUTER, GATEWAY, LEAF etc
58 Kind() int
59 //Gets the ID associated with a client
60 GetID() uint64
61 }
62
63 // NkeyUser is for multiple nkey based users
64 type NkeyUser struct {
65 Nkey string `json:"user"`
66 Issued int64 `json:"issued,omitempty"` // this is a copy of the issued at (iat) field in the jwt
67 Permissions *Permissions `json:"permissions,omitempty"`
68 Account *Account `json:"account,omitempty"`
69 SigningKey string `json:"signing_key,omitempty"`
70 AllowedConnectionTypes map[string]struct{} `json:"connection_types,omitempty"`
71 ProxyRequired bool `json:"proxy_required,omitempty"`
72 defaultPerms bool
73 }
74
75 // User is for multiple accounts/users.
76 type User struct {
77 Username string `json:"user"`
78 Password string `json:"password"`
79 Permissions *Permissions `json:"permissions,omitempty"`
80 Account *Account `json:"account,omitempty"`
81 ConnectionDeadline time.Time `json:"connection_deadline,omitempty"`
82 AllowedConnectionTypes map[string]struct{} `json:"connection_types,omitempty"`
83 ProxyRequired bool `json:"proxy_required,omitempty"`
84 }
85
86 // clone performs a deep copy of the User struct, returning a new clone with
87 // all values copied.
88 func (u *User) clone() *User {
89 if u == nil {
90 return nil
91 }
92 clone := &User{}
93 *clone = *u
94 // Account is not cloned because it is always by reference to an existing struct.
95 clone.Permissions = u.Permissions.clone()
96
97 if u.AllowedConnectionTypes != nil {
98 clone.AllowedConnectionTypes = make(map[string]struct{})
99 for k, v := range u.AllowedConnectionTypes {
100 clone.AllowedConnectionTypes[k] = v
101 }
102 }
103
104 return clone
105 }
106
107 // clone performs a deep copy of the NkeyUser struct, returning a new clone with
108 // all values copied.
109 func (n *NkeyUser) clone() *NkeyUser {
110 if n == nil {
111 return nil
112 }
113 clone := &NkeyUser{}
114 *clone = *n
115 // Account is not cloned because it is always by reference to an existing struct.
116 clone.Permissions = n.Permissions.clone()
117
118 if n.AllowedConnectionTypes != nil {
119 clone.AllowedConnectionTypes = make(map[string]struct{})
120 for k, v := range n.AllowedConnectionTypes {
121 clone.AllowedConnectionTypes[k] = v
122 }
123 }
124
125 return clone
126 }
127
128 // SubjectPermission is an individual allow and deny struct for publish
129 // and subscribe authorizations.
130 type SubjectPermission struct {
131 Allow []string `json:"allow,omitempty"`
132 Deny []string `json:"deny,omitempty"`
133 }
134
135 // ResponsePermission can be used to allow responses to any reply subject
136 // that is received on a valid subscription.
137 type ResponsePermission struct {
138 MaxMsgs int `json:"max"`
139 Expires time.Duration `json:"ttl"`
140 }
141
142 // Permissions are the allowed subjects on a per
143 // publish or subscribe basis.
144 type Permissions struct {
145 Publish *SubjectPermission `json:"publish"`
146 Subscribe *SubjectPermission `json:"subscribe"`
147 Response *ResponsePermission `json:"responses,omitempty"`
148 }
149
150 // RoutePermissions are similar to user permissions
151 // but describe what a server can import/export from and to
152 // another server.
153 type RoutePermissions struct {
154 Import *SubjectPermission `json:"import"`
155 Export *SubjectPermission `json:"export"`
156 }
157
158 // clone will clone an individual subject permission.
159 func (p *SubjectPermission) clone() *SubjectPermission {
160 if p == nil {
161 return nil
162 }
163 clone := &SubjectPermission{}
164 if p.Allow != nil {
165 clone.Allow = make([]string, len(p.Allow))
166 copy(clone.Allow, p.Allow)
167 }
168 if p.Deny != nil {
169 clone.Deny = make([]string, len(p.Deny))
170 copy(clone.Deny, p.Deny)
171 }
172 return clone
173 }
174
175 // clone performs a deep copy of the Permissions struct, returning a new clone
176 // with all values copied.
177 func (p *Permissions) clone() *Permissions {
178 if p == nil {
179 return nil
180 }
181 clone := &Permissions{}
182 if p.Publish != nil {
183 clone.Publish = p.Publish.clone()
184 }
185 if p.Subscribe != nil {
186 clone.Subscribe = p.Subscribe.clone()
187 }
188 if p.Response != nil {
189 clone.Response = &ResponsePermission{
190 MaxMsgs: p.Response.MaxMsgs,
191 Expires: p.Response.Expires,
192 }
193 }
194 return clone
195 }
196
197 // wsCanMapCerts returns true if the websocket listener collects client
198 // certificates, which mqtt and leafnode connections over it need to be mapped.
199 func (o *Options) wsCanMapCerts() bool {
200 return o.Websocket.Port != 0 && o.Websocket.TLSConfig != nil &&
201 o.Websocket.TLSConfig.ClientAuth >= tls.RequestClientCert
202 }
203
204 // canTLSMap returns true if verify_and_map on any listener that uses the users
205 // table could select this user, which makes it a certificate identity. Cluster
206 // and gateway map onto their own configured user, so they do not count.
207 func (o *Options) canTLSMap(u *User) bool {
208 // The mapping lookup skips users not allowed on the connection type.
209 allowed := func(cts ...string) bool {
210 if len(u.AllowedConnectionTypes) == 0 {
211 return true
212 }
213 for _, ct := range cts {
214 if _, ok := u.AllowedConnectionTypes[ct]; ok {
215 return true
216 }
217 }
218 return false
219 }
220 // Only a listener that is started can map, and in-process connections have
221 // no TLS state, so they never do.
222 if o.TLSMap && !o.DontListen && allowed(jwt.ConnectionTypeStandard) {
223 return true
224 }
225 if o.Websocket.TLSMap && o.Websocket.Port != 0 && allowed(jwt.ConnectionTypeWebsocket) {
226 return true
227 }
228 // Mqtt over websocket maps with the mqtt listener, not the websocket one,
229 // but takes its certificate from the websocket transport.
230 if o.MQTT.TLSMap && o.MQTT.Port != 0 &&
231 (allowed(jwt.ConnectionTypeMqtt) ||
232 o.wsCanMapCerts() && allowed(jwt.ConnectionTypeMqttWS)) {
233 return true
234 }
235 // Leafnodes only use the users table when the leafnode block sets no
236 // credentials of its own, see isLeafNodeAuthorized.
237 return o.LeafNode.TLSMap && o.LeafNode.Port != 0 &&
238 o.LeafNode.Username == _EMPTY_ && o.LeafNode.Nkey == _EMPTY_ &&
239 len(o.LeafNode.Users) == 0 &&
240 (allowed(jwt.ConnectionTypeLeafnode) ||
241 o.wsCanMapCerts() && allowed(jwt.ConnectionTypeLeafnodeWS))
242 }
243
244 // checkAuthforWarnings will look for insecure settings and log concerns.
245 // Lock is assumed held.
246 func (s *Server) checkAuthforWarnings() {
247 warn := false
248 opts := s.getOpts()
249 if opts.Password != _EMPTY_ && !isBcrypt(opts.Password) {
250 warn = true
251 }
252 for _, u := range s.users {
253 // Skip warn if using TLS certs based auth
254 // unless a password has been left in the config.
255 if u.Password == _EMPTY_ && opts.canTLSMap(u) {
256 continue
257 }
258 // Check if this is our internal sys client created on the fly.
259 if s.sysAccOnlyNoAuthUser != _EMPTY_ && u.Username == s.sysAccOnlyNoAuthUser {
260 continue
261 }
262 if !isBcrypt(u.Password) {
263 warn = true
264 break
265 }
266 }
267 if warn {
268 // Warning about using plaintext passwords.
269 s.Warnf("Plaintext passwords detected, use nkeys or bcrypt")
270 }
271 }
272
273 // If Users or Nkeys options have definitions without an account defined,
274 // assign them to the default global account.
275 // Lock should be held.
276 func (s *Server) assignGlobalAccountToOrphanUsers(nkeys map[string]*NkeyUser, users map[string]*User) {
277 for _, u := range users {
278 if u.Account == nil {
279 u.Account = s.gacc
280 }
281 }
282 for _, u := range nkeys {
283 if u.Account == nil {
284 u.Account = s.gacc
285 }
286 }
287 }
288
289 // If the given permissions has a ResponsePermission
290 // set, ensure that defaults are set (if values are 0)
291 // and that a Publish permission is set, and Allow
292 // is disabled if not explicitly set.
293 func validateResponsePermissions(p *Permissions) {
294 if p == nil || p.Response == nil {
295 return
296 }
297 if p.Publish == nil {
298 p.Publish = &SubjectPermission{}
299 }
300 if p.Publish.Allow == nil {
301 // We turn off the blanket allow statement.
302 p.Publish.Allow = []string{}
303 }
304 // If there is a response permission, ensure
305 // that if value is 0, we set the default value.
306 if p.Response.MaxMsgs == 0 {
307 p.Response.MaxMsgs = DEFAULT_ALLOW_RESPONSE_MAX_MSGS
308 }
309 if p.Response.Expires == 0 {
310 p.Response.Expires = DEFAULT_ALLOW_RESPONSE_EXPIRATION
311 }
312 }
313
314 // configureAuthorization will do any setup needed for authorization.
315 // Lock is assumed held.
316 func (s *Server) configureAuthorization() {
317 opts := s.getOpts()
318 if opts == nil {
319 return
320 }
321
322 // Check for multiple users first
323 // This just checks and sets up the user map if we have multiple users.
324 if opts.CustomClientAuthentication != nil {
325 s.info.AuthRequired = true
326 } else if s.trustedKeys != nil {
327 s.info.AuthRequired = true
328 } else if opts.Nkeys != nil || opts.Users != nil {
329 s.nkeys, s.users = s.buildNkeysAndUsersFromOptions(opts.Nkeys, opts.Users)
330 s.info.AuthRequired = true
331 } else if opts.Username != _EMPTY_ || opts.Authorization != _EMPTY_ {
332 s.info.AuthRequired = true
333 } else {
334 s.users = nil
335 s.nkeys = nil
336 s.info.AuthRequired = false
337 }
338
339 // Do similar for websocket config
340 s.wsConfigAuth(&opts.Websocket)
341 // And for mqtt config
342 s.mqttConfigAuth(&opts.MQTT)
343
344 // Check for server configured auth callouts.
345 if opts.AuthCallout != nil {
346 s.mu.Unlock()
347 // Give operator log entries if not valid account and auth_users.
348 _, err := s.lookupAccount(opts.AuthCallout.Account)
349 s.mu.Lock()
350 if err != nil {
351 s.Errorf("Authorization callout account %q not valid", opts.AuthCallout.Account)
352 }
353 for _, u := range opts.AuthCallout.AuthUsers {
354 // Check for user in users and nkeys since this is server config.
355 var found bool
356 if len(s.users) > 0 {
357 _, found = s.users[u]
358 }
359 if !found && len(s.nkeys) > 0 {
360 _, found = s.nkeys[u]
361 }
362 if !found {
363 s.Errorf("Authorization callout user %q not valid: %v", u, err)
364 }
365 }
366 }
367 }
368
369 // Takes the given slices of NkeyUser and User options and build
370 // corresponding maps used by the server. The users are cloned
371 // so that server does not reference options.
372 // The global account is assigned to users that don't have an
373 // existing account.
374 // Server lock is held on entry.
375 func (s *Server) buildNkeysAndUsersFromOptions(nko []*NkeyUser, uo []*User) (map[string]*NkeyUser, map[string]*User) {
376 var nkeys map[string]*NkeyUser
377 var users map[string]*User
378
379 if nko != nil {
380 nkeys = make(map[string]*NkeyUser, len(nko))
381 for _, u := range nko {
382 copy := u.clone()
383 if u.Account != nil {
384 if v, ok := s.accounts.Load(u.Account.Name); ok {
385 copy.Account = v.(*Account)
386 }
387 }
388 if copy.Permissions != nil {
389 validateResponsePermissions(copy.Permissions)
390 }
391 nkeys[u.Nkey] = copy
392 }
393 }
394 if uo != nil {
395 users = make(map[string]*User, len(uo))
396 for _, u := range uo {
397 copy := u.clone()
398 if u.Account != nil {
399 if v, ok := s.accounts.Load(u.Account.Name); ok {
400 copy.Account = v.(*Account)
401 }
402 }
403 if copy.Permissions != nil {
404 validateResponsePermissions(copy.Permissions)
405 }
406 users[u.Username] = copy
407 }
408 }
409 s.assignGlobalAccountToOrphanUsers(nkeys, users)
410 return nkeys, users
411 }
412
413 // checkAuthentication will check based on client type and
414 // return boolean indicating if client is authorized.
415 func (s *Server) checkAuthentication(c *client) bool {
416 switch c.kind {
417 case CLIENT:
418 return s.isClientAuthorized(c)
419 case ROUTER:
420 return s.isRouterAuthorized(c)
421 case GATEWAY:
422 return s.isGatewayAuthorized(c)
423 case LEAF:
424 return s.isLeafNodeAuthorized(c)
425 default:
426 return false
427 }
428 }
429
430 // isClientAuthorized will check the client against the proper authorization method and data.
431 // This could be nkey, token, or username/password based.
432 func (s *Server) isClientAuthorized(c *client) bool {
433 opts := s.getOpts()
434
435 // Check custom auth first, then jwts, then nkeys, then
436 // multiple users with TLS map if enabled, then token,
437 // then single user/pass.
438 if opts.CustomClientAuthentication != nil && !opts.CustomClientAuthentication.Check(c) {
439 return false
440 }
441
442 if opts.CustomClientAuthentication == nil && !s.processClientOrLeafAuthentication(c, opts) {
443 return false
444 }
445
446 if c.kind == CLIENT || c.kind == LEAF {
447 // Generate an event if we have a system account.
448 s.accountConnectEvent(c)
449 }
450
451 return true
452 }
453
454 // returns false if the client needs to be disconnected
455 func (c *client) matchesPinnedCert(tlsPinnedCerts PinnedCertSet) bool {
456 if tlsPinnedCerts == nil {
457 return true
458 }
459 tlsState := c.GetTLSConnectionState()
460 if tlsState == nil || len(tlsState.PeerCertificates) == 0 || tlsState.PeerCertificates[0] == nil {
461 c.Debugf("Failed pinned cert test as client did not provide a certificate")
462 return false
463 }
464 sha := sha256.Sum256(tlsState.PeerCertificates[0].RawSubjectPublicKeyInfo)
465 keyId := hex.EncodeToString(sha[:])
466 if _, ok := tlsPinnedCerts[keyId]; !ok {
467 c.Debugf("Failed pinned cert test for key id: %s", keyId)
468 return false
469 }
470 return true
471 }
472
473 var (
474 mustacheRE = regexp.MustCompile(`{{2}([^}]+)}{2}`)
475 maxPermTemplateSubjectExpansions = 4096
476 errPermTemplateExpansionLimit error = fmt.Errorf("template expansion exceeds limit")
477 )
478
479 func processUserPermissionsTemplate(lim jwt.UserPermissionLimits, ujwt *jwt.UserClaims, acc *Account) (jwt.UserPermissionLimits, error) {
480 nArrayCartesianProduct := func(a ...[]string) [][]string {
481 c := 1
482 for _, a := range a {
483 c *= len(a)
484 }
485 if c == 0 {
486 return nil
487 }
488 p := make([][]string, c)
489 b := make([]string, c*len(a))
490 n := make([]int, len(a))
491 s := 0
492 for i := range p {
493 e := s + len(a)
494 pi := b[s:e]
495 p[i] = pi
496 s = e
497 for j, n := range n {
498 pi[j] = a[j][n]
499 }
500 for j := len(n) - 1; j >= 0; j-- {
501 n[j]++
502 if n[j] < len(a[j]) {
503 break
504 }
505 n[j] = 0
506 }
507 }
508 return p
509 }
510 isTag := func(op string) []string {
511 if len(op) >= 4 && strings.EqualFold("tag(", op[:4]) && strings.HasSuffix(op, ")") {
512 v := strings.TrimPrefix(op, "tag(")
513 v = strings.TrimSuffix(v, ")")
514 return []string{"tag", v}
515 } else if len(op) >= 12 && strings.EqualFold("account-tag(", op[:12]) && strings.HasSuffix(op, ")") {
516 v := strings.TrimPrefix(op, "account-tag(")
517 v = strings.TrimSuffix(v, ")")
518 return []string{"account-tag", v}
519 }
520 return nil
521 }
522 applyTemplate := func(list jwt.StringList, failOnBadSubject bool) (jwt.StringList, error) {
523 found := false
524 FOR_FIND:
525 for i := 0; i < len(list); i++ {
526 // check if templates are present
527 if mustacheRE.MatchString(list[i]) {
528 found = true
529 break FOR_FIND
530 }
531 }
532 if !found {
533 return list, nil
534 }
535 // process the templates
536 emittedList := make([]string, 0, len(list))
537 for i := 0; i < len(list); i++ {
538 // find all the templates {{}} in this acl
539 tokens := mustacheRE.FindAllString(list[i], -1)
540 srcs := make([]string, len(tokens))
541 values := make([][]string, len(tokens))
542 hasTags := false
543 for tokenNum, tk := range tokens {
544 srcs[tokenNum] = tk
545 op := strings.TrimSpace(strings.TrimSuffix(strings.TrimPrefix(tk, "{{"), "}}"))
546 if strings.EqualFold("name()", op) {
547 values[tokenNum] = []string{ujwt.Name}
548 } else if strings.EqualFold("subject()", op) {
549 values[tokenNum] = []string{ujwt.Subject}
550 } else if strings.EqualFold("account-name()", op) {
551 acc.mu.RLock()
552 values[tokenNum] = []string{acc.nameTag}
553 acc.mu.RUnlock()
554 } else if strings.EqualFold("account-subject()", op) {
555 // this always has an issuer account since this is a scoped signer
556 values[tokenNum] = []string{ujwt.IssuerAccount}
557 } else if isTag(op) != nil {
558 hasTags = true
559 match := isTag(op)
560 var tags jwt.TagList
561 if match[0] == "account-tag" {
562 acc.mu.RLock()
563 tags = acc.tags
564 acc.mu.RUnlock()
565 } else {
566 tags = ujwt.Tags
567 }
568 tagPrefix := fmt.Sprintf("%s:", strings.ToLower(match[1]))
569 var valueList []string
570 for _, tag := range tags {
571 if strings.HasPrefix(tag, tagPrefix) {
572 tagValue := strings.TrimPrefix(tag, tagPrefix)
573 valueList = append(valueList, tagValue)
574 }
575 }
576 if len(valueList) != 0 {
577 values[tokenNum] = valueList
578 } else if failOnBadSubject {
579 return nil, fmt.Errorf("generated invalid subject %q: %q is not defined", list[i], match[1])
580 } else {
581 // generate an invalid subject?
582 values[tokenNum] = []string{" "}
583 }
584 } else {
585 return nil, fmt.Errorf("template operation in %q: %q is not defined", list[i], op)
586 }
587 }
588 if !hasTags {
589 subj := list[i]
590 for idx, m := range srcs {
591 subj = strings.Replace(subj, m, values[idx][0], -1)
592 }
593 if IsValidSubject(subj) {
594 emittedList = append(emittedList, subj)
595 } else if failOnBadSubject {
596 return nil, fmt.Errorf("generated invalid subject")
597 }
598 } else {
599 expCount := 1
600 for _, v := range values {
601 if len(v) == 0 {
602 expCount = 0
603 break
604 }
605 if expCount > maxPermTemplateSubjectExpansions/len(v) {
606 return nil, fmt.Errorf("%w: %d", errPermTemplateExpansionLimit, maxPermTemplateSubjectExpansions)
607 }
608 expCount *= len(v)
609 }
610 if len(emittedList) > maxPermTemplateSubjectExpansions-expCount {
611 return nil, fmt.Errorf("%w: %d", errPermTemplateExpansionLimit, maxPermTemplateSubjectExpansions)
612 }
613 a := nArrayCartesianProduct(values...)
614 for _, aa := range a {
615 subj := list[i]
616 for j := 0; j < len(srcs); j++ {
617 subj = strings.Replace(subj, srcs[j], aa[j], -1)
618 }
619 if IsValidSubject(subj) {
620 emittedList = append(emittedList, subj)
621 } else if failOnBadSubject {
622 return nil, fmt.Errorf("generated invalid subject")
623 }
624 }
625 }
626 }
627 return emittedList, nil
628 }
629
630 subAllowWasNotEmpty := len(lim.Permissions.Sub.Allow) > 0
631 pubAllowWasNotEmpty := len(lim.Permissions.Pub.Allow) > 0
632
633 var err error
634 if lim.Permissions.Sub.Allow, err = applyTemplate(lim.Permissions.Sub.Allow, false); err != nil {
635 return jwt.UserPermissionLimits{}, err
636 } else if lim.Permissions.Sub.Deny, err = applyTemplate(lim.Permissions.Sub.Deny, true); err != nil {
637 return jwt.UserPermissionLimits{}, err
638 } else if lim.Permissions.Pub.Allow, err = applyTemplate(lim.Permissions.Pub.Allow, false); err != nil {
639 return jwt.UserPermissionLimits{}, err
640 } else if lim.Permissions.Pub.Deny, err = applyTemplate(lim.Permissions.Pub.Deny, true); err != nil {
641 return jwt.UserPermissionLimits{}, err
642 }
643
644 // if pub/sub allow were not empty, but are empty post template processing, add in a "deny >" to compensate
645 if subAllowWasNotEmpty && len(lim.Permissions.Sub.Allow) == 0 {
646 lim.Permissions.Sub.Deny.Add(">")
647 }
648 if pubAllowWasNotEmpty && len(lim.Permissions.Pub.Allow) == 0 {
649 lim.Permissions.Pub.Deny.Add(">")
650 }
651 return lim, nil
652 }
653
654 func (s *Server) processClientOrLeafAuthentication(c *client, opts *Options) (authorized bool) {
655 var (
656 nkey *NkeyUser
657 ujwt string
658 juc *jwt.UserClaims
659 acc *Account
660 user *User
661 ok bool
662 err error
663 ao bool // auth override
664 )
665
666 // Little helper that will log the error as a debug statement, set the auth error in
667 // the connection and return false to indicate authentication failure.
668 setProxyAuthError := func(err error) bool {
669 c.Debugf(err.Error())
670 c.setAuthError(err)
671 return false
672 }
673
674 // Indicate if this connection came from a trusted proxy. Note that if
675 // trustedProxy could be false even if the connection is proxied, but it
676 // means that there was no trusted proxy configured.
677 trustedProxy, ok := s.proxyCheck(c, opts)
678 if trustedProxy && !ok {
679 return setProxyAuthError(ErrAuthProxyNotTrusted)
680 }
681
682 var proxyRequired bool
683 // Check if we have auth callouts enabled at the server level or in the bound account.
684 defer func() {
685 authErr := c.getAuthError()
686 if authErr == nil {
687 authErr = ErrAuthentication
688 }
689 reason := getAuthErrClosedState(authErr).String()
690 // No-op
691 if juc == nil && opts.AuthCallout == nil {
692 if !authorized {
693 s.sendAccountAuthErrorEvent(c, c.acc, reason)
694 }
695 return
696 }
697 // We have a juc, check if externally managed, i.e. should be delegated
698 // to the auth callout service.
699 if juc != nil && !acc.hasExternalAuth() {
700 if !authorized {
701 s.sendAccountAuthErrorEvent(c, c.acc, reason)
702 }
703 return
704 }
705 // Check config-mode. The global account is a condition since users that
706 // are not found in the config are implicitly bound to the global account.
707 // This means those users should be implicitly delegated to auth callout
708 // if configured. Exclude LEAF connections from this check.
709 if c.kind != LEAF && juc == nil && opts.AuthCallout != nil && c.acc.Name != globalAccountName {
710 // If no allowed accounts are defined, then all accounts are in scope.
711 // Otherwise see if the account is in the list.
712 delegated := len(opts.AuthCallout.AllowedAccounts) == 0
713 if !delegated {
714 for _, n := range opts.AuthCallout.AllowedAccounts {
715 if n == c.acc.Name {
716 delegated = true
717 break
718 }
719 }
720 }
721
722 // Not delegated, so return with previous authorized result.
723 if !delegated {
724 if !authorized {
725 s.sendAccountAuthErrorEvent(c, c.acc, reason)
726 }
727 return
728 }
729 }
730
731 // We have auth callout set here.
732 var skip bool
733 // Check if we are on the list of auth_users.
734 userID := c.getRawAuthUser()
735 if juc != nil {
736 skip = acc.isExternalAuthUser(userID)
737 } else {
738 for _, u := range opts.AuthCallout.AuthUsers {
739 if userID == u {
740 skip = true
741 break
742 }
743 }
744 }
745
746 // If we are here we have an auth callout defined and we have failed auth so far
747 // so we will callout to our auth backend for processing.
748 if !skip {
749 authorized, reason = s.processClientOrLeafCallout(c, opts, proxyRequired, trustedProxy, ujwt)
750 }
751 // Check if we are authorized and in the auth callout account, and if so add in deny publish permissions for the auth subject.
752 if authorized {
753 var authAccountName string
754 if juc == nil && opts.AuthCallout != nil {
755 authAccountName = opts.AuthCallout.Account
756 } else if juc != nil {
757 authAccountName = acc.Name
758 }
759 c.mu.Lock()
760 if c.acc != nil && c.acc.Name == authAccountName {
761 c.mergeDenyPermissions(pub, []string{AuthCalloutSubject})
762 }
763 c.mu.Unlock()
764 } else {
765 // If we are here we failed external authorization.
766 // Send an account scoped event. Server config mode acc will be nil,
767 // so lookup the auth callout assigned account, that is where this will be sent.
768 if acc == nil {
769 acc, _ = s.lookupAccount(opts.AuthCallout.Account)
770 }
771 s.sendAccountAuthErrorEvent(c, acc, reason)
772 }
773 }()
774
775 s.mu.Lock()
776 authRequired := s.info.AuthRequired
777 if !authRequired {
778 // If no auth required for regular clients, then check if
779 // we have an override for MQTT or Websocket clients.
780 switch c.clientType() {
781 case MQTT:
782 authRequired = s.mqtt.authOverride
783 case WS:
784 authRequired = s.websocket.authOverride
785 }
786 }
787 if !authRequired {
788 // TODO(dlc) - If they send us credentials should we fail?
789 s.mu.Unlock()
790 if c.kind == LEAF {
791 // Auth is not required, register the leaf node with the selected account.
792 // Otherwise, auth needs to match client auth.
793 return s.registerLeafWithAccount(c, opts.LeafNode.Account)
794 }
795 return true
796 }
797 var (
798 username string
799 password string
800 token string
801 noAuthUser string
802 pinnedAcounts map[string]struct{}
803 )
804 tlsMap := opts.TLSMap
805 if c.kind == CLIENT {
806 switch c.clientType() {
807 case MQTT:
808 mo := &opts.MQTT
809 // Always override TLSMap.
810 tlsMap = mo.TLSMap
811 // The rest depends on if there was any auth override in
812 // the mqtt's config.
813 if s.mqtt.authOverride {
814 noAuthUser = mo.NoAuthUser
815 username = mo.Username
816 password = mo.Password
817 token = mo.Token
818 ao = true
819 }
820 case WS:
821 wo := &opts.Websocket
822 // Always override TLSMap.
823 tlsMap = wo.TLSMap
824 // The rest depends on if there was any auth override in
825 // the websocket's config.
826 if s.websocket.authOverride {
827 noAuthUser = wo.NoAuthUser
828 username = wo.Username
829 password = wo.Password
830 token = wo.Token
831 ao = true
832 }
833 }
834 } else {
835 tlsMap = opts.LeafNode.TLSMap
836 }
837
838 if !ao {
839 noAuthUser = opts.NoAuthUser
840 // If a leaf connects using websocket, and websocket{} block has a no_auth_user
841 // use that one instead.
842 if c.kind == LEAF && c.isWebsocket() && opts.Websocket.NoAuthUser != _EMPTY_ {
843 noAuthUser = opts.Websocket.NoAuthUser
844 }
845 username = opts.Username
846 password = opts.Password
847 token = opts.Authorization
848 }
849
850 // MQTT can carry JWTs in the password field. Reconstruct it here for auth
851 // processing and auth callout, but do not populate c.opts.JWT yet or it would
852 // be exposed through monitoring and advisory paths even when the password is
853 // not actually a JWT.
854 if ujwt == _EMPTY_ && c.isMqtt() && c.opts.JWT == _EMPTY_ {
855 // Don't set juc here, leave that to the next s.trustedKeys != nil block,
856 // so that we don't try to trust a JWT when we aren't in operator mode. We
857 // will allow it to be passed through auth callout though.
858 if _, err := jwt.DecodeUserClaims(c.opts.Password); err == nil {
859 ujwt = c.opts.Password
860 }
861 }
862
863 // Check if we have trustedKeys defined in the server. If so we require a user jwt.
864 if s.trustedKeys != nil {
865 if ujwt == _EMPTY_ {
866 // Need to be sure that it's a NATS JWT, otherwise we will not correctly
867 // attempt the default sentinel below.
868 if _, err = jwt.DecodeUserClaims(c.opts.JWT); err == nil {
869 ujwt = c.opts.JWT
870 }
871 }
872 if ujwt == _EMPTY_ {
873 // Didn't fall through with a valid NATS JWT, so try the default sentinel
874 // if configured.
875 if opts.DefaultSentinel != _EMPTY_ {
876 c.opts.JWT = opts.DefaultSentinel
877 ujwt = c.opts.JWT
878 }
879 }
880 if ujwt == _EMPTY_ {
881 s.mu.Unlock()
882 c.Debugf("Authentication requires a user JWT")
883 return false
884 }
885 if juc, err = jwt.DecodeUserClaims(ujwt); err != nil {
886 s.mu.Unlock()
887 c.Debugf("User JWT not valid: %v", err)
888 return false
889 }
890 if proxyRequired = juc.ProxyRequired; proxyRequired && !trustedProxy {
891 s.mu.Unlock()
892 return setProxyAuthError(ErrAuthProxyRequired)
893 }
894 vr := jwt.CreateValidationResults()
895 juc.Validate(vr)
896 if vr.IsBlocking(true) {
897 s.mu.Unlock()
898 c.Debugf("User JWT no longer valid: %+v", vr)
899 return false
900 }
901 pinnedAcounts = opts.resolverPinnedAccounts
902 }
903
904 // Check if we have nkeys or users for client.
905 hasNkeys := len(s.nkeys) > 0
906 hasUsers := len(s.users) > 0
907 if hasNkeys {
908 if (c.kind == CLIENT || c.kind == LEAF) && noAuthUser != _EMPTY_ &&
909 c.opts.Username == _EMPTY_ && c.opts.Password == _EMPTY_ && c.opts.Token == _EMPTY_ && c.opts.Nkey == _EMPTY_ {
910 if _, exists := s.nkeys[noAuthUser]; exists {
911 c.mu.Lock()
912 c.opts.Nkey = noAuthUser
913 c.mu.Unlock()
914 }
915 }
916 if c.opts.Nkey != _EMPTY_ {
917 nkey, ok = s.nkeys[c.opts.Nkey]
918 if !ok || !c.connectionTypeAllowed(nkey.AllowedConnectionTypes) {
919 s.mu.Unlock()
920 return false
921 }
922 }
923 }
924 if hasUsers && nkey == nil {
925 // Check if we are tls verify and are mapping users from the client_certificate.
926 if tlsMap {
927 authorized := checkClientTLSCertSubject(c, func(u string, certDN *ldap.DN, _ bool) (string, bool) {
928 // First do literal lookup using the resulting string representation
929 // of RDNSequence as implemented by the pkix package from Go.
930 if u != _EMPTY_ {
931 usr, ok := s.users[u]
932 if !ok || !c.connectionTypeAllowed(usr.AllowedConnectionTypes) {
933 return _EMPTY_, false
934 }
935 user = usr
936 return usr.Username, true
937 }
938
939 if certDN == nil {
940 return _EMPTY_, false
941 }
942
943 // Look through the accounts for a DN that is equal to the one
944 // presented by the certificate.
945 dns := make(map[*User]*ldap.DN)
946 for _, usr := range s.users {
947 if !c.connectionTypeAllowed(usr.AllowedConnectionTypes) {
948 continue
949 }
950 // TODO: Use this utility to make a full validation pass
951 // on start in case tlsmap feature is being used.
952 inputDN, err := ldap.ParseDN(usr.Username)
953 if err != nil {
954 continue
955 }
956 if inputDN.Equal(certDN) {
957 user = usr
958 return usr.Username, true
959 }
960
961 // In case it did not match exactly, then collect the DNs
962 // and try to match later in case the DN was reordered.
963 dns[usr] = inputDN
964 }
965
966 // Check in case the DN was reordered.
967 for usr, inputDN := range dns {
968 if inputDN.RDNsMatch(certDN) {
969 user = usr
970 return usr.Username, true
971 }
972 }
973 return _EMPTY_, false
974 })
975 if !authorized {
976 s.mu.Unlock()
977 return false
978 }
979 if c.opts.Username != _EMPTY_ {
980 s.Warnf("User %q found in connect proto, but user required from cert", c.opts.Username)
981 }
982 // Already checked that the client didn't send a user in connect
983 // but we set it here to be able to identify it in the logs.
984 c.opts.Username = user.Username
985 } else {
986 if (c.kind == CLIENT || c.kind == LEAF) && noAuthUser != _EMPTY_ &&
987 c.opts.Username == _EMPTY_ && c.opts.Password == _EMPTY_ && c.opts.Token == _EMPTY_ {
988 if u, exists := s.users[noAuthUser]; exists {
989 c.mu.Lock()
990 c.opts.Username = u.Username
991 c.opts.Password = u.Password
992 c.mu.Unlock()
993 }
994 }
995 if c.opts.Username != _EMPTY_ {
996 user, ok = s.users[c.opts.Username]
997 if !ok || !c.connectionTypeAllowed(user.AllowedConnectionTypes) {
998 s.mu.Unlock()
999 return false
1000 }
1001 }
1002 }
1003 }
1004 s.mu.Unlock()
1005
1006 // If we have a jwt and a userClaim, make sure we have the Account, etc associated.
1007 // We need to look up the account. This will use an account resolver if one is present.
1008 if juc != nil {
1009 issuer := juc.Issuer
1010 if juc.IssuerAccount != _EMPTY_ {
1011 issuer = juc.IssuerAccount
1012 }
1013 if pinnedAcounts != nil {
1014 if _, ok := pinnedAcounts[issuer]; !ok {
1015 c.Debugf("Account %s not listed as operator pinned account", issuer)
1016 atomic.AddUint64(&s.pinnedAccFail, 1)
1017 return false
1018 }
1019 }
1020 if acc, err = s.LookupAccount(issuer); acc == nil {
1021 c.Debugf("Account JWT lookup error: %v", err)
1022 return false
1023 }
1024 acc.mu.RLock()
1025 aissuer := acc.Issuer
1026 acc.mu.RUnlock()
1027 if !s.isTrustedIssuer(aissuer) {
1028 c.Debugf("Account JWT not signed by trusted operator")
1029 return false
1030 }
1031 if scope, ok := acc.hasIssuer(juc.Issuer); !ok {
1032 c.Debugf("User JWT issuer is not known")
1033 return false
1034 } else if scope != nil {
1035 if err := scope.ValidateScopedSigner(juc); err != nil {
1036 c.Debugf("User JWT is not valid: %v", err)
1037 return false
1038 } else if uSc, ok := scope.(*jwt.UserScope); !ok {
1039 c.Debugf("User JWT is not valid")
1040 return false
1041 } else if juc.UserPermissionLimits, err = processUserPermissionsTemplate(uSc.Template, juc, acc); err != nil {
1042 c.Debugf("User JWT generated invalid permissions")
1043 return false
1044 }
1045 }
1046 if acc.IsExpired() {
1047 c.Debugf("Account JWT has expired")
1048 return false
1049 }
1050 if juc.BearerToken && acc.failBearer() {
1051 c.Debugf("Account does not allow bearer tokens")
1052 return false
1053 }
1054 // We check the allowed connection types, but only after processing
1055 // of scoped signer (so that it updates `juc` with what is defined
1056 // in the account.
1057 allowedConnTypes, err := convertAllowedConnectionTypes(juc.AllowedConnectionTypes)
1058 if err != nil {
1059 // We got an error, which means some connection types were unknown. As long as
1060 // a valid one is returned, we proceed with auth. If not, we have to reject.
1061 // In other words, suppose that JWT allows "WEBSOCKET" in the array. No error
1062 // is returned and allowedConnTypes will contain "WEBSOCKET" only.
1063 // Client will be rejected if not a websocket client, or proceed with rest of
1064 // auth if it is.
1065 // Now suppose JWT allows "WEBSOCKET, MQTT" and say MQTT is not known by this
1066 // server. In this case, allowedConnTypes would contain "WEBSOCKET" and we
1067 // would get `err` indicating that "MQTT" is an unknown connection type.
1068 // If a websocket client connects, it should still be allowed, since after all
1069 // the admin wanted to allow websocket and mqtt connection types.
1070 // However, say that the JWT only allows "MQTT" (and again suppose this server
1071 // does not know about MQTT connection type), then since the allowedConnTypes
1072 // map would be empty (no valid types found), and since empty means allow-all,
1073 // then we should reject because the intent was to allow connections for this
1074 // user only as an MQTT client.
1075 c.Debugf("%v", err)
1076 if len(allowedConnTypes) == 0 {
1077 return false
1078 }
1079 }
1080 if !c.connectionTypeAllowed(allowedConnTypes) {
1081 c.Debugf("Connection type not allowed")
1082 return false
1083 }
1084 // Skip validation of nonce when presented with a bearer token.
1085 // While support for bearer tokens was added for WebSockets, there is no
1086 // security benefit in restricting their use to that client protocol: the
1087 // client can just go use the other protocol.
1088 if !juc.BearerToken {
1089 // Verify the signature against the nonce.
1090 if c.opts.Sig == _EMPTY_ {
1091 c.Debugf("Signature missing")
1092 return false
1093 }
1094 sig, err := base64.RawURLEncoding.DecodeString(c.opts.Sig)
1095 if err != nil {
1096 // Allow fallback to normal base64.
1097 sig, err = base64.StdEncoding.DecodeString(c.opts.Sig)
1098 if err != nil {
1099 c.Debugf("Signature not valid base64")
1100 return false
1101 }
1102 }
1103 pub, err := nkeys.FromPublicKey(juc.Subject)
1104 if err != nil {
1105 c.Debugf("User nkey not valid: %v", err)
1106 return false
1107 }
1108 if err := pub.Verify(c.nonce, sig); err != nil {
1109 c.Debugf("Signature not verified")
1110 return false
1111 }
1112 }
1113 if acc.checkUserRevoked(juc.Subject, juc.IssuedAt) {
1114 c.Debugf("User authentication revoked")
1115 return false
1116 }
1117 if !validateSrc(juc, c.host) {
1118 c.Errorf("Bad src Ip %s", c.host)
1119 return false
1120 }
1121 allowNow, validFor := validateTimes(juc)
1122 if !allowNow {
1123 c.Errorf("Outside connect times")
1124 return false
1125 }
1126
1127 nkey = buildInternalNkeyUser(juc, allowedConnTypes, acc)
1128 if err := c.RegisterNkeyUser(nkey); err != nil {
1129 return false
1130 }
1131
1132 // Warn about JetStream restrictions
1133 if c.perms != nil {
1134 deniedPub := []string{}
1135 deniedSub := []string{}
1136 for _, sub := range denyAllJs {
1137 if c.perms.pub.deny != nil {
1138 if c.perms.pub.deny.HasInterest(sub) {
1139 deniedPub = append(deniedPub, sub)
1140 }
1141 }
1142 if c.perms.sub.deny != nil {
1143 if c.perms.sub.deny.HasInterest(sub) {
1144 deniedSub = append(deniedSub, sub)
1145 }
1146 }
1147 }
1148 if len(deniedPub) > 0 || len(deniedSub) > 0 {
1149 c.Debugf("Connected %s has JetStream denied on pub: %v sub: %v", c.kindString(), deniedPub, deniedSub)
1150 }
1151 }
1152
1153 // Hold onto the user's public key.
1154 c.mu.Lock()
1155 c.pubKey = juc.Subject
1156 // If this is a MQTT client, we purposefully didn't populate the JWT as it could contain
1157 // a password or token. Now we know it's a valid JWT, we can populate it.
1158 if c.isMqtt() {
1159 c.opts.JWT = ujwt
1160 }
1161 c.tags = juc.Tags
1162 c.nameTag = juc.Name
1163 c.mu.Unlock()
1164
1165 // Check if we need to set an auth timer if the user jwt expires.
1166 c.setExpiration(juc.Claims(), validFor)
1167
1168 acc.mu.RLock()
1169 c.Debugf("Authenticated JWT: %s %q (claim-name: %q, claim-tags: %q) "+
1170 "signed with %q by Account %q (claim-name: %q, claim-tags: %q) signed with %q has mappings %t accused %p",
1171 c.kindString(), juc.Subject, juc.Name, juc.Tags, juc.Issuer, issuer, acc.nameTag, acc.tags, acc.Issuer, acc.hasMappings(), acc)
1172 acc.mu.RUnlock()
1173 return true
1174 }
1175
1176 if nkey != nil {
1177 if proxyRequired = nkey.ProxyRequired; proxyRequired && !trustedProxy {
1178 return setProxyAuthError(ErrAuthProxyRequired)
1179 }
1180 // If we did not match noAuthUser check signature which is required.
1181 if nkey.Nkey != noAuthUser {
1182 if c.opts.Sig == _EMPTY_ {
1183 c.Debugf("Signature missing")
1184 return false
1185 }
1186 sig, err := base64.RawURLEncoding.DecodeString(c.opts.Sig)
1187 if err != nil {
1188 // Allow fallback to normal base64.
1189 sig, err = base64.StdEncoding.DecodeString(c.opts.Sig)
1190 if err != nil {
1191 c.Debugf("Signature not valid base64")
1192 return false
1193 }
1194 }
1195 pub, err := nkeys.FromPublicKey(c.opts.Nkey)
1196 if err != nil {
1197 c.Debugf("User nkey not valid: %v", err)
1198 return false
1199 }
1200 if err := pub.Verify(c.nonce, sig); err != nil {
1201 c.Debugf("Signature not verified")
1202 return false
1203 }
1204 }
1205 if err := c.RegisterNkeyUser(nkey); err != nil {
1206 return false
1207 }
1208 return true
1209 }
1210 if user != nil {
1211 if proxyRequired = user.ProxyRequired; proxyRequired && !trustedProxy {
1212 return setProxyAuthError(ErrAuthProxyRequired)
1213 }
1214 // A user with no password is a certificate only identity when mapping is
1215 // enabled on another listener, so do not let comparePasswords match two
1216 // empty passwords. The no_auth_user needs no credentials either way.
1217 if !tlsMap && user.Password == _EMPTY_ && user.Username != noAuthUser && opts.canTLSMap(user) {
1218 c.Debugf("User %q requires a client certificate", user.Username)
1219 return false
1220 }
1221 ok = comparePasswords(user.Password, c.opts.Password)
1222 // If we are authorized, register the user which will properly setup any permissions
1223 // for pub/sub authorizations.
1224 if ok {
1225 c.RegisterUser(user)
1226 }
1227 return ok
1228 }
1229
1230 // Check for the use of simple auth.
1231 if c.kind == CLIENT || c.kind == LEAF {
1232 if proxyRequired = opts.ProxyRequired; proxyRequired && !trustedProxy {
1233 return setProxyAuthError(ErrAuthProxyRequired)
1234 }
1235 if token != _EMPTY_ {
1236 return comparePasswords(token, c.opts.Token)
1237 } else if username != _EMPTY_ {
1238 if username != c.opts.Username {
1239 return false
1240 }
1241 return comparePasswords(password, c.opts.Password)
1242 }
1243 }
1244 return false
1245 }
1246
1247 // If there are configured trusted proxies and this connection comes
1248 // from a proxy whose signature can be verified by one of the known
1249 // trusted key, this function will return `true, true`. If the signature
1250 // cannot be verified by any, it will return `true, false`.
1251 // If the connection is not proxied, or there are no configured trusted
1252 // proxies, then this function returns `false, false`.
1253 //
1254 // Server lock MUST NOT be held on entry since this function will grab
1255 // the read lock to extract the list of proxy trusted keys. The signature
1256 // verification process will be done outside of the lock.
1257 func (s *Server) proxyCheck(c *client, opts *Options) (bool, bool) {
1258 // If there is no signature or no configured trusted proxy, return false.
1259 psig := c.opts.ProxySig
1260 if psig == _EMPTY_ || opts.Proxies == nil || len(opts.Proxies.Trusted) == 0 {
1261 return false, false
1262 }
1263 // Decode the signature.
1264 sig, err := base64.RawURLEncoding.DecodeString(psig)
1265 if err != nil {
1266 c.Debugf("Proxy signature not valid base64")
1267 return true, false
1268 }
1269 // Go through the trusted keys and verify the signature.
1270 s.mu.RLock()
1271 keys := slices.Clone(s.proxiesKeyPairs)
1272 s.mu.RUnlock()
1273 for _, kp := range keys {
1274 // We stop at the first that is valid.
1275 if err := kp.Verify(c.nonce, sig); err == nil {
1276 pub, _ := kp.PublicKey()
1277 // Need to hold both locks so the proxiedConns is only
1278 // registered while the client isn't closed.
1279 s.mu.Lock()
1280 c.mu.Lock()
1281 if c.isClosed() {
1282 c.mu.Unlock()
1283 s.mu.Unlock()
1284 return true, true
1285 }
1286 // Track which proxy public key is used by this connection.
1287 c.proxyKey = pub
1288 cid := c.cid
1289 c.mu.Unlock()
1290 // Track this proxied connection so that it can be closed
1291 // if the trusted key is removed on configuration reload
1292 if s.proxiedConns == nil {
1293 s.proxiedConns = make(map[string]map[uint64]*client)
1294 }
1295 clients := s.proxiedConns[pub]
1296 if clients == nil {
1297 clients = make(map[uint64]*client)
1298 }
1299 clients[cid] = c
1300 s.proxiedConns[pub] = clients
1301 s.mu.Unlock()
1302 return true, true
1303 }
1304 }
1305 // We could not verify the signature, so indicate failure.
1306 return true, false
1307 }
1308
1309 func getTLSAuthDCs(rdns *pkix.RDNSequence) string {
1310 dcOID := asn1.ObjectIdentifier{0, 9, 2342, 19200300, 100, 1, 25}
1311 dcs := []string{}
1312 for _, rdn := range *rdns {
1313 if len(rdn) == 0 {
1314 continue
1315 }
1316 for _, atv := range rdn {
1317 value, ok := atv.Value.(string)
1318 if !ok {
1319 continue
1320 }
1321 if atv.Type.Equal(dcOID) {
1322 dcs = append(dcs, "DC="+value)
1323 }
1324 }
1325 }
1326 return strings.Join(dcs, ",")
1327 }
1328
1329 type tlsMapAuthFn func(string, *ldap.DN, bool) (string, bool)
1330
1331 func checkClientTLSCertSubject(c *client, fn tlsMapAuthFn) bool {
1332 tlsState := c.GetTLSConnectionState()
1333 if tlsState == nil {
1334 c.Debugf("User required in cert, no TLS connection state")
1335 return false
1336 }
1337 if len(tlsState.PeerCertificates) == 0 {
1338 c.Debugf("User required in cert, no peer certificates found")
1339 return false
1340 }
1341 cert := tlsState.PeerCertificates[0]
1342 if len(tlsState.PeerCertificates) > 1 {
1343 c.Debugf("Multiple peer certificates found, selecting first")
1344 }
1345
1346 hasSANs := len(cert.DNSNames) > 0
1347 hasEmailAddresses := len(cert.EmailAddresses) > 0
1348 hasSubject := len(cert.Subject.String()) > 0
1349 hasURIs := len(cert.URIs) > 0
1350 if !hasSANs && !hasEmailAddresses && !hasSubject && !hasURIs {
1351 c.Debugf("User required in cert, none found")
1352 return false
1353 }
1354
1355 switch {
1356 case hasEmailAddresses:
1357 for _, u := range cert.EmailAddresses {
1358 if match, ok := fn(u, nil, false); ok {
1359 c.Debugf("Using email found in cert for auth [%q]", match)
1360 return true
1361 }
1362 }
1363 fallthrough
1364 case hasSANs:
1365 for _, u := range cert.DNSNames {
1366 if match, ok := fn(u, nil, true); ok {
1367 c.Debugf("Using SAN found in cert for auth [%q]", match)
1368 return true
1369 }
1370 }
1371 fallthrough
1372 case hasURIs:
1373 for _, u := range cert.URIs {
1374 if match, ok := fn(u.String(), nil, false); ok {
1375 c.Debugf("Using URI found in cert for auth [%q]", match)
1376 return true
1377 }
1378 }
1379 }
1380
1381 // Use the string representation of the full RDN Sequence including
1382 // the domain components in case there are any.
1383 rdn := cert.Subject.ToRDNSequence().String()
1384
1385 // Match using the raw subject to avoid ignoring attributes.
1386 // https://github.com/golang/go/issues/12342
1387 dn, err := ldap.FromRawCertSubject(cert.RawSubject)
1388 if err == nil {
1389 if match, ok := fn(_EMPTY_, dn, false); ok {
1390 c.Debugf("Using DistinguishedNameMatch for auth [%q]", match)
1391 return true
1392 }
1393 c.Debugf("DistinguishedNameMatch could not be used for auth [%q]", rdn)
1394 }
1395
1396 var rdns pkix.RDNSequence
1397 if _, err := asn1.Unmarshal(cert.RawSubject, &rdns); err == nil {
1398 // If found domain components then include roughly following
1399 // the order from https://tools.ietf.org/html/rfc2253
1400 //
1401 // NOTE: The original sequence from string representation by ToRDNSequence does not follow
1402 // the correct ordering, so this addition ofdomainComponents would likely be deprecated in
1403 // another release in favor of using the correct ordered as parsed by the go-ldap library.
1404 //
1405 dcs := getTLSAuthDCs(&rdns)
1406 if len(dcs) > 0 {
1407 u := strings.Join([]string{rdn, dcs}, ",")
1408 if match, ok := fn(u, nil, false); ok {
1409 c.Debugf("Using RDNSequence for auth [%q]", match)
1410 return true
1411 }
1412 c.Debugf("RDNSequence could not be used for auth [%q]", u)
1413 }
1414 }
1415
1416 // If no match, then use the string representation of the RDNSequence
1417 // from the subject without the domainComponents.
1418 if match, ok := fn(rdn, nil, false); ok {
1419 c.Debugf("Using certificate subject for auth [%q]", match)
1420 return true
1421 }
1422
1423 c.Debugf("User in cert [%q], not found", rdn)
1424 return false
1425 }
1426
1427 func dnsAltNameLabels(dnsAltName string) []string {
1428 return strings.Split(strings.ToLower(dnsAltName), ".")
1429 }
1430
1431 // Check DNS name according to https://tools.ietf.org/html/rfc6125#section-6.4.1
1432 func dnsAltNameMatches(dnsAltNameLabels []string, urls []*url.URL) bool {
1433 URLS:
1434 for _, url := range urls {
1435 if url == nil {
1436 continue URLS
1437 }
1438 hostLabels := strings.Split(strings.ToLower(url.Hostname()), ".")
1439 // Following https://tools.ietf.org/html/rfc6125#section-6.4.3, should not => will not, may => will not
1440 // The wildcard * never matches multiple label and only matches the left most label.
1441 if len(hostLabels) != len(dnsAltNameLabels) {
1442 continue URLS
1443 }
1444 i := 0
1445 // only match wildcard on left most label
1446 if dnsAltNameLabels[0] == "*" {
1447 i++
1448 }
1449 for ; i < len(dnsAltNameLabels); i++ {
1450 if dnsAltNameLabels[i] != hostLabels[i] {
1451 continue URLS
1452 }
1453 }
1454 return true
1455 }
1456 return false
1457 }
1458
1459 // checkRouterAuth checks optional router authorization which can be nil or username/password.
1460 func (s *Server) isRouterAuthorized(c *client) bool {
1461 // Snapshot server options.
1462 opts := s.getOpts()
1463
1464 // Check custom auth first, then TLS map if enabled
1465 // then single user/pass.
1466 if opts.CustomRouterAuthentication != nil {
1467 return opts.CustomRouterAuthentication.Check(c)
1468 }
1469
1470 if opts.Cluster.TLSMap || opts.Cluster.TLSCheckKnownURLs {
1471 return checkClientTLSCertSubject(c, func(user string, _ *ldap.DN, isDNSAltName bool) (string, bool) {
1472 if user == _EMPTY_ {
1473 return _EMPTY_, false
1474 }
1475 if opts.Cluster.TLSCheckKnownURLs && isDNSAltName {
1476 if dnsAltNameMatches(dnsAltNameLabels(user), opts.Routes) {
1477 return _EMPTY_, true
1478 }
1479 }
1480 if opts.Cluster.TLSMap && opts.Cluster.Username == user {
1481 return _EMPTY_, true
1482 }
1483 return _EMPTY_, false
1484 })
1485 }
1486
1487 if opts.Cluster.Username == _EMPTY_ {
1488 return true
1489 }
1490
1491 if opts.Cluster.Username != c.opts.Username {
1492 return false
1493 }
1494 if !comparePasswords(opts.Cluster.Password, c.opts.Password) {
1495 return false
1496 }
1497 return true
1498 }
1499
1500 // isGatewayAuthorized checks optional gateway authorization which can be nil or username/password.
1501 func (s *Server) isGatewayAuthorized(c *client) bool {
1502 // Snapshot server options.
1503 opts := s.getOpts()
1504
1505 // Check whether TLS map is enabled, otherwise use single user/pass.
1506 if opts.Gateway.TLSMap || opts.Gateway.TLSCheckKnownURLs {
1507 return checkClientTLSCertSubject(c, func(user string, _ *ldap.DN, isDNSAltName bool) (string, bool) {
1508 if user == _EMPTY_ {
1509 return _EMPTY_, false
1510 }
1511 if opts.Gateway.TLSCheckKnownURLs && isDNSAltName {
1512 labels := dnsAltNameLabels(user)
1513 for _, gw := range opts.Gateway.Gateways {
1514 if gw != nil && dnsAltNameMatches(labels, gw.URLs) {
1515 return _EMPTY_, true
1516 }
1517 }
1518 }
1519 if opts.Gateway.TLSMap && opts.Gateway.Username == user {
1520 return _EMPTY_, true
1521 }
1522 return _EMPTY_, false
1523 })
1524 }
1525
1526 if opts.Gateway.Username == _EMPTY_ {
1527 return true
1528 }
1529
1530 if opts.Gateway.Username != c.opts.Username {
1531 return false
1532 }
1533 return comparePasswords(opts.Gateway.Password, c.opts.Password)
1534 }
1535
1536 func (s *Server) registerLeafWithAccount(c *client, account string) bool {
1537 var err error
1538 acc := s.globalAccount()
1539 if account != _EMPTY_ {
1540 acc, err = s.lookupAccount(account)
1541 if err != nil {
1542 s.Errorf("authentication of user %q failed, unable to lookup account %q: %v",
1543 c.opts.Username, account, err)
1544 return false
1545 }
1546 }
1547 if err = c.registerWithAccount(acc); err != nil {
1548 return false
1549 }
1550 return true
1551 }
1552
1553 // isLeafNodeAuthorized will check for auth for an inbound leaf node connection.
1554 func (s *Server) isLeafNodeAuthorized(c *client) bool {
1555 opts := s.getOpts()
1556
1557 setProxyAuthError := func(err error) bool {
1558 c.Debugf(err.Error())
1559 c.setAuthError(err)
1560 return false
1561 }
1562
1563 isAuthorized := func(username, password, account string, proxyRequired bool) bool {
1564 trustedProxy, ok := s.proxyCheck(c, opts)
1565 if trustedProxy && !ok {
1566 return setProxyAuthError(ErrAuthProxyNotTrusted)
1567 }
1568 // A given user may not be required, but if the boolean is set at the
1569 // authorization top-level, then override.
1570 if !proxyRequired && opts.LeafNode.ProxyRequired {
1571 proxyRequired = true
1572 }
1573 if proxyRequired && !trustedProxy {
1574 return setProxyAuthError(ErrAuthProxyRequired)
1575 }
1576 if username != c.opts.Username {
1577 return false
1578 }
1579 if !comparePasswords(password, c.opts.Password) {
1580 return false
1581 }
1582 return s.registerLeafWithAccount(c, account)
1583 }
1584
1585 // If leafnodes config has an authorization{} stanza, this takes precedence.
1586 // The user in CONNECT must match. We will bind to the account associated
1587 // with that user (from the leafnode's authorization{} config).
1588 if opts.LeafNode.Username != _EMPTY_ {
1589 return isAuthorized(opts.LeafNode.Username, opts.LeafNode.Password, opts.LeafNode.Account,
1590 opts.LeafNode.ProxyRequired)
1591 } else if opts.LeafNode.Nkey != _EMPTY_ {
1592 trustedProxy, ok := s.proxyCheck(c, opts)
1593 if trustedProxy && !ok {
1594 return false
1595 }
1596 if opts.LeafNode.ProxyRequired && !trustedProxy {
1597 return setProxyAuthError(ErrAuthProxyRequired)
1598 }
1599 if c.opts.Nkey != opts.LeafNode.Nkey {
1600 return false
1601 }
1602 if c.opts.Sig == _EMPTY_ {
1603 c.Debugf("Signature missing")
1604 return false
1605 }
1606 sig, err := base64.RawURLEncoding.DecodeString(c.opts.Sig)
1607 if err != nil {
1608 // Allow fallback to normal base64.
1609 sig, err = base64.StdEncoding.DecodeString(c.opts.Sig)
1610 if err != nil {
1611 c.Debugf("Signature not valid base64")
1612 return false
1613 }
1614 }
1615 pub, err := nkeys.FromPublicKey(c.opts.Nkey)
1616 if err != nil {
1617 c.Debugf("User nkey not valid: %v", err)
1618 return false
1619 }
1620 if err := pub.Verify(c.nonce, sig); err != nil {
1621 c.Debugf("Signature not verified")
1622 return false
1623 }
1624 return s.registerLeafWithAccount(c, opts.LeafNode.Account)
1625 } else if len(opts.LeafNode.Users) > 0 {
1626 if opts.LeafNode.TLSMap {
1627 var user *User
1628 found := checkClientTLSCertSubject(c, func(u string, _ *ldap.DN, _ bool) (string, bool) {
1629 // This is expected to be a very small array.
1630 for _, usr := range opts.LeafNode.Users {
1631 if u == usr.Username {
1632 user = usr
1633 return u, true
1634 }
1635 }
1636 return _EMPTY_, false
1637 })
1638 if !found {
1639 return false
1640 }
1641 if c.opts.Username != _EMPTY_ {
1642 s.Warnf("User %q found in connect proto, but user required from cert", c.opts.Username)
1643 }
1644 c.opts.Username = user.Username
1645 // EMPTY will result in $G
1646 accName := _EMPTY_
1647 if user.Account != nil {
1648 accName = user.Account.GetName()
1649 }
1650 // This will authorize since are using an existing user,
1651 // but it will also register with proper account.
1652 return isAuthorized(user.Username, user.Password, accName, user.ProxyRequired)
1653 }
1654
1655 // This is expected to be a very small array.
1656 for _, u := range opts.LeafNode.Users {
1657 if u.Username == c.opts.Username {
1658 var accName string
1659 if u.Account != nil {
1660 accName = u.Account.Name
1661 }
1662 return isAuthorized(u.Username, u.Password, accName, u.ProxyRequired)
1663 }
1664 }
1665 return false
1666 }
1667
1668 // We are here if we accept leafnode connections without any credentials.
1669
1670 // Still, if the CONNECT has some user info, we will bind to the
1671 // user's account or to the specified default account (if provided)
1672 // or to the global account.
1673 return s.isClientAuthorized(c)
1674 }
1675
1676 // Support for bcrypt stored passwords and tokens.
1677 var validBcryptPrefix = regexp.MustCompile(`^\$2[abxy]\$\d{2}\$.*`)
1678
1679 // isBcrypt checks whether the given password or token is bcrypted.
1680 func isBcrypt(password string) bool {
1681 if strings.HasPrefix(password, "$") {
1682 return validBcryptPrefix.MatchString(password)
1683 }
1684
1685 return false
1686 }
1687
1688 func comparePasswords(serverPassword, clientPassword string) bool {
1689 // Check to see if the server password is a bcrypt hash
1690 if isBcrypt(serverPassword) {
1691 if err := bcrypt.CompareHashAndPassword([]byte(serverPassword), []byte(clientPassword)); err != nil {
1692 return false
1693 }
1694 } else {
1695 // stringToBytes should be constant-time near enough compared to
1696 // turning a string into []byte normally.
1697 spass := stringToBytes(serverPassword)
1698 cpass := stringToBytes(clientPassword)
1699 if subtle.ConstantTimeCompare(spass, cpass) == 0 {
1700 return false
1701 }
1702 }
1703 return true
1704 }
1705
1706 func validateAuth(o *Options) error {
1707 if err := validatePinnedCerts(o.TLSPinnedCerts); err != nil {
1708 return err
1709 }
1710 for _, u := range o.Users {
1711 if err := validateAllowedConnectionTypes(u.AllowedConnectionTypes); err != nil {
1712 return err
1713 }
1714 if err := validatePermissionSubjects(u.Permissions); err != nil {
1715 return fmt.Errorf("invalid permissions for user %q: %w", u.Username, err)
1716 }
1717 }
1718 for _, u := range o.Nkeys {
1719 if err := validateAllowedConnectionTypes(u.AllowedConnectionTypes); err != nil {
1720 return err
1721 }
1722 if err := validatePermissionSubjects(u.Permissions); err != nil {
1723 return fmt.Errorf("invalid permissions for nkey %q: %w", u.Nkey, err)
1724 }
1725 }
1726 return validateNoAuthUser(o, o.NoAuthUser)
1727 }
1728
1729 func validatePermissionSubjects(p *Permissions) error {
1730 if p == nil {
1731 return nil
1732 }
1733 if p.Publish != nil {
1734 if err := checkPermSubjectArray(p.Publish.Allow, false); err != nil {
1735 return fmt.Errorf("publish allow: %w", err)
1736 }
1737 if err := checkPermSubjectArray(p.Publish.Deny, false); err != nil {
1738 return fmt.Errorf("publish deny: %w", err)
1739 }
1740 }
1741 if p.Subscribe != nil {
1742 if err := checkPermSubjectArray(p.Subscribe.Allow, true); err != nil {
1743 return fmt.Errorf("subscribe allow: %w", err)
1744 }
1745 if err := checkPermSubjectArray(p.Subscribe.Deny, true); err != nil {
1746 return fmt.Errorf("subscribe deny: %w", err)
1747 }
1748 }
1749 return nil
1750 }
1751
1752 func validateAllowedConnectionTypes(m map[string]struct{}) error {
1753 for ct := range m {
1754 ctuc := strings.ToUpper(ct)
1755 switch ctuc {
1756 case jwt.ConnectionTypeStandard, jwt.ConnectionTypeWebsocket,
1757 jwt.ConnectionTypeLeafnode, jwt.ConnectionTypeLeafnodeWS,
1758 jwt.ConnectionTypeMqtt, jwt.ConnectionTypeMqttWS,
1759 jwt.ConnectionTypeInProcess:
1760 default:
1761 return fmt.Errorf("unknown connection type %q", ct)
1762 }
1763 if ctuc != ct {
1764 delete(m, ct)
1765 m[ctuc] = struct{}{}
1766 }
1767 }
1768 return nil
1769 }
1770
1771 func validateNoAuthUser(o *Options, noAuthUser string) error {
1772 if noAuthUser == _EMPTY_ {
1773 return nil
1774 }
1775 if len(o.TrustedOperators) > 0 {
1776 return fmt.Errorf("no_auth_user not compatible with Trusted Operator")
1777 }
1778
1779 if o.Nkeys == nil && o.Users == nil {
1780 return fmt.Errorf(`no_auth_user: "%s" present, but users/nkeys are not defined`, noAuthUser)
1781 }
1782 for _, u := range o.Users {
1783 if u.Username == noAuthUser {
1784 return nil
1785 }
1786 }
1787 for _, u := range o.Nkeys {
1788 if u.Nkey == noAuthUser {
1789 return nil
1790 }
1791 }
1792 return fmt.Errorf(
1793 `no_auth_user: "%s" not present as user or nkey in authorization block or account configuration`,
1794 noAuthUser)
1795 }
1796
1797 func validateProxies(o *Options) error {
1798 if o.Proxies == nil {
1799 return nil
1800 }
1801 for _, p := range o.Proxies.Trusted {
1802 if !nkeys.IsValidPublicKey(p.Key) {
1803 return fmt.Errorf("proxy trusted key %q is invalid", p.Key)
1804 }
1805 }
1806 return nil
1807 }
1808
1809 // Create a list of nkeys.KeyPair corresponding to the public keys
1810 // of the Proxies.TrustedKeys list.
1811 // Server lock must be held on entry.
1812 func (s *Server) processProxiesTrustedKeys() {
1813 // We could be here on reload.
1814 if s.proxiesKeyPairs != nil {
1815 s.proxiesKeyPairs = s.proxiesKeyPairs[:0]
1816 }
1817 if opts := s.getOpts(); opts.Proxies == nil {
1818 return
1819 }
1820 for _, p := range s.getOpts().Proxies.Trusted {
1821 // Can't fail since we have already checked that it was a valid key.
1822 kp, _ := nkeys.FromPublicKey(p.Key)
1823 s.proxiesKeyPairs = append(s.proxiesKeyPairs, kp)
1824 }
1825 }
1826
1827 // Returns the connection's `ClosedState` for the given authenication error.
1828 func getAuthErrClosedState(authErr error) ClosedState {
1829 switch authErr {
1830 case ErrAuthProxyNotTrusted:
1831 return ProxyNotTrusted
1832 case ErrAuthProxyRequired:
1833 return ProxyRequired
1834 default:
1835 return AuthenticationViolation
1836 }
1837 }