Commit Graph
77 Commits
Author SHA1 Message Date
Michael Wilson 49c64aabcb Move the authorizer into its own package. (#22776)
* Move the authorizer into its own package.

The Authorizer and associated functions and constants have been moved into
their own package `authz`. This will allow us to more easily create separate
services for gRPC functionality so that we're not pushing as much into the
`lib/auth` package.

Though this PR is large, the only actual code change here is making
`ContextForLocalUser` exported and changing the `permissions_test.go` so that
it doesn't rely on the `lib/auth` package.

* Use context functions.

* Test and linting fixes.

* Add in a temporary alias file to ensure e still compiles.

* Use functions instead of var aliases for performance reasons.

* Adding in godocs, cleaning up tests.

* Fix tests.

* Add a few more aliases.
2023-03-09 02:21:10 +00:00
Zac Bergquist cfb40186e1 tctl: add edit command (#18826)
This command allows you to modify a resource in place by opening
the resource YAML in your text editor.

The editor is selected by checking the following, in order of
precedence:

- the TELEPORT_EDITOR environment variable
- the VISUAL environment variable
- the EDITOR environment variable
- defaulting to 'vi'

We also prevent renaming resources with this command.
See gravitational/webapps#1465 where we do the same for the web UI.
2022-12-29 17:30:14 -07:00
Cam Hutchison 45642fbc0e Remove SAML connector and tests (#18285)
Remove the SAML connector from the OSS repository. It has been migrated
to the enterprise repository.
2022-11-28 14:45:12 +11:00
Cam Hutchison 7656052fd7 auth: Remove Upsert/Delete from SAMLService interface (#18634)
Remove the Upsert and Delete methods from the SAMLService interface. It
was intended for these to be part of the SAML "plugin", however they are
needed for the operator tests to be able to create and delete the SAML
connectors.

The methods are back to being implemented directly in the `auth.Server`.
This does not cause any real issues with the rest in the enterprise repo
as the upsert/delete logic is just manipulating the local backend with
no actual SAML logic in it. The `Get*` methods had already been kept in
the `auth.Server` for the same reason.

This narrows the `SAMLService` interface to just creating the SAML auth
request and validating the response that comes back from the SAML
identity provider. This is the core of the SAML-specific logic.

Issue: https://github.com/gravitational/teleport.e/issues/525
2022-11-24 15:54:05 +11:00
Cam Hutchison 6bac096d28 auth: Split SAML connector code to own type (#18255)
Create a new type - `SAMLAuthService` - and move the implementation of
the SAML connector from the auth Service to this new type. This
decoupling will make it easier to move out of tree in a later commit.

This also lays the basic groundwork for running without the SAML
connector at all, returning a NotImplemented error for all the SAML
logic if the SAMLAuthService is not plugged in.

A number of names in the `auth` package have been exported to facilitate
moving the SAML connector out of this repository. The types exported do
not need to be exported for this commit, but for subsequent commits that
move the `SAMLAuthService` out of the `auth` package.

Also apply a small fix to to emit `apievents.SAMLConnector*` events of
`apievents.OIDCConnector*` events in the SAML connector.
2022-11-16 14:24:43 +11:00
Cam Hutchison 33dea32274 Move SAML connection validation after auth checks (#17531)
Move the validation for SAML connectors being inserted or updated (Upsert)
from before the role check for Insert/Update to after it. The validation
can perform an HTTP GET request if the `entity_descriptor_url` field is
set. This should at least require that the user have permission to
Upsert a SAML OIDC connector.

Ensure that roles exist that are referenced in SAML connectors, as the
roles in SAML connectors are validated as the connector is inserted or
updated. The validation has moved to auth.Server (from grpcserver) so
that is now required in tests that operate against auth.Server.

Add a test case to test that an access denied error is returned when
upserting an invalid SAML connector instead of a validation failure,
showing that we are not using input from untrusted sources. Also test
that validation is still performed when access is permitted and that a
valid SAML connector can be upserted.
2022-11-01 07:31:48 +00:00
Brian Joerger ce20b20753 PIV login enforcement (#15874)
Add private key policy enforcement.

  - Add private key policy cert extensions and enforcement.

  - Add private key policy settings and attestation logic.

  - Wire attestation request through login endpoints.

  - Store attestation data for reissue requests.

  - Add private key policy discovery and logic.

  - Relogin on hardware key policy errors.

  - Include integration with Teleport Connect.
2022-09-30 23:27:48 +00:00
Joel da7316973c Validate SAML connectors upon creation (#16565) 2022-09-29 18:46:08 +00:00
Joel 6caba42ec1 Add support for IdP-Initiated SAML2 login (#13924) 2022-08-22 18:27:44 +00:00
Edoardo Spadolini 58b01b964b Embed auth.Cache in auth.Server (#14698)
* Embed auth.Cache in auth.Server

* Hit the backend during Auth initialization

* Bypass the cache when rotating CAs

* Services.UpsertTrustedCluster is different

* Bypass the cache in waitForTunnelConnections

* Fix infinite recursion

* More cache bypassing during init and rotations

* Rename Services to Uncached in auth.Server

* Further cleanups

* Don't start the auth cache immediately

* Go back to Services rather than Uncached

* Comments and a missing method
2022-07-27 21:05:53 +00:00
Andrew Burke b7efbcebb0 Add error message for failed SSO authorization (#9622)
This change, along with gravitational/webapps#530, adds a new error message for when a user successfully authenticates with SSO but fails to match any roles.
2022-07-15 23:55:25 +00:00
Brian Joerger 2aae5b5899 Fix SSO AuthRequest backwards compatibility. (#13589) 2022-06-17 01:21:29 +00:00
Joel efd10847bf Modernize role mapping in github connectors (#10456) 2022-06-08 15:34:15 +00:00
Brian Joerger 9cc58cca44 gRPC conversions - SSO Auth Connectors (#13073) 2022-06-08 01:45:06 +00:00
Krzysztof Skrzętnicki 9377f7c681 New commands: tctl sso test, tctl sso configure for GitHub (#12783)
* Implement `tctl sso` commands for GitHub auth.

* Mark RFDs as implemented.
2022-05-26 23:26:35 +00:00
Krzysztof Skrzętnickiandrosstimothy 414c82a341 Changes for tctl sso test, tctl sso configure commands [OIDC] (#12519)
* Changes for tctl sso test, tctl sso configure commands [OIDC]

Co-authored-by: rosstimothy <39066650+rosstimothy@users.noreply.github.com>
2022-05-17 16:30:19 +00:00
Krzysztof SkrzętnickiandRoman Tkachenko 734362909b Changes for tctl sso test, tctl sso configure commands [SAML] (#11508)
* Changes for tctl sso test, tctl sso configure commands.

* Log SSO diagnostic information for SSO test flows. 

Co-authored-by: Roman Tkachenko <roman@goteleport.com>
2022-05-04 11:48:20 +02:00
Zac Bergquist 3f507dfd06 Remove uses of deprecated ioutil package 2022-03-16 15:05:42 -06:00
rosstimothy 550d23d15d Fix goroutine and memory leak in watchCertAuthorities (#10871)
* Fix goroutine and memory leak in watchCertAuthorities

The CA Watcher was blocking both on writing to a channel when the watcher
was closed and on HTTP calls that had no request timeout or context passed
to cause cancellation.

All resourceWatcher implementations that had a bug which may cause them to block
on writing to a channel forever were fixed by selecting on the write and ctx.Done.

Adding context.Context to all Get/Put/Post/Delete methods on the auth HTTPClient to
force callers to propagate context. Prior all calls used context.TODO which
prevents requests from being properly cancelled.

Add context propagation to RotateCertAuthority, RotateExternalCertAuthority,
GetCertAuthority, GetCertAuthorities. This is needed to get the correct ctx
from the CertAtuhorityWatcher all the way down to the HTTPClient that makes
the call.

Closes #10648
2022-03-10 11:05:39 -05:00
Edoardo Spadolini 2598401589 Add access requests to audit events (#9758)
* Refactor most uses of `UserMetadata` into a handful of functions

* Add access requests to `UserMetadata`

* Explanation for the reserved field in SessionStart
2022-01-25 16:56:18 +00:00
Brian Joerger 9b8b9d6d0c rollback - Upgrade api version. (#7751) 2021-07-30 15:34:19 -07:00
Brian Joerger c040aca4c1 Upgrade api version. (#7609) 2021-07-28 13:51:21 -07:00
Tim Buckley 2cb7485ace Add workaround for Ping SAML auth requiring signing headers (#7297)
* Add workaround for PingID SAML auth

PingID's SAML auth requires `SigAlg` and `Signature` fields to be set
as query parameters during auth requests when "Enforce Signed Authn
Request" is enabled in the Ping app settings. This adds a workaround
to force gosaml2 to include these parameters when it otherwise would
not. This workaround is enabled when `provider: ping` is set in the
connector properties.

* Add `TestPingSAMLWorkaround` unit test

* Consistently refer to Ping (PingId, PingOne, etc) as just Ping

* Revert fixtures change as metadata is now embedded in `saml_test`

* Improve comments for Ping behavior workarounds

* Improve comment explanation for the `Ping` constant
2021-06-16 11:00:33 -05:00
Brian Joerger 4d36870ff0 Remove remaining API aliases (#7137) 2021-06-08 12:08:55 -07:00
Brian Joerger 7bff7c41bd Remove API aliases (#6983) 2021-06-04 13:29:31 -07:00
a-palchikov b6f4d6fc71 Log traits to role mapping warnings on case-insensitive matches (#6209)
* Compute warnings when mapping traits to roles
* Log warnings for case-insensitive traits to role matches.
Updates https://github.com/gravitational/teleport/issues/6016.
Co-authored-by: Andrew Lytvynov <andrew@goteleport.com>
2021-05-25 08:39:22 -07:00
Andrew Lytvynov ac9ba539ce Use cmp.Equal instead of manual Equals methods (#5828)
* Use cmp.Equal instead of manual Equals methods

Equals methods can get out-of-sync with the fields added in structs they
compare. Using `cmp.Equal` handles that, removes a ton of code and makes
it more explicit when specific fields are excluded from comparison.

* Use gogoproto equal plugin for comparing proto values

This will be faster than reflect-based go-cmp.
2021-05-06 11:47:31 -07:00
Lisa Kim 7931977d72 [web] Add ability to switchback to default roles/expiry (#6373)
- Preserve login time with WebSession when user first creates a web session to derive
"default" expiry when user wants to switch back
- Change the signature of ExtendWebSession to accept a 
NewWebSessionRequest struct that contains session information
- Create renewSessionRequest object to read from web request for endpoint renewSession
- Endpoint now also returns SessionExpires time that is used as countdown in UI
2021-04-19 18:53:09 -07:00
Lisa Kim 940c83c161 Make SSO login failure event emit more specific errors (#6108)
Purpose is to allow users with admin privilege that are able to view audit logs, 
to be able to debug SSO login failures from the UI as much as possible

* Return generic error message for sso console login failures to hide
  sensitive data from reaching client. Previously errors were returning as
  empty messages b/c of a trace bug.
* Remove emit event for createOIDCClient to allow outer caller to
  emit event and prevent double emits on error.
* Temporarily direct users to check teleports log on errors that come back 
  empty to tsh client.
2021-03-25 10:36:47 -07:00
Brian Joerger 4398797f14 Pass context through new gRPC converted endpoints. (#6118) 2021-03-23 18:26:52 -07:00
Lisa Kim 84a4f00114 Define cloud billing event types and codes (#6037)
* Exported auth.clientImpersonator and auth.clientUsername for use in e
2021-03-23 17:23:01 -07:00
Alexander Klizhentas f17625c1a8 Adds controls for impersonation requests. (#6009) (#6073)
Fixes #5352

```yaml
allow:
  impersonate:
    users: ['alice', 'bob']
    roles: ['*']
    where: 'contains(user.spec.traits["groups"], impersonate_role.traits)'
```

Adds "impersonator" to all X.509 and SSH client certs
issued using impersonation and does best effort to track
requests by impersonators in audit events.

Limits certs TTL to the impersonator's max session TTL.

Prevents impersonating users to recursively impersonate
other users.

Allows impersonating users to renew their own certificate,
for example to set route to cluster.

Adds missing token permission for editor role.
2021-03-19 16:04:43 -07:00
a-palchikov 86908cc2f3 Web UI disconnects (#5276)
* Use fake clock consistently in units tests.
* Split web session management into two interfaces and implement them separately for clear separation
* Split session management into New/Validate to make it aparent where the sessions are created and where existing sessions are managed. Remove ttlmap in favor of a simple map and handle expirations
explicitly.
Add web session management to gRPC server for the cache.

* Reintroduce web sessions APIs under a getter interface.
* Add SubKind to WatchKind for gRPC and add conversions from/to protobuf. Fix web sessions unit tests.
* lib/web: create/insert session context in ValidateSession if the session has not yet been added to session cache.
lib/cache: add event filter for web session in auth cache.
lib/auth: propagate web session subkind in gRPC event.

* Add implicit migrations for legacy web session key path for queries.
* Integrate web token in lib/web
* Add a bearer token when upserting a web session
* Fix tests. Use fake clock wherever possible.

* Converge session cache handling in lib/web

* Clean up and add doc comments where necessary

* Use correct form of sessions/tokens controller for ServerWithRoles. Use fake time in web tests

* Converge the web sessions/tokens handling in lib/auth to match the old behavior w.r.t access checking (e.g. implicit handling of the local user identity).

* Use cached reads and waiters only when necessary. Query sessions/tokens using best-effort - first looking in the cache and falling back to a proxy client

* Properly propagate events about deletes for values with subkind.

* Update to retrofit changes after recent teleport API refactorings

* Update comment on removing legacy code to move the deadline to 7.x

* Do not close the resources on the session when it expires - this beats the purpose of this PR.
Also avoid a race between closing the cached clients and an existing reference to the session by letting the session linger for longer before removing it.

* Move web session/token request structs to the api client proto package

* Only set HTTP fs on the web handler if the UI is enabled

* Properly tear down web session test by releasing resources at the end. Fix the web UI assets configuration by removing DisableUI and instead use the presence of assets (HTTP file system) as an indicator that the web UI has been enabled.

* Decrease the expired session cache clean up threshold to 2m. Only log the expiration error message for errors other than not found

* Add test for terminal disconnect when using two proxies in HA mode
2021-02-04 16:50:18 +01:00
Brian Joerger ce87251ea0 api dependency reduction - marshalers (#5384)
Refactor Marshal logic on types, and move it into /lib/services to reduce dependencies in /api.
2021-02-01 10:26:50 -08:00
Brian Joerger 626ad243eb api dependency reduction - utils constants (#5363)
Moved constants and utils used in /api into /api/constants and /api/utils respectively.
2021-01-29 09:37:01 -08:00
Brian Joerger c3e86f1696 Refactor API Dependencies - tlsca and gosaml2 (#5242) 2021-01-20 17:30:03 -08:00
Brian Joerger 76b6b6d84d Refactor lib/utils/parse dependency in api package. (#5261) 2021-01-19 11:32:07 -08:00
Sasha Klizhentas f88cbaf575 Makes SAML error messages friendly to users. 2021-01-14 15:12:04 -08:00
Ben Arent 09928a7f2b Cherry pick Gravitational -> GoTeleport (#4932) 2020-11-25 11:18:55 -08:00
Forrest Marshall af05ce3eeb extended dynamic access API
Various improvements related to extending the dynamic access
API, including:

- Support for users with no statically defined roles.

- Unify trait mapping logic (e.g. claims_to_roles) across
the connector types.

- Support for matcher syntax and claims_to_roles mappings when
configuring which roles a user is able to request.

- Allow tsh or the web UI to automatically generate wildcard
access requests when dictated by role configuration.

- Allow RBAC configuration to attach annotations to pending
access requests which can be consumed by plugins.

- Allow plugins to attach annotations to approvals/denials
which appear in the audit log, and may also be looked up
later to determine additional info about a resolution.

- Support prompts, request reasons, and approval/denial
reasons for access requests.
2020-11-05 12:18:26 -08:00
Andrew Lytvynov 92ed2db38a Fixing golint warnings, batch 1
Mostly cosmetic changes:
- making receiver names consistent
- renaming `foo.FooBar` to `foo.Bar` (using package name as prefix)
- removing redundant `else` branches
- changing `a += 1` to `a++`
2020-10-13 00:22:49 +00:00
Andrew Lytvynov e095e30342 Add kubernetes cluster name to TLS certs
K8s cluster name is specified during login (for now) and gets plumbed to
a new extensions on the TLS cert. The name is validated against all
known k8s clusters reported via proxy heartbeats. If no name is
provided, the extension remains empty.

The name in the cert will get used by proxies for routing, once we fully
support multiple k8s clusters per teleport cluster.

This was tested with direct and github login flows.
2020-10-07 16:26:54 +00:00
Sasha Klizhentas d160507430 Session streaming
This commit introduces GRPC API for streaming sessions.

It adds structured events and sync streaming
that avoids storing events on disk.

You can find design in rfd/0002-streaming.md RFD.
2020-09-28 23:08:56 -07:00
Andrew Lytvynov 1b7401f670 Plumb RouteToCluster through SSO login flows
This lets the user log into a leaf cluster directly via tsh and
provision the correct k8s credentials for it.
2020-07-01 18:15:48 +00:00
Andrew Lytvynov 960f13efda Update e-ref 2020-06-18 19:01:35 +00:00
Andrew Lytvynov 5bd66a396e Plumb caller username for CRUD events via contexts
Our auth middleware already attaches a TLS identity as context value.
Plumb contexts through and extract the username when recording events.
If the received context doesn't have an identity attached, use "system"
as username.

Lots of noise here due to missing context.Context plumbing :(
We should eventually plumb contexts to all those RPC interfaces.

Updates #3816
2020-06-18 19:01:35 +00:00
Andrew Lytvynov a9eae02374 errcheck: add missing error handling in lib/auth 2020-06-03 21:57:04 +00:00
Lisa Kim da7500d671 Emit audit events when upserting/deleting auth connectors (#3736) 2020-05-19 17:08:23 -07:00
Lisa Kim 118ad19101 Emit correct event user who updates user records (#3635)
* Add UpdateUser rpc to proto
* Differentiate between create and update in github,oidc,saml
* Edit updated_by event field to be more generic (used with contexts to capture user modifying records)
* Update security issue by removing secrets from user when update/upsert/create (forrest)
* Update createUser in resource_command and require force for updates
2020-05-05 16:49:32 -07:00
Andrew Lytvynov bd2c9a0828 Fix staticcheck findings in lib/auth
Fixed findings:
```
lib/auth/clt.go:294:12: SA1019: grpc.WithDialer is deprecated: use WithContextDialer instead.  Will be supported throughout 1.x.  (staticcheck)
	dialer := grpc.WithDialer(func(addr string, timeout time.Duration) (net.Conn, error) {ion error: desc = "transport: Erro
	         ^
lib/auth/clt.go:1462:5: SA1019: grpc.Code is deprecated: use status.Code instead.  (staticcheck)site-A Type:proxy Addr:{Addr:local
	if grpc.Code(err) != codes.Unimplemented {
	  ^
lib/auth/clt.go:1500:5: SA1019: grpc.Code is deprecated: use status.Code instead.  (staticcheck)rsetunnel/agentpool.go:312
	if grpc.Code(err) != codes.Unimplemented {
	  ^
lib/auth/saml.go:294:33: SA5011: possible nil pointer dereference (staticcheck)
		events.EventUser:          re.auth.Username,
		                             ^
lib/auth/auth_test.go:119:2: SA4006: this value of `ws` is never used (staticcheck)ats. stats:map[connected:1 connect
	ws, err := s.a.AuthenticateWebUser(AuthenticateUserRequest{
	^
lib/auth/auth_test.go:160:2: SA4006: this value of `ws` is never used (staticcheck)ver.go:425
	ws, err := s.a.AuthenticateWebUser(AuthenticateUserRequest{
	^
lib/auth/auth_test.go:243:2: SA4006: this value of `roles` is never used (staticcheck)es that discovery protocol recover
	roles, err = s.a.ValidateToken(tok)
	^
lib/auth/password_test.go:228:2: SA4006: this value of `err` is never used (staticcheck)necting -> connected. leaseID:5 ta
	token, err := s.a.CreateResetPasswordToken(context.TODO(), CreateResetPasswordTokenRequest{7.0.0.1:46150. reversetunnel/srv.g
	^
lib/auth/tls_test.go:109:2: SA4006: this value of `err` is never used (staticcheck)ry(c *check.C) {
	err = s.server.AuthServer.Trust(remoteServer, nil)
	^
lib/auth/tls_test.go:195:2: SA4006: this value of `err` is never used (staticcheck)meout=10000&_sync=OFF, poll stream
	err = s.server.AuthServer.Trust(remoteServer, nil)
	^
lib/auth/tls_test.go:360:2: SA4006: this value of `newProxy` is never used (staticcheck) be received and the connection ad
	newProxy, err := s.server.NewClient(TestBuiltin(teleport.RoleProxy))o/src/github.com/gravitational/tel
	^
lib/auth/tls_test.go:388:2: SA4006: this value of `err` is never used (staticcheck)o/src/github.com/gravitational/tel
	err = s.server.Auth().autoRotateCertAuthorities()
	^
lib/auth/tls_test.go:1074:2: SA4006: this value of `err` is never used (staticcheck)uest, we will recover session id a
	err = os.MkdirAll(filepath.Join(uploadDir, "upload", "sessions", defaults.Namespace), 0755)reversetunnel/agent.go:458
	^
lib/auth/tls_test.go:1263:2: SA4006: this value of `err` is never used (staticcheck)quests channel. leaseID:5 target:l
	err = clt.UpsertPassword(user, pass)
	^
lib/auth/tls_test.go:1691:2: SA4006: this value of `err` is never used (staticcheck)
	userCerts, err = adminClient.GenerateUserCerts(context.TODO(), proto.UserCertsRequest{et:localhost:20088 reversetunnel/t
	^
lib/auth/auth_with_roles.go:860:32: SA1029: should not use built-in type string as key for value; define your own type to avoid collisions (staticcheck)
	return context.WithValue(ctx, events.AccessRequestUpdateBy, user)ts is received, if it's been longe
	                             ^
lib/auth/auth_with_roles.go:876:32: SA1029: should not use built-in type string as key for value; define your own type to avoid collisions (staticcheck)
	return context.WithValue(ctx, events.AccessRequestDelegator, delegator)ime = f.process.Clock.Now()
	                             ^
lib/auth/middleware.go:316:69: SA1029: should not use built-in type string as key for value; define your own type to avoid collisions (staticcheck)
	requestWithContext := r.WithContext(context.WithValue(baseContext, ContextUser, user))rocess.Infof("Teleport has recover
	                                                                  ^ion to @remote-auth-server [] in r
lib/auth/apiserver.go:285:42: SA1029: should not use built-in type string as key for value; define your own type to avoid collisions (staticcheck)
			ctx := context.WithValue(r.Context(), contextParams, p)et:localhost:20088 reversetunnel/t
			                                     ^
```
2020-04-29 22:40:15 +00:00