events

package
v1.3.3-0...-f31c912 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 9, 2024 License: AGPL-3.0 Imports: 40 Imported by: 347

Documentation

Overview

Package events implements the audit log interface events.IAuditLog using filesystem backend.

Audit logs ----------

Audit logs are events associated with user logins, server access and session log events like session.start.

Example audit log event:

{"addr.local":"172.10.1.20:3022",

 "addr.remote":"172.10.1.254:58866",
 "event":"session.start",
 "login":"root",
 "user":"klizhentas@gmail.com"
}

Session Logs ------------

Session logs are a series of events and recorded SSH interactive session playback.

Example session log event:

{
  "time":"2018-01-04T02:12:40.245Z",
  "event":"print",
  "bytes":936,
  "ms":40962,
  "offset":16842,
  "ei":31,
  "ci":29
}

Print event fields ------------------

Print event specifies session output - PTY io recorded by Teleport node or Proxy based on the configuration.

* "offset" is an offset in bytes from a start of a session * "ms" is a delay in milliseconds from the last event occurred * "ci" is a chunk index ordering only print events * "ei" is an event index ordering events from the first one

As in example of print event above, "ei" - is a session event index - 31, while "ci" is a chunk index - meaning that this event is 29th in a row of print events.

Client streaming session logs ------------------------------

Session related logs are delivered in order defined by clients. Every event is ordered and has a session-local index, every next event has index incremented.

Client delivers session events in batches, where every event in the batch is guaranteed to be in continuous order (e.g. no cases with events delivered in a single batch to have missing event or chunk index).

Disk File format ----------------

On disk file format is designed to be compatible with NFS filesystems and provides guarantee that only one auth server writes to the file at a time.

Main Audit Log Format =====================

The main log files are saved as:

/var/lib/teleport/log/<auth-server-id>/<date>.log

The log file is rotated every 24 hours. The old files must be cleaned up or archived by an external tool.

Log file format: utc_date,action,json_fields

Common JSON fields - user : teleport user - login : server OS login, the user logged in as - addr.local : server address:port - addr.remote: connected client's address:port - sid : session ID (GUID format)

Examples: 2016-04-25 22:37:29 +0000 UTC,session.start,{"addr.local":"127.0.0.1:3022","addr.remote":"127.0.0.1:35732","login":"root","sid":"4a9d97de-0b36-11e6-a0b3-d8cb8ae5080e","user":"vincent"} 2016-04-25 22:54:31 +0000 UTC,exec,{"addr.local":"127.0.0.1:3022","addr.remote":"127.0.0.1:35949","command":"-bash -c ls /","login":"root","user":"vincent"}

Session log file format =======================

Each session has its own session log stored as several files:

Index file contains a list of event files and chunks files associated with a session:

/var/lib/teleport/log/sessions/<auth-server-id>/<session-id>.index

The format of the index file contains of two or more lines with pointers to other files:

{"file_name":"<session-id>-<first-event-in-file-index>.events","type":"events","index":<first-event-in-file-index>} {"file_name":"<session-id>-<first-chunk-in-file-offset>.chunks","type":"chunks","offset":<first-chunk-in-file-offset>}

Files:

/var/lib/teleport/log/<auth-server-id>/<session-id>-<first-event-in-file-index>.events
/var/lib/teleport/log/<auth-server-id>/<session-id>-<first-chunk-in-file-offset>.chunks

Where:

  • .events (same events as in the main log, but related to the session)
  • .chunks (recorded session bytes: PTY IO)

Examples ~~~~~~~~

**Single auth server**

In the simplest case, single auth server a1 log for a single session id s1 will consist of three files:

/var/lib/teleport/a1/s1.index

With contents:

{"file_name":"s1-0.events","type":"events","index":0} {"file_name":"s1-0.chunks","type":"chunks","offset":0}

This means that all session events are located in s1-0.events file starting from the first event with index 0 and all chunks are located in file s1-0.chunks file with the byte offset from the start - 0.

File with session events /var/lib/teleport/a1/s1-0.events will contain:

{"ei":0,"event":"session.start", ...} {"ei":1,"event":"resize",...} {"ei":2,"ci":0, "event":"print","bytes":40,"offset":0} {"ei":3,"event":"session.end", ...}

File with recorded session /var/lib/teleport/a1/s1-0.chunks will contain 40 bytes emitted by print event with chunk index 0

**Multiple Auth Servers**

In High Availability mode scenario, multiple auth servers will be

deployed behind a load balancer.

Any auth server can go down during session and clients will retry the delivery to the other auth server.

Both auth servers have mounted /var/lib/teleport/log as a shared NFS folder.

To make sure that only one auth server writes to a file at a time, each auth server writes to it's own file in a sub folder named with host UUID of the server.

Client sends the chunks of events related to the session s1 in order, but load balancer sends first batch of event to the first server a1, and the second batch of event to the second server a2.

Server a1 will produce the following file:

/var/lib/teleport/a1/s1.index

With contents:

{"file_name":"s1-0.events","type":"events","index":0} {"file_name":"s1-0.chunks","type":"chunks","offset":0}

Events file /var/lib/teleport/a1/s1-0.events will contain:

{"ei":0,"event":"session.start", ...} {"ei":1,"event":"resize",...} {"ei":2,"ci":0, "event":"print","bytes":40,"offset":0}

Events file /var/lib/teleport/a1/s1-0.chunks will contain 40 bytes emitted by print event with chunk index.

Server a2 will produce the following file:

/var/lib/teleport/a2/s1.index

With contents:

{"file_name":"s1-3.events","type":"events","index":3} {"file_name":"s1-40.chunks","type":"chunks","offset":40}

Events file /var/lib/teleport/a2/s1-4.events will contain:

{"ei":3,"ci":1, "event":"print","bytes":15,"ms":713,"offset":40} {"ei":4,"event":"session.end", ...}

Events file /var/lib/teleport/a2/s1-40.chunks will contain 15 bytes emitted by print event with chunk index 1 and comes after delay of 713 milliseconds.

Offset 40 indicates that the first chunk stored in the file s1-40.chunks comes at an offset of 40 bytes from the start of the session.

Log Search and Playback -----------------------

Log search and playback is aware of multiple auth servers, merges indexes, event streams stored on multiple auth servers.

Index

Constants

View Source
const (
	// EventType is event type/kind
	EventType = "event"
	// EventID is a unique event identifier
	EventID = "uid"
	// EventCode is a code that uniquely identifies a particular event type
	EventCode = "code"
	// EventTime is event time
	EventTime = "time"
	// EventLogin is OS login
	EventLogin = "login"
	// EventUser is teleport user name
	EventUser = "user"
	// EventProtocol specifies protocol that was captured
	EventProtocol = "proto"
	// EventProtocolsSSH specifies SSH as a type of captured protocol
	EventProtocolSSH = "ssh"
	// EventProtocolKube specifies kubernetes as a type of captured protocol
	EventProtocolKube = "kube"
	// EventProtocolTDP specifies Teleport Desktop Protocol (TDP)
	// as a type of captured protocol
	EventProtocolTDP = "tdp"
	// LocalAddr is a target address on the host
	LocalAddr = "addr.local"
	// RemoteAddr is a client (user's) address
	RemoteAddr = "addr.remote"
	// EventCursor is an event ID (used as cursor value for enumeration, not stored)
	EventCursor = "id"

	// EventIndex is an event index as received from the logging server
	EventIndex = "ei"

	// EventNamespace is a namespace of the session event
	EventNamespace = "namespace"

	// SessionPrintEvent event happens every time a write occurs to
	// terminal I/O during a session
	SessionPrintEvent = "print"

	// SessionPrintEventBytes says how many bytes have been written into the session
	// during "print" event
	SessionPrintEventBytes = "bytes"

	// SessionEventTimestamp is an offset (in milliseconds) since the beginning of the
	// session when the terminal IO event happened
	SessionEventTimestamp = "ms"

	// SessionStartEvent indicates that session has been initiated
	// or updated by a joining party on the server
	SessionStartEvent = "session.start"

	// SessionEndEvent indicates that a session has ended
	SessionEndEvent = "session.end"

	// SessionUploadEvent indicates that session has been uploaded to the external storage
	SessionUploadEvent = "session.upload"

	// URL is used for a session upload URL
	URL = "url"

	// SessionEventID is a unique UUID of the session.
	SessionEventID = "sid"

	// SessionServerID is the UUID of the server the session occurred on.
	SessionServerID = "server_id"

	// SessionServerHostname is the hostname of the server the session occurred on.
	SessionServerHostname = "server_hostname"

	// SessionServerAddr is the address of the server the session occurred on.
	SessionServerAddr = "server_addr"

	// SessionStartTime is the timestamp at which the session began.
	SessionStartTime = "session_start"

	// SessionRecordingType is the type of session recording.
	// Possible values are node (default), proxy, node-sync, proxy-sync, or off.
	SessionRecordingType = "session_recording"

	// SessionEndTime is the timestamp at which the session ended.
	SessionEndTime = "session_stop"

	// SessionEnhancedRecording is used to indicate if the recording was an
	// enhanced recording or not.
	SessionEnhancedRecording = "enhanced_recording"

	// SessionInteractive is used to indicate if the session was interactive
	// (has PTY attached) or not (exec session).
	SessionInteractive = "interactive"

	// SessionParticipants is a list of participants in the session.
	SessionParticipants = "participants"

	// SessionServerLabels are the labels (static and dynamic) of the server the
	// session occurred on.
	SessionServerLabels = "server_labels"

	// SessionClusterName is the cluster name that the session occurred in
	SessionClusterName = "cluster_name"

	// SessionByteOffset is the number of bytes written to session stream since
	// the beginning
	SessionByteOffset = "offset"

	// SessionJoinEvent indicates that someone joined a session
	SessionJoinEvent = "session.join"
	// SessionLeaveEvent indicates that someone left a session
	SessionLeaveEvent = "session.leave"

	// Data transfer events.
	SessionDataEvent = "session.data"
	DataTransmitted  = "tx"
	DataReceived     = "rx"

	// ClientDisconnectEvent is emitted when client is disconnected
	// by the server due to inactivity or any other reason
	ClientDisconnectEvent = "client.disconnect"

	// Reason is a field that specifies reason for event, e.g. in disconnect
	// event it explains why server disconnected the client
	Reason = "reason"

	// UserLoginEvent indicates that a user logged into web UI or via tsh
	UserLoginEvent = "user.login"
	// LoginMethod is the event field indicating how the login was performed
	LoginMethod = "method"
	// LoginMethodLocal represents login with username/password
	LoginMethodLocal = "local"
	// LoginMethodClientCert represents login with client certificate
	LoginMethodClientCert = "client.cert"
	// LoginMethodOIDC represents login with OIDC
	LoginMethodOIDC = "oidc"
	// LoginMethodSAML represents login with SAML
	LoginMethodSAML = "saml"
	// LoginMethodGithub represents login with Github
	LoginMethodGithub = "github"
	// LoginMethodHeadless represents headless login request
	LoginMethodHeadless = "headless"

	// UserUpdatedEvent is emitted when the user is updated.
	UserUpdatedEvent = "user.update"

	// UserDeleteEvent is emitted when the user is deleted.
	UserDeleteEvent = "user.delete"

	// UserCreateEvent is emitted when the user is created.
	UserCreateEvent = "user.create"

	// UserPasswordChangeEvent is when the user changes their own password.
	UserPasswordChangeEvent = "user.password_change"

	// UserExpires is when the user will expire.
	UserExpires = "expires"

	// UserRoles is a list of roles for the user.
	UserRoles = "roles"

	// IdentityAttributes is a map of user attributes
	// received from identity provider
	IdentityAttributes = "attributes"

	// UserConnector is the connector used to create the user.
	UserConnector = "connector"

	// AccessRequestCreateEvent is emitted when a new access request is created.
	AccessRequestCreateEvent = "access_request.create"
	// AccessRequestUpdateEvent is emitted when a request's state is updated.
	AccessRequestUpdateEvent = "access_request.update"
	// AccessRequestReviewEvent is emitted when a review is applied to a request.
	AccessRequestReviewEvent = "access_request.review"
	// AccessRequestDeleteEvent is emitted when a new access request is deleted.
	AccessRequestDeleteEvent = "access_request.delete"
	// AccessRequestResourceSearch is emitted when a user searches for
	// resources as part of a search-based access request.
	AccessRequestResourceSearch = "access_request.search"
	// AccessRequestDelegator is used by teleport plugins to indicate the identity
	// which caused them to update state.
	AccessRequestDelegator = "delegator"
	// AccessRequestState is the state of a request.
	AccessRequestState = "state"
	// AccessRequestID is the ID of an access request.
	AccessRequestID = "id"

	// BillingCardCreateEvent is emitted when a user creates a new credit card.
	BillingCardCreateEvent = "billing.create_card"
	// BillingCardDeleteEvent is emitted when a user deletes a credit card.
	BillingCardDeleteEvent = "billing.delete_card"
	// BillingCardUpdateEvent is emitted when a user updates an existing credit card.
	BillingCardUpdateEvent = "billing.update_card"
	// BillingInformationUpdateEvent is emitted when a user updates their billing information.
	BillingInformationUpdateEvent = "billing.update_info"

	// UpdatedBy indicates the user who modified some resource:
	//  - updating a request state
	//  - updating a user record
	UpdatedBy = "updated_by"

	// RecoveryTokenCreateEvent is emitted when a new recovery token is created.
	RecoveryTokenCreateEvent = "recovery_token.create"
	// ResetPasswordTokenCreateEvent is emitted when a new reset password token is created.
	ResetPasswordTokenCreateEvent = "reset_password_token.create"
	// ResetPasswordTokenTTL is TTL of reset password token.
	ResetPasswordTokenTTL = "ttl"
	// PrivilegeTokenCreateEvent is emitted when a new user privilege token is created.
	PrivilegeTokenCreateEvent = "privilege_token.create"

	// FieldName contains name, e.g. resource name, etc.
	FieldName = "name"

	// ExecEvent is an exec command executed by script or user on
	// the server side
	ExecEvent        = "exec"
	ExecEventCommand = "command"
	ExecEventCode    = "exitCode"
	ExecEventError   = "exitError"

	// SubsystemEvent is the result of the execution of a subsystem.
	SubsystemEvent = "subsystem"
	SubsystemName  = "name"
	SubsystemError = "exitError"

	// X11 forwarding event
	X11ForwardEvent   = "x11-forward"
	X11ForwardSuccess = "success"
	X11ForwardErr     = "error"

	// Port forwarding event
	PortForwardEvent   = "port"
	PortForwardAddr    = "addr"
	PortForwardSuccess = "success"
	PortForwardErr     = "error"

	// AuthAttemptEvent is authentication attempt that either
	// succeeded or failed based on event status
	AuthAttemptEvent   = "auth"
	AuthAttemptSuccess = "success"
	AuthAttemptErr     = "error"
	AuthAttemptMessage = "message"

	// SCPEvent means data transfer that occurred on the server
	SCPEvent          = "scp"
	SCPPath           = "path"
	SCPLengh          = "len"
	SCPAction         = "action"
	SCPActionUpload   = "upload"
	SCPActionDownload = "download"

	// SFTPEvent means a user attempted a file operation
	SFTPEvent = "sftp"
	SFTPPath  = "path"

	// ResizeEvent means that some user resized PTY on the client
	ResizeEvent  = "resize"
	TerminalSize = "size" // expressed as 'W:H'

	// SessionUploadIndex is a very large number of the event index
	// to indicate that this is the last event in the chain
	// used for the last event of the sesion - session upload
	SessionUploadIndex = math.MaxInt32
	// SessionDataIndex is a very large number of the event index
	// to indicate one of the last session events, used to report
	// data transfer
	SessionDataIndex = math.MaxInt32 - 1

	// SessionCommandEvent is emitted when an executable is run within a session.
	SessionCommandEvent = "session.command"

	// SessionDiskEvent is emitted when a file is opened within an session.
	SessionDiskEvent = "session.disk"

	// SessionNetworkEvent is emitted when a network connection is initiated with a
	// session.
	SessionNetworkEvent = "session.network"

	// PID is the ID of the process.
	PID = "pid"

	// PPID is the PID of the parent process.
	PPID = "ppid"

	// CgroupID is the internal cgroupv2 ID of the event.
	CgroupID = "cgroup_id"

	// Program is name of the executable.
	Program = "program"

	// Path is the full path to the executable.
	Path = "path"

	// Argv is the list of arguments to the program. Note, the first element does
	// not contain the name of the process.
	Argv = "argv"

	// ReturnCode is the return code of execve.
	ReturnCode = "return_code"

	// Flags are the flags passed to open.
	Flags = "flags"

	// SrcAddr is the source IP address of the connection.
	SrcAddr = "src_addr"

	// DstAddr is the destination IP address of the connection.
	DstAddr = "dst_addr"

	// DstPort is the destination port of the connection.
	DstPort = "dst_port"

	// TCPVersion is the version of TCP (4 or 6).
	TCPVersion = "version"

	// RoleCreatedEvent fires when role is created or upserted.
	RoleCreatedEvent = "role.created"
	// RoleUpdatedEvent fires when role is updated.
	RoleUpdatedEvent = "role.updated"
	// RoleDeletedEvent fires when role is deleted.
	RoleDeletedEvent = "role.deleted"

	// TrustedClusterCreateEvent is the event for creating a trusted cluster.
	TrustedClusterCreateEvent = "trusted_cluster.create"
	// TrustedClusterDeleteEvent is the event for removing a trusted cluster.
	TrustedClusterDeleteEvent = "trusted_cluster.delete"
	// TrustedClusterTokenCreateEvent is the event for creating new provisioning
	// token for a trusted cluster. Deprecated in favor of
	// [ProvisionTokenCreateEvent].
	TrustedClusterTokenCreateEvent = "trusted_cluster_token.create"

	// ProvisionTokenCreateEvent is the event for creating a provisioning token,
	// also known as Join Token. See [types.ProvisionToken].
	ProvisionTokenCreateEvent = "join_token.create"

	// GithubConnectorCreatedEvent fires when a Github connector is created.
	GithubConnectorCreatedEvent = "github.created"
	// GithubConnectorUpdatedEvent fires when a Github connector is updated.
	GithubConnectorUpdatedEvent = "github.updated"
	// GithubConnectorDeletedEvent fires when a Github connector is deleted.
	GithubConnectorDeletedEvent = "github.deleted"
	// OIDCConnectorCreatedEvent fires when OIDC connector is created.
	OIDCConnectorCreatedEvent = "oidc.created"
	// OIDCConnectorUpdatedEvent fires when OIDC connector is updated.
	OIDCConnectorUpdatedEvent = "oidc.updated"
	// OIDCConnectorDeletedEvent fires when OIDC connector is deleted.
	OIDCConnectorDeletedEvent = "oidc.deleted"
	// SAMLConnectorCreatedEvent fires when SAML connector is created.
	SAMLConnectorCreatedEvent = "saml.created"
	// SAMLConnectorUpdatedEvent fires when SAML connector is updated.
	SAMLConnectorUpdatedEvent = "saml.updated"
	// SAMLConnectorDeletedEvent fires when SAML connector is deleted.
	SAMLConnectorDeletedEvent = "saml.deleted"

	// SessionRejectedEvent fires when a user's attempt to create an authenticated
	// session has been rejected due to exceeding a session control limit.
	SessionRejectedEvent = "session.rejected"

	// SessionConnectEvent is emitted when any ssh connection is made
	SessionConnectEvent = "session.connect"

	// AppCreateEvent is emitted when an application resource is created.
	AppCreateEvent = "app.create"
	// AppUpdateEvent is emitted when an application resource is updated.
	AppUpdateEvent = "app.update"
	// AppDeleteEvent is emitted when an application resource is deleted.
	AppDeleteEvent = "app.delete"

	// AppSessionStartEvent is emitted when a user is issued an application certificate.
	AppSessionStartEvent = "app.session.start"
	// AppSessionEndEvent is emitted when a user connects to a TCP application.
	AppSessionEndEvent = "app.session.end"

	// AppSessionChunkEvent is emitted at the start of a 5 minute chunk on each
	// proxy. This chunk is used to buffer 5 minutes of audit events at a time
	// for applications.
	AppSessionChunkEvent = "app.session.chunk"

	// AppSessionRequestEvent is an HTTP request and response.
	AppSessionRequestEvent = "app.session.request"

	// AppSessionDynamoDBRequestEvent is emitted when DynamoDB client sends
	// a request via app access session.
	AppSessionDynamoDBRequestEvent = "app.session.dynamodb.request"

	// DatabaseCreateEvent is emitted when a database resource is created.
	DatabaseCreateEvent = "db.create"
	// DatabaseUpdateEvent is emitted when a database resource is updated.
	DatabaseUpdateEvent = "db.update"
	// DatabaseDeleteEvent is emitted when a database resource is deleted.
	DatabaseDeleteEvent = "db.delete"

	// DatabaseSessionStartEvent is emitted when a database client attempts
	// to connect to a database.
	DatabaseSessionStartEvent = "db.session.start"
	// DatabaseSessionEndEvent is emitted when a database client disconnects
	// from a database.
	DatabaseSessionEndEvent = "db.session.end"
	// DatabaseSessionQueryEvent is emitted when a database client executes
	// a query.
	DatabaseSessionQueryEvent = "db.session.query"
	// DatabaseSessionQueryFailedEvent is emitted when database client's request
	// to execute a database query/command was unsuccessful.
	DatabaseSessionQueryFailedEvent = "db.session.query.failed"
	// DatabaseSessionPostgresParseEvent is emitted when a Postgres client
	// creates a prepared statement using extended query protocol.
	DatabaseSessionPostgresParseEvent = "db.session.postgres.statements.parse"
	// DatabaseSessionPostgresBindEvent is emitted when a Postgres client
	// readies a prepared statement for execution and binds it to parameters.
	DatabaseSessionPostgresBindEvent = "db.session.postgres.statements.bind"
	// DatabaseSessionPostgresExecuteEvent is emitted when a Postgres client
	// executes a previously bound prepared statement.
	DatabaseSessionPostgresExecuteEvent = "db.session.postgres.statements.execute"
	// DatabaseSessionPostgresCloseEvent is emitted when a Postgres client
	// closes an existing prepared statement.
	DatabaseSessionPostgresCloseEvent = "db.session.postgres.statements.close"
	// DatabaseSessionPostgresFunctionEvent is emitted when a Postgres client
	// calls an internal function.
	DatabaseSessionPostgresFunctionEvent = "db.session.postgres.function"

	// DatabaseSessionMySQLStatementPrepareEvent is emitted when a MySQL client
	// creates a prepared statement using the prepared statement protocol.
	DatabaseSessionMySQLStatementPrepareEvent = "db.session.mysql.statements.prepare"
	// DatabaseSessionMySQLStatementExecuteEvent is emitted when a MySQL client
	// executes a prepared statement using the prepared statement protocol.
	DatabaseSessionMySQLStatementExecuteEvent = "db.session.mysql.statements.execute"
	// DatabaseSessionMySQLStatementSendLongDataEvent is emitted when a MySQL
	// client sends long bytes stream using the prepared statement protocol.
	DatabaseSessionMySQLStatementSendLongDataEvent = "db.session.mysql.statements.send_long_data"
	// DatabaseSessionMySQLStatementCloseEvent is emitted when a MySQL client
	// deallocates a prepared statement using the prepared statement protocol.
	DatabaseSessionMySQLStatementCloseEvent = "db.session.mysql.statements.close"
	// DatabaseSessionMySQLStatementResetEvent is emitted when a MySQL client
	// resets the data of a prepared statement using the prepared statement
	// protocol.
	DatabaseSessionMySQLStatementResetEvent = "db.session.mysql.statements.reset"
	// DatabaseSessionMySQLStatementFetchEvent is emitted when a MySQL client
	// fetches rows from a prepared statement using the prepared statement
	// protocol.
	DatabaseSessionMySQLStatementFetchEvent = "db.session.mysql.statements.fetch"
	// DatabaseSessionMySQLStatementBulkExecuteEvent is emitted when a MySQL
	// client executes a bulk insert of a prepared statement using the prepared
	// statement protocol.
	DatabaseSessionMySQLStatementBulkExecuteEvent = "db.session.mysql.statements.bulk_execute"

	// DatabaseSessionMySQLInitDBEvent is emitted when a MySQL client changes
	// the default schema for the connection.
	DatabaseSessionMySQLInitDBEvent = "db.session.mysql.init_db"
	// DatabaseSessionMySQLCreateDBEvent is emitted when a MySQL client creates
	// a schema.
	DatabaseSessionMySQLCreateDBEvent = "db.session.mysql.create_db"
	// DatabaseSessionMySQLDropDBEvent is emitted when a MySQL client drops a
	// schema.
	DatabaseSessionMySQLDropDBEvent = "db.session.mysql.drop_db"
	// DatabaseSessionMySQLShutDownEvent is emitted when a MySQL client asks
	// the server to shut down.
	DatabaseSessionMySQLShutDownEvent = "db.session.mysql.shut_down"
	// DatabaseSessionMySQLProcessKillEvent is emitted when a MySQL client asks
	// the server to terminate a connection.
	DatabaseSessionMySQLProcessKillEvent = "db.session.mysql.process_kill"
	// DatabaseSessionMySQLDebugEvent is emitted when a MySQL client asks the
	// server to dump internal debug info to stdout.
	DatabaseSessionMySQLDebugEvent = "db.session.mysql.debug"
	// DatabaseSessionMySQLRefreshEvent is emitted when a MySQL client sends
	// refresh commands.
	DatabaseSessionMySQLRefreshEvent = "db.session.mysql.refresh"

	// DatabaseSessionSQLServerRPCRequestEvent is emitted when MSServer client sends
	// RPC request command.
	DatabaseSessionSQLServerRPCRequestEvent = "db.session.sqlserver.rpc_request"

	// DatabaseSessionElasticsearchRequestEvent is emitted when Elasticsearch client sends
	// a generic request.
	DatabaseSessionElasticsearchRequestEvent = "db.session.elasticsearch.request"

	// DatabaseSessionOpenSearchRequestEvent is emitted when OpenSearch client sends
	// a request.
	DatabaseSessionOpenSearchRequestEvent = "db.session.opensearch.request"

	// DatabaseSessionDynamoDBRequestEvent is emitted when DynamoDB client sends
	// a request via database-access.
	DatabaseSessionDynamoDBRequestEvent = "db.session.dynamodb.request"

	// DatabaseSessionMalformedPacketEvent is emitted when SQL packet is malformed.
	DatabaseSessionMalformedPacketEvent = "db.session.malformed_packet"

	// DatabaseSessionCassandraBatchEvent is emitted when a Cassandra client executes a batch of queries.
	DatabaseSessionCassandraBatchEvent = "db.session.cassandra.batch"
	// DatabaseSessionCassandraPrepareEvent is emitted when a Cassandra client sends prepare packet.
	DatabaseSessionCassandraPrepareEvent = "db.session.cassandra.prepare"
	// DatabaseSessionCassandraExecuteEvent is emitted when a Cassandra client sends executed packet.
	DatabaseSessionCassandraExecuteEvent = "db.session.cassandra.execute"
	// DatabaseSessionCassandraRegisterEvent is emitted when a Cassandra client sends the register packet.
	DatabaseSessionCassandraRegisterEvent = "db.session.cassandra.register"

	// SessionRejectedReasonMaxConnections indicates that a session.rejected event
	// corresponds to enforcement of the max_connections control.
	SessionRejectedReasonMaxConnections = "max_connections limit reached"
	// SessionRejectedReasonMaxSessions indicates that a session.rejected event
	// corresponds to enforcement of the max_sessions control.
	SessionRejectedReasonMaxSessions = "max_sessions limit reached"

	// Maximum is an event field specifying a maximal value (e.g. the value
	// of `max_connections` for a `session.rejected` event).
	Maximum = "max"

	// KubeRequestEvent fires when a proxy handles a generic kubernetes
	// request.
	KubeRequestEvent = "kube.request"

	// KubernetesClusterCreateEvent is emitted when a kubernetes cluster resource is created.
	KubernetesClusterCreateEvent = "kube.create"
	// KubernetesClusterUpdateEvent is emitted when a kubernetes cluster resource is updated.
	KubernetesClusterUpdateEvent = "kube.update"
	// KubernetesClusterDeleteEvent is emitted when a kubernetes cluster resource is deleted.
	KubernetesClusterDeleteEvent = "kube.delete"

	// MFADeviceAddEvent is an event type for users adding MFA devices.
	MFADeviceAddEvent = "mfa.add"
	// MFADeviceDeleteEvent is an event type for users deleting MFA devices.
	MFADeviceDeleteEvent = "mfa.delete"

	// LockCreatedEvent fires when a lock is created/updated.
	LockCreatedEvent = "lock.created"
	// LockDeletedEvent fires when a lock is deleted.
	LockDeletedEvent = "lock.deleted"

	// RecoveryCodeGeneratedEvent is an event type for generating a user's recovery tokens.
	RecoveryCodeGeneratedEvent = "recovery_code.generated"
	// RecoveryCodeUsedEvent is an event type when a recovery token was used.
	RecoveryCodeUsedEvent = "recovery_code.used"

	// WindowsDesktopSessionStartEvent is emitted when a user attempts
	// to connect to a desktop.
	WindowsDesktopSessionStartEvent = "windows.desktop.session.start"
	// WindowsDesktopSessionEndEvent is emitted when a user disconnects
	// from a desktop.
	WindowsDesktopSessionEndEvent = "windows.desktop.session.end"

	// CertificateCreateEvent is emitted when a certificate is issued.
	CertificateCreateEvent = "cert.create"

	// RenewableCertificateGenerationMismatchEvent is emitted when a renewable
	// certificate's generation counter is invalid.
	RenewableCertificateGenerationMismatchEvent = "cert.generation_mismatch"

	// CertificateTypeUser is the CertificateType for certificate events pertaining to user certificates.
	CertificateTypeUser = "user"

	// DesktopRecordingEvent is emitted as a desktop access session is recorded.
	DesktopRecordingEvent = "desktop.recording"
	// DesktopClipboardReceiveEvent is emitted when Teleport receives
	// clipboard data from a remote desktop.
	DesktopClipboardReceiveEvent = "desktop.clipboard.receive"
	// DesktopClipboardSendEvent is emitted when local clipboard data
	// is sent to Teleport.
	DesktopClipboardSendEvent = "desktop.clipboard.send"
	// DesktopSharedDirectoryStartEvent is emitted when when Teleport
	// successfully begins sharing a new directory to a remote desktop.
	DesktopSharedDirectoryStartEvent = "desktop.directory.share"
	// DesktopSharedDirectoryReadEvent is emitted when data is read from a shared directory.
	DesktopSharedDirectoryReadEvent = "desktop.directory.read"
	// DesktopSharedDirectoryWriteEvent is emitted when data is written to a shared directory.
	DesktopSharedDirectoryWriteEvent = "desktop.directory.write"
	// UpgradeWindowStartUpdateEvent is emitted when the upgrade window start time
	// is updated. Used only for teleport cloud.
	UpgradeWindowStartUpdateEvent = "upgradewindowstart.update"

	// SessionRecordingAccessEvent is emitted when a session recording is accessed
	SessionRecordingAccessEvent = "session.recording.access"

	// SSMRunEvent is emitted when a run of an install script
	// completes on a discovered EC2 node
	SSMRunEvent = "ssm.run"

	// DeviceEvent is the catch-all event for Device Trust events.
	// Deprecated: Use one of the more specific event codes below.
	DeviceEvent = "device"
	// DeviceCreateEvent is emitted on device registration.
	// This is an inventory management event.
	DeviceCreateEvent = "device.create"
	// DeviceDeleteEvent is emitted on device deletion.
	// This is an inventory management event.
	DeviceDeleteEvent = "device.delete"
	// DeviceUpdateEvent is emitted on device updates.
	// This is an inventory management event.
	DeviceUpdateEvent = "device.update"
	// DeviceEnrollEvent is emitted when a device is enrolled.
	// Enrollment events are issued due to end-user action, using the trusted
	// device itself.
	DeviceEnrollEvent = "device.enroll"
	// DeviceAuthenticateEvent is emitted when a device is authenticated.
	// Authentication events are issued due to end-user action, using the trusted
	// device itself.
	DeviceAuthenticateEvent = "device.authenticate"
	// DeviceEnrollTokenCreateEvent is emitted when a new enrollment token is
	// issued for a device.
	// Device enroll tokens are issued by either a device admin or during
	// client-side auto-enrollment.
	DeviceEnrollTokenCreateEvent = "device.token.create"

	// BotJoinEvent is emitted when a bot joins
	BotJoinEvent = "bot.join"
	// BotCreateEvent is emitted when a bot is created
	BotCreateEvent = "bot.create"
	// BotUpdateEvent is emitted when a bot is updated
	BotUpdateEvent = "bot.update"
	// BotDeleteEvent is emitted when a bot is deleted
	BotDeleteEvent = "bot.delete"

	// InstanceJoinEvent is emitted when an instance joins
	InstanceJoinEvent = "instance.join"

	// LoginRuleCreateEvent is emitted when a login rule is created or updated.
	LoginRuleCreateEvent = "login_rule.create"
	// LoginRuleDeleteEvent is emitted when a login rule is deleted.
	LoginRuleDeleteEvent = "login_rule.delete"

	// SAMLIdPAuthAttemptEvent is emitted when a user has attempted to authorize against the SAML IdP.
	SAMLIdPAuthAttemptEvent = "saml.idp.auth"

	// SAMLIdPServiceProviderCreateEvent is emitted when a service provider has been created.
	SAMLIdPServiceProviderCreateEvent = "saml.idp.service.provider.create"

	// SAMLIdPServiceProviderUpdateEvent is emitted when a service provider has been updated.
	SAMLIdPServiceProviderUpdateEvent = "saml.idp.service.provider.update"

	// SAMLIdPServiceProviderDeleteEvent is emitted when a service provider has been deleted.
	SAMLIdPServiceProviderDeleteEvent = "saml.idp.service.provider.delete"

	// SAMLIdPServiceProviderDeleteAllEvent is emitted when all service providers have been deleted.
	SAMLIdPServiceProviderDeleteAllEvent = "saml.idp.service.provider.delete_all"

	// OktaGroupsUpdate event is emitted when the groups synced from Okta have been updated.
	OktaGroupsUpdateEvent = "okta.groups.update"

	// OktaApplicationsUpdateEvent is emitted when the applications synced from Okta have been updated.
	OktaApplicationsUpdateEvent = "okta.applications.update"

	// OktaSyncFailureEvent is emitted when the Okta synchronization fails.
	OktaSyncFailureEvent = "okta.sync.failure"

	// OktaAssignmentProcessEvent is emitted when an assignment is processed.
	OktaAssignmentProcessEvent = "okta.assignment.process"

	// OktaAssignmentCleanupEvent is emitted when an assignment is cleaned up.
	OktaAssignmentCleanupEvent = "okta.assignment.cleanup"

	// AccessListCreateEvent is emitted when an access list is created.
	AccessListCreateEvent = "access_list.create"

	// AccessListUpdateEvent is emitted when an access list is updated.
	AccessListUpdateEvent = "access_list.update"

	// AccessListDeleteEvent is emitted when an access list is deleted.
	AccessListDeleteEvent = "access_list.delete"

	// AccessListReviewEvent is emitted when an access list is reviewed.
	AccessListReviewEvent = "access_list.review"

	// AccessListMemberCreateEvent is emitted when a member is added to an access list.
	AccessListMemberCreateEvent = "access_list.member.create"

	// AccessListMemberUpdateEvent is emitted when a member is updated in an access list.
	AccessListMemberUpdateEvent = "access_list.member.update"

	// AccessListMemberDeleteEvent is emitted when a member is deleted from an access list.
	AccessListMemberDeleteEvent = "access_list.member.delete"

	// AccessListMemberDeleteAllForAccessListEvent is emitted when all members are deleted from an access list.
	AccessListMemberDeleteAllForAccessListEvent = "access_list.member.delete_all_for_access_list"

	// UnknownEvent is any event received that isn't recognized as any other event type.
	UnknownEvent = apievents.UnknownEvent

	// SecReportsAuditQueryRunEvent is emitted when a security report query is run.
	SecReportsAuditQueryRunEvent = "secreports.audit.query.run"

	// SecReportsReportRunEvent is emitted when a security report is run.
	SecReportsReportRunEvent = "secreports.report.run"

	// ExternalAuditStorageEnableEvent is emitted when External Audit Storage is
	// enabled.
	ExternalAuditStorageEnableEvent = "external_audit_storage.enable"
	// ExternalAuditStorageDisableEvent is emitted when External Audit Storage is
	// disabled.
	ExternalAuditStorageDisableEvent = "external_audit_storage.disable"
)
View Source
const (
	// V1 is the V1 version of slice chunks API,
	// it is 0 because it was not defined before
	V1 = 0
	// V2 is the V2 version of slice chunks  API
	V2 = 2
	// V3 is almost like V2, but it assumes
	// that session recordings are being uploaded
	// at the end of the session, so it skips writing session event index
	// on the fly
	V3 = 3
)
View Source
const (
	// SessionLogsDir is a subdirectory inside the eventlog data dir
	// where all session-specific logs and streams are stored, like
	// in /var/lib/teleport/log/sessions
	SessionLogsDir = "sessions"

	// StreamingSessionsDir is a subdirectory of sessions (/var/lib/teleport/log/upload/streaming)
	// that is used in new versions of the uploader. This directory is used in asynchronous
	// recording modes where recordings are buffered to disk before being uploaded
	// to the auth server.
	StreamingSessionsDir = "streaming"

	// CorruptedSessionsDir is a subdirectory of sessions (/var/lib/teleport/log/upload/corrupted)
	// where corrupted session recordings are placed. This ensures that the uploader doesn't
	// continue to try to upload corrupted sessions, but preserves the recording in case it contains
	// valuable info.
	CorruptedSessionsDir = "corrupted"

	// RecordsDir is an auth server subdirectory with session recordings that is used
	// when the auth server is not configured for external cloud storage. It is not
	// used by nodes, proxies, or other Teleport services.
	RecordsDir = "records"

	// PlaybackDir is a directory for caching downloaded sessions during playback.
	PlaybackDir = "playbacks"

	// LogfileExt defines the ending of the daily event log file
	LogfileExt = ".log"

	// SymlinkFilename is a name of the symlink pointing to the last
	// current log file
	SymlinkFilename = "events.log"

	// AuditBackoffTimeout is a time out before audit logger will
	// start losing events
	AuditBackoffTimeout = 5 * time.Second

	// NetworkBackoffDuration is a standard backoff on network requests
	// usually is slow, e.g. once in 30 seconds
	NetworkBackoffDuration = time.Second * 30

	// NetworkRetryDuration is a standard retry on network requests
	// to retry quickly, e.g. once in one second
	NetworkRetryDuration = time.Second

	// FastAttempts is the initial amount of fast retry attempts
	// before switching to slow mode
	FastAttempts = 10

	// DiskAlertThreshold is the disk space alerting threshold.
	DiskAlertThreshold = 90

	// DiskAlertInterval is disk space check interval.
	DiskAlertInterval = 5 * time.Minute

	// InactivityFlushPeriod is a period of inactivity
	// that triggers upload of the data - flush.
	InactivityFlushPeriod = 5 * time.Minute

	// AbandonedUploadPollingRate defines how often to check for
	// abandoned uploads which need to be completed.
	AbandonedUploadPollingRate = apidefaults.SessionTrackerTTL / 6
)
View Source
const (
	// UserLocalLoginCode is the successful local user login event code.
	UserLocalLoginCode = "T1000I"
	// UserLocalLoginFailureCode is the unsuccessful local user login event code.
	UserLocalLoginFailureCode = "T1000W"
	// UserSSOLoginCode is the successful SSO user login event code.
	UserSSOLoginCode = "T1001I"
	// UserSSOLoginFailureCode is the unsuccessful SSO user login event code.
	UserSSOLoginFailureCode = "T1001W"
	// UserCreateCode is the user create event code.
	UserCreateCode = "T1002I"
	// UserUpdateCode is the user update event code.
	UserUpdateCode = "T1003I"
	// UserDeleteCode is the user delete event code.
	UserDeleteCode = "T1004I"
	// UserPasswordChangeCode is an event code for when user changes their own password.
	UserPasswordChangeCode = "T1005I"
	// MFADeviceAddEventCode is an event code for users adding MFA devices.
	MFADeviceAddEventCode = "T1006I"
	// MFADeviceDeleteEventCode is an event code for users deleting MFA devices.
	MFADeviceDeleteEventCode = "T1007I"
	// RecoveryCodesGenerateCode is an event code for generation of recovery codes.
	RecoveryCodesGenerateCode = "T1008I"
	// RecoveryCodeUseSuccessCode is an event code for when a
	// recovery code was used successfully.
	RecoveryCodeUseSuccessCode = "T1009I"
	// RecoveryCodeUseFailureCode is an event code for when a
	// recovery code was not used successfully.
	RecoveryCodeUseFailureCode = "T1009W"
	// UserSSOTestFlowLoginCode is the successful SSO test flow user login event code.
	UserSSOTestFlowLoginCode = "T1010I"
	// UserSSOTestFlowLoginFailureCode is the unsuccessful SSO test flow user login event code.
	UserSSOTestFlowLoginFailureCode = "T1011W"
	// UserHeadlessLoginRequestedCode is an event code for when headless login attempt was requested.
	UserHeadlessLoginRequestedCode = "T1012I"
	// UserHeadlessLoginApprovedCode is an event code for when headless login attempt was successfully approved.
	UserHeadlessLoginApprovedCode = "T1013I"
	// UserHeadlessLoginApprovedFailureCode is an event code for when headless login was approved with an error.
	UserHeadlessLoginApprovedFailureCode = "T1013W"
	// UserHeadlessLoginRejectedCode is an event code for when headless login attempt was rejected.
	UserHeadlessLoginRejectedCode = "T1014W"

	// BillingCardCreateCode is an event code for when a user creates a new credit card.
	BillingCardCreateCode = "TBL00I"
	// BillingCardDeleteCode is an event code for when a user deletes a credit card.
	BillingCardDeleteCode = "TBL01I"
	// BillingCardUpdateCode is an event code for when a user updates an existing credit card.
	BillingCardUpdateCode = "TBL02I"
	// BillingInformationUpdateCode is an event code for when a user updates their billing info.
	BillingInformationUpdateCode = "TBL03I"

	// SessionRejectedCode is an event code for when a user's attempt to create an
	// session/connection has been rejected.
	SessionRejectedCode = "T1006W"

	// SessionStartCode is the session start event code.
	SessionStartCode = "T2000I"
	// SessionJoinCode is the session join event code.
	SessionJoinCode = "T2001I"
	// TerminalResizeCode is the terminal resize event code.
	TerminalResizeCode = "T2002I"
	// SessionLeaveCode is the session leave event code.
	SessionLeaveCode = "T2003I"
	// SessionEndCode is the session end event code.
	SessionEndCode = "T2004I"
	// SessionUploadCode is the session upload event code.
	SessionUploadCode = "T2005I"
	// SessionDataCode is the session data event code.
	SessionDataCode = "T2006I"
	// AppSessionStartCode is the application session start code.
	AppSessionStartCode = "T2007I"
	// AppSessionChunkCode is the application session chunk create code.
	AppSessionChunkCode = "T2008I"
	// AppSessionRequestCode is the application request/response code.
	AppSessionRequestCode = "T2009I"
	// SessionConnectCode is the session connect event code.
	SessionConnectCode = "T2010I"
	// AppSessionEndCode is the application session end event code.
	AppSessionEndCode = "T2011I"
	// SessionRecordingAccessCode is the session recording view data event code.
	SessionRecordingAccessCode = "T2012I"
	// AppSessionDynamoDBRequestCode is the application request/response code.
	AppSessionDynamoDBRequestCode = "T2013I"

	// AppCreateCode is the app.create event code.
	AppCreateCode = "TAP03I"
	// AppUpdateCode is the app.update event code.
	AppUpdateCode = "TAP04I"
	// AppDeleteCode is the app.delete event code.
	AppDeleteCode = "TAP05I"

	// DatabaseSessionStartCode is the database session start event code.
	DatabaseSessionStartCode = "TDB00I"
	// DatabaseSessionStartFailureCode is the database session start failure event code.
	DatabaseSessionStartFailureCode = "TDB00W"
	// DatabaseSessionEndCode is the database session end event code.
	DatabaseSessionEndCode = "TDB01I"
	// DatabaseSessionQueryCode is the database query event code.
	DatabaseSessionQueryCode = "TDB02I"
	// DatabaseSessionQueryFailedCode is the database query failure event code.
	DatabaseSessionQueryFailedCode = "TDB02W"
	// DatabaseSessionMalformedPacketCode is the db.session.malformed_packet event code.
	DatabaseSessionMalformedPacketCode = "TDB06I"

	// PostgresParseCode is the db.session.postgres.statements.parse event code.
	PostgresParseCode = "TPG00I"
	// PostgresBindCode is the db.session.postgres.statements.bind event code.
	PostgresBindCode = "TPG01I"
	// PostgresExecuteCode is the db.session.postgres.statements.execute event code.
	PostgresExecuteCode = "TPG02I"
	// PostgresCloseCode is the db.session.postgres.statements.close event code.
	PostgresCloseCode = "TPG03I"
	// PostgresFunctionCallCode is the db.session.postgres.function event code.
	PostgresFunctionCallCode = "TPG04I"

	// MySQLStatementPrepareCode is the db.session.mysql.statements.prepare event code.
	MySQLStatementPrepareCode = "TMY00I"
	// MySQLStatementExecuteCode is the db.session.mysql.statements.execute event code.
	MySQLStatementExecuteCode = "TMY01I"
	// MySQLStatementSendLongDataCode is the db.session.mysql.statements.send_long_data event code.
	MySQLStatementSendLongDataCode = "TMY02I"
	// MySQLStatementCloseCode is the db.session.mysql.statements.close event code.
	MySQLStatementCloseCode = "TMY03I"
	// MySQLStatementResetCode is the db.session.mysql.statements.reset event code.
	MySQLStatementResetCode = "TMY04I"
	// MySQLStatementFetchCode is the db.session.mysql.statements.fetch event code.
	MySQLStatementFetchCode = "TMY05I"
	// MySQLStatementBulkExecuteCode is the db.session.mysql.statements.bulk_execute event code.
	MySQLStatementBulkExecuteCode = "TMY06I"
	// MySQLInitDBCode is the db.session.mysql.init_db event code.
	MySQLInitDBCode = "TMY07I"
	// MySQLCreateDBCode is the db.session.mysql.create_db event code.
	MySQLCreateDBCode = "TMY08I"
	// MySQLDropDBCode is the db.session.mysql.drop_db event code.
	MySQLDropDBCode = "TMY09I"
	// MySQLShutDownCode is the db.session.mysql.shut_down event code.
	MySQLShutDownCode = "TMY10I"
	// MySQLProcessKillCode is the db.session.mysql.process_kill event code.
	MySQLProcessKillCode = "TMY11I"
	// MySQLDebugCode is the db.session.mysql.debug event code.
	MySQLDebugCode = "TMY12I"
	// MySQLRefreshCode is the db.session.mysql.refresh event code.
	MySQLRefreshCode = "TMY13I"

	// SQLServerRPCRequestCode is the db.session.sqlserver.rpc_request event code.
	SQLServerRPCRequestCode = "TMS00I"

	// CassandraBatchEventCode is the db.session.cassandra.batch event code.
	CassandraBatchEventCode = "TCA01I"
	// CassandraPrepareEventCode is the db.session.cassandra.prepare event code.
	CassandraPrepareEventCode = "TCA02I"
	// CassandraExecuteEventCode is the db.session.cassandra.execute event code.
	CassandraExecuteEventCode = "TCA03I"
	// CassandraRegisterEventCode is the db.session.cassandra.register event code.
	CassandraRegisterEventCode = "TCA04I"

	// ElasticsearchRequestCode is the db.session.elasticsearch.request event code.
	ElasticsearchRequestCode = "TES00I"
	// ElasticsearchRequestFailureCode is the db.session.elasticsearch.request event failure code.
	ElasticsearchRequestFailureCode = "TES00E"

	// OpenSearchRequestCode is the db.session.opensearch.request event code.
	OpenSearchRequestCode = "TOS00I"
	// OpenSearchRequestFailureCode is the db.session.opensearch.request event failure code.
	OpenSearchRequestFailureCode = "TOS00E"

	// DynamoDBRequestCode is the db.session.dynamodb.request event code.
	DynamoDBRequestCode = "TDY01I"
	// DynamoDBRequestFailureCode is the db.session.dynamodb.request event failure code.
	// This is indicates that the database agent http transport failed to round trip the request.
	DynamoDBRequestFailureCode = "TDY01E"

	// DatabaseCreateCode is the db.create event code.
	DatabaseCreateCode = "TDB03I"
	// DatabaseUpdateCode is the db.update event code.
	DatabaseUpdateCode = "TDB04I"
	// DatabaseDeleteCode is the db.delete event code.
	DatabaseDeleteCode = "TDB05I"

	// DesktopSessionStartCode is the desktop session start event code.
	DesktopSessionStartCode = "TDP00I"
	// DesktopSessionStartFailureCode is event code for desktop sessions
	// that failed to start.
	DesktopSessionStartFailureCode = "TDP00W"
	// DesktopSessionEndCode is the desktop session end event code.
	DesktopSessionEndCode = "TDP01I"
	// DesktopClipboardSendCode is the desktop clipboard send code.
	DesktopClipboardSendCode = "TDP02I"
	// DesktopClipboardReceiveCode is the desktop clipboard receive code.
	DesktopClipboardReceiveCode = "TDP03I"
	// DesktopSharedDirectoryStartCode is the desktop directory start code.
	DesktopSharedDirectoryStartCode = "TDP04I"
	// DesktopSharedDirectoryStartFailureCode is the desktop directory start code
	// for when a start operation fails, or for when the internal cache state was corrupted
	// causing information loss, or for when the internal cache has exceeded its max size.
	DesktopSharedDirectoryStartFailureCode = "TDP04W"
	// DesktopSharedDirectoryReadCode is the desktop directory read code.
	DesktopSharedDirectoryReadCode = "TDP05I"
	// DesktopSharedDirectoryReadFailureCode is the desktop directory read code
	// for when a read operation fails, or for if the internal cache state was corrupted
	// causing information loss, or for when the internal cache has exceeded its max size.
	DesktopSharedDirectoryReadFailureCode = "TDP05W"
	// DesktopSharedDirectoryWriteCode is the desktop directory write code.
	DesktopSharedDirectoryWriteCode = "TDP06I"
	// DesktopSharedDirectoryWriteFailureCode is the desktop directory write code
	// for when a write operation fails, or for if the internal cache state was corrupted
	// causing information loss, or for when the internal cache has exceeded its max size.
	DesktopSharedDirectoryWriteFailureCode = "TDP06W"

	// SubsystemCode is the subsystem event code.
	SubsystemCode = "T3001I"
	// SubsystemFailureCode is the subsystem failure event code.
	SubsystemFailureCode = "T3001E"
	// ExecCode is the exec event code.
	ExecCode = "T3002I"
	// ExecFailureCode is the exec failure event code.
	ExecFailureCode = "T3002E"
	// PortForwardCode is the port forward event code.
	PortForwardCode = "T3003I"
	// PortForwardFailureCode is the port forward failure event code.
	PortForwardFailureCode = "T3003E"
	// SCPDownloadCode is the file download event code.
	SCPDownloadCode = "T3004I"
	// SCPDownloadFailureCode is the file download event failure code.
	SCPDownloadFailureCode = "T3004E"
	// SCPUploadCode is the file upload event code.
	SCPUploadCode = "T3005I"
	// SCPUploadFailureCode is the file upload failure event code.
	SCPUploadFailureCode = "T3005E"
	// ClientDisconnectCode is the client disconnect event code.
	ClientDisconnectCode = "T3006I"
	// AuthAttemptFailureCode is the auth attempt failure event code.
	AuthAttemptFailureCode = "T3007W"
	// X11ForwardCode is the x11 forward event code.
	X11ForwardCode = "T3008I"
	// X11ForwardFailureCode is the x11 forward failure event code.
	X11ForwardFailureCode = "T3008W"
	// KubeRequestCode is an event code for a generic kubernetes request.
	//
	// Note: some requests (like exec into a pod) use other codes (like
	// ExecCode).
	KubeRequestCode = "T3009I"

	// KubernetesClusterCreateCode is the kube.create event code.
	KubernetesClusterCreateCode = "T3010I"
	// KubernetesClusterUpdateCode is the kube.update event code.
	KubernetesClusterUpdateCode = "T3011I"
	// KubernetesClusterDeleteCode is the kube.delete event code.
	KubernetesClusterDeleteCode = "T3012I"

	// The following codes correspond to SFTP file operations.
	SFTPOpenCode            = "TS001I"
	SFTPOpenFailureCode     = "TS001E"
	SFTPCloseCode           = "TS002I"
	SFTPCloseFailureCode    = "TS002E"
	SFTPReadCode            = "TS003I"
	SFTPReadFailureCode     = "TS003E"
	SFTPWriteCode           = "TS004I"
	SFTPWriteFailureCode    = "TS004E"
	SFTPLstatCode           = "TS005I"
	SFTPLstatFailureCode    = "TS005E"
	SFTPFstatCode           = "TS006I"
	SFTPFstatFailureCode    = "TS006E"
	SFTPSetstatCode         = "TS007I"
	SFTPSetstatFailureCode  = "TS007E"
	SFTPFsetstatCode        = "TS008I"
	SFTPFsetstatFailureCode = "TS008E"
	SFTPOpendirCode         = "TS009I"
	SFTPOpendirFailureCode  = "TS009E"
	SFTPReaddirCode         = "TS010I"
	SFTPReaddirFailureCode  = "TS010E"
	SFTPRemoveCode          = "TS011I"
	SFTPRemoveFailureCode   = "TS011E"
	SFTPMkdirCode           = "TS012I"
	SFTPMkdirFailureCode    = "TS012E"
	SFTPRmdirCode           = "TS013I"
	SFTPRmdirFailureCode    = "TS013E"
	SFTPRealpathCode        = "TS014I"
	SFTPRealpathFailureCode = "TS014E"
	SFTPStatCode            = "TS015I"
	SFTPStatFailureCode     = "TS015E"
	SFTPRenameCode          = "TS016I"
	SFTPRenameFailureCode   = "TS016E"
	SFTPReadlinkCode        = "TS017I"
	SFTPReadlinkFailureCode = "TS017E"
	SFTPSymlinkCode         = "TS018I"
	SFTPSymlinkFailureCode  = "TS018E"
	SFTPLinkCode            = "TS019I"
	SFTPLinkFailureCode     = "TS019E"

	// SessionCommandCode is a session command code.
	SessionCommandCode = "T4000I"
	// SessionDiskCode is a session disk code.
	SessionDiskCode = "T4001I"
	// SessionNetworkCode is a session network code.
	SessionNetworkCode = "T4002I"

	// AccessRequestCreateCode is the the access request creation code.
	AccessRequestCreateCode = "T5000I"
	// AccessRequestUpdateCode is the access request state update code.
	AccessRequestUpdateCode = "T5001I"
	// AccessRequestReviewCode is the access review application code.
	AccessRequestReviewCode = "T5002I"
	// AccessRequestDeleteCode is the access request deleted code.
	AccessRequestDeleteCode = "T5003I"
	// AccessRequestResourceSearchCode is the access request resource search code.
	AccessRequestResourceSearchCode = "T5004I"

	// ResetPasswordTokenCreateCode is the token create event code.
	ResetPasswordTokenCreateCode = "T6000I"
	// RecoveryTokenCreateCode is the recovery token create event code.
	RecoveryTokenCreateCode = "T6001I"
	// PrivilegeTokenCreateCode is the privilege token create event code.
	PrivilegeTokenCreateCode = "T6002I"

	// TrustedClusterCreateCode is the event code for creating a trusted cluster.
	TrustedClusterCreateCode = "T7000I"
	// TrustedClusterDeleteCode is the event code for removing a trusted cluster.
	TrustedClusterDeleteCode = "T7001I"
	// TrustedClusterTokenCreateCode is the event code for creating new
	// provisioning token for a trusted cluster. Deprecated in favor of
	// [ProvisionTokenCreateEvent].
	TrustedClusterTokenCreateCode = "T7002I"

	// ProvisionTokenCreateCode is the event code for creating a provisioning
	// token, also known as Join Token. See
	// [github.com/gravitational/teleport/api/types.ProvisionToken].
	ProvisionTokenCreateCode = "TJT00I"

	// GithubConnectorCreatedCode is the Github connector created event code.
	GithubConnectorCreatedCode = "T8000I"
	// GithubConnectorDeletedCode is the Github connector deleted event code.
	GithubConnectorDeletedCode = "T8001I"
	// GithubConnectorUpdatedCode is the Github connector updated event code.
	GithubConnectorUpdatedCode = "T80002I"

	// OIDCConnectorCreatedCode is the OIDC connector created event code.
	OIDCConnectorCreatedCode = "T8100I"
	// OIDCConnectorDeletedCode is the OIDC connector deleted event code.
	OIDCConnectorDeletedCode = "T8101I"
	// OIDCConnectorUpdatedCode is the OIDC connector updated event code.
	OIDCConnectorUpdatedCode = "T8102I"

	// SAMLConnectorCreatedCode is the SAML connector created event code.
	SAMLConnectorCreatedCode = "T8200I"
	// SAMLConnectorDeletedCode is the SAML connector deleted event code.
	SAMLConnectorDeletedCode = "T8201I"
	// SAMLConnectorUpdatedCode is the SAML connector updated event code.
	SAMLConnectorUpdatedCode = "T8202I"

	// RoleCreatedCode is the role created event code.
	RoleCreatedCode = "T9000I"
	// RoleDeletedCode is the role deleted event code.
	RoleDeletedCode = "T9001I"
	// RoleUpdatedCode is the role created event code.
	RoleUpdatedCode = "T9002I"

	// BotJoinCode is the 'bot.join' event code.
	BotJoinCode = "TJ001I"
	// InstanceJoinCode is the 'node.join' event code.
	InstanceJoinCode = "TJ002I"

	// BotCreateCode is the `bot.create` event code.
	BotCreateCode = "TB001I"
	// BotUpdateCode is the `bot.update` event code.
	BotUpdateCode = "TB002I"
	// BotDeleteCode is the `bot.delete` event code.
	BotDeleteCode = "TB003I"

	// LockCreatedCode is the lock created event code.
	LockCreatedCode = "TLK00I"
	// LockDeletedCode is the lock deleted event code.
	LockDeletedCode = "TLK01I"

	// CertificateCreateCode is the certificate issuance event code.
	CertificateCreateCode = "TC000I"

	// RenewableCertificateGenerationMismatchCode is the renewable cert
	// generation mismatch code.
	RenewableCertificateGenerationMismatchCode = "TCB00W"

	// UpgradeWindowStartUpdatedCode is the edit code of UpgradeWindowStartUpdateEvent.
	UpgradeWindowStartUpdatedCode = "TUW01I"

	// SSMRunSuccessCode is the discovery script success code.
	SSMRunSuccessCode = "TDS00I"
	// SSMRunFailCode is the discovery script success code.
	SSMRunFailCode = "TDS00W"

	// DeviceCreateCode is the device creation/registration code.
	DeviceCreateCode = "TV001I"
	// DeviceDeleteCode is the device deletion code.
	DeviceDeleteCode = "TV002I"
	// DeviceEnrollTokenCreateCode is the device enroll token creation code
	DeviceEnrollTokenCreateCode = "TV003I"
	// DeviceEnrollTokenSpentCode is the device enroll token spent code.
	DeviceEnrollTokenSpentCode = "TV004I"
	// DeviceEnrollCode is the device enrollment completion code.
	DeviceEnrollCode = "TV005I"
	// DeviceAuthenticateCode is the device authentication code.
	DeviceAuthenticateCode = "TV006I"
	// DeviceUpdateCode is the device update code.
	DeviceUpdateCode = "TV007I"

	// LoginRuleCreateCode is the login rule create code.
	LoginRuleCreateCode = "TLR00I"
	// LoginRuleDeleteCode is the login rule delete code.
	LoginRuleDeleteCode = "TLR01I"

	// SAMLIdPAuthAttemptCode is the SAML IdP auth attempt code.
	SAMLIdPAuthAttemptCode = "TSI000I"

	// SAMLIdPServiceProviderCreateCode is the SAML IdP service provider create code.
	SAMLIdPServiceProviderCreateCode = "TSI001I"

	// SAMLIdPServiceProviderCreateFailureCode is the SAML IdP service provider create failure code.
	SAMLIdPServiceProviderCreateFailureCode = "TSI001W"

	// SAMLIdPServiceProviderUpdateCode is the SAML IdP service provider update code.
	SAMLIdPServiceProviderUpdateCode = "TSI002I"

	// SAMLIdPServiceProviderUpdateFailureCode is the SAML IdP service provider update failure code.
	SAMLIdPServiceProviderUpdateFailureCode = "TSI002W"

	// SAMLIdPServiceProviderDeleteCode is the SAML IdP service provider delete code.
	SAMLIdPServiceProviderDeleteCode = "TSI003I"

	// SAMLIdPServiceProviderDeleteFailureCode is the SAML IdP service provider delete failure code.
	SAMLIdPServiceProviderDeleteFailureCode = "TSI003W"

	// SAMLIdPServiceProviderDeleteAllCode is the SAML IdP service provider delete all code.
	SAMLIdPServiceProviderDeleteAllCode = "TSI004I"

	// SAMLIdPServiceProviderDeleteAllFailureCode is the SAML IdP service provider delete all failure code.
	SAMLIdPServiceProviderDeleteAllFailureCode = "TSI004W"

	// OktaGroupsUpdateCode is the Okta groups updated code.
	OktaGroupsUpdateCode = "TOK001I"

	// OktaApplicationsUpdateCode is the Okta applications updated code.
	OktaApplicationsUpdateCode = "TOK002I"

	// OktaSyncFailureCode is the Okta synchronization failure code.
	OktaSyncFailureCode = "TOK003E"

	// OktaAssignmentProcessSuccessCode is the Okta assignment process success code.
	OktaAssignmentProcessSuccessCode = "TOK004I"

	// OktaAssignmentProcessFailureCode is the Okta assignment process failure code.
	OktaAssignmentProcessFailureCode = "TOK004E"

	// OktaAssignmentCleanupSuccessCode is the Okta assignment cleanup success code.
	OktaAssignmentCleanupSuccessCode = "TOK005I"

	// OktaAssignmentCleanupFailureCode is the Okta assignment cleanup failure code.
	OktaAssignmentCleanupFailureCode = "TOK005E"

	// AccessListCreateSuccessCode is the access list create success code.
	AccessListCreateSuccessCode = "TAL001I"

	// AccessListCreateFailureCode is the access list create failure code.
	AccessListCreateFailureCode = "TAL001E"

	// AccessListUpdateSuccessCode is the access list update success code.
	AccessListUpdateSuccessCode = "TAL002I"

	// AccessListUpdateFailureCode is the access list update failure code.
	AccessListUpdateFailureCode = "TAL002E"

	// AccessListDeleteSuccessCode is the access list delete success code.
	AccessListDeleteSuccessCode = "TAL003I"

	// AccessListDeleteFailureCode is the access list delete failure code.
	AccessListDeleteFailureCode = "TAL003E"

	// AccessListReviewSuccessCode is the access list review success code.
	AccessListReviewSuccessCode = "TAL004I"

	// AccessListReviewFailureCode is the access list review failure code.
	AccessListReviewFailureCode = "TAL004E"

	// AccessListMemberCreateSuccessCode is the access list member create success code.
	AccessListMemberCreateSuccessCode = "TAL005I"

	// AccessListMemberCreateFailureCode is the access list member create failure code.
	AccessListMemberCreateFailureCode = "TAL005E"

	// AccessListMemberUpdateSuccessCode is the access list member update success code.
	AccessListMemberUpdateSuccessCode = "TAL006I"

	// AccessListMemberUpdateFailureCode is the access list member update failure code.
	AccessListMemberUpdateFailureCode = "TAL006E"

	// AccessListMemberDeleteSuccessCode is the access list member delete success code.
	AccessListMemberDeleteSuccessCode = "TAL007I"

	// AccessListMemberDeleteFailureCode is the access list member delete failure code.
	AccessListMemberDeleteFailureCode = "TAL007E"

	// AccessListMemberDeleteAllForAccessListSuccessCode is the access list all member delete success code.
	AccessListMemberDeleteAllForAccessListSuccessCode = "TAL008I"

	// AccessListMemberDeleteAllForAccessListFailureCode is the access list member delete failure code.
	AccessListMemberDeleteAllForAccessListFailureCode = "TAL008E"

	// SecReportsAuditQueryRunCode is used when a custom Security Reports Query is run.
	SecReportsAuditQueryRunCode = "SRE001I"

	// SecReportsReportRunCode is used when a report in run.
	SecReportsReportRunCode = "SRE002I"

	// ExternalAuditStorageEnableCode is the External Audit Storage enabled code.
	ExternalAuditStorageEnableCode = "TEA001I"
	// ExternalAuditStorageDisableCode is the External Audit Storage disabled code.
	ExternalAuditStorageDisableCode = "TEA002I"

	// UnknownCode is used when an event of unknown type is encountered.
	UnknownCode = apievents.UnknownCode
)

There is no strict algorithm for picking an event code, however existing event codes are currently loosely categorized as follows:

  • Teleport event codes start with "T" and belong in this const block.

  • Related events are grouped starting with the same number. eg: All user related events are grouped under 1xxx.

  • Suffix code with one of these letters: I (info), W (warn), E (error).

After defining an event code, make sure to keep `web/packages/teleport/src/services/audit/types.ts` in sync.

View Source
const (
	// Int32Size is a constant for 32 bit integer byte size
	Int32Size = 4

	// Int64Size is a constant for 64 bit integer byte size
	Int64Size = 8

	// ConcurrentUploadsPerStream limits the amount of concurrent uploads
	// per stream
	ConcurrentUploadsPerStream = 1

	// MaxProtoMessageSizeBytes is maximum protobuf marshaled message size
	MaxProtoMessageSizeBytes = 64 * 1024

	// MaxUploadParts is the maximum allowed number of parts in a multi-part upload
	// on Amazon S3.
	MaxUploadParts = 10000

	// MinUploadPartSizeBytes is the minimum allowed part size when uploading a part to
	// Amazon S3.
	MinUploadPartSizeBytes = 1024 * 1024 * 5

	// ReservedParts is the amount of parts reserved by default
	ReservedParts = 100

	// ProtoStreamV1 is a version of the binary protocol
	ProtoStreamV1 = 1

	// ProtoStreamV1PartHeaderSize is the size of the part of the protocol stream
	// on disk format, it consists of
	// * 8 bytes for the format version
	// * 8 bytes for meaningful size of the part
	// * 8 bytes for optional padding size at the end of the slice
	ProtoStreamV1PartHeaderSize = Int64Size * 3

	// ProtoStreamV1RecordHeaderSize is the size of the header
	// of the record header, it consists of the record length
	ProtoStreamV1RecordHeaderSize = Int32Size
)
View Source
const AsyncBufferSize = 1024

AsyncBufferSize is a default buffer size for async emitters

View Source
const (
	// MaxChunkBytes defines the maximum size of a session stream chunk that
	// can be requested via AuditLog.GetSessionChunk(). Set to 5MB
	MaxChunkBytes = 1024 * 1024 * 5
)
View Source
const MaxEventBytesInResponse = 1024 * 1024

This is the max size of all the events we return when searching for events. 1 MiB was picked as a good middleground that's commonly used by the backends and is well below the max size limit of a response message. This may sometimes result in an even smaller size when serialized as protobuf but we have no good way to check so we go by raw from each backend.

View Source
const (
	// UseFIPSQueryParam is the URL query parameter used for enabling
	// FIPS endpoints for AWS S3/Dynamo.
	UseFIPSQueryParam = "use_fips_endpoint"
)

Variables

View Source
var (

	// AuditFailedEmit increments the counter if audit event failed to emit
	AuditFailedEmit = prometheus.NewCounter(
		prometheus.CounterOpts{
			Name: "audit_failed_emit_events",
			Help: "Number of times emitting audit event failed.",
		},
	)

	// MetricStoredTrimmedEvents counts the number of events that were trimmed
	// before being stored.
	MetricStoredTrimmedEvents = prometheus.NewCounter(
		prometheus.CounterOpts{
			Namespace: teleport.MetricNamespace,
			Name:      "audit_stored_trimmed_events",
			Help:      "Number of events that were trimmed before being stored",
		})

	// MetricQueriedTrimmedEvents counts the number of events that were trimmed
	// before being returned from a query.
	MetricQueriedTrimmedEvents = prometheus.NewCounter(
		prometheus.CounterOpts{
			Namespace: teleport.MetricNamespace,
			Name:      "audit_queried_trimmed_events",
			Help:      "Number of events that were trimmed before being returned from a query",
		})
)

Functions

func Export

func Export(ctx context.Context, rs io.ReadSeeker, w io.Writer, exportFormat string) error

Export converts session files from binary/protobuf to text/JSON.

func FIPSProtoStateToAWSState

FIPSProtoStateToAWSState converts a FIPS proto state to an aws endpoints.FIPSEndpointState

func FromEventFields

func FromEventFields(fields EventFields) (events.AuditEvent, error)

FromEventFields converts from the typed dynamic representation to the new typed interface-style representation.

This is mainly used to convert from the backend format used by our various event backends.

func GetSessionID

func GetSessionID(event events.AuditEvent) string

GetSessionID pulls the session ID from the events that have a SessionMetadata. For other events an empty string is returned.

func GetTeleportUser

func GetTeleportUser(event events.AuditEvent) string

GetTeleportUser pulls the teleport user from the events that have a UserMetadata. For other events an empty string is returned.

func IsPermanentEmitError

func IsPermanentEmitError(err error) bool

IsPermanentEmitError checks if the error contains either a sole trace.BadParameter error in its chain, or a trace.Aggregate error composed entirely of BadParameters.

func ParseFileTime

func ParseFileTime(filename string) (time.Time, error)

ParseFileTime parses file's timestamp encoded into filename

func SetupAndRecordEvent

func SetupAndRecordEvent(ctx context.Context, s SessionPreparerRecorder, e apievents.AuditEvent) error

SetupAndRecordEvent will set necessary event fields for session-related events and record them.

func StartNewUploadCompleter

func StartNewUploadCompleter(ctx context.Context, cfg UploadCompleterConfig) error

StartNewUploadCompleter starts an upload completer background process that will will close once the provided ctx is closed.

func ValidateServerMetadata

func ValidateServerMetadata(event apievents.AuditEvent, serverID string, isProxy bool) error

ValidateServerMetadata checks that event server ID of the event if present, matches the passed server ID and namespace has proper syntax

Types

type AsyncEmitter

type AsyncEmitter struct {
	// contains filtered or unexported fields
}

AsyncEmitter accepts events to a buffered channel and emits events in a separate goroutine without blocking the caller.

func NewAsyncEmitter

func NewAsyncEmitter(cfg AsyncEmitterConfig) (*AsyncEmitter, error)

NewAsyncEmitter returns emitter that submits events without blocking the caller. It will start losing events on buffer overflow.

func (*AsyncEmitter) Close

func (a *AsyncEmitter) Close() error

Close closes emitter and cancels all in flight events.

func (*AsyncEmitter) EmitAuditEvent

func (a *AsyncEmitter) EmitAuditEvent(ctx context.Context, event apievents.AuditEvent) error

EmitAuditEvent emits audit event without blocking the caller. It will start losing events on buffer overflow, but it never fails.

type AsyncEmitterConfig

type AsyncEmitterConfig struct {
	// Inner emits events to the underlying store
	Inner apievents.Emitter
	// BufferSize is a default buffer size for emitter
	BufferSize int
}

AsyncEmitterConfig provides parameters for emitter

func (*AsyncEmitterConfig) CheckAndSetDefaults

func (c *AsyncEmitterConfig) CheckAndSetDefaults() error

CheckAndSetDefaults checks and sets default values

type AuditLog added in v1.0.0

type AuditLog struct {
	sync.RWMutex
	AuditLogConfig
	// contains filtered or unexported fields
}

AuditLog is a new combined facility to record Teleport events and sessions. It implements AuditLogSessionStreamer

func NewAuditLog added in v1.0.0

func NewAuditLog(cfg AuditLogConfig) (*AuditLog, error)

NewAuditLog creates and returns a new Audit Log object which will store its log files in a given directory.

func (*AuditLog) Close added in v1.0.0

func (l *AuditLog) Close() error

Closes the audit log, which includes closing all file handles and releasing all session loggers

func (*AuditLog) CurrentFile

func (l *AuditLog) CurrentFile() string

CurrentFile returns the path to the current local file being used for logging.

func (l *AuditLog) CurrentFileSymlink() string

CurrentFileSymlink returns the path to the symlink pointing at the current local file being used for logging.

func (*AuditLog) EmitAuditEvent added in v1.0.0

func (l *AuditLog) EmitAuditEvent(ctx context.Context, event apievents.AuditEvent) error

EmitAuditEvent adds a new event to the local file log

func (*AuditLog) GetSessionChunk added in v1.0.0

func (l *AuditLog) GetSessionChunk(namespace string, sid session.ID, offsetBytes, maxBytes int) ([]byte, error)

GetSessionChunk returns a reader which console and web clients request to receive a live stream of a given session. The reader allows access to a session stream range from offsetBytes to offsetBytes+maxBytes

func (*AuditLog) GetSessionEvents added in v1.0.0

func (l *AuditLog) GetSessionEvents(namespace string, sid session.ID, afterN int) ([]EventFields, error)

Returns all events that happen during a session sorted by time (oldest first).

Can be filtered by 'after' (cursor value to return events newer than)

func (*AuditLog) SearchEvents added in v1.0.0

func (l *AuditLog) SearchEvents(ctx context.Context, req SearchEventsRequest) ([]apievents.AuditEvent, string, error)

func (*AuditLog) SearchSessionEvents

func (l *AuditLog) SearchSessionEvents(ctx context.Context, req SearchSessionEventsRequest) ([]apievents.AuditEvent, string, error)

func (*AuditLog) StreamSessionEvents

func (l *AuditLog) StreamSessionEvents(ctx context.Context, sessionID session.ID, startIndex int64) (chan apievents.AuditEvent, chan error)

StreamSessionEvents streams all events from a given session recording. An error is returned on the first channel if one is encountered. Otherwise the event channel is closed when the stream ends. The event channel is not closed on error to prevent race conditions in downstream select statements.

type AuditLogConfig

type AuditLogConfig struct {
	// DataDir is the directory where audit log stores the data
	DataDir string

	// ServerID is the id of the audit log server
	ServerID string

	// RotationPeriod defines how frequently to rotate the log file
	RotationPeriod time.Duration

	// Clock is a clock either real one or used in tests
	Clock clockwork.Clock

	// UIDGenerator is used to generate unique IDs for events
	UIDGenerator utils.UID

	// GID if provided will be used to set group ownership of the directory
	// to GID
	GID *int

	// UID if provided will be used to set user ownership of the directory
	// to UID
	UID *int

	// DirMask if provided will be used to set directory mask access
	// otherwise set to default value
	DirMask *os.FileMode

	// PlaybackRecycleTTL is a time after uncompressed playback files will be
	// deleted
	PlaybackRecycleTTL time.Duration

	// UploadHandler is a pluggable external upload handler,
	// used to fetch sessions from external sources
	UploadHandler MultipartHandler

	// ExternalLog is a pluggable external log service
	ExternalLog AuditLogger

	// Context is audit log context
	Context context.Context
}

AuditLogConfig specifies configuration for AuditLog server

func (*AuditLogConfig) CheckAndSetDefaults

func (a *AuditLogConfig) CheckAndSetDefaults() error

CheckAndSetDefaults checks and sets defaults

type AuditLogSessionStreamer

type AuditLogSessionStreamer interface {
	AuditLogger
	SessionStreamer
}

AuditLogSessionStreamer is the primary (and the only external-facing) interface for AuditLogger and SessionStreamer.

type AuditLogger

type AuditLogger interface {
	// Closer releases connection and resources associated with log if any
	io.Closer

	// Emitter emits an audit event
	apievents.Emitter

	// SearchEvents is a flexible way to find events.
	//
	// Event types to filter can be specified and pagination is handled by an iterator key that allows
	// a query to be resumed.
	//
	// The only mandatory requirement is a date range (UTC).
	//
	// This function may never return more than 1 MiB of event data.
	SearchEvents(ctx context.Context, req SearchEventsRequest) ([]apievents.AuditEvent, string, error)

	// SearchSessionEvents is a flexible way to find session events.
	// Only session.end events are returned by this function.
	// This is used to find completed sessions.
	//
	// Event types to filter can be specified and pagination is handled by an iterator key that allows
	// a query to be resumed.
	//
	// This function may never return more than 1 MiB of event data.
	SearchSessionEvents(ctx context.Context, req SearchSessionEventsRequest) ([]apievents.AuditEvent, string, error)
}

AuditLogger defines which methods need to implemented by audit loggers.

type ByTimeAndIndex

type ByTimeAndIndex []EventFields

ByTimeAndIndex sorts events by time extracting timestamp from JSON field and if there are several session events with the same session by event index, regardless of the time

func (ByTimeAndIndex) Len

func (f ByTimeAndIndex) Len() int

func (ByTimeAndIndex) Less

func (f ByTimeAndIndex) Less(i, j int) bool

func (ByTimeAndIndex) Swap

func (f ByTimeAndIndex) Swap(i, j int)

type CallbackEmitter

type CallbackEmitter struct {
	CallbackEmitterConfig
}

CallbackEmitter invokes a callback on every action, is used in tests to inject failures

func NewCallbackEmitter

func NewCallbackEmitter(cfg CallbackEmitterConfig) (*CallbackEmitter, error)

NewCallbackEmitter returns an emitter that invokes a callback on every action, is used in tests to inject failures

func (*CallbackEmitter) EmitAuditEvent

func (c *CallbackEmitter) EmitAuditEvent(ctx context.Context, event apievents.AuditEvent) error

type CallbackEmitterConfig

type CallbackEmitterConfig struct {
	// OnEmitAuditEvent is called on emit audit event on a stream
	OnEmitAuditEvent func(ctx context.Context, event apievents.AuditEvent) error
}

CallbackEmitterConfig provides parameters for emitter

func (*CallbackEmitterConfig) CheckAndSetDefaults

func (c *CallbackEmitterConfig) CheckAndSetDefaults() error

CheckAndSetDefaults checks and sets default values

type CallbackStream

type CallbackStream struct {
	// contains filtered or unexported fields
}

CallbackStream call

func (*CallbackStream) Close

func (s *CallbackStream) Close(ctx context.Context) error

Close flushes non-uploaded flight stream data without marking the stream completed and closes the stream instance

func (*CallbackStream) Complete

func (s *CallbackStream) Complete(ctx context.Context) error

Complete closes the stream and marks it finalized

func (*CallbackStream) Done

func (s *CallbackStream) Done() <-chan struct{}

Done returns channel closed when streamer is closed should be used to detect sending errors

func (*CallbackStream) RecordEvent

RecordEvent records a session event

func (*CallbackStream) Status

func (s *CallbackStream) Status() <-chan apievents.StreamStatus

Status returns channel receiving updates about stream status last event index that was uploaded and upload ID

type CallbackStreamer

type CallbackStreamer struct {
	CallbackStreamerConfig
}

CallbackStreamer ensures that event fields have been set properly and reports statistics for every wrapper

func NewCallbackStreamer

func NewCallbackStreamer(cfg CallbackStreamerConfig) (*CallbackStreamer, error)

NewCallbackStreamer returns streamer that invokes callback on every action, is used in tests to inject failures

func (*CallbackStreamer) CreateAuditStream

func (s *CallbackStreamer) CreateAuditStream(ctx context.Context, sid session.ID) (apievents.Stream, error)

CreateAuditStream creates audit event stream

func (*CallbackStreamer) ResumeAuditStream

func (s *CallbackStreamer) ResumeAuditStream(ctx context.Context, sid session.ID, uploadID string) (apievents.Stream, error)

ResumeAuditStream resumes audit event stream

type CallbackStreamerConfig

type CallbackStreamerConfig struct {
	// Inner emits events to the underlying store
	Inner Streamer
	// OnCreateAuditStream is called on create audit stream
	OnCreateAuditStream func(ctx context.Context, sid session.ID, inner Streamer) (apievents.Stream, error)
	// OnResumeAuditStream is called on resuming audit stream
	OnResumeAuditStream func(ctx context.Context, sid session.ID, uploadID string, inner Streamer) (apievents.Stream, error)
	// OnRecordEvent is called on emit audit event on a stream
	OnRecordEvent func(ctx context.Context, sid session.ID, event apievents.PreparedSessionEvent) error
}

CallbackStreamerConfig provides parameters for streamer

func (*CallbackStreamerConfig) CheckAndSetDefaults

func (c *CallbackStreamerConfig) CheckAndSetDefaults() error

CheckAndSetDefaults checks and sets default values

type CheckingEmitter

type CheckingEmitter struct {
	CheckingEmitterConfig
}

CheckingEmitter ensures that event fields have been set properly and reports statistics for every wrapper

func NewCheckingEmitter

func NewCheckingEmitter(cfg CheckingEmitterConfig) (*CheckingEmitter, error)

NewCheckingEmitter returns emitter that checks that all required fields are properly set

func (*CheckingEmitter) EmitAuditEvent

func (r *CheckingEmitter) EmitAuditEvent(ctx context.Context, event apievents.AuditEvent) error

EmitAuditEvent emits audit event

type CheckingEmitterConfig

type CheckingEmitterConfig struct {
	// Inner emits events to the underlying store
	Inner apievents.Emitter
	// Clock is a clock interface, used in tests
	Clock clockwork.Clock
	// UIDGenerator is unique ID generator
	UIDGenerator utils.UID
	// ClusterName specifies the name of this teleport cluster
	// as configured on the auth server
	ClusterName string
}

CheckingEmitterConfig provides parameters for emitter

func (*CheckingEmitterConfig) CheckAndSetDefaults

func (w *CheckingEmitterConfig) CheckAndSetDefaults() error

CheckAndSetDefaults checks and sets default values

type DiscardAuditLog added in v1.1.0

type DiscardAuditLog struct{}

DiscardAuditLog is do-nothing, discard-everything implementation of IAuditLog interface used for cases when audit is turned off

func NewDiscardAuditLog

func NewDiscardAuditLog() *DiscardAuditLog

NewDiscardAuditLog returns a no-op audit log instance

func (*DiscardAuditLog) Close

func (d *DiscardAuditLog) Close() error

func (*DiscardAuditLog) EmitAuditEvent added in v1.1.0

func (d *DiscardAuditLog) EmitAuditEvent(ctx context.Context, event apievents.AuditEvent) error

func (*DiscardAuditLog) GetSessionChunk added in v1.1.0

func (d *DiscardAuditLog) GetSessionChunk(namespace string, sid session.ID, offsetBytes, maxBytes int) ([]byte, error)

func (*DiscardAuditLog) GetSessionEvents added in v1.1.0

func (d *DiscardAuditLog) GetSessionEvents(namespace string, sid session.ID, after int) ([]EventFields, error)

func (*DiscardAuditLog) SearchEvents added in v1.1.0

func (*DiscardAuditLog) SearchSessionEvents

func (*DiscardAuditLog) StreamSessionEvents

func (d *DiscardAuditLog) StreamSessionEvents(ctx context.Context, sessionID session.ID, startIndex int64) (chan apievents.AuditEvent, chan error)

type DiscardEmitter

type DiscardEmitter struct{}

DiscardEmitter discards all events

func NewDiscardEmitter

func NewDiscardEmitter() *DiscardEmitter

NewDiscardEmitter returns a no-op discard emitter

func (*DiscardEmitter) EmitAuditEvent

func (*DiscardEmitter) EmitAuditEvent(ctx context.Context, event apievents.AuditEvent) error

EmitAuditEvent discards audit event

type DiscardRecorder

type DiscardRecorder struct {
	// contains filtered or unexported fields
}

DiscardRecorder returns a stream that discards all events

func NewDiscardRecorder

func NewDiscardRecorder() *DiscardRecorder

NewDiscardRecorder returns a [SessionRecorderChecker] that discards events.

func (*DiscardRecorder) Close

func (d *DiscardRecorder) Close(ctx context.Context) error

Close flushes non-uploaded flight stream data without marking the stream completed and closes the stream instance

func (*DiscardRecorder) Complete

func (d *DiscardRecorder) Complete(ctx context.Context) error

Complete marks the stream as closed

func (*DiscardRecorder) Done

func (d *DiscardRecorder) Done() <-chan struct{}

Done returns channel closed when streamer is closed should be used to detect sending errors

func (*DiscardRecorder) RecordEvent

RecordEvent discards session event

func (*DiscardRecorder) Status

func (*DiscardRecorder) Status() <-chan apievents.StreamStatus

Status returns a channel that always blocks

func (*DiscardRecorder) Write

func (d *DiscardRecorder) Write(p []byte) (n int, err error)

Write discards data

type DiscardStreamer

type DiscardStreamer struct{}

DiscardStreamer creates DiscardRecorders

func NewDiscardStreamer

func NewDiscardStreamer() *DiscardStreamer

NewDiscardStreamer returns a streamer that creates streams that discard events

func (*DiscardStreamer) CreateAuditStream

func (*DiscardStreamer) CreateAuditStream(ctx context.Context, sid session.ID) (apievents.Stream, error)

CreateAuditStream creates a stream that discards all events

func (*DiscardStreamer) ResumeAuditStream

func (*DiscardStreamer) ResumeAuditStream(ctx context.Context, sid session.ID, uploadID string) (apievents.Stream, error)

ResumeAuditStream resumes a stream that discards all events

type Event

type Event struct {
	// Name is the event name.
	Name string
	// Code is the unique event code.
	Code string
}

Event describes an audit log event.

type EventFields added in v1.0.0

type EventFields utils.Fields

EventFields instance is attached to every logged event

func ToEventFields

func ToEventFields(event events.AuditEvent) (EventFields, error)

ToEventFields converts from the typed interface-style event representation to the old dynamic map style representation in order to provide outer compatibility with existing public API routes when the backend is updated with the typed events.

func (EventFields) AsString added in v1.0.0

func (f EventFields) AsString() string

String returns a string representation of an event structure

func (EventFields) GetCode

func (f EventFields) GetCode() string

GetCode returns the event code

func (EventFields) GetID

func (f EventFields) GetID() string

GetID returns the unique event ID

func (EventFields) GetInt added in v1.0.0

func (f EventFields) GetInt(key string) int

GetInt returns an int representation of a logged field

func (EventFields) GetString added in v1.0.0

func (f EventFields) GetString(key string) string

GetString returns a string representation of a logged field

func (EventFields) GetStrings

func (f EventFields) GetStrings(key string) []string

GetString returns a slice-of-strings representation of a logged field.

func (EventFields) GetTime added in v1.0.0

func (f EventFields) GetTime(key string) time.Time

GetTime returns a time.Time representation of a logged field

func (EventFields) GetTimestamp

func (f EventFields) GetTimestamp() time.Time

GetTimestamp returns the event timestamp (when it was emitted)

func (EventFields) GetType added in v1.0.0

func (f EventFields) GetType() string

GetType returns the type (string) of the event

func (EventFields) HasField

func (f EventFields) HasField(key string) bool

HasField returns true if the field exists in the event.

type FileLog

type FileLog struct {
	*log.Entry
	FileLogConfig
	// contains filtered or unexported fields
}

FileLog is a file local audit events log, logs all events to the local file in json encoded form

func NewFileLog

func NewFileLog(cfg FileLogConfig) (*FileLog, error)

NewFileLog returns a new instance of a file log

func (*FileLog) Close

func (l *FileLog) Close() error

Close closes the audit log, which includes closing all file handles and releasing all session loggers.

func (*FileLog) EmitAuditEvent

func (l *FileLog) EmitAuditEvent(ctx context.Context, event apievents.AuditEvent) error

EmitAuditEvent adds a new event to the log.

func (*FileLog) SearchEvents

func (l *FileLog) SearchEvents(ctx context.Context, req SearchEventsRequest) ([]apievents.AuditEvent, string, error)

SearchEvents is a flexible way to find events.

Event types to filter can be specified and pagination is handled by an iterator key that allows a query to be resumed.

The only mandatory requirement is a date range (UTC).

This function may never return more than 1 MiB of event data.

func (*FileLog) SearchSessionEvents

func (l *FileLog) SearchSessionEvents(ctx context.Context, req SearchSessionEventsRequest) ([]apievents.AuditEvent, string, error)

type FileLogConfig

type FileLogConfig struct {
	// RotationPeriod defines how frequently to rotate the log file
	RotationPeriod time.Duration
	// Dir is a directory where logger puts the files
	Dir string
	// SymlinkDir is a directory for symlink pointer to the current log
	SymlinkDir string
	// Clock is a clock interface, used in tests
	Clock clockwork.Clock
	// UIDGenerator is used to generate unique IDs for events
	UIDGenerator utils.UID
	// SearchDirs is a function that returns
	// search directories, if not set, only Dir is used
	SearchDirs func() ([]string, error)
	// MaxScanTokenSize define maximum line entry size.
	MaxScanTokenSize int
}

FileLogConfig is a configuration for file log

func (*FileLogConfig) CheckAndSetDefaults

func (cfg *FileLogConfig) CheckAndSetDefaults() error

CheckAndSetDefaults checks and sets config defaults

type Header struct {
	// Tar detected tar format
	Tar bool
	// Proto is for proto format
	Proto bool
	// ProtoVersion is a version of the format, valid if Proto is true
	ProtoVersion int64
}

Header returns information about playback

func DetectFormat

func DetectFormat(r io.ReadSeeker) (*Header, error)

DetectFormat detects format by reading first bytes of the header. Callers should call Seek() to reuse reader after calling this function.

type LoggingEmitter

type LoggingEmitter struct{}

LoggingEmitter logs all events with info level

func NewLoggingEmitter

func NewLoggingEmitter() *LoggingEmitter

NewLoggingEmitter returns an emitter that logs all events to the console with the info level

func (*LoggingEmitter) EmitAuditEvent

func (*LoggingEmitter) EmitAuditEvent(ctx context.Context, event apievents.AuditEvent) error

EmitAuditEvent logs audit event, skips session print events, session disk events and app session request events, because they are very verbose.

type MultiEmitter

type MultiEmitter struct {
	// contains filtered or unexported fields
}

MultiEmitter writes audit events to multiple emitters

func NewMultiEmitter

func NewMultiEmitter(emitters ...apievents.Emitter) *MultiEmitter

NewMultiEmitter returns emitter that writes events to all emitters

func (*MultiEmitter) EmitAuditEvent

func (m *MultiEmitter) EmitAuditEvent(ctx context.Context, event apievents.AuditEvent) error

EmitAuditEvent emits audit event to all emitters

type MultiLog

type MultiLog struct {
	*MultiEmitter
	// contains filtered or unexported fields
}

MultiLog is a logger that fan outs write operations to all loggers, and performs all read and search operations on the first logger that implements the operation

func NewMultiLog

func NewMultiLog(loggers ...AuditLogger) (*MultiLog, error)

NewMultiLog returns a new instance of a multi logger

func (*MultiLog) Close

func (m *MultiLog) Close() error

Close releases connections and resources associated with logs if any

func (*MultiLog) SearchEvents

func (m *MultiLog) SearchEvents(ctx context.Context, req SearchEventsRequest) (events []apievents.AuditEvent, lastKey string, err error)

SearchEvents is a flexible way to find events.

Event types to filter can be specified and pagination is handled by an iterator key that allows a query to be resumed.

The only mandatory requirement is a date range (UTC).

This function may never return more than 1 MiB of event data.

func (*MultiLog) SearchSessionEvents

func (m *MultiLog) SearchSessionEvents(ctx context.Context, req SearchSessionEventsRequest) (events []apievents.AuditEvent, lastKey string, err error)

SearchSessionEvents is a flexible way to find session events. Only session.end and windows.desktop.session.end events are returned by this function. This is used to find completed sessions.

Event types to filter can be specified and pagination is handled by an iterator key that allows a query to be resumed.

type MultipartHandler

type MultipartHandler interface {
	UploadHandler
	MultipartUploader
}

MultipartHandler handles both multipart uploads and downloads

type MultipartUploader

type MultipartUploader interface {
	// CreateUpload creates a multipart upload
	CreateUpload(ctx context.Context, sessionID session.ID) (*StreamUpload, error)
	// CompleteUpload completes the upload
	CompleteUpload(ctx context.Context, upload StreamUpload, parts []StreamPart) error
	// ReserveUploadPart reserves an upload part. Reserve is used to identify
	// upload errors beforehand.
	ReserveUploadPart(ctx context.Context, upload StreamUpload, partNumber int64) error
	// UploadPart uploads part and returns the part
	UploadPart(ctx context.Context, upload StreamUpload, partNumber int64, partBody io.ReadSeeker) (*StreamPart, error)
	// ListParts returns all uploaded parts for the completed upload in sorted order
	ListParts(ctx context.Context, upload StreamUpload) ([]StreamPart, error)
	// ListUploads lists uploads that have been initiated but not completed with
	// earlier uploads returned first
	ListUploads(ctx context.Context) ([]StreamUpload, error)
	// GetUploadMetadata gets the upload metadata
	GetUploadMetadata(sessionID session.ID) UploadMetadata
}

MultipartUploader handles multipart uploads and downloads for session streams

type NoOpPreparer

type NoOpPreparer struct{}

NoOpPreparer is a SessionEventPreparer that doesn't change events

func (*NoOpPreparer) PrepareSessionEvent

func (m *NoOpPreparer) PrepareSessionEvent(event apievents.AuditEvent) (apievents.PreparedSessionEvent, error)

PrepareSessionEvent returns the event unchanged

type Preparer

type Preparer struct {
	// contains filtered or unexported fields
}

Preparer sets necessary unset fields in session events.

func NewPreparer

func NewPreparer(cfg PreparerConfig) (*Preparer, error)

func (*Preparer) PrepareSessionEvent

func (c *Preparer) PrepareSessionEvent(event apievents.AuditEvent) (apievents.PreparedSessionEvent, error)

PrepareSessionEvent will set necessary event fields for session-related events and must be called before the event is recorded, regardless of whether the event will be recorded, emitted, or both.

type PreparerConfig

type PreparerConfig struct {
	// SessionID defines the session to record.
	SessionID session.ID

	// ServerID is a server ID to write
	ServerID string

	// Namespace is the session namespace.
	Namespace string

	// Clock is used to override time in tests
	Clock clockwork.Clock

	// UID is UID generator
	UID utils.UID

	// ClusterName defines the name of this teleport cluster.
	ClusterName string
}

PreparerConfig configures an event setter

func (*PreparerConfig) CheckAndSetDefaults

func (cfg *PreparerConfig) CheckAndSetDefaults() error

CheckAndSetDefaults checks and sets defaults

type ProtoReader

type ProtoReader struct {
	// contains filtered or unexported fields
}

ProtoReader reads protobuf encoding from reader

func NewProtoReader

func NewProtoReader(r io.Reader) *ProtoReader

NewProtoReader returns a new proto reader with slice pool

func (*ProtoReader) Close

func (r *ProtoReader) Close() error

Close releases reader resources

func (*ProtoReader) GetStats

func (r *ProtoReader) GetStats() ProtoReaderStats

GetStats returns stats about processed events

func (*ProtoReader) Read

Read returns next event or io.EOF in case of the end of the parts

func (*ProtoReader) ReadAll

func (r *ProtoReader) ReadAll(ctx context.Context) ([]apievents.AuditEvent, error)

ReadAll reads all events until EOF

func (*ProtoReader) Reset

func (r *ProtoReader) Reset(reader io.Reader) error

Reset sets reader to read from the new reader without resetting the stats, could be used to deduplicate the events

type ProtoReaderStats

type ProtoReaderStats struct {
	// SkippedEvents is a counter with encountered
	// events recorded several times or events
	// that have been out of order as skipped
	SkippedEvents int64
	// OutOfOrderEvents is a counter with events
	// received out of order
	OutOfOrderEvents int64
	// TotalEvents contains total amount of
	// processed events (including duplicates)
	TotalEvents int64
}

ProtoReaderStats contains some reader statistics

func (ProtoReaderStats) ToFields

func (p ProtoReaderStats) ToFields() log.Fields

ToFields returns a copy of the stats to be used as log fields

type ProtoStream

type ProtoStream struct {
	// contains filtered or unexported fields
}

ProtoStream implements concurrent safe event emitter that uploads the parts in parallel to S3

func NewProtoStream

func NewProtoStream(cfg ProtoStreamConfig) (*ProtoStream, error)

NewProtoStream uploads session recordings in the protobuf format.

The individual session stream is represented by continuous globally ordered sequence of events serialized to binary protobuf format.

The stream is split into ordered slices of gzipped audit events.

Each slice is composed of three parts:

1. Slice starts with 24 bytes version header

* 8 bytes for the format version (used for future expansion) * 8 bytes for meaningful size of the part * 8 bytes for padding at the end of the slice (if present)

2. V1 body of the slice is gzipped protobuf messages in binary format.

3. Optional padding (if specified in the header), required to bring slices to minimum slice size.

The slice size is determined by S3 multipart upload requirements:

https://docs.aws.amazon.com/AmazonS3/latest/dev/qfacts.html

This design allows the streamer to upload slices using S3-compatible APIs in parallel without buffering to disk.

func (*ProtoStream) Close

func (s *ProtoStream) Close(ctx context.Context) error

Close flushes non-uploaded flight stream data without marking the stream completed and closes the stream instance

func (*ProtoStream) Complete

func (s *ProtoStream) Complete(ctx context.Context) error

Complete completes the upload, waits for completion and returns all allocated resources.

func (*ProtoStream) Done

func (s *ProtoStream) Done() <-chan struct{}

Done returns channel closed when streamer is closed should be used to detect sending errors

func (*ProtoStream) RecordEvent

RecordEvent emits a single audit event to the stream

func (*ProtoStream) Status

func (s *ProtoStream) Status() <-chan apievents.StreamStatus

Status returns channel receiving updates about stream status last event index that was uploaded and upload ID

type ProtoStreamConfig

type ProtoStreamConfig struct {
	// Upload is the upload this stream is handling
	Upload StreamUpload
	// Uploader handles upload to the storage
	Uploader MultipartUploader
	// BufferPool is a sync pool with buffers
	BufferPool *utils.BufferSyncPool
	// SlicePool is a sync pool with allocated slices
	SlicePool *utils.SliceSyncPool
	// MinUploadBytes submits upload when they have reached min bytes (could be more,
	// but not less), due to the nature of gzip writer
	MinUploadBytes int64
	// CompletedParts is a list of completed parts, used for resuming stream
	CompletedParts []StreamPart
	// InactivityFlushPeriod sets inactivity period
	// after which streamer flushes the data to the uploader
	// to avoid data loss
	InactivityFlushPeriod time.Duration
	// Clock is used to override time in tests
	Clock clockwork.Clock
	// ConcurrentUploads sets concurrent uploads per stream
	ConcurrentUploads int
}

ProtoStreamConfig configures proto stream

func (*ProtoStreamConfig) CheckAndSetDefaults

func (cfg *ProtoStreamConfig) CheckAndSetDefaults() error

CheckAndSetDefaults checks and sets default values

type ProtoStreamer

type ProtoStreamer struct {
	// contains filtered or unexported fields
}

ProtoStreamer creates protobuf-based streams uploaded to the storage backends, for example S3 or GCS

func NewProtoStreamer

func NewProtoStreamer(cfg ProtoStreamerConfig) (*ProtoStreamer, error)

NewProtoStreamer creates protobuf-based streams

func (*ProtoStreamer) CreateAuditStream

func (s *ProtoStreamer) CreateAuditStream(ctx context.Context, sid session.ID) (apievents.Stream, error)

CreateAuditStream creates audit stream and upload

func (*ProtoStreamer) CreateAuditStreamForUpload

func (s *ProtoStreamer) CreateAuditStreamForUpload(ctx context.Context, sid session.ID, upload StreamUpload) (apievents.Stream, error)

CreateAuditStreamForUpload creates audit stream for existing upload, this function is useful in tests

func (*ProtoStreamer) ResumeAuditStream

func (s *ProtoStreamer) ResumeAuditStream(ctx context.Context, sid session.ID, uploadID string) (apievents.Stream, error)

ResumeAuditStream resumes the stream that has not been completed yet

type ProtoStreamerConfig

type ProtoStreamerConfig struct {
	Uploader MultipartUploader
	// MinUploadBytes submits upload when they have reached min bytes (could be more,
	// but not less), due to the nature of gzip writer
	MinUploadBytes int64
	// ConcurrentUploads sets concurrent uploads per stream
	ConcurrentUploads int
}

ProtoStreamerConfig specifies configuration for the part

func (*ProtoStreamerConfig) CheckAndSetDefaults

func (cfg *ProtoStreamerConfig) CheckAndSetDefaults() error

CheckAndSetDefaults checks and sets streamer defaults

type ReportingStream

type ReportingStream struct {
	apievents.Stream
	// contains filtered or unexported fields
}

ReportingStream reports status of uploads to the events channel

func (*ReportingStream) Complete

func (s *ReportingStream) Complete(ctx context.Context) error

Complete closes the stream and marks it finalized

type ReportingStreamer

type ReportingStreamer struct {
	// contains filtered or unexported fields
}

ReportingStreamer reports upload events to the eventsC channel, if the channel is not nil.

func NewReportingStreamer

func NewReportingStreamer(streamer Streamer, eventsC chan UploadEvent) *ReportingStreamer

NewReportingStreamer reports upload events to the eventsC channel, if the channel is not nil.

func (*ReportingStreamer) CreateAuditStream

func (s *ReportingStreamer) CreateAuditStream(ctx context.Context, sid session.ID) (apievents.Stream, error)

CreateAuditStream creates audit event stream

func (*ReportingStreamer) ResumeAuditStream

func (s *ReportingStreamer) ResumeAuditStream(ctx context.Context, sid session.ID, uploadID string) (apievents.Stream, error)

ResumeAuditStream resumes audit event stream

type SSHPlaybackWriter

type SSHPlaybackWriter struct {
	EventsPath string
	ChunksPath string
	// contains filtered or unexported fields
}

SSHPlaybackWriter reads messages from an SessionReader and writes them to disk in a format suitable for SSH session playback.

func WriteForSSHPlayback

func WriteForSSHPlayback(ctx context.Context, sid session.ID, reader SessionReader, dir string) (*SSHPlaybackWriter, error)

WriteForSSHPlayback reads events from an SessionReader and writes them to disk in a format optimized for playback.

func (*SSHPlaybackWriter) Close

func (w *SSHPlaybackWriter) Close() error

Close closes all files

func (*SSHPlaybackWriter) SessionChunks

func (w *SSHPlaybackWriter) SessionChunks() ([]byte, error)

SessionChunks interprets the file at the given path as gzip-compressed list of session events and returns the uncompressed contents as a result.

func (*SSHPlaybackWriter) SessionEvents

func (w *SSHPlaybackWriter) SessionEvents() ([]EventFields, error)

SessionEvents returns slice of event fields from gzipped events file.

func (*SSHPlaybackWriter) Write

func (w *SSHPlaybackWriter) Write(ctx context.Context) error

Write writes all events from the SessionReader and writes files to disk in the format optimized for playback.

type SearchEventsLimiter

type SearchEventsLimiter struct {
	AuditLogger
	// contains filtered or unexported fields
}

SearchEventsLimiter allows to wrap any AuditLogger with rate limit on search events endpoints. Note it share limiter for both SearchEvents and SearchSessionEvents.

func NewSearchEventLimiter

func NewSearchEventLimiter(cfg SearchEventsLimiterConfig) (*SearchEventsLimiter, error)

NewSearchEventLimiter returns instance of new SearchEventsLimiter.

func (*SearchEventsLimiter) SearchEvents

func (*SearchEventsLimiter) SearchSessionEvents

type SearchEventsLimiterConfig

type SearchEventsLimiterConfig struct {
	// RefillTime determines the duration of time between the addition of tokens to the bucket.
	RefillTime time.Duration
	// RefillAmount is the number of tokens that are added to the bucket during interval
	// specified by RefillTime.
	RefillAmount int
	// Burst defines number of available tokens. It's initially full and refilled
	// based on RefillAmount and RefillTime.
	Burst int
	// AuditLogger is auditLogger that will be wrapped with limiter on search endpoints.
	AuditLogger AuditLogger
}

SearchEventsLimiterConfig is configuration for SearchEventsLimiter.

func (*SearchEventsLimiterConfig) CheckAndSetDefaults

func (cfg *SearchEventsLimiterConfig) CheckAndSetDefaults() error

type SearchEventsRequest

type SearchEventsRequest struct {
	// From is oldest date of returned events, can be zero.
	From time.Time
	// To is the newest date of returned events.
	To time.Time
	// EventTypes is optional, if not set, returns all events.
	EventTypes []string
	// Limit is the maximum amount of events returned.
	Limit int
	// Order specifies an ascending or descending order of events.
	Order types.EventOrder
	// StartKey is used to resume a query in order to enable pagination.
	// If the previous response had LastKey set then this should be
	// set to its value. Otherwise leave empty.
	StartKey string
}

type SearchSessionEventsRequest

type SearchSessionEventsRequest struct {
	// From is oldest date of returned events, can be zero.
	From time.Time
	// To is the newest date of returned events.
	To time.Time
	// Limit is the maximum amount of events returned.
	Limit int
	// Order specifies an ascending or descending order of events.
	Order types.EventOrder
	// StartKey is used to resume a query in order to enable pagination.
	// If the previous response had LastKey set then this should be
	// set to its value. Otherwise leave empty.
	StartKey string
	// Cond can be used to pass additional expression to query, can be empty.
	Cond *types.WhereExpr
	// SessionID is optional parameter to return session events only to given session.
	SessionID string
}

type ServerMetadataGetter

type ServerMetadataGetter interface {
	// GetServerID returns event server ID
	GetServerID() string

	// GetServerNamespace returns event server namespace
	GetServerNamespace() string

	// GetClusterName returns the originating teleport cluster name
	GetClusterName() string

	// GetForwardedBy returns the ID of the server that forwarded this event.
	GetForwardedBy() string
}

ServerMetadataGetter represents interface that provides information about its server id

type ServerMetadataSetter

type ServerMetadataSetter interface {
	// SetServerID sets server ID of the event
	SetServerID(string)

	// SetServerNamespace returns event server namespace
	SetServerNamespace(string)
}

ServerMetadataSetter represents interface that provides information about its server id

type SessionEventPreparer

type SessionEventPreparer interface {
	PrepareSessionEvent(event apievents.AuditEvent) (apievents.PreparedSessionEvent, error)
}

SessionEventPreparer will set necessary event fields for session-related events and must be called before the event is used, regardless of whether the event will be recorded, emitted, or both.

type SessionMetadataGetter

type SessionMetadataGetter interface {
	// GetSessionID returns event session ID
	GetSessionID() string
}

SessionMetadataGetter represents interface that provides information about events' session metadata

type SessionMetadataSetter

type SessionMetadataSetter interface {
	// SetSessionID sets event session ID
	SetSessionID(string)

	// SetClusterName sets teleport cluster name
	SetClusterName(string)
}

SessionMetadataSetter represents interface that sets session metadata

type SessionPreparerRecorder

type SessionPreparerRecorder interface {
	SessionEventPreparer
	SessionRecorder
}

SessionPreparerRecorder sets necessary session event fields and records them.

func NewSessionPreparerRecorder

func NewSessionPreparerRecorder(setter SessionEventPreparer, recorder SessionRecorder) SessionPreparerRecorder

NewSessionPreparerRecorder returns a SessionPreparerRecorder that can both setup and record session events.

func WithNoOpPreparer

func WithNoOpPreparer(rec SessionRecorder) SessionPreparerRecorder

WithNoOpPreparer wraps rec with a SessionEventPreparer that will leave events unchanged

type SessionReader

type SessionReader interface {
	// Read reads session events
	Read(context.Context) (apievents.AuditEvent, error)
}

SessionReader provides method to read session events one by one

type SessionRecorder

type SessionRecorder interface {
	io.Writer
	apievents.Stream
}

SessionRecorder records session events. It can be used both as a io.Writer when recording raw session data and as a apievents.Recorder when recording session events.

type SessionStreamer

type SessionStreamer interface {
	// GetSessionChunk returns a reader which can be used to read a byte stream
	// of a recorded session starting from 'offsetBytes' (pass 0 to start from the
	// beginning) up to maxBytes bytes.
	//
	// If maxBytes > MaxChunkBytes, it gets rounded down to MaxChunkBytes
	GetSessionChunk(namespace string, sid session.ID, offsetBytes, maxBytes int) ([]byte, error)

	// Returns all events that happen during a session sorted by time
	// (oldest first).
	//
	// after is used to return events after a specified cursor ID
	GetSessionEvents(namespace string, sid session.ID, after int) ([]EventFields, error)

	// StreamSessionEvents streams all events from a given session recording. An error is returned on the first
	// channel if one is encountered. Otherwise the event channel is closed when the stream ends.
	// The event channel is not closed on error to prevent race conditions in downstream select statements.
	StreamSessionEvents(ctx context.Context, sessionID session.ID, startIndex int64) (chan apievents.AuditEvent, chan error)
}

SessionStreamer supports streaming session chunks or events.

type SessionWriter

type SessionWriter struct {
	// contains filtered or unexported fields
}

SessionWriter wraps session stream and writes session events to it

func NewSessionWriter

func NewSessionWriter(cfg SessionWriterConfig) (*SessionWriter, error)

NewSessionWriter returns a new instance of session writer

func (*SessionWriter) Close

func (a *SessionWriter) Close(ctx context.Context) error

Close closes the stream and completes it, note that this behavior is different from Stream.Close, that aborts it, because of the way the writer is usually used the interface - io.WriteCloser has only close method

func (*SessionWriter) Complete

func (a *SessionWriter) Complete(ctx context.Context) error

Complete closes the stream and marks it finalized, releases associated resources, in case of failure, closes this stream on the client side

func (*SessionWriter) Done

func (a *SessionWriter) Done() <-chan struct{}

Done returns channel closed when streamer is closed should be used to detect sending errors

func (*SessionWriter) PrepareSessionEvent

func (a *SessionWriter) PrepareSessionEvent(event apievents.AuditEvent) (apievents.PreparedSessionEvent, error)

PrepareSessionEvent will set necessary event fields for session-related events and must be called before the event is recorded, regardless of whether the event will be recorded, emitted, or both.

func (*SessionWriter) RecordEvent

RecordEvent emits audit event

func (*SessionWriter) Stats

func (a *SessionWriter) Stats() SessionWriterStats

Stats returns up to date stats from this session writer

func (*SessionWriter) Status

func (a *SessionWriter) Status() <-chan apievents.StreamStatus

Status returns channel receiving updates about stream status last event index that was uploaded and upload ID

func (*SessionWriter) Write

func (a *SessionWriter) Write(data []byte) (int, error)

Write takes a chunk and writes it into the audit log

type SessionWriterConfig

type SessionWriterConfig struct {
	// SessionID defines the session to record.
	SessionID session.ID

	// Component is a component used for logging
	Component string

	// MakeEvents converts bytes written via the io.Writer interface
	// into AuditEvents that are written to the stream.
	// For backwards compatibility, SessionWriter will convert bytes to
	// SessionPrint events when MakeEvents is not provided.
	MakeEvents func([]byte) []apievents.AuditEvent

	// Preparer will set necessary fields of events created by Write.
	Preparer SessionEventPreparer

	// Streamer is used to create and resume audit streams
	Streamer Streamer

	// Context is a context to cancel the writes
	// or any other operations
	Context context.Context

	// Clock is used to override time in tests
	Clock clockwork.Clock

	// BackoffTimeout is a backoff timeout
	// if set, failed audit write events will be lost
	// if session writer fails to write events after this timeout
	BackoffTimeout time.Duration

	// BackoffDuration is a duration of the backoff before the next try
	BackoffDuration time.Duration
}

SessionWriterConfig configures session writer

func (*SessionWriterConfig) CheckAndSetDefaults

func (cfg *SessionWriterConfig) CheckAndSetDefaults() error

CheckAndSetDefaults checks and sets defaults

type SessionWriterStats

type SessionWriterStats struct {
	// AcceptedEvents is a total amount of events accepted for writes
	AcceptedEvents int64
	// LostEvents provides stats about lost events due to timeouts
	LostEvents int64
	// SlowWrites is a stat about how many times
	// events could not be written right away. It is a noisy
	// metric, so only used in debug modes.
	SlowWrites int64
}

SessionWriterStats provides stats about lost events and slow writes

type StreamEmitter

type StreamEmitter interface {
	apievents.Emitter
	Streamer
}

StreamEmitter supports emitting single events to the audit log and streaming events to a session recording.

type StreamPart

type StreamPart struct {
	// Number is a part number
	Number int64
	// ETag is a part e-tag
	ETag string
}

StreamPart represents uploaded stream part

type StreamUpload

type StreamUpload struct {
	// ID is unique upload ID
	ID string
	// SessionID is a session ID of the upload
	SessionID session.ID
	// Initiated contains the timestamp of when the upload
	// was initiated, not always initialized
	Initiated time.Time
}

StreamUpload represents stream multipart upload

func (*StreamUpload) CheckAndSetDefaults

func (u *StreamUpload) CheckAndSetDefaults() error

CheckAndSetDefaults checks and sets default values

func (StreamUpload) String

func (u StreamUpload) String() string

String returns user friendly representation of the upload

type Streamer

type Streamer interface {
	// CreateAuditStream creates event stream
	CreateAuditStream(context.Context, session.ID) (apievents.Stream, error)
	// ResumeAuditStream resumes the stream for session upload that
	// has not been completed yet.
	ResumeAuditStream(ctx context.Context, sid session.ID, uploadID string) (apievents.Stream, error)
}

Streamer creates and resumes event streams for session IDs

type StreamerAndEmitter

type StreamerAndEmitter struct {
	Streamer
	apievents.Emitter
}

StreamerAndEmitter combines streamer and emitter to create stream emitter

type UploadCompleter

type UploadCompleter struct {
	// contains filtered or unexported fields
}

UploadCompleter periodically scans uploads that have not been completed and completes them

func NewUploadCompleter

func NewUploadCompleter(cfg UploadCompleterConfig) (*UploadCompleter, error)

NewUploadCompleter returns a new UploadCompleter.

func (*UploadCompleter) CheckUploads

func (u *UploadCompleter) CheckUploads(ctx context.Context) error

CheckUploads fetches uploads and completes any abandoned uploads

func (*UploadCompleter) Close

func (u *UploadCompleter) Close()

Close stops the UploadCompleter

func (*UploadCompleter) Serve

func (u *UploadCompleter) Serve(ctx context.Context) error

Serve runs the upload completer until closed or until ctx is canceled.

type UploadCompleterConfig

type UploadCompleterConfig struct {
	// AuditLog is used for storing logs
	AuditLog AuditLogSessionStreamer
	// Uploader allows the completer to list and complete uploads
	Uploader MultipartUploader
	// SessionTracker is used to discover the current state of a
	// sesssions with active uploads.
	SessionTracker services.SessionTrackerService
	// Component is a component used in logging
	Component string
	// CheckPeriod is a period for checking the upload
	CheckPeriod time.Duration
	// Clock is used to override clock in tests
	Clock clockwork.Clock
	// ClusterName identifies the originating teleport cluster
	ClusterName string
}

UploadCompleterConfig specifies configuration for the uploader

func (*UploadCompleterConfig) CheckAndSetDefaults

func (cfg *UploadCompleterConfig) CheckAndSetDefaults() error

CheckAndSetDefaults checks and sets default values

type UploadEvent

type UploadEvent struct {
	// SessionID is a session ID
	SessionID string
	// UploadID specifies upload ID for a successful upload
	UploadID string
	// Error is set in case if event resulted in error
	Error error
	// Created is a time of when the event has been created
	Created time.Time
}

UploadEvent is emitted by uploader and is used in tests

type UploadHandler

type UploadHandler interface {
	// Upload uploads session tarball and returns URL with uploaded file
	// in case of success.
	Upload(ctx context.Context, sessionID session.ID, readCloser io.Reader) (string, error)
	// Download downloads session tarball and writes it to writer
	Download(ctx context.Context, sessionID session.ID, writer io.WriterAt) error
}

UploadHandler is a function supplied by the user, it will upload the file

type UploadMetadata

type UploadMetadata struct {
	// URL is the url at which the session recording is located
	// it is free-form and uploader-specific
	URL string
	// SessionID is the event session ID
	SessionID session.ID
}

UploadMetadata contains data about the session upload

type UploadMetadataGetter

type UploadMetadataGetter interface {
	GetUploadMetadata(sid session.ID) UploadMetadata
}

UploadMetadataGetter gets the metadata for session upload

type WriterEmitter

type WriterEmitter struct {
	*WriterLog
	// contains filtered or unexported fields
}

WriterEmitter is an emitter that emits all events to the external writer

func NewWriterEmitter

func NewWriterEmitter(w io.WriteCloser) *WriterEmitter

NewWriterEmitter returns a new instance of emitter writing to writer

func (*WriterEmitter) Close

func (w *WriterEmitter) Close() error

Close closes the underlying io.WriteCloser passed in NewWriterEmitter

func (*WriterEmitter) EmitAuditEvent

func (w *WriterEmitter) EmitAuditEvent(ctx context.Context, event apievents.AuditEvent) error

EmitAuditEvent writes the event to the writer

type WriterLog

type WriterLog struct {
	// contains filtered or unexported fields
}

WriterLog is an audit log that emits all events to the external writer

func NewWriterLog

func NewWriterLog(w io.WriteCloser) *WriterLog

NewWriterLog returns a new instance of writer log

func (*WriterLog) Close

func (w *WriterLog) Close() error

Close releases connection and resources associated with log if any

func (*WriterLog) SearchEvents

func (w *WriterLog) SearchEvents(ctx context.Context, req SearchEventsRequest) (events []apievents.AuditEvent, lastKey string, err error)

SearchEvents is a flexible way to find events.

Event types to filter can be specified and pagination is handled by an iterator key that allows a query to be resumed.

The only mandatory requirement is a date range (UTC). Results must always show up sorted by date (newest first)

func (*WriterLog) SearchSessionEvents

func (w *WriterLog) SearchSessionEvents(ctx context.Context, req SearchSessionEventsRequest) (events []apievents.AuditEvent, lastKey string, err error)

SearchSessionEvents is a flexible way to find session events. Only session.end and windows.desktop.session.end events are returned by this function. This is used to find completed sessions.

Event types to filter can be specified and pagination is handled by an iterator key that allows a query to be resumed.

Directories

Path Synopsis
Package firestoreeventsLog implements Firestore storage backend for Teleport event storage.
Package firestoreeventsLog implements Firestore storage backend for Teleport event storage.
Package gcssessionsHandler implements GCS storage for Teleport session recording persistence.
Package gcssessionsHandler implements GCS storage for Teleport session recording persistence.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL