events

package
v1.2.3-fred.7 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2022 License: Apache-2.0 Imports: 38 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"

	// SessionEvent 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"

	// 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"
	// BotTokenCreateEvent is emitted when a new bot join user token is created
	BotTokenCreateEvent = "bot_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/updated.
	RoleCreatedEvent = "role.created"
	// 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 join token for a trusted cluster.
	TrustedClusterTokenCreateEvent = "trusted_cluster_token.create"

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

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

	// SessionConnect 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"

	// 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"

	// 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"
	// 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"

	// UnknownEvent is any event received that isn't recognized as any other event type.
	UnknownEvent = apievents.UnknownEvent
)
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"

	// StreamingLogsDir is a subdirectory of sessions /var/lib/teleport/log/streaming
	// 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.
	StreamingLogsDir = "streaming"

	// 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"
)
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"

	// 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"

	// 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"

	// 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"

	// 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"

	// 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 join token for a trusted cluster.
	TrustedClusterTokenCreateCode = "T7002I"

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

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

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

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

	// 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"

	// 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).

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

	// 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 (
	// 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.",
		},
	)
)

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 GenerateTestSession

func GenerateTestSession(params SessionParams) []apievents.AuditEvent

GenerateTestSession generates test session events starting with session start event, adds printEvents events and returns the result.

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 IsPermanentEmitError

func IsPermanentEmitError(err error) bool

IsPermanentEmitError checks if the error contains underlying BadParameter error.

func NewCheckingStream

func NewCheckingStream(stream apievents.Stream, clock clockwork.Clock, clusterName string) apievents.Stream

NewCheckingStream wraps stream and makes sure event UIDs and timing are in place

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 IAuditLog

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) 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, includePrintEvents bool) ([]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)

This function is usually used in conjunction with GetSessionReader to replay recorded session streams.

func (*AuditLog) SearchEvents added in v1.0.0

func (l *AuditLog) SearchEvents(fromUTC, toUTC time.Time, namespace string, eventType []string, limit int, order types.EventOrder, startKey string) ([]apievents.AuditEvent, string, error)

func (*AuditLog) SearchSessionEvents

func (l *AuditLog) SearchSessionEvents(fromUTC, toUTC time.Time, limit int, order types.EventOrder, startKey string, cond *types.WhereExpr, sessionID string) ([]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 IAuditLog

	// 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 AuditReader

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

AuditReader provides method to read audit events one by one

type AuditWriter

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

AuditWriter wraps session stream and writes audit events to it

func NewAuditWriter

func NewAuditWriter(cfg AuditWriterConfig) (*AuditWriter, error)

NewAuditWriter returns a new instance of session writer

func (*AuditWriter) Close

func (a *AuditWriter) 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 (*AuditWriter) Complete

func (a *AuditWriter) 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 (*AuditWriter) Done

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

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

func (*AuditWriter) EmitAuditEvent

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

EmitAuditEvent emits audit event

func (*AuditWriter) Stats

func (a *AuditWriter) Stats() AuditWriterStats

Stats returns up to date stats from this audit writer

func (*AuditWriter) Status

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

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

func (*AuditWriter) Write

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

Write takes a chunk and writes it into the audit log

type AuditWriterConfig

type AuditWriterConfig 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

	// RecordOutput stores info on whether to record session output
	RecordOutput bool

	// 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, AuditWriter will convert bytes to
	// SessionPrint events when MakeEvents is not provided.
	MakeEvents func([]byte) []apievents.AuditEvent

	// 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

	// UID is UID generator
	UID utils.UID

	// BackoffTimeout is a backoff timeout
	// if set, failed audit write events will be lost
	// if audit 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

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

AuditWriterConfig configures audit writer

func (*AuditWriterConfig) CheckAndSetDefaults

func (cfg *AuditWriterConfig) CheckAndSetDefaults() error

CheckAndSetDefaults checks and sets defaults

type AuditWriterStats

type AuditWriterStats 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
}

