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.
* 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.
`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
* 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
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.
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
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
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.
* 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
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.
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.
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.
* 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>
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.
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#17126Closes#17871
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.
* 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.
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.
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
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.
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/
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.
* 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>