Commit graph

346 commits

Author SHA1 Message Date
Sasha Klizhentas c0bb732545 Adds ACME - auto cert management
This commit fixes #5177

Initial implementation uses dir backend as a cache and is OK
for small clusters, but will be a problem for many proxies.

This implementation uses Go autocert that is quite limited
compared to Caddy's certmagic or lego.

Autocert has no OCSP stapling and no locking for cache for example.
However, it is much simpler and has no dependencies.
It will be easier to extend to use Teleport backend as a cert cache.

```yaml
proxy_service:
  public_addr: ['example.com']
  # ACME - automatic certificate management environment.
  #
  # It provisions certificates for domains and
  # valid subdomains in public_addr section.
  #
  # The sudomains are valid if there is a registered application.
  # For example, app.example.com will get a cert if app is a regsitered
  # application access app. The sudomain cookie.example.com is not.
  #
  # Teleport acme is using TLS-ALPN-01 challenge:
  #
  # https://letsencrypt.org/docs/challenge-types/#tls-alpn-01
  #
  acme:
    # By default acme is disabled.
    enabled: true
    # Use a custom URI, for example staging is
    #
    # https://acme-staging-v02.api.letsencrypt.org/directory
    #
    # Default is letsencrypt.org production URL:
    #
    # https://acme-v02.api.letsencrypt.org/directory
    uri: ''
    # Set email to receive alerts and other correspondence
    # from your certificate authority.
    email: 'alice@example.com'
```
2020-12-22 17:33:20 -08:00
a-palchikov ca60c7eb35
Add SetLevel to utils.Logger interface (#5082) 2020-12-11 12:59:09 +01:00
a-palchikov 7c87576a8b
flaky tests: consistent logging (#4849)
* Update logrus package to fix data races
* Introduce a logger that uses the test context to log the messages so they are output if a test fails for improved trouble-shooting.
* Revert introduction of test logger - simply leave logger configuration at debug level outputting to stderr during tests.
* Run integration test for e as well
* Use make with a cap and append to only copy the relevant roles.
* Address review comments
* Update integration test suite to use test-local logger that would only output logs iff a specific test has failed - no logs from other test cases will be output.
* Revert changes to InitLoggerForTests API
* Create a new logger instance when applying defaults or merging with file service configuration
* Introduce a local logger interface to be able to test file configuration merge.
* Fix kube integration tests w.r.t log
* Move goroutine profile dump into a separate func to handle parameters consistently for all invocations
2020-12-07 15:35:15 +01:00
Andrew Lytvynov c6832ec606
Set server_addr in audit events from connection info (#4985)
This sets a useful server IP, when no advertise_ip is set. Previously,
the address was taken from the listener, and is usually "0.0.0.0:3022"
or "[::]:3022".

Also, add some test cases in utils for IPv6 handling.
2020-11-25 12:08:37 -08:00
Ben Arent 09928a7f2b
Cherry pick Gravitational -> GoTeleport (#4932) 2020-11-25 11:18:55 -08:00
Andrew Lytvynov aceffd9a35
Add more data to k8s session events (#4858)
Added fields:
- kube users/groups
- pod name/namespace
- container name/image
- node name

Container image and node name need to be fetched from the k8s API, they
are not known from just the client request. This fetch is optional, and
if it fails (like due to permission errors), those fields will be
missing.

Since kubernetes_service can talk to k8s API and proxy_service can't,
all session events are now emitted by kubernetes_service and skipped by
the proxy (used to be the other way around).
2020-11-17 23:46:51 +00:00
Andrew Lytvynov 43178f34d8
Add a depth limit to RBAC expression parser (#4848)
Our current parsing code runtime grows exponentially with nested
selectors (e.g. '{{a.b.c.d.e.f}}'), mostly due to memory churn from
slice allocations. With 100,000 levels of selectors, parsing takes ~80s
on my machine.
If an attacker can submit these expressions for parsing, they can DoS
the auth server with relatively small payloads (<1MB).

All real-world expressions are <10 AST nodes deep. Add a sanity check of
1000 levels to protect against malicious inputs.

We can optimize the code later on, but it's not very useful for real
world performance.
2020-11-17 18:53:38 +00:00
Sasha Klizhentas c623aa4dc5 Add cluster labels
Fixes #3604

This commit adds support for cluster_labels
role parameter limiting access to remote clusters by label.
New tctl update rc provides interface to set labels on remote clusters.

Consider two clusers, `one` - root and `remote` - leaf.

```bash
$ tsh clusters
Cluster Name Status
------------ ------
one          online
two          online
```

Create the trusted cluster join token with labels:

```bash
$ tctl tokens add --type=trusted_cluster --labels=env=prod
```

Every cluster joined using this token will inherit env:prod labels.

Alternatively, update remote cluster labels by modifying
`rc` command. Letting remote clusters to propagate their labels
creates a problem of rogue clusters updating their labels to bad values.

Instead, administrator of root cluster control the labels
using remote clusters API without fear of override:

```bash
$ tctl get rc

kind: remote_cluster
metadata:
  name: two
status:
  connection: online
  last_heartbeat: "2020-09-14T03:13:59.35518164Z"
version: v3
```

```bash
$ tctl update rc/two --set-labels=env=prod

cluster two has been updated
```

```bash
$ tctl get rc
kind: remote_cluster
metadata:
  labels:
    env: prod
  name: two
status:
  connection: online
  last_heartbeat: "2020-09-14T03:13:59.35518164Z"
```

Update the role to deny access to prod env:

```yaml
kind: role
metadata:
  name: dev
spec:
  allow:
    logins: [root]
    node_labels:
      '*': '*'

    # Cluster labels control what clusters user can connect to. The wildcard ('*') means
    # any cluster. If no role in the role set is using labels and cluster is not labeled,
    # the cluster labels check is not applied. Otherwise, cluster labels are always enforced.
    # This makes the feature backwards-compatible.
    cluster_labels:
      'env': 'staging'
  deny:
    # cluster labels control what clusters user can connect to. The wildcard ('*') means
    # any cluster. By default none is set in deny rules to preserve backwards compatibility
    cluster_labels:
      'env': 'prod'
```

```bash
$ tctl create -f dev.yaml
```

Cluster two is now invisible to user with `dev` role.

```bash
$ tsh clusters
Cluster Name Status
------------ ------
one          online
```
2020-11-03 16:10:15 -08:00
Russell Jones 904b0d0488 Added Application Access.
Added support for an identity aware, RBAC enforcing, mutually
authenticated, web application proxy to Teleport.

* Updated services.Server to support an application servers.
* Updated services.WebSession to support application sessions.
* Added CRUD RPCs for "AppServers".
* Added CRUD RPCs for "AppSessions".
* Added RBAC support using labels for applications.
* Added JWT signer as a services.CertAuthority type.
* Added support for signing and verifying JWT tokens.
* Refactored dynamic label and heartbeat code into standalone packages.
* Added application support to web proxies and new "app_service" to
  proxy mutually authenticated connections from proxy to an internal
  application.
2020-11-03 14:32:13 -08:00
Brian Joerger 9379b676f1
Add new helper function for parsing multiple addresses at once. (#4675) 2020-11-03 13:50:22 -08:00
Andrew Lytvynov 5ec194cd0d
Implement kubernetes_service registration and startup (#4611)
* Implement kubernetes_service registration and sratup

The new service now starts, registers (locally or via a join token) and
heartbeats its presence to the auth server.

This service can handle k8s requests (like a proxy) but not to remote
teleport clusters. Proxies will be responsible for routing those.
The client (tsh) will not yet go to this service, until proxy routing is
implemented. I manually tweaked server addres in kubeconfig to test it.

You can also run `tctl get kube_service` to list all registered
instances. The self-reported info is currently limited - only listening
address is set.

* Address review feedback
2020-10-30 17:19:53 +00:00
Sasha Klizhentas 7b8bfe4f60 Backoff on network errors and mark corrupted records.
Uploader retries slower on network errors and picks the pace
after any upload has succeeded.

Records that were corrupted, will never get uploaded.

The uploader will create streams indefinitely, clogging the auth server
with streams. Now uploader writes marker for bad session uploads
and does not attempt to reupload.
2020-10-21 14:33:04 -07:00
Andrew Lytvynov 566b7cc457 RFD 1: user testify/require instead of testify/assert
`require` is a sister package to `assert` that terminates the test on
failure. `assert` records the failure but lets the test proceed, which
is un-intuitive.

Also update all existing tests to match.
2020-10-16 00:15:25 +00:00
Andrew Lytvynov 01516c5744 Partial revert of negative regexps in RBAC labels
This change was not backwards compatible - variable interpolation should
work in node_labels.

This commit partially reverts
https://github.com/gravitational/teleport/pull/4253 and
https://github.com/gravitational/teleport/pull/4430
2020-10-15 21:46:06 +00: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
Sasha Klizhentas c1b1c6a154 Improves logging and error handling in filesessions.
Adds chaos tests for async file upload.

Fixes playback for legacy sessions stored unpacked on disk
2020-10-06 13:41:17 -07:00
Andrew Lytvynov 63da43245e Validate node_labels syntax at role creation time
Also improve error output and user validation.
Based on missed feedback in https://github.com/gravitational/teleport/pull/4253#pullrequestreview-499061448
2020-10-05 18:00:55 +00:00
Andrew Lytvynov 5d357db004 Improve error logging for identity file parsing
Addresses feedback from https://github.com/gravitational/teleport/pull/4318#pullrequestreview-499067377

- improve error logging to be more actionable
- add missing license headers to files
- use utils.SyncBuffer in testlog.FailuresOnly
2020-10-02 17:05:19 +00:00
Andrew Lytvynov 75d7fbb508 Migrate services.MatchLabels to parse.Matcher
This should be backwards-compatible plus add the {{regexp.match(...)}}
and {{regexp.not_match(...)}} functions.
2020-09-29 21:25:50 +00:00
Andrew Lytvynov 1330415d33 utils/parse: implement Matcher
Matchers use a similar syntax to Expressions, but behave differently:
- Expressions get evaluated - they interpolate some values and return a
  final string.
- Matchers check whether some string matches a value

Matchers implement the same logic as utils.SliceMatchesRegex and add 2
new functions:
- {{regexp.match("foo")}} - match input against a raw regex
- {{regexp.not_match("foo")}} - same as match, but inverts the result
2020-09-29 21:25:50 +00:00
Andrew Lytvynov bb69574e02 utils/parse: support string literal expressions
No need to handle literal expressions (e.g. without "{{foo.bar}}"
substitutions) at the higher level. Something like "foo" is a valid
expression which always returns "foo" regardless of traits.
2020-09-29 21:25:50 +00:00
Andrew Lytvynov e9b7a25d6a utils/parse: rewrite tests in the new RFD style 2020-09-29 21:25:50 +00:00
Andrew Lytvynov d91716e150 Unit tests for user reverse tunnels 2020-09-29 21:03:42 +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
Forrest Marshall ae2336dfd0 concurrent session control
Adds support for Concurrent Session Control and a new
semaphore API.  Roles now support two new configuration
options, `max_ssh_connections` and `max_ssh_sessions`
which correspond to the total number of authenticated
ssh connections per cluster, and the number of ssh sessions
within a connection respectively.  Attempting to exceed
these limits generate variants of the `session.rejected`
audit event and cause the connection/session to be
rejected.
2020-09-17 11:02:35 -07:00
Sasha Klizhentas 0f4e82548f Initial work on semaphores 2020-09-17 11:02:35 -07:00
quin quintero dc267752fc
Updated message when user without ~/.tsh logs out (#4200)
* return only trace.NotFound

* supressed error message when user does not have ~/.tsh directory

* return only trace.NotFound

* handled permission issue and file path not found error

* formatting

* nit

* Make milv happy

* Revert "Make milv happy"

This reverts commit 5a24e9f725.

Co-authored-by: Ben Arent <ben@gravitational.com>
2020-09-09 22:44:30 +00:00
Joshua Behrens 19d482dad3
Allow user with at sign in name (#4002)
* Allow @ in scp targets
* Allow @ in proxyjump usernames
* Allow @ in tsh usernames
2020-07-21 10:41:31 -03:00
Andrew Lytvynov 617afc7e6f Fix remaining gosimple findings
List of fixed items:

```
integration/helpers.go:1279:2               gosimple  S1000: should use for range instead of for { select {} }
integration/integration_test.go:144:5       gosimple  S1009: should omit nil check; len() for nil slices is defined as zero
integration/integration_test.go:173:5       gosimple  S1009: should omit nil check; len() for nil slices is defined as zero
integration/integration_test.go:296:28      gosimple  S1019: should use make(chan error) instead
integration/integration_test.go:570:41      gosimple  S1019: should use make(chan interface{}) instead
integration/integration_test.go:685:40      gosimple  S1019: should use make(chan interface{}) instead
integration/integration_test.go:759:33      gosimple  S1019: should use make(chan string) instead
lib/auth/init_test.go:62:2                  gosimple  S1021: should merge variable declaration with assignment on next line
lib/auth/tls_test.go:1658:22                gosimple  S1024: should use time.Until instead of t.Sub(time.Now())
lib/backend/dynamo/dynamodbbk.go:420:5      gosimple  S1004: should use !bytes.Equal(expected.Key, replaceWith.Key) instead
lib/backend/dynamo/dynamodbbk.go:656:12     gosimple  S1039: unnecessary use of fmt.Sprintf
lib/backend/etcdbk/etcd.go:458:5            gosimple  S1004: should use !bytes.Equal(expected.Key, replaceWith.Key) instead
lib/backend/firestore/firestorebk.go:407:5  gosimple  S1004: should use !bytes.Equal(expected.Key, replaceWith.Key) instead
lib/backend/lite/lite.go:317:5              gosimple  S1004: should use !bytes.Equal(expected.Key, replaceWith.Key) instead
lib/backend/lite/lite.go:336:6              gosimple  S1004: should use !bytes.Equal(value, expected.Value) instead
lib/backend/memory/memory.go:365:5          gosimple  S1004: should use !bytes.Equal(expected.Key, replaceWith.Key) instead
lib/backend/memory/memory.go:376:5          gosimple  S1004: should use !bytes.Equal(existingItem.Value, expected.Value) instead
lib/backend/test/suite.go:327:10            gosimple  S1024: should use time.Until instead of t.Sub(time.Now())
lib/client/api.go:1410:9                    gosimple  S1003: should use strings.ContainsRune(name, ':') instead
lib/client/api.go:2355:32                   gosimple  S1019: should use make([]ForwardedPort, len(spec)) instead
lib/client/keyagent_test.go:85:2            gosimple  S1021: should merge variable declaration with assignment on next line
lib/client/player.go:54:33                  gosimple  S1019: should use make(chan int) instead
lib/config/configuration.go:1024:52         gosimple  S1019: should use make(services.CommandLabels) instead
lib/config/configuration.go:1025:44         gosimple  S1019: should use make(map[string]string) instead
lib/config/configuration.go:930:21          gosimple  S1003: should use strings.Contains(clf.Roles, defaults.RoleNode) instead
lib/config/configuration.go:931:22          gosimple  S1003: should use strings.Contains(clf.Roles, defaults.RoleAuthService) instead
lib/config/configuration.go:932:23          gosimple  S1003: should use strings.Contains(clf.Roles, defaults.RoleProxy) instead
lib/service/supervisor.go:387:2             gosimple  S1001: should use copy() instead of a loop
lib/tlsca/parsegen.go:140:9                 gosimple  S1034: assigning the result of this type assertion to a variable (switch generalKey := generalKey.(type)) could eliminate type assertions in switch cases
lib/utils/certs.go:140:9                    gosimple  S1034: assigning the result of this type assertion to a variable (switch generalKey := generalKey.(type)) could eliminate type assertions in switch cases
lib/utils/certs.go:167:40                   gosimple  S1010: should omit second index in slice, s[a:len(s)] is identical to s[a:]
lib/utils/certs.go:204:5                    gosimple  S1004: should use !bytes.Equal(certificateChain[0].SubjectKeyId, certificateChain[0].AuthorityKeyId) instead
lib/utils/parse/parse.go:116:45             gosimple  S1003: should use strings.Contains(variable, "}}") instead
lib/utils/parse/parse.go:116:6              gosimple  S1003: should use strings.Contains(variable, "{{") instead
lib/utils/socks/socks.go:192:10             gosimple  S1025: should use String() instead of fmt.Sprintf
lib/utils/socks/socks.go:199:10             gosimple  S1025: should use String() instead of fmt.Sprintf
lib/web/apiserver.go:1054:18                gosimple  S1024: should use time.Until instead of t.Sub(time.Now())
lib/web/apiserver.go:1954:9                 gosimple  S1039: unnecessary use of fmt.Sprintf
tool/tsh/tsh.go:1193:14                     gosimple  S1024: should use time.Until instead of t.Sub(time.Now())
```
2020-05-27 19:36:38 +00:00
Andrew Lytvynov d5c26cc1d7 Auto-assign ports in utils.LoadBalancer tests
Expose the listening address via new Addr() method.
2020-05-21 20:38:37 +00:00
Andrew Lytvynov d52ca0617d Add missing error checks in lib/srv and lib/sshutils
There's many more left in lib/srv, but this change is already big.
Some errors are left unhandled, where it makes sense.
2020-05-15 16:56:44 +00:00
Andrew Lytvynov a48c40ad78 gosimple: replace time.Now().Sub(x) with time.Since(x) 2020-05-15 16:32:45 +00:00
Andrew Lytvynov e5478c937d Remove unnecessary type conversions
Caught by `unconvert` linter. No behavior changes here.
2020-05-11 16:44:27 +00:00
Andrew Lytvynov 44cfbd4b6d Fix common misspellings detected by misspell linter 2020-05-11 16:44:27 +00:00
Andrew Lytvynov b1eae4ac4c Remove unused functions and methods throughout lib/...
This code is not caught by linters because it's exported and they assume
there's some external users.
Since teleport is relatively self-contained, we can tell for sure
whether something is called or not.
2020-05-06 00:02:53 +00:00
Andrew Lytvynov bdd388e0d0 Fix remaining staticcheck findings in lib/...
Fixed findings:
```
lib/sshutils/server_test.go:163:2: SA4006: this value of `clt` is never used (staticcheck)
	clt, err := ssh.Dial("tcp", srv.Addr(), &cc)
	^
lib/sshutils/server_test.go:91:3: SA5001: should check returned error before deferring ch.Close() (staticcheck)
		defer ch.Close()
		^
lib/shell/shell_test.go:33:2: SA4006: this value of `shell` is never used (staticcheck)
	shell, err = GetLoginShell("non-existent-user")
	^
lib/cgroup/cgroup_test.go:111:2: SA9003: empty branch (staticcheck)
	if err != nil {
	^
lib/cgroup/cgroup_test.go:119:2: SA5001: should check returned error before deferring service.Close() (staticcheck)
	defer service.Close()
	^
lib/client/keystore_test.go:138:2: SA4006: this value of `keyCopy` is never used (staticcheck)
	keyCopy, err = s.store.GetKey("host.a", "bob")
	^
lib/client/api.go:1604:3: SA4004: the surrounding loop is unconditionally terminated (staticcheck)
		return makeProxyClient(sshClient, m), nil
		^
lib/backend/test/suite.go:156:2: SA4006: this value of `err` is never used (staticcheck)
	result, err = s.B.GetRange(ctx, prefix("/prefix/c/c1"), backend.RangeEnd(prefix("/prefix/c/cz")), backend.NoLimit)
	^
lib/utils/timeout_test.go:84:2: SA1019: t.Dial is deprecated: Use DialContext instead, which allows the transport to cancel dials as soon as they are no longer needed. If both are set, DialContext takes priority.  (staticcheck)
	t.Dial = func(network string, addr string) (net.Conn, error) {
	^
lib/utils/websocketwriter.go:83:3: SA4006: this value of `err` is never used (staticcheck)
		utf8, err = w.encoder.String(string(data))
		^
lib/utils/loadbalancer_test.go:134:2: SA4006: this value of `out` is never used (staticcheck)
	out, err = Roundtrip(frontend.String())
	^
lib/utils/loadbalancer_test.go:209:2: SA4006: this value of `out` is never used (staticcheck)
	out, err = RoundtripWithConn(conn)
	^
lib/srv/forward/sshserver.go:582:3: SA4004: the surrounding loop is unconditionally terminated (staticcheck)
		return
		^
lib/service/service.go:347:4: SA4006: this value of `err` is never used (staticcheck)
			i, err = auth.GenerateIdentity(process.localAuth, id, principals, dnsNames)
			^
lib/service/signals.go:60:3: SA1016: syscall.SIGKILL cannot be trapped (did you mean syscall.SIGTERM?) (staticcheck)
		syscall.SIGKILL, // fast shutdown
		^
lib/config/configuration_test.go:184:2: SA4006: this value of `conf` is never used (staticcheck)
	conf, err = ReadFromFile(s.configFileBadContent)
	^
lib/config/configuration.go:129:2: SA5001: should check returned error before deferring reader.Close() (staticcheck)
	defer reader.Close()
	^
lib/kube/kubeconfig/kubeconfig_test.go:227:2: SA4006: this value of `err` is never used (staticcheck)
	tlsCert, err := ca.GenerateCertificate(tlsca.CertificateRequest{
	^
lib/srv/sess.go:720:3: SA4006: this value of `err` is never used (staticcheck)
		result, err := s.term.Wait()
		^
lib/multiplexer/multiplexer_test.go:169:11: SA1006: printf-style function with dynamic format string and no further arguments should use print-style function instead (staticcheck)
	_, err = fmt.Fprintf(conn, proxyLine.String())
	        ^
lib/multiplexer/multiplexer_test.go:221:11: SA1006: printf-style function with dynamic format string and no further arguments should use print-style function instead (staticcheck)
	_, err = fmt.Fprintf(conn, proxyLine.String())
	        ^
```
2020-04-28 15:17:44 +00:00
Andrew Lytvynov 7ccdd87496 Enable more Go linters: varcheck,bodyclose,structcheck
All changes should be noop, except for
`integration/integration_test.go`.

The integration test was ignoring `recordingMode` test case parameter
and always used `RecordAtNode`. When switching to `recordingMode`, test
cases with `RecordAtProxy` fail with a confusing error about missing
user agent. Filed https://github.com/gravitational/teleport/issues/3606
to track that separately and unblock enabling `structcheck` linter.
2020-04-24 15:52:43 +00:00
Forrest Marshall 4e9eed9ac0 cache event fanout & reversetunnel improvements
- cache now perforams in-memory fanout of events, eliminating
spurious event generation due to cache init/reset.

- removed old unused logic from reversetunnel agents.

- replaced seekpool with simpler ttl-cache and semaphore-like
lease system.

- add jittered backoff to agent connection attempts to
reduce "thundering herd" effect.

- improved reversetunnel logging.

- improved LB usage in tests.
2020-04-23 14:03:52 -07:00
Andrew Lytvynov be8d931877 Fix a data race in utils.SyncBuffer
`SyncBuffer` has a goroutine running `io.Copy` to read from the
underlying pipe. Close stops the pipe, but doesn't wait for the last
chunk of data to be written by `io.Copy` to the buffer.

Both `Bytes` and `String` assume that the buffer received no further
writes after `Close`.

Add explicit synchronization between `io.Copy` goroutine and `Close`.
2020-04-17 20:05:38 +00:00
Andrew Lytvynov d1ea40d074 Enable linters: deadcode,goimports,govet,typecheck
And fix the relevant findings for these linters.

Also, set extra flags for `golangci-lint run` to make sure no findings
are suppressed.
2020-04-17 17:46:51 +00:00
Andrew Lytvynov f8661edea3 Clean up dead code across the codebase
Spring cleaning!
A very mechanical cleanup using several linters (unused, deadcode,
structcheck). Build and tests still pass so no behavior should be
affected.
2020-04-09 21:10:12 +00:00
Alexander Klizhentas 73ecb48232
Adds support for kubernetes_users, extend interpolation (#3404) (#3418)
This commit fixes #3369, refs #3374

It adds support for kuberenetes_users section in roles,
allowing Teleport proxy to impersonate user identities.

It also extends variable interpolation syntax by adding
suffix and prefix to variables and function `email.local`:

Example:

```yaml
kind: role
version: v3
metadata:
  name: admin
spec:
  allow:
    # extract email local part from the email claim
    logins: ['{{email.local(external.email)}}']

    # impersonate a kubernetes user with IAM prefix
    kubernetes_users: ['IAM#{{external.email}}']

  # the deny section uses the identical format as the 'allow' section.
  # the deny rules always override allow rules.
  deny: {}
```

Some notes on email.local behavior:

* This is the only function supported in the template variables for now
* In case if the email.local will encounter invalid email address,
it will interpolate to empty value, will be removed from resulting
output.

Changes in impersonation behavior:

* By default, if no kubernetes_users is set, which is a majority of cases,
  user will impersonate themselves, which is the backwards-compatible behavior.

* As long as at least one `kubernetes_users` is set, the forwarder will start
  limiting the list of users allowed by the client to impersonate.

* If the users' role set does not include actual user name, it will be rejected,
  otherwise there will be no way to exclude the user from the list).

* If the `kuberentes_users` role set includes only one user
  (quite frequently that's the real intent), teleport will default to it,
  otherwise it will refuse to select.

  This will enable the use case when `kubernetes_users` has just one field to
  link the user identity with the IAM role, for example `IAM#{{external.email}}`

* Previous versions of the forwarding proxy were denying all external
impersonation headers, this commit allows 'Impesrsonate-User' and
'Impersonate-Group' header values that are allowed by role set.

* Previous versions of the forwarding proxy ignored 'Deny' section of the roles
when applied to impersonation, this commit fixes that - roles with deny
kubernetes_users and kubernetes_groups section will not allow
impersonation of those users and groups.
2020-03-07 16:32:37 -08:00
Russell Jones b3b4b1556a Fix kernel verson lookup for RHEL/CentOS 8.
Drop everything after "-" when looking up the kernel version to make it
easier for the semver library to compare kernel versions.
2020-01-20 14:04:36 -08:00
Benjamin Alpert 219cada7cc Added S3 third party support (#3054) 2020-01-02 17:56:53 -08:00
Russell Jones 77e8b63470 Enhanced Session Recording.
Added package cgroup to orchestrate cgroups. Only support for cgroup2
was added to utilize because cgroup2 cgroups have unique IDs that can be
used correlated with BPF events.

Added bpf package that contains three BPF programs: execsnoop,
opensnoop, and tcpconnect. The bpf package starts and stops these
programs as well  correlating their output with Teleport sessions
and emitting them to the audit log.

Added support for Teleport to re-exec itself before launching a shell.
This allows Teleport to start a child process, capture it's PID, place
the PID in a cgroup, and then continue to process. Once the process is
continued it can be tracked by it's cgroup ID.

Reduced the total number of connections to a host so Teleport does not
quickly exhaust all file descriptors. Exhausting all file descriptors
happens very quickly when disk events are emitted to the audit log which
are emitted at a very high rate.

Added tarballs for exec sessions. Updated session.start and session.end
events with additional metadata. Updated the format of session tarballs
to include enhanced events.

Added file configuration for enhanced session recording. Added code to
startup enhanced session recording and pass package to SSH nodes.
2019-12-02 15:10:39 -08:00
Jie Yu a1542f53a3 Fix a bug in socks5 when rendering remote address
When the remote address is an IP address, we cannot directly convert
byte array to string. Otherwise, we will see hex strings like
"\xac\x11\x01\xc8:443".

See more details about the bug in:
https://community.gravitational.com/t/ssh-dynamic-port-forwarding-not-working/432

The above reported issue is resolved after applying the patch.
2019-11-05 12:02:34 -08:00
Russell Jones 3e826e5c92 Update default ciphersuites.
Drop TLS_RSA_WITH_AES_128_GCM_SHA{256,384} from default ciphersuites
due to being banned by HTTP2 which breaks GRPC clients. For more
information see: https://tools.ietf.org/html/rfc7540#appendix-A.

This has a nice side effect of Teleport now only supporting ciphersuites
that support PFS.

Note that both ciphersuites can still be be added back in file
configuration.
2019-10-24 15:15:55 -07:00
Roman Tkachenko 07b25088ec Remote tctl execution. (#2991)
* Teach tctl to use remote auth servers and identity.

* Tests and cleanups.
2019-09-24 14:01:30 -07:00
Russell Jones 8bd706d56a Validate incoming events against x509 identity.
Validate all incoming events (and archives) to ensure that the server ID
within the event matches the x509 identity of the connected host. This
check makes sure nodes can only submit events for themselves.

In addition, make sure session recordings to disk or S3 can not be
overwritten.
2019-09-03 13:44:20 -07:00
Russell Jones 3eb31bd867 Sanitize tar paths before extraction.
When extracting tar archive, don't allow files to be extracted outside
the specified directory.
2019-09-03 13:44:20 -07:00