AuditWriterStats provides stats about lost events and slow writes

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 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) EmitAuditEvent

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

EmitAuditEvent emits audit 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)
	// OnEmitAuditEvent is called on emit audit event on a stream
	OnEmitAuditEvent func(ctx context.Context, sid session.ID, event apievents.AuditEvent) 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 CheckingStream

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

CheckingStream verifies every event

func (*CheckingStream) Close

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

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

func (*CheckingStream) Complete

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

Complete closes the stream and marks it finalized

func (*CheckingStream) Done

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

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

func (*CheckingStream) EmitAuditEvent

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

EmitAuditEvent emits audit event

func (*CheckingStream) Status

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

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

type CheckingStreamer

type CheckingStreamer struct {
	CheckingStreamerConfig
}

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

func NewCheckingStreamer

func NewCheckingStreamer(cfg CheckingStreamerConfig) (*CheckingStreamer, error)

NewCheckingStreamer returns streamer that checks that all required fields are properly set

func (*CheckingStreamer) CreateAuditStream

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

CreateAuditStream creates audit event stream

func (*CheckingStreamer) ResumeAuditStream

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

ResumeAuditStream resumes audit event stream

type CheckingStreamerConfig

type CheckingStreamerConfig struct {
	// Inner emits events to the underlying store
	Inner Streamer
	// 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.
	ClusterName string
}

CheckingStreamerConfig provides parameters for streamer

func (*CheckingStreamerConfig) CheckAndSetDefaults

func (w *CheckingStreamerConfig) 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, includePrintEvents bool) ([]EventFields, error)

func (*DiscardAuditLog) SearchEvents added in v1.1.0

func (d *DiscardAuditLog) SearchEvents(fromUTC, toUTC time.Time, namespace string, eventType []string, limit int, order types.EventOrder, startKey string) ([]apievents.AuditEvent, string, error)

func (*DiscardAuditLog) SearchSessionEvents

func (d *DiscardAuditLog) SearchSessionEvents(fromUTC, toUTC time.Time, limit int, order types.EventOrder, startKey string, cond *types.WhereExpr, sessionID string) ([]apievents.AuditEvent, string, error)

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) CreateAuditStream

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

CreateAuditStream creates a stream that discards all events

func (*DiscardEmitter) EmitAuditEvent

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

EmitAuditEvent discards audit event

func (*DiscardEmitter) ResumeAuditStream

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

ResumeAuditStream resumes a stream that discards all events

type DiscardStream

type DiscardStream struct{}

DiscardStream returns a stream that discards all events

func (*DiscardStream) Close

func (*DiscardStream) Close(ctx context.Context) error

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

func (*DiscardStream) Complete

func (*DiscardStream) Complete(ctx context.Context) error

Complete does nothing

func (*DiscardStream) Done

func (*DiscardStream) Done() <-chan struct{}

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

func (*DiscardStream) EmitAuditEvent

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

EmitAuditEvent discards audit event

func (*DiscardStream) Status

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

Status returns a channel that always blocks

func (*DiscardStream) Write

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

Write discards data

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) GetSessionChunk

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

func (*FileLog) GetSessionEvents

func (l *FileLog) GetSessionEvents(namespace string, sid session.ID, after int, fetchPrintEvents bool) ([]EventFields, error)

func (*FileLog) SearchEvents

