Commit Graph
293 Commits
Author SHA1 Message Date
Michael Wilson 8f628084d5 Introduce the Okta service. (#22899)
The Okta service and client have been introduced. This will allow for the
maintenance of Okta objects via our gRPC server and auth client. Some
additional improvements have been made so that the local okta service now
better reflects the gRPC definition.

Additionally, the gRPC authorization mechanism has been lifted out of
`lib/auth/grpcserver.go` and moved into a common authorizer. Finally, the
ability to check access to verbs has been lifted out of the `pluginsv1`
service into that same authorizer. This will hopefully provide a good base
for separate gRPC services in the future.
2023-03-14 16:25:22 +00:00
rosstimothy 9d066364a8 Migrate GetCertAuthorities to gRPC (#22985)
Adds a new `GetCertAuthorities` unary RPC to
`teleport.v1.trust.TrustService` and deprecates the equivalent
HTTP endpoint. All associated interfaces have been updated to remove
the marshal options as well.
2023-03-14 14:45:01 +00:00
Tiago Silva 674a3a1ec1 Removes deprecated KindKubeService objects (#22663)
This PR removes the `types.KindKubeService` objects that were
deprecated in Teleport 11.

Teleport 12 removed the double heartbeat and for Teleport 13 we can
safely drop the support of the old hearbeat based on `types.Server`
objects.

Clients older than Teleport 12 connecting to a Teleport 13 server will
fail since they cannot heartbeat using the old mechanism.
2023-03-13 10:55:39 +00:00
Tiago Silva 6161969add Fix panic when AuditWriter fails on moderated sessions (#22869)
An assignment before checking the error was replacing the session event
emitter with a `nil` value which eventually panic when the caller
function tries to close the session.
2023-03-10 21:20:47 +00:00
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
rosstimothy fa3bb9ac59 Ensure that the webclient closes connections (#22832)
The `http.Client.Transport` created in `newWebClient` wraps a
chain of `http.RoundTripper` over an underlying `http.Transport`.
Since we cannot guarantee that each `http.RoundTipper` has a
`CloseIdleConnections` method the usage of
`defer clt.CloseIdleConnections()` does not guarantee that the http
connections created during Find/Ping/etc are closed.

To prevent leaking connections implementations of `http.RoundTripper`
have added a `CloseIdleConnections` method added that forwards the
request on to the wrapped interface. The `otelhttp.Transport` does
not implement this method either so care has been taken to wrap it
in a `http.RoundTripper` which will call the root transport in
`enforceCloseIdleConnections`. An upstream issue has been filed
with otelhttp: https://github.com/open-telemetry/opentelemetry-go-contrib/issues/3543
to get the method added to their `Transport` implementation.

This wasn't noticed prior to upgrading to go1.20 becuase prior to
[this](https://github.com/golang/go/commit/4e7e7ae1406c70d9cc0809ec11105a55a60a0b70)
commit the `ReadHeaderTimeout` set on the Proxy web api http.Server
would cause the connection to appear idle and get terminated by the
server.

`TestWebClientClosesIdleConnections` was added to capture the leak
in connections as reported in #22757 and prevent any regressions.
2023-03-10 15:21:16 +00:00
rosstimothy 95d6d0fee1 Migrate GetCertAuthority to gRPC (#22624)
The HTTP client created by `auth.NewClient` has an idle timeout of
30s and each instance periodically gets cert authorities in
`TeleportProcess.syncRotationStateCycle`. If there has been no
activity when the ticker expires then the request will result in a
brand new connection to Auth to be established. This can cause a
spikes in open file descriptors on the Proxy when there are a large
number of instances connected via a tunnel.

To prevent periodic dialing when retrieving cert authorities the
endpoint has been migrated to the new Trust gRPC service. For now
only the get endpoint has been migrated but the rest of the CRUD
operations for cert authorities should be migrated from the HTTP
api to the gRPC service as well.
2023-03-10 14:32:34 +00:00
Zac Bergquist 2ae9d770fc Refactor tctl's dependencies (#22693)
* Move configuration from lib/service to lib/service/servicecfg

The new servicecfg package will hold only configuration for services.
This will allow other packages (like tctl and tsh) to depend on
servicecfg without pulling in all of lib/service (which has a number
of platform-specific details).

This is the first step towards being able to build tctl for Windows.

* Move PAM and BPF config into servicecfg

This breaks a compile-time dependency on BPF/PAM for tctl.
2023-03-09 17:48:36 +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
Tiago Silva 1fd58c539b Validate static labels assigned to Kubernetes service (#22701)
This PR introduces the static label's key validation to Kubernetes Service.
Services with invalid labels fail to hearbeat their clusters but the
service is kept working. This change forces the service to fail fast
during startup if any key is invalid.

Fixes #22696
2023-03-08 15:28:42 +00:00
Anton Miniailo 8f3b2b181b Enabled IP pinning enforcement for Kube and DB (#22310) 2023-03-08 14:20:47 +00:00
Tiago Silva 3a6ada7459 Add Kubernetes Access tracing (#22308)
* initial tracing commit

* reply with code review comments
2023-03-02 18:15:53 +00:00
Tiago Silva 5f4c4f6884 Fix Kube impersonation header overwrite when dealing with remote clusters (#22240)
* Fix Kube impersonation header overwrite when dealing with remote clusters

When forwarding exec requests to remote clusters I introduced an empty
header that failed the validation in `setupImpersonationHeaders`. This
results in the request being denied.

This problem only affects Teleport 11 and 10, but I am fixing the behaviour
on master as well.

Fixes #22226

* add tests
2023-02-24 18:02:22 +00:00
Tiago Silva 91eb3c6bbc Inherit kubernetes_resources from roles when using access requests to (#22127)
Kube

This PR fixes the inheritance of `kubernetes_resources` from the user's roles when the user has active access requests to a `kube_cluster`.

If the user had an active request to a `kube_cluster`, Teleport ignored the role's `kubernetes_resources` and returned an empty set for the allowed and denied pods. This resulted in the user being unable to see any pods in the cluster.

Fixes #22126
2023-02-23 15:35:28 +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
d89879c2f5 Add gRPC service definition for Plugin resources (#21750)
* Add plugin exchange service

* Add Plugin methods to auth

* Add gRPC-layer methods for Plugin

* Add RBAC presets for Plugin

* Test GetPlugin()/NoSecrets access

* Make error assertions more correct in role test

* Deny setting credentials if user can not read them

* gofmt

* Apply minor suggestions from code review

Co-authored-by: rosstimothy <39066650+rosstimothy@users.noreply.github.com>
Co-authored-by: Tiago Silva <tiago.silva@goteleport.com>

* Move dependency into an existing block in go.mod

* Improve error messages for failed type assertions

* DRY WithSecrets access checks for Plugins

* Run new tests in parallel

* Improve error assertions in auth_with_roles_test

* TestGetPluginWithSecrets: split cases to subtests

* Clean up test servers and clients

* Add proto for plugin service

* Remove Plugin methods from auth service

Moved to a dedicated service

* Remove plugin-related auth methods

Moved to a dedicated service in Enterprise

* Remove CreatePlugin test from auth_with_roles_test

Moved to a dedicated service in Enterprise

* Pass "backend getter" to local plugins service

This pattern is used in Enterprise to set up secondary services
before auth (and backend) are created.

* Rename InitialCredentials to BootstrapCredentials

* Add plugins service to genproto.sh

* Reformat generated proto

* Remove obsolete PluginExchangeService

The equivalent of this is now in Enterprise

* Add kube service to genproto.sh; regenerate

* Add ListPlugins to plugin backend service

* Reimplement GetPlugins on top of ListPlugins

This is a "convenience" implementation for the backend service layer.

* Replace GetPlugins with ListPlugins in gRPC schema

* Fix ListKubernetesResources unit test

* Simplify plugin pagination key to just the name

* Use existing constant for page size

* Make dummy clients return errors instead of panic

* Remove obsolete field

* Ensure go.mod is valid for corresponding e changes

* Fix passing mutex ref

* Move teleport-plugins import to e_imports

* Revert oauth change in go.mod

* Use limit+1 to look-ahead when paginating plugins

* Test plugin pagination with pageSize > numPlugins

* Add descriptive messages to gRPC dummy clients

* Plugin: add RW for editor; remove secrets from gRPC

* Make message more descriptive for dummy gRPC conn

---------

Co-authored-by: rosstimothy <39066650+rosstimothy@users.noreply.github.com>
Co-authored-by: Tiago Silva <tiago.silva@goteleport.com>
2023-02-23 14:32:41 +00:00
0db64bbabe Fix Moderated session on leave pause action. (#21366)
* Fix Moderated session on leave pause action.

* Unpause when moderator rejoins session with onLeave=pause

This commite fixes a case when the moderator rejoins a paused session
but Teleport didn't resume the operations and the session was still
locked to everyone.

* Fix panic when re-joining SSH session.

* Update lib/kube/proxy/sess.go

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

* Update lib/kube/proxy/sess.go

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

* Fix typo

Co-authored-by: Tiago Silva <tiago.silva@goteleport.com>

---------

Co-authored-by: Tiago Silva <tiago.silva@goteleport.com>
Co-authored-by: Noah Stride <noah.stride@goteleport.com>
2023-02-17 14:11:59 +00:00
Tiago Silva 6ce42b4ac1 Add minor improvements to lib/kube/proxy (#21885)
This PR resolves the comments pointed out by @jakule during the review
of #21846.
2023-02-16 13:49:20 +00:00
Noah StrideandAlan Parra f3ba5750a8 Make tctl nodes add / tctl tokens add use CreateToken RPC (#21189)
* Start removing generateToken

* Refactor `tokens add` to use `CreateToken` RPC

* Correct deprecation version

* Remove calls to GenerateToken

* Start tests for token crud

* Allow user role rules to be provided wth CreateUserAndRole helper

* Add TestCreateToken to tls_test

* Add TestUpsertToken

* Add GetTokens test

* Add TestGetToken

* Add test for DeleteToken RPC

* Dedupe error assertions

* Add support for emitting trusted cluster token creation events to Create/UpsertToken

* Fix imports

* Change parameter order to appease linter

* Fix broken token expiry test

* Fix token expiry time for TestAuth_RegisterUsingToken

* Remove unnecessary cleanup

* Apply suggestions from code review

Co-authored-by: Alan Parra <alan.parra@goteleport.com>

* Change test comment from deprecation notice

* `make gprc` after code review changes

* Update lib/auth/tls_test.go

Co-authored-by: Alan Parra <alan.parra@goteleport.com>

* Update lib/auth/tls_test.go

Co-authored-by: Alan Parra <alan.parra@goteleport.com>

* Update lib/auth/tls_test.go

Co-authored-by: Alan Parra <alan.parra@goteleport.com>

* Update lib/auth/tls_test.go

Co-authored-by: Alan Parra <alan.parra@goteleport.com>

* Rename tests

* Update lib/auth/tls_test.go

Co-authored-by: Alan Parra <alan.parra@goteleport.com>

* More test cases for GetTokens

* Improve message on duplicate token

---------

Co-authored-by: Alan Parra <alan.parra@goteleport.com>
2023-02-16 09:36:55 +00:00
Tiago Silva 263884dab0 Change error response formatting for "/version" endpoint (#21289)
* Change formatting for "/version" endpoint

This PR changes the formatting for "/version" endpoint since Kubernetes
clients do not expect a JSON response on that endpoint.
This PR returns the error message directly into the body without any
formatting so that `kubectl` is able to present the desired error.

```
kubectl version --short
Flag --short has been deprecated, and will be removed in the future. The --short output will become the default.
Client Version: v1.25.4
Kustomize Version: v4.5.7
Error from server (InternalError): an error on the server ("this user cannot request kubernetes access, has no assigned groups or users") has prevented the request from succeeding
```

Fixes #20900

* change message wording

* add validation when generating kube creds

* fix typo
2023-02-14 20:44:54 +00:00
Tiago Silva a3ed4249c3 Fix kube agent shutdown during upgrades (#21537)
During binary upgrades, Teleport forks the agents and calls the shutdown
method for each one of them.

Kubernetes Agent was calling the `http.Server` shutdown method and which
wasn't stopping the heartbeats neither handling the listeners.
This PR fixes the shutdown behaviour for Kube agent and avoids deleting
the heartbeated resources when the agent is reloading.
2023-02-10 11:05:40 +00:00
Tiago Silva e5dfcba6ef Moderated sessions request is not forwarded into the leaf cluster (#21422)
* fix remote cluster redirection fail

* fix forwarder
2023-02-10 10:37:36 +00:00
Tiago Silva 1bbaf23d86 Add Pod resource search web API (#20183)
This PR introduces a web API for users to search, from the UI, for Kubernetes pods whose access is only granted by their `search_as_roles`.
The new API can be used to create access requests for those resources.

The new API is located
```bash
curl 'https://<proxy_endpoint>:3080/v1/webapi/sites/<teleport_cluster>/pods?kubeCluster=<kube_cluster>&kubeNamespace=<kube_namespace|empty>&searchAsRoles=yes&limit=10&startKey=&query=&search=&sort=name:asc' \
   | jq .
```
The JSON response:

```json
{
  "items": [
    {
      "kind": "pod",
      "name": "coredns-6d4b75cb6d-k84h9",
      "labels": [
        {
          "name": "k8s-app",
          "value": "kube-dns"
        },
        {
          "name": "pod-template-hash",
          "value": "6d4b75cb6d"
        }
      ],
      "namespace": "kube-system",
      "cluster": "minikube"
    },
    {
      "kind": "pod",
      "name": "etcd-minikube",
      "labels": [
        {
          "name": "component",
          "value": "etcd"
        },
        {
          "name": "tier",
          "value": "control-plane"
        }
      ],
      "namespace": "kube-system",
      "cluster": "minikube"
    },
    {
      "kind": "pod",
      "name": "kube-apiserver-minikube",
      "labels": [
        {
          "name": "component",
          "value": "kube-apiserver"
        },
        {
          "name": "tier",
          "value": "control-plane"
        }
      ],
      "namespace": "kube-system",
      "cluster": "minikube"
    },
    {
      "kind": "pod",
      "name": "kube-controller-manager-minikube",
      "labels": [
        {
          "name": "component",
          "value": "kube-controller-manager"
        },
        {
          "name": "tier",
          "value": "control-plane"
        }
      ],
      "namespace": "kube-system",
      "cluster": "minikube"
    },
    {
      "kind": "pod",
      "name": "kube-proxy-g7j5r",
      "labels": [
        {
          "name": "controller-revision-hash",
          "value": "94985b49"
        },
        {
          "name": "k8s-app",
          "value": "kube-proxy"
        },
        {
          "name": "pod-template-generation",
          "value": "1"
        }
      ],
      "namespace": "kube-system",
      "cluster": "minikube"
    },
    {
      "kind": "pod",
      "name": "kube-scheduler-minikube",
      "labels": [
        {
          "name": "component",
          "value": "kube-scheduler"
        },
        {
          "name": "tier",
          "value": "control-plane"
        }
      ],
      "namespace": "kube-system",
      "cluster": "minikube"
    },
    {
      "kind": "pod",
      "name": "nginx-deployment-6595874d85-6j2zm",
      "labels": [
        {
          "name": "app",
          "value": "nginx"
        },
        {
          "name": "pod-template-hash",
          "value": "6595874d85"
        }
      ],
      "namespace": "default",
      "cluster": "minikube"
    },
    {
      "kind": "pod",
      "name": "nginx-deployment-6595874d85-7xgmb",
      "labels": [
        {
          "name": "app",
          "value": "nginx"
        },
        {
          "name": "pod-template-hash",
          "value": "6595874d85"
        }
      ],
      "namespace": "default",
      "cluster": "minikube"
    },
    {
      "kind": "pod",
      "name": "nginx-deployment-6595874d85-c4kz8",
      "labels": [
        {
          "name": "app",
          "value": "nginx"
        },
        {
          "name": "pod-template-hash",
          "value": "6595874d85"
        }
      ],
      "namespace": "default",
      "cluster": "minikube"
    },
    {
      "kind": "pod",
      "name": "storage-provisioner",
      "labels": [
        {
          "name": "addonmanager.kubernetes.io/mode",
          "value": "Reconcile"
        },
        {
          "name": "integration-test",
          "value": "storage-provisioner"
        }
      ],
      "namespace": "kube-system",
      "cluster": "minikube"
    }
  ],
  "startKey": "teleport-agent-0",
  "totalCount": 11
}
```

Part of #20324 and #19573
Updates #19573
2023-02-09 21:29:58 +00:00
Jakub Nyckowski 79ebdc89c8 Bump golangci-lint to v1.51.1 (#21440) 2023-02-08 00:44:08 +00:00
Tiago Silva 4d09eea9b0 Add gRPC Kubernetes Service (#21103)
This PR introduces a gRPC service to retrieve the pods available using the `search_as_roles` configured in the user's roles.

This gRPC service receives a TLS identity and manipulates it to access the Teleport Kubernetes Proxy and retrieve the pods available for a hypothetical user that has the `search_as_roles` defined for its roles.
The response does not leak the certificate nor the pod details other than `name`, `namespace` and `labels`.

```mermaid
sequenceDiagram
    participant User as User
    participant gRPC as grpc Server
    participant Auth as Auth Server
    participant KubeProxy as Kube Proxy
    participant KubeSVC as Kube Service
    User->>+gRPC: ListKubeResources(cluster,namespace)
    Note left of gRPC: Includes search_as_roles <br/> and preview_as_roles <br/>into identity!
    gRPC-->>+Auth: Sign cert with ProcessKubeCSR
    Auth-->>-gRPC: Signed certificate
    gRPC->>+KubeProxy: list pods "v1.../namespaces/{namespace}/pods"
    KubeProxy-->>+KubeSVC: list pods "v1.../namespaces/{namespace}/pods"
    KubeSVC-->>-KubeProxy: filtered response
    Note left of KubeSVC: Applies Pod RBAC filtering!
    KubeProxy-->>-gRPC: response
    gRPC->>-User:Return name, namespace and labels
```

Part of #21107 and #19573
2023-02-06 22:45:31 +00:00
Tiago Silva df05a9385c Fix forwarding of impersonated headers for kubectl exec/portforward (#21102)
This PR fixes the impersonation headers propagation when using the SPDY
roundtrip. SPDY roundtrip creates a new http request and loses the
impersonation headers received from the client. When this happens for
users that define multiple `kubernetes_users`, the requests are denied
because Teleport forces you to select a user.

With the changes introduced we conserve the headers received from the
client.

Fixes #21088
2023-02-02 15:21:20 +00:00
David Boslee cc36d290a1 Add metrics to track connection ingress (#19734)
* Add metrics to track connection ingress

* Add connection unwrapping

* Add license

* Remove debug logging

* Add ingress reporter tests

* Remove circular dependency

* Fix import formatting

* Missing defer

* Fix spelling of accepted

* Add _total suffix to counters

* Add godocs and fix nits

* Add test for http conn state reporter

* Use loop to unwrap netConnGetters

* Test meterics after http conn closed

* Ensure conns implement conn getter interface
2023-02-01 23:45:34 +00:00
Tiago Silva 4e91b1e367 Fix data race when closing listener (#21002)
This PR fixes a data race when closing the listener.

Fixes #20998
2023-01-31 20:11:26 +00:00
Tiago Silva 89b20d6b3b Add support for compressed Kubernetes API responses (#20981)
This PR adds support for `gzip` compressed responses received from
the Kubernetes API.

Most Kubernetes vendors run with compression disabled since it causes a lot of CPU
spikes and timeouts but at least IBM cloud has it enabled.
(https://github.com/kubernetes/kubernetes/issues/112296)

Fixes #20980
2023-01-31 16:05:17 +00:00
Marek Smoliński 978fd03a22 Don't use the KubeSNIPrefix SNI TLS Routing Prefix (#20277)
* Don't use the KubeSNIPrefix SNI TLS Routing Prefix

* update ut

* update

* update

* Update

* update
2023-01-30 10:15:18 +00:00
Alan Parra 8ef8324b8c Enable role-based device authz for DB, k8s and SSH (#20640)
* Expose device verification methods in lib/devicetrust/authz

* Set device fields in auth.Context.GetAccessState

* Enable role-based device verification for SSH

* Enable role-based device verification for DBs

* Add TODO for better SSH error messages

* Do not override device error on lib/kube/proxy

* Run gci
2023-01-27 21:11:01 +00:00
Tiago Silva a420a0be57 Renew Kubernetes cluster credentials until the cluster is removed from inventory (#20786)
This PR renews the dynamic credentials until the cluster is removed instead of renewing it once.
2023-01-26 21:31:55 +00:00
Tiago Silva 605a7d00f4 Adds tsh kubectl support (#20031)
This PR implements a `kubectl` wrapper inside `tsh` that creates resource access requests, waits for their approval and retries the command when it detects that access to a pod was denied due to missing role or Kubernetes RBAC principals permissions.


Part of #18434
Updates #19573
2023-01-23 14:34:40 +00:00
Tiago Silva 10045bd349 Increase ReadDeadline to accommodate slow clients (#20468)
Increases deadline until the agent receives the first byte to 10s.
It's required to accommodate setups with high latency and where the time
between the TCP being accepted and the time for the first byte is longer
than the default value -  1s.

Fixes #20442
2023-01-21 10:18:07 +00:00
Tiago Silva 08e842540e Fix goroutine leaks during tests execution in /lib/kube/proxy package (#20330)
This PR fixes goroutine leaks that occur during the test run because some resources were cleaned up incorrectly.
2023-01-20 14:53:54 +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
Tiago Silva 071e36acf1 tsh, tctl support for creating Pod access requests (#20272)
This PR introduces support for creating resource access requests to `pod` resources to `tsh` and their approval from `tsh` and `tctl`. 

Adds support `tsh request create --resource /<cluster>/pod/<kube_cluster>/<namespace>/<podname>`.

Part of #18434
2023-01-17 17:12:31 +00:00
Tiago Silva c6d3f81f20 Disables TestListPodRBAC to run in parallel with other tests (#20267)
Running computationally expensive tests causes connection failures that lead to test failures.
This PR tries to overcome this problem by making only the subtests run in parallel.
2023-01-16 18:22:52 +00:00
Tiago Silva 7dde7c2811 Kubernetes Per-Pod RBAC (#19613)
This PR introduces a mechanism to control access to Pods in Kubernetes clusters based on access criteria defined in user Roles or Resource Access Requests.

New `Role` version - `v6` - introduced a new field `kubernetes_resources` that allows admins to restrict access to a subset of cluster resources based on the configuration provided. 
This PR implements the resource control for `pods` and allows 

```yaml
kubernetes_resources:
- kind: pod
  name: nginx-*
  namespace: default
- kind: pod
  name: *
  namespace: dev
```

It also implements the logic blocks for supporting Resource Access Requests to Kubernetes Pods. The tsh boilerplate is not included in this PR and will be included in future PRs.
An example of usage:

```
tsh request search --kind pod --kube-cluster=minikube
Name                              Namespace Labels                                 Resource ID
--------------------------------- --------- -------------------------------------- ---------------------------------------------
nginx-deployment-6595874d85-6j2zm default   app=nginx,pod-template-hash=6595874d85 /tele.teleport.local/pod/minikube/default/...
nginx-deployment-6595874d85-7xgmb default   app=nginx,pod-template-hash=6595874d85 /tele.teleport.local/pod/minikube/default/...
nginx-deployment-6595874d85-c4kz8 default   app=nginx,pod-template-hash=6595874d85 /tele.teleport.local/pod/minikube/default/...
test                              default   run=test                               /tele.teleport.local/pod/minikube/default/...

To request access to these resources, run
> tsh request create --resource /tele.teleport.local/pod/minikube/default/nginx-deployment-6595874d85-6j2zm --resource /tele.teleport.local/pod/minikube/default/nginx-deployment-6595874d85-7xgmb --resource /tele.teleport.local/pod/minikube/default/nginx-deployment-6595874d85-c4kz8 --resource /tele.teleport.local/pod/minikube/default/test \
    --reason <request reason>
```



Part of #18434
2023-01-13 14:44:13 +00:00
Tiago Silva fea5b84f81 Disables kubeconfig update on tsh login when --kube-cluster is empty (#19694)
This PR disables the update of kubeconfig when `tsh login` does not have the `--kube-cluster` flag.

The new behavior will update the kubeconfig only if the user provided a non-empty value in  `--kube-cluster`.

This PR also introduces a mechanism to restore the current context on `tsh logout`. On `tsh login --kube-cluster=<cluster>` or `tsh kube login <cluster>`, Teleport updates the selected context - if it's not from Teleport - to add an extension whose key is: `selected_context`. Once `tsh logout` is called and the active context was a Teleport cluster, we restore the current context to the cluster that has the `selected_context` key in extensions.

Fixes #9718
2023-01-12 12:00:07 +00:00
Alan Parra ba1282df62 Improve UserMetadata audit logging (#20081)
Improve UserMetadata audit logging by using `tlsca.Identity.GetUserMetadata()`
more consistently in audit logs.

There are still a handful of logs that don't include the data above for lack of
context (in the general sense and in the Go context sense), but many more
entries now call back to identity in some way.

Related to gravitational/teleport.e#514.
2023-01-11 21:03:17 +00:00
Brian Joerger 488af75797 Client store generalization (#19420)
- Add a generalized client store made up of a key, profile, and trusted certs store. Each sub store can support different backends (~/.tsh, identity_file, in-memory). 
- Replace custom identity file handling with in-memory client store.
- Fix issues with trusted certs handling.
2023-01-06 01:34:04 +00:00
Tiago Silva 6d98acfc03 Include active access requests into Kube Proxy credentials cache key (#19889)
When users access a cluster, Teleport caches their credentials to avoid generating a new cert key pair each time they run a command on the cluster. If the user's certificate includes an active access request that was later discarded, the Teleport Kubernetes Proxy continues to use the cached credentials - which include the dropped access request - resulting in subsequent requests being denied by Teleport. The problem persists even if the user assumes another access request that grants him access to the cluster.

This situation happens because Kubernetes Proxy stores in a TTL map the user's certificate to avoid generating and signing it each time the user hits the proxy. The lookup in cache happens using a key that includes the `kubeCluster`, `username`, `certificate_expiration`, `kube_users`, and `kube_groups` but does not include the `active_requests`.

This PR adds the `active_requests` into the cache's key to distinguish different certificate requests for the same user.

Fixes #19884
2023-01-05 17:42:44 +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
Tiago Silva dd39253288 Fixes TestModeratedSessions flaky test (#19878)
The `fileStreamer` continues to write events after the server shuts down and races against the `os.RemoveAll` call during the test cleanup causing the test to fail.

Using `node-sync` recording mode to write the events and session recordings directly to AuthClient solves the issue.

Fixes #19847
2023-01-04 23:04:59 +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
Tiago Silva ae90d5f4df Fix goroutine leak when using multiResizeQueue and spdy connection leak (#19732)
This PR fixes multiple goroutine and memory leaks when interactive sessions are used. 

- When the session terminates, the `multiResizeQueue` never returns, and the resize stream goroutine blocks. 
- A goroutine leak exited when the server received resizing events after the connection terminated - this happens with fast exec requests.
- A memory leak existed when users tried to leave the session after the `session.tracker` was closed. 

This PR also releases the connection monitor earlier. When the server is under heavy load, it might take a while for the connection to return an `EOF` - which triggers the service monitor automatic release - and the service monitor resources were leaking until the server resumed normal operation.

It also fixes reloads when new parties join and leave the `multiResizeQueue`.
2022-12-31 14:43:27 +00:00
Tiago Silva c3fe7c092f Update Kubernetes Dependencies (#19695)
This PR replaces the following PRs opened by dependabot:
- #19678 
- #19677 

It also bumps:

- Bump k8s.io/api from v0.25.4 to v0.26.0
- Bump k8s.io/apiextensions-apiserver from v0.25.4 to v0.26.0
- Bump k8s.io/apimachinery from v0.25.4 to v0.26.0
- Bump k8s.io/apiserver from v0.25.4 to v0.26.0
- Bump k8s.io/cli-runtime from v0.25.4 to v0.26.0
- Bump k8s.io/kubectl from v0.25.4 to v0.26.0
- Bump k8s.io/utils v0.0.0-20220728103510-ee6ede2d64ed to v0.0.0-20221128185143-99ec85e7a448
- Bump sigs.k8s.io/controller-runtime from v0.13.1 to v0.14.1
2022-12-29 22:49:22 +00:00
Anton Miniailo a039ce1cf9 Add secure IP propagation from teleport proxy to auth server via ALPN (#19008)
* Add secure IP propagation from proxy to auth server when using ALPN

We're using PROXY protocol extensions called TLVs to send
signed JWT and proxy's certificate to the auth server. Auth
validates JWT using provided signing certificate and host CA
to make sure that IP information comes from our internal proxy.
2022-12-23 22:12:42 +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