Commit Graph
121 Commits
Author SHA1 Message Date
rosstimothy c2fc9a9375 Add idle connection timeouts to http clients and servers (#22885)
Sets `http.Server.IdleTimeout` and `http.Client.IdleConnTimeout`
on clients and servers which didn't have them set. A default of
360s was chosen to be on par with the default of an NLB without
being identical.

This was added as another safety measure to prevent leaking any
idle connections indefinitely as seen in #22757.

`apidefaults.DefaultDialTimeout` was also renamed to
`apidefaults.DefaultIOTimeout` to better reflect its usage.
2023-03-10 16:47:06 +00:00
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
rosstimothy 7f5c185d5b Adds a new credentials.TransportCredentials to auth and refactors (#21850)
`auth.Middleware` to make use of them. This allows for less redundancy
per RPC and provides the ability to perform session control when grpc
connections are established.

The `auth.Middleware.withAuthenticatedUser` function was called from all
interceptors of any gRPC server that leveraged `auth.Middleware`. This
was constructing the identity of the client from the TLS certificate
per RPC. Since the identity of a connection cannot change between RPCs
there is no need to construct the identity in an interceptor. Instead,
the new `auth.TransportCredentials` can build the identity once after the
TLS handshake completes. When interceptors or gRPC handlers need to
acquire the identity they can do so using the same
mechanism via `peer.Peer.AuthInfo` and assert on the new `auth.IdentityInfo`
type:

```go
    peerInfo, ok := peer.FromContext(ctx)
	if !ok {
		return
	}

	connInfo, ok := peerInfo.AuthInfo.(auth.IdentityInfo)
	if !ok {
	    return
	}

	identity := connInfo.IdentityGetter.GetIdentity()
	connState := connInfo.TLSInfo.State
```

The gRPC server that is served on the Proxy ssh port needs to hold the
same invariants as the ssh server available on the same port. This
means that connection limits need to be enforced when new connections
are established. To achieve this the new `auth.TransportCredentials` can
be provided with an `auth.ConnectionEnforcer` and an `auth.Authorizer`
to first build an identity, then ensures that the user is authorized and
finally that the user has not exceeded their connection limits.

Other minor changes include providing the cluster name to the
`auth.Middleware` instead of it looking the value up from the cache every
time an identity is created. Some interceptors were also moved around or
removed to eliminate the chances of having duplicate interceptors end up in
the interceptor chain.

Part of #19812
2023-02-23 14:55:06 +00:00
Krzysztof Skrzętnicki 20d4c79812 App access: rewrite redirects to public app address from leaf cluster. (#21067)
Fixes #8112.
2023-02-17 13:35:23 +00:00
STeve (Xin) Huang 2115f58fec Align AWS assume-role request duration with cert expiration (#21670)
* Limit AWS access AssumeRole duration

* add info header

* add UT

* minor refactor

* beef up user message
2023-02-16 14:57:12 +00:00
Anton MiniailoandNoah Stride 13fad744d6 Adjust clientIP/pinnedIP fields according to IP pinning RFD (#21866)
* Adjust clientIP/pinnedIP fields according to IP pinning RFD

* Improve wording.

Co-authored-by: Noah Stride <noah.stride@goteleport.com>

---------

Co-authored-by: Noah Stride <noah.stride@goteleport.com>
2023-02-15 19:36:19 +00:00
STeve (Xin) Huang 5de49223c7 Skip deleting database servers on agent shutdown during binary upgrade (#21156)
* Skip deleting database servers on agent shutdown during upgrade

* implement Shutdown(context.Context)

* and dedicated "XXXAndDelete" functions
2023-02-09 15:58:09 +00:00
STeve (Xin) Huang 2111f51441 Support assumed roles for "tsh proxy aws" (#20568)
* Support assumed roles for "tsh proxy aws"

* fix typo for RenameHeader

* add error handler

* review comments

* enhance bad parameter

* fix typo

* Forbit requests by assumed role in endpoint url mode.

* fix host check
2023-01-30 21:21:43 +00:00
Gavin Frazar fc372383dc fix tsh proxy aws --endpoint-url (#20804)
* Update tests to catch aws sigv4 errors

* Fix aws sigv4 with tsh aws proxy -e

* fix imports

* write header
2023-01-28 01:42:36 +00:00
Gavin Frazar 6d9bb25505 update app access reserved headers (#20741)
* Add x-teleport-api-error to reserved headers
* Update app tests for rewritten headers
* Add test case for x-teleport-api-error
* Fix test for XForwardedSsl since it was effectively untested before
* Refactor leaf test to parse the response from dumper app
* Update docs reference reserved headers
2023-01-27 00:01:02 +00:00
Krzysztof SkrzętnickiandEdoardo Spadolini 4a8658ab25 Change Azure and GCP server-side handlers to ensure timeout tests pass. (#20281)
* Change Azure and GCP server-side handlers to ensure timeout tests pass.

Co-authored-by: Edoardo Spadolini <edoardo.spadolini@goteleport.com>
2023-01-23 15:24:10 +00:00
Alan Parra 11d58e25c7 Refactor AccessMFAParams and MFAParams to allow additional data (#20300)
Refactor `services.AccessMFAParams` and the accompanying `MFAParams` methods so
they may be extended to carry additional data (eg, information required to
perform device trust checks).

This PR refactors existing code without adding any new functionality, so it may
be backported to older branches to alleviate eventual conflicts. Follow up
changes will take advantage of it to add support for device trust.

Related to gravitational/teleport.e#514.
2023-01-17 20:02:38 +00:00
Krzysztof Skrzętnicki 4c7c660036 GCP CLI support: server-side request handler (#19789)
* Also: minor changes to the Azure handler, harmonizing the timeout handling with the implementation found in the GCP one.
2023-01-11 15:50:20 +00:00
Tiago Silva 40861809a6 Add RoleV6 resource type (#19324)
This PR includes a new Role resource version that is compatible with V5 spec.

The new resource introduces the `kubernetes_resources` definition that allows operators to limit the Kubernetes resources that each member can access. The `kubernetes_resources` entries must follow the following format: `{"kind":"<kind>", "namespace":"<namespace>","name":"<pod>"}`. Currently, it only supports objects of `kind` `pod`. Valid examples `<namespace>/<name>:
- `*/*`: matches all pods in all namespaces.
- `default/*`: matches all pods in the `default` namespace.
- `*/nginx-*`: matches every pod prefixed with `nginx-` in every namespace.

For older resource versions - V5, V4, V3 - `kubernetes_resources` is automatically populated with `{"kind":"pod","namespace":"*","name":"*"}` to keep compatibility. For the newest version, it's mandatory to define its value otherwise access to pods will be denied.

Part of #18434
2023-01-05 09:58:12 +00:00
Alan Parra f942a4ebc8 Enable Authorizer-based device authorization (#19659)
Enable device authorization by plugging into auth.Authorizer and selectively
disabling it for processes that don't (yet) want device authz.

`GenerateUserCerts` is modified to issue device-aware certificates (DB/k8s
access), as well as `CreateAppSession`. The latter is not necessary for DB
access, but it does enable App Access to issue device-aware certs - commands
such as `tsh apps login` and `tsh proxy app` can benefit from those.

DB access is now ready to benefit from trusted devices. k8s access is likely
supported with these changes as well, but I've postponed enabling it after I've
done more testing.

Both `GenerateUserCerts` and `GenerateUserSingleUseCerts` now do early
device-aware authorization; this creates a better UX, as it allows us to return
error messages directly via `tsh`, instead of having to pipe them through
database-specific protocols. Further PRs could improve errors for scenarios
where the existing certificate became lacking due to higher server-side authz
enforcement.

gravitational/teleport.e#514
2023-01-03 17:09:15 +00:00
Marco André Dinis 6286488be3 Database: validate AWS Account ID (#19638)
When the AWS Account ID is provided, we must check that it is a valid
one.

AWS Account ID is a well documented field: 12-digit string

This check is meant to prevent typos when creating Databases mainly from
the Web UI in the context of Teleport Discover.
2022-12-28 12:42:39 +00:00
Gavin Frazar eccfd9342e Refactor app access (#19387)
* Move logic out of RoundTrip and into ServeHTTP as a middleware before handing off to oxy forwarder
* Move AWS signing service code into lib/utils/aws/signing.go
* use app server close context for audit event emitting
* add go doc comments.
* refactor request rewriting to make the copy in a more robust way.
* pass status code as uint32 rather than casting in audit emitter
* clone request instead of making a new request, and rewrite url to force https
* update header handling
* Set oxy forwarder to PassHostHeader=false to ensure the host header is
  the URL being sought.
* Remove code that deleted forwarding headers previously, we should keep
  those (X-Forwarded-*).
* Audit log the AWS Host sought rather than the incoming request Host
  header (prior behavior maintained, we just rewrite the request
  differently using Clone).
* Remove obsolete header copying helper func
2022-12-23 00:56:27 +00:00
Steven Martin e1ebc332f8 spell fixes (#19419) 2022-12-16 19:01:28 +00:00
Gabriel Corado f6d8887a33 fix(app): clone tls configuration for websocket dialer (#19396) 2022-12-16 12:58:25 +00:00
Krzysztof Skrzętnicki dd67a49ab5 Azure CLI access (#18675) 2022-12-12 19:34:53 +00:00
Isaiah Becker-Mayer fc33246807 Fixes dissonance between disconnect_expired_cert vs require_session_mfa (#18607) 2022-12-07 17:00:38 +00:00
Jakub Nyckowski 9379243390 Use pre-generated RSA keys in tests (#18750)
Many of our tests (db package, I'm looking at you) generate many RSA keys. This has two main side effects; makes our tests slow and flaky as CPU usage spikes in random moments when the tests are run in parallel.
This change pre-generates RSA keys at the beginning of each test module and reuse them in randomized order to reduce the situation that one key has been used multiple times in one test.
I had to move a few files to avoid circular dependencies.
2022-12-05 19:33:49 +00:00
Zac Bergquist c9e64e1c0e Make the uploader responsible for creating the directories it needs
This removes a bunch of custom code where we manually create uploader
directories in tests because the full uploader service is not running.
2022-12-04 11:50:29 -05:00
Zac Bergquist 2314ebf7e6 uploader: move corrupted uploads to separate directory
This ensures that the uploader won't busy loop over the same corrupted
upload file, while ensuring that the file is still preserved.

Fixes #18936
2022-12-04 11:50:29 -05:00
Michael Wilson fb47005d1a Take cloud labels into account for application access permissions calculation. (#18492)
The app access service now takes cloud labels into account for determining 
permissions to an application. Previously, the app service didn't recognize 
cloud labels w/r/t determining whether users had access to a particular 
application. This was particularly confusing because this worked in the UI, 
i.e. the application would show in the list of applications the user had 
permissions to, but the app service itself would reject them. This is because 
the dynamic and cloud labels were not being properly injected into the 
application before running authorize within the app service.
2022-11-21 14:19:10 +00:00
Zac Bergquist da7680ad0b Use x/exp/slices instead of home grown utilities (#18524)
We were inconsistent throughout the codebase and would sometimes
use the slices package and other times use our own equivalents
in api/.

This removes our versions in favor of the golang.org/x package that
does the same, which has the added benefit of reducing the surface
area of the public API module.

Note: despite existing uses of the slices package, for some reason
it didn't show up in go.mod or go.sum. Fixed that too.
2022-11-17 15:25:46 +00:00
Gavin FrazarandTobiasz Heller d9b80fb2a7 Emit new event for DynamoDB requests via app access (#17595)
* protobuf update

* Update proto to use dynamodb request event specific to app-access

We will include a similar event for dynamodb via database-access.
We split the events so that app and database access events are not coupled.
This way we do not have to include optional database/app metadata in one event too.

* Update protos

* Update oneof

* Move AppMetaData up with the other metadata and add a 'target' field

* Remove operation plane

* Fix typo

* Configure signing service with transport instead of http client

* Protect from resource exhaustion attacks

* Add IsDynamoDB to types.Application

* Add new event and code for dynamodb requests

* Add async emitter to app access

* Add audit.go to unify app access auditing

* Refactor auditing in app access

* Use the new audit's onSessionChunk/onRequest methods
* Put the session context in the session chunk
* Use a TeeStreamer to send AppSessionDynamoDBRequest directly to audit log as well as session file
* Change streamWriter to streamCloser in sessionChunk to clarify that it should only be used for closing

* Update handler test to test dynamodb events

* Update test to use streamCloser

* Update sever test

* Add doc strings

* Return error from audit interface methods so callers can choose what do to with it

* Move app session start/end into audit interface

* Configure tcpServer to use the server's emitter instead of auth
  client, as an Audit interface.
* Have tcpServer call onSessionStart/End instead of emitting events
  itself.

* Remove unneeded check type

* Rename Transport -> RoundTripper

* Fix test after renaming field

* Rename drainBody and defer body closing

* Fix subtle named return mistake

* Update lib/service/service.go

Co-authored-by: Tobiasz Heller <14020794+tobiaszheller@users.noreply.github.com>

* Update lib/service/service.go

Co-authored-by: Tobiasz Heller <14020794+tobiaszheller@users.noreply.github.com>

* Rename ok->shouldSkipCleanup to make the purpose of it more clear

* Refactor request body decoding into aws utils

* Use request instead of signed request for audit event

* Determine if req is for a dynamo endpoint instead of checking app uri

* Remove obsolete app func IsDynamoDB

* Update handler test

* Use generic console app uri to test that we differentiate request by endpoint instead of app uri
* Use a dynamodb request which has a body to test that we include the body in the audit event
* Test for expected body JSON

* fix lint

* Fixup merge

Co-authored-by: Tobiasz Heller <14020794+tobiaszheller@users.noreply.github.com>
2022-11-15 22:58:15 +00:00
STeve (Xin) Huang 7c0866a2ae Fix issue AWS app access sends requests without path (#18355) 2022-11-14 14:05:53 +00:00
Michael Wilson 85fac93653 Make TestTCP* tests in appaccess more deterministic. (#18233)
The appaccess TestTCP* tests are highly reliant on time. This has been
reduced (but not eliminated) by using a fakeClock and a channel for
signaling monitor triggered connection closures.
2022-11-08 21:40:54 +00:00
Zac Bergquist c2e79f1fa9 Include all active sessions in the web API (#17945)
Also update the active sessions test to operate based on the presence
of session trackers rather than actually starting a session. This
allows us to test additional session types and is more deterministic.

For app sessions, use the name from the types.Application, since
the value in the cert is only present for CLI sessions.

For database sessions, use the database service name, which maps
to the Teleport database service the user is connecting to, since
the actual "logical" database name is not required.

Closes #17126
Closes #17871
2022-11-07 20:09:37 +00:00
Michael Wilson 3d483e2d13 Add in app access connection monitoring. (#17436)
Application access connection monitoring has been introduced so that, when a
lock is created, application access connections will be interrupted until the
lock has been cleared. This includes web sockets and TCP applications.
2022-11-05 02:44:57 +00:00
Jakub Nyckowski 0ee91f6c37 Enable GCI linter (#17894) 2022-10-28 20:20:28 +00:00
Steven Martin 6040d0f4f6 Spell fixes (#17090) 2022-10-14 00:50:27 +00:00
756eb91ede Add X-Forwarded-SSL and X-Forwarded-Port to appaccess. (#16965)
* Add X-Forwarded-SSL and X-Forwarded-Port to appaccess.

Application Access now adds in X-Forwarded-Ssl and X-Forwarded-Port headers.
Tests have been added and adjusted to look for these new headers as well.

* Update lib/srv/app/header_rewriter.go

Co-authored-by: Ryan Clark <ryan.clark@goteleport.com>

* Update integration/appaccess/fixtures.go

Co-authored-by: Roman Tkachenko <roman@goteleport.com>

* Remove common.XForwardedPort

* Change order of websocket delegates.

* Make ReservedHeaders more future-proofed.
2022-10-12 16:54:53 +00:00
Mike Wilson e15f4f351e Add traits to JWT payload.
The JWT payload now includes user traits.
2022-10-10 14:52:06 -04:00
Brian Joerger 1c690d7968 v11 deprecation (#17047)
* Complete deprecation for OIDC RedirectURL - #12054.

* Complete deprecation for CreateSessionTracker - #12304.

* Complete deprecation for SSO Auth Request http endpoints - #13073.

* Complete deprecation for #12795.

* Complete deprecation for http GenerateToken - #9024.
2022-10-06 18:33:35 +00:00
Zac Bergquist e547957f93 Remove [direct] dependency on go.uber.org/atomic (#17035)
Reintroducing the change from #16884 now that Go 1.19.2 has been
released with the fix.

This reverts the revert from  09de0ba530.
2022-10-05 01:24:46 +00:00
Lisa Kim 8bb0636863 Partial delete deprecated code for "DELETE IN 11.0.0" and lower (#16947)
* Deleted 
   - GetAppServers
   - GetApplicationServers 
   - GetDatabaseServers 
   - GetKubeService 
   - UpsertAppServer
   - DeleteAppServer
   - DeleteAllAppServers
   - RotateUserTokenSecrets
* Delete list nodes fallback
* Use AppServer type for heartbeat test
2022-10-04 17:58:30 +00:00
STeve (Xin) Huang 684f3e5468 Refactor TestResolveEndpoints to avoid test failure when AWS SDK changes (#16943) 2022-10-04 12:32:36 +00:00
Zac Bergquist 09de0ba530 Revert "Remove [direct] dependency on go.uber.org/atomic (#16884)" (#16918)
This reverts commit 4f3aa9a3f2.

We're unable to build for 32-bit Linux due to
https://github.com/golang/go/issues/55152,
which looks like it will be fixed with Go 1.19.2 next week.

We'll re-evaluate with the next Go release and reintroduce this change
as soon as we can.
2022-09-30 22:41:45 +00:00
Zac Bergquist 4f3aa9a3f2 Remove [direct] dependency on go.uber.org/atomic (#16884)
Go 1.19's sync/atomic package provides the same functionality
2022-09-30 20:39:05 +00:00
Alan Parra e61da10df2 Update (even more) Go dependencies (#16900)
Do another large batch of dependency updates.

Most updates are around minor versions, so _theoretically_ safe. The following
v0.x updates draw attention:

* cloud.google.com/go/iam (likely safe, as Google is largely trunk-based)
* github.com/Microsoft/go-winio

Notable exceptions are k8s-related modules, which are harder to update for
various reasons.

* Update Go dependencies
* Fix lib/srv/app/aws/endpoints_test.go
2022-09-30 19:22:35 +00:00
Brian Joerger 2654add770 RequireMFAType (#16034)
Replace role/authPref RequireSessionMFA (bool) with RequireMFAType
(string).

  - Add new RequireMFAType constant values with custom boolean marshalling.

  - Add RequireMFAType to role and auth preference and deprecate
RequireSessionMFA.

  - Add session-mfa override login when hardware_key_touch is enforced.

  - Add protobuf enum for RequireMFAType.

  - Add support for proto enums in protoc-gen-crd and update Kubernetes
Operator manifests.
2022-09-22 20:30:32 +00:00
rosstimothy ebfbfd496e Use testauthority instead of native to generate keys in tests (#16486)
* use test authority

* use testauthority for InitConfig RSAKeyPairSource

* add named returns to test authority
2022-09-21 20:53:09 +00:00
Alan Parra a75fcc21d8 Update golangci-lint to 1.49.0 (#16507)
Update metalinter, fix a few lint warnings and replace deprecated linters.

`deadcode`, `structcheck` and `varcheck` are abandoned and now replaced by [`unused`][1].

Since 1.19, `go fmt` reformats godocs according to https://go.dev/doc/comment. I've done a bulk-reformatting of the codebase to keep the linter happy. Backporting is mostly harmless (the exception being `lib/services/role_test.go`, that for some reason breaks the _old_ linter using the new format).

[1]: https://golangci-lint.run/usage/linters/

* Bump golangci-lint version
* Replace abandoned linters
* Fix bodyclose on lib/auth/github.com
* Fix bodyclose on lib/kube/proxy/streamproto/proto_test.go
* Fix bodyclose on lib/srv/alpnproxy/proxy_test.go
* Fix bodyclose on lib/web/conn_upgrade_test.go
* Silence staticcheck on lib/kube/proxy/forwarder_test.go
* Silence staticcheck on lib/utils/certs_test.go
* Address BuildNameToCertificate deprecation warnings
* Run `go fmt ./...`
* Run `go fmt ./...` on api/
* Ignore formatting in role_test.go
* Remove redundant initializers in lib/srv/uacc/
* Update e/
2022-09-19 22:38:59 +00:00
rosstimothy 54d32e1aa8 Use tracing handler per server not per route (#16342)
Tracing handlers consume a large amount of memory over time, which
makes using one per route suboptimal (See https://github.com/open-telemetry/opentelemetry-go-contrib/issues/2413).
Wrapping all `http.Server` handlers with a tracing handler provides
the same tracing abilities for a fraction of the memory usage. A new
span formatter is added which allows servers to still contain the
request span in the span name.
2022-09-13 16:31:53 +00:00
STeve (Xin) Huang 1dadb34b29 Support AWS Console for US GovCloud Partition (#13442) 2022-08-31 16:29:40 +00:00
STeve (Xin) Huang fac43c5925 Fix an issue tsh aws s3 fails when using path with special characters (#15784) 2022-08-24 18:33:32 +00:00
Roman TkachenkoandAlex Vandiver 31b4a00a86 (buddy) Pass JWT headers on websocket requests (#15667)
* transport: Rewrite headers, including JWTs, for websockets.

Applications can otherwise 401 on websocket requests, as they do not
present any authentication headers.

docs: Fix the reserved JWT header name.

Signed-off-by: Roman Tkachenko <roman@goteleport.com>

* Add test for JWT header in websocket apps

Signed-off-by: Roman Tkachenko <roman@goteleport.com>
Co-authored-by: Alex Vandiver <alex@chmrr.net>
2022-08-22 20:43:50 +00:00
Zac Bergquist d1c6b0618e Fix lint warnings (#15312)
Mostly duplicated imports and redundant types in struct literals.
2022-08-08 20:20:29 +00:00