func (l *FileLog) SearchEvents(fromUTC, toUTC time.Time, namespace string, eventTypes []string, limit int, order types.EventOrder, startAfter string) ([]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(fromUTC, toUTC time.Time, limit int, order types.EventOrder, startKey string, cond *types.WhereExpr, sessionID string) ([]apievents.AuditEvent, string, error)

func (*FileLog) StreamSessionEvents

func (l *FileLog) 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 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 IAuditLog added in v1.0.0

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

	// EmitAuditEvent emits audit event
	EmitAuditEvent(context.Context, apievents.AuditEvent) error

	// 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 tells to use only return events after a specified cursor Id
	//
	// This function is usually used in conjunction with GetSessionReader to
	// replay recorded session streams.
	GetSessionEvents(namespace string, sid session.ID, after int, includePrintEvents bool) ([]EventFields, 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.
	SearchEvents(fromUTC, toUTC time.Time, namespace string, eventTypes []string, limit int, order types.EventOrder, startKey string) ([]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(fromUTC, toUTC time.Time, limit int, order types.EventOrder, startKey string, cond *types.WhereExpr, sessionID string) ([]apievents.AuditEvent, string, 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)
}

IAuditLog is the primary (and the only external-facing) interface for AuditLogger. If you wish to implement a different kind of logger (not filesystem-based), you have to implement this interface

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 MemoryUpload

type MemoryUpload struct {

	// Initiated contains the timestamp of when the upload
	// was initiated, not always initialized
	Initiated time.Time
	// contains filtered or unexported fields
}

MemoryUpload is used in tests

type MemoryUploader

type MemoryUploader struct {
	Clock clockwork.Clock
	// contains filtered or unexported fields
}

MemoryUploader uploads all bytes to memory, used in tests

func NewMemoryUploader

func NewMemoryUploader(eventsC ...chan UploadEvent) *MemoryUploader

NewMemoryUploader returns a new memory uploader implementing multipart upload

func (*MemoryUploader) CompleteUpload

func (m *MemoryUploader) CompleteUpload(ctx context.Context, upload StreamUpload, parts []StreamPart) error

CompleteUpload completes the upload

func (*MemoryUploader) CreateUpload

func (m *MemoryUploader) CreateUpload(ctx context.Context, sessionID session.ID) (*StreamUpload, error)

CreateUpload creates a multipart upload

func (*MemoryUploader) Download

func (m *MemoryUploader) Download(ctx context.Context, sessionID session.ID, writer io.WriterAt) error

Download downloads session tarball and writes it to writer

func (*MemoryUploader) GetParts

func (m *MemoryUploader) GetParts(uploadID string) ([][]byte, error)

GetParts returns upload parts uploaded up to date, sorted by part number

func (*MemoryUploader) GetUploadMetadata

func (m *MemoryUploader) GetUploadMetadata(sid session.ID) UploadMetadata

GetUploadMetadata gets the session upload metadata

func (*MemoryUploader) ListParts

func (m *MemoryUploader) ListParts(ctx context.Context, upload StreamUpload) ([]StreamPart, error)

ListParts returns all uploaded parts for the completed upload in sorted order

func (*MemoryUploader) ListUploads

func (m *MemoryUploader) ListUploads(ctx context.Context) ([]StreamUpload, error)

ListUploads lists uploads that have been initiated but not completed with earlier uploads returned first.

func (*MemoryUploader) ReserveUploadPart

func (m *MemoryUploader) ReserveUploadPart(ctx context.Context, upload StreamUpload, partNumber int64) error

ReserveUploadPart reserves an upload part.

func (*MemoryUploader) Reset

func (m *MemoryUploader) Reset()

Reset resets all state, removes all uploads and objects

func (*MemoryUploader) Upload

func (m *MemoryUploader) Upload(ctx context.Context, sessionID session.ID, readCloser io.Reader) (string, error)

Upload uploads session tarball and returns URL with uploaded file in case of success.

func (*MemoryUploader) UploadPart

func (m *MemoryUploader) UploadPart(ctx context.Context, upload StreamUpload, partNumber int64, partBody io.ReadSeeker) (*StreamPart, error)

UploadPart uploads part and returns the part

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 ...IAuditLog) (*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) GetSessionChunk

func (m *MultiLog) GetSessionChunk(namespace string, sid session.ID, offsetBytes, maxBytes int) (data []byte, err error)

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

func (*MultiLog) GetSessionEvents

func (m *MultiLog) GetSessionEvents(namespace string, sid session.ID, after int, fetchPrintEvents bool) (events []EventFields, err error)

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

after tells to use only return events after a specified cursor Id

This function is usually used in conjunction with GetSessionReader to replay recorded session streams.

func (*MultiLog) SearchEvents

func (m *MultiLog) SearchEvents(fromUTC, toUTC time.Time, namespace string, eventTypes []string, limit int, order types.EventOrder, startKey string) (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(fromUTC, toUTC time.Time, limit int, order types.EventOrder, startKey string, cond *types.WhereExpr, sessionID string) (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.

func (*MultiLog) StreamSessionEvents

func (m *MultiLog) 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 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 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) EmitAuditEvent

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

EmitAuditEvent 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 AuditReader and writes them to disk in a format suitable for SSH session playback.

func WriteForSSHPlayback

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

WriteForSSHPlayback reads events from an AuditReader 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 AuditReader and writes files to disk in the format optimized for playback.

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 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 SessionParams

type SessionParams struct {
	// PrintEvents sets up print events count
	PrintEvents int64
	// Clock is an optional clock setting start
	// and offset time of the event
	Clock clockwork.Clock
	// ServerID is an optional server ID
	ServerID string
	// SessionID is an optional session ID to set
	SessionID string
	// ClusterName is an optional originating cluster name
	ClusterName string
}

SessionParams specifies optional parameters for generated session

func (*SessionParams) SetDefaults

func (p *SessionParams) SetDefaults()

SetDefaults sets parameters defaults

type StreamEmitter

type StreamEmitter interface {
	apievents.Emitter
	Streamer
}

StreamEmitter supports submitting single events and streaming session events

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 StreamWriter

type StreamWriter interface {
	io.Writer
	apievents.Stream
}

StreamWriter implements io.Writer to be plugged into the multi-writer associated with every session. It forwards session stream to the audit log

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 TeeStream

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

TeeStream sends non print events to emitter in addition to the stream itself

func (*TeeStream) Close

func (t *TeeStream) Close(ctx context.Context) error

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

func (*TeeStream) Complete

func (t *TeeStream) Complete(ctx context.Context) error

Complete closes the stream and marks it finalized

func (*TeeStream) Done

func (t *TeeStream) Done() <-chan struct{}

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

func (*TeeStream) EmitAuditEvent

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

EmitAuditEvent emits audit events and forwards session control events to the audit log

func (*TeeStream) Status

func (t *TeeStream) Status() <-chan apievents.StreamStatus

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

type TeeStreamer

type TeeStreamer struct {
	apievents.Emitter
	// contains filtered or unexported fields
}

TeeStreamer creates streams that forwards non print events to emitter

func NewTeeStreamer

func NewTeeStreamer(streamer Streamer, emitter apievents.Emitter) *TeeStreamer

NewTeeStreamer returns a streamer that forwards non print event to emitter in addition to sending them to the stream

func (*TeeStreamer) CreateAuditStream

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

CreateAuditStream creates audit event stream

func (*TeeStreamer) ResumeAuditStream

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

ResumeAuditStream resumes audit event stream

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) 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 IAuditLog
	// 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) GetSessionChunk

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

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

func (*WriterLog) GetSessionEvents

func (w *WriterLog) GetSessionEvents(namespace string, sid session.ID, after int, includePrintEvents bool) ([]EventFields, error)

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

after tells to use only return events after a specified cursor Id

This function is usually used in conjunction with GetSessionReader to replay recorded session streams.

func (*WriterLog) SearchEvents

func (w *WriterLog) SearchEvents(fromUTC, toUTC time.Time, namespace string, eventTypes []string, limit int, order types.EventOrder, startKey string) (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(fromUTC, toUTC time.Time, limit int, order types.EventOrder, startKey string, cond *types.WhereExpr, sessionID string) (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.

func (*WriterLog) StreamSessionEvents

func (w *WriterLog) 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.

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