-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Capture postgres extended protocol messages in audit log (#6303)
- Loading branch information
Showing
18 changed files
with
1,062 additions
and
450 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,152 @@ | ||
/* | ||
Copyright 2021 Gravitational, Inc. | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
*/ | ||
|
||
package db | ||
|
||
import ( | ||
"context" | ||
"testing" | ||
"time" | ||
|
||
"github.com/gravitational/teleport/api/types" | ||
"github.com/gravitational/teleport/api/types/events" | ||
"github.com/gravitational/teleport/lib/auth" | ||
libevents "github.com/gravitational/teleport/lib/events" | ||
|
||
"github.com/gravitational/trace" | ||
"github.com/sirupsen/logrus" | ||
"github.com/stretchr/testify/require" | ||
) | ||
|
||
// TestAuditPostgres verifies proper audit events are emitted for Postgres | ||
// connections. | ||
func TestAuditPostgres(t *testing.T) { | ||
ctx := context.Background() | ||
testCtx := setupTestContext(ctx, t) | ||
t.Cleanup(func() { testCtx.Close() }) | ||
go testCtx.startHandlingPostgresConnections() | ||
|
||
_, role, err := auth.CreateUserAndRole(testCtx.tlsServer.Auth(), "alice", []string{"admin"}) | ||
require.NoError(t, err) | ||
|
||
role.SetDatabaseNames(types.Allow, []string{"postgres"}) | ||
role.SetDatabaseUsers(types.Allow, []string{"postgres"}) | ||
err = testCtx.tlsServer.Auth().UpsertRole(ctx, role) | ||
require.NoError(t, err) | ||
|
||
// Access denied should trigger an unsuccessful session start event. | ||
_, err = testCtx.postgresClient(ctx, "alice", "notpostgres", "notpostgres") | ||
require.Error(t, err) | ||
requireEvent(t, testCtx, libevents.DatabaseSessionStartFailureCode) | ||
|
||
// Connect should trigger successful session start event. | ||
psql, err := testCtx.postgresClient(ctx, "alice", "postgres", "postgres") | ||
require.NoError(t, err) | ||
requireEvent(t, testCtx, libevents.DatabaseSessionStartCode) | ||
|
||
// Simple query should trigger the query event. | ||
_, err = psql.Exec(ctx, "select 1").ReadAll() | ||
require.NoError(t, err) | ||
requireQueryEvent(t, testCtx, libevents.DatabaseSessionQueryCode, "select 1") | ||
|
||
// Prepared statement execution should also trigger a query event. | ||
result := psql.ExecParams(ctx, "select now()", nil, nil, nil, nil).Read() | ||
require.NoError(t, result.Err) | ||
requireQueryEvent(t, testCtx, libevents.DatabaseSessionQueryCode, "select now()") | ||
|
||
// Closing connection should trigger session end event. | ||
err = psql.Close(ctx) | ||
require.NoError(t, err) | ||
requireEvent(t, testCtx, libevents.DatabaseSessionEndCode) | ||
} | ||
|
||
// TestAuditMySQL verifies proper audit events are emitted for MySQL | ||
// connections. | ||
func TestAuditMySQL(t *testing.T) { | ||
ctx := context.Background() | ||
testCtx := setupTestContext(ctx, t) | ||
t.Cleanup(func() { testCtx.Close() }) | ||
go testCtx.startHandlingMySQLConnections() | ||
|
||
_, role, err := auth.CreateUserAndRole(testCtx.tlsServer.Auth(), "alice", []string{"admin"}) | ||
require.NoError(t, err) | ||
|
||
role.SetDatabaseUsers(types.Allow, []string{"root"}) | ||
err = testCtx.tlsServer.Auth().UpsertRole(ctx, role) | ||
require.NoError(t, err) | ||
|
||
// Access denied should trigger an unsuccessful session start event. | ||
_, err = testCtx.mysqlClient("alice", "notroot") | ||
require.Error(t, err) | ||
requireEvent(t, testCtx, libevents.DatabaseSessionStartFailureCode) | ||
|
||
// Connect should trigger successful session start event. | ||
mysql, err := testCtx.mysqlClient("alice", "root") | ||
require.NoError(t, err) | ||
requireEvent(t, testCtx, libevents.DatabaseSessionStartCode) | ||
|
||
// Simple query should trigger the query event. | ||
_, err = mysql.Execute("select 1") | ||
require.NoError(t, err) | ||
requireQueryEvent(t, testCtx, libevents.DatabaseSessionQueryCode, "select 1") | ||
|
||
// Closing connection should trigger session end event. | ||
err = mysql.Close() | ||
require.NoError(t, err) | ||
requireEvent(t, testCtx, libevents.DatabaseSessionEndCode) | ||
} | ||
|
||
func requireEvent(t *testing.T, testCtx *testContext, code string) { | ||
event := waitForEvent(t, testCtx, code) | ||
require.Equal(t, code, event.GetCode()) | ||
} | ||
|
||
func requireQueryEvent(t *testing.T, testCtx *testContext, code, query string) { | ||
event := waitForEvent(t, testCtx, code) | ||
require.Equal(t, code, event.GetCode()) | ||
require.Equal(t, query, event.(*events.DatabaseSessionQuery).DatabaseQuery) | ||
} | ||
|
||
func waitForEvent(t *testing.T, testCtx *testContext, code string) events.AuditEvent { | ||
select { | ||
case event := <-testCtx.emitter.eventsCh: | ||
return event | ||
case <-time.After(time.Second): | ||
t.Fatalf("didn't receive %v event after 1 second", code) | ||
} | ||
return nil | ||
} | ||
|
||
// testEmitter pushes all received audit events into a channel. | ||
type testEmitter struct { | ||
eventsCh chan events.AuditEvent | ||
log logrus.FieldLogger | ||
} | ||
|
||
// newTestEmitter returns a new instance of test emitter. | ||
func newTestEmitter() *testEmitter { | ||
return &testEmitter{ | ||
eventsCh: make(chan events.AuditEvent, 100), | ||
log: logrus.WithField(trace.Component, "emitter"), | ||
} | ||
} | ||
|
||
// EmitAuditEvent records the provided event in the test emitter. | ||
func (e *testEmitter) EmitAuditEvent(ctx context.Context, event events.AuditEvent) error { | ||
e.log.Infof("EmitAuditEvent(%v)", event) | ||
e.eventsCh <- event | ||
return nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,141 @@ | ||
/* | ||
Copyright 2021 Gravitational, Inc. | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
*/ | ||
|
||
package common | ||
|
||
import ( | ||
"sync" | ||
|
||
"github.com/gravitational/trace" | ||
) | ||
|
||
// StatementsCache contains prepared statements client executes during a | ||
// database session. | ||
// | ||
// Currently only used to support Postgres extended protocol message flow | ||
// to capture prepared statement queries in the audit log: | ||
// | ||
// https://www.postgresql.org/docs/10/protocol-flow.html#PROTOCOL-FLOW-EXT-QUERY | ||
type StatementsCache struct { | ||
// cache maps prepared statement name to the statement itself. | ||
cache map[string]*Statement | ||
// mu is used to synchronize cache access. | ||
mu sync.RWMutex | ||
} | ||
|
||
// Statement represents a prepared statement. | ||
type Statement struct { | ||
// Name is the prepared statement name. | ||
// | ||
// Can be empty (Postgres "unnamed statement"). | ||
Name string | ||
// Query is the statement query string. | ||
Query string | ||
// Portals contains "destination portals" that bind prepared statement to | ||
// parameters. | ||
// | ||
// In Postgres extended query protocol, clients execute these "portals" | ||
// and not prepared statements directly. | ||
Portals map[string]*Portal | ||
} | ||
|
||
// Portal represents a destination portal that binds a prepared statement | ||
// to parameters. | ||
type Portal struct { | ||
// Name is the portal name. | ||
// | ||
// Can be empty (Postgres "unnamed portal"). | ||
Name string | ||
// Query is the prepared statement query string. | ||
Query string | ||
// Parameters are the query parameters. | ||
Parameters []string | ||
} | ||
|
||
// NewStatementsCache returns a new instance of prepared statements cache. | ||
func NewStatementsCache() *StatementsCache { | ||
return &StatementsCache{cache: make(map[string]*Statement)} | ||
} | ||
|
||
// Save adds the provided prepared statement information to the cache. | ||
func (s *StatementsCache) Save(statementName, query string) { | ||
s.mu.Lock() | ||
defer s.mu.Unlock() | ||
s.cache[statementName] = &Statement{ | ||
Name: statementName, | ||
Query: query, | ||
Portals: make(map[string]*Portal), | ||
} | ||
} | ||
|
||
// Get returns the specified prepared statement from the cache. | ||
func (s *StatementsCache) Get(statementName string) (*Statement, error) { | ||
s.mu.RLock() | ||
defer s.mu.RUnlock() | ||
if statement, ok := s.cache[statementName]; ok { | ||
return statement, nil | ||
} | ||
return nil, trace.NotFound("prepared statement %q is not in cache", statementName) | ||
} | ||
|
||
// GetPortal returns the specified destination portal from the cache. | ||
func (s *StatementsCache) GetPortal(portalName string) (*Portal, error) { | ||
s.mu.RLock() | ||
defer s.mu.RUnlock() | ||
for _, statement := range s.cache { | ||
if portal, ok := statement.Portals[portalName]; ok { | ||
return portal, nil | ||
} | ||
} | ||
return nil, trace.NotFound("destination portal %q is not in cache", portalName) | ||
} | ||
|
||
// Bind adds the provided destination portal to the cache. | ||
func (s *StatementsCache) Bind(statementName, portalName string, parameters ...string) error { | ||
s.mu.Lock() | ||
defer s.mu.Unlock() | ||
for name, statement := range s.cache { | ||
if name == statementName { | ||
s.cache[name].Portals[portalName] = &Portal{ | ||
Name: portalName, | ||
Query: statement.Query, | ||
Parameters: parameters, | ||
} | ||
return nil | ||
} | ||
} | ||
return trace.NotFound("prepared statement %q is not in cache", statementName) | ||
} | ||
|
||
// Remove removes the specified prepared statement from the cache, along with | ||
// all its destination portals. | ||
func (s *StatementsCache) Remove(statementName string) { | ||
s.mu.Lock() | ||
defer s.mu.Unlock() | ||
delete(s.cache, statementName) | ||
} | ||
|
||
// RemovePortal removes the specified destination portal from the cache. | ||
func (s *StatementsCache) RemovePortal(portalName string) { | ||
s.mu.Lock() | ||
defer s.mu.Unlock() | ||
for statementName, statement := range s.cache { | ||
if _, ok := statement.Portals[portalName]; ok { | ||
delete(s.cache[statementName].Portals, portalName) | ||
return | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,148 @@ | ||
/* | ||
Copyright 2021 Gravitational, Inc. | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
*/ | ||
|
||
package common | ||
|
||
import ( | ||
"testing" | ||
|
||
"github.com/gravitational/trace" | ||
"github.com/stretchr/testify/require" | ||
) | ||
|
||
// TestStatementsCache verifies functionality of the cache that holds per-session | ||
// prepared statements and their parameters. | ||
func TestStatementsCache(t *testing.T) { | ||
cache := NewStatementsCache() | ||
|
||
// Full parse/bind/execute flow with an unnamed statement/portal. | ||
cache.Save(testUnnamedStatement1.Name, testUnnamedStatement1.Query) | ||
cache.Bind(testUnnamedStatement1.Name, testUnnamedPortal1.Name, testUnnamedPortal1.Parameters...) | ||
|
||
statement, err := cache.Get(unnamedStatement) | ||
require.NoError(t, err) | ||
require.Equal(t, testUnnamedStatement1, statement) | ||
|
||
portal, err := cache.GetPortal(unnamedPortal) | ||
require.NoError(t, err) | ||
require.Equal(t, testUnnamedPortal1, portal) | ||
|
||
// Make sure another unnamed statement replaces the previous one. | ||
cache.Save(testUnnamedStatement2.Name, testUnnamedStatement2.Query) | ||
cache.Bind(testUnnamedStatement2.Name, testUnnamedPortal2.Name, testUnnamedPortal2.Parameters...) | ||
|
||
statement, err = cache.Get(unnamedStatement) | ||
require.NoError(t, err) | ||
require.Equal(t, testUnnamedStatement2, statement) | ||
|
||
portal, err = cache.GetPortal(unnamedPortal) | ||
require.NoError(t, err) | ||
require.Equal(t, testUnnamedPortal2, portal) | ||
|
||
// Create a named statement and a couple of destination portals. | ||
cache.Save(testStatement.Name, testStatement.Query) | ||
cache.Bind(testStatement.Name, testPortal1.Name, testPortal1.Parameters...) | ||
cache.Bind(testStatement.Name, testPortal2.Name, testPortal2.Parameters...) | ||
|
||
statement, err = cache.Get(testStatement.Name) | ||
require.NoError(t, err) | ||
require.Equal(t, testStatement, statement) | ||
|
||
portal1, err := cache.GetPortal(testPortal1.Name) | ||
require.NoError(t, err) | ||
require.Equal(t, testPortal1, portal1) | ||
|
||
portal2, err := cache.GetPortal(testPortal2.Name) | ||
require.NoError(t, err) | ||
require.Equal(t, testPortal2, portal2) | ||
|
||
// Try to get a couple non-existent statements/portals. | ||
_, err = cache.Get("unknown") | ||
require.IsType(t, trace.NotFound(""), err) | ||
|
||
_, err = cache.GetPortal("unknown") | ||
require.IsType(t, trace.NotFound(""), err) | ||
|
||
// Close a portal. | ||
cache.RemovePortal(testPortal1.Name) | ||
|
||
_, err = cache.GetPortal(testPortal1.Name) | ||
require.IsType(t, trace.NotFound(""), err) | ||
|
||
// Close a statement and make sure its portal is gone as well. | ||
cache.Remove(testStatement.Name) | ||
|
||
_, err = cache.Get(testStatement.Name) | ||
require.IsType(t, trace.NotFound(""), err) | ||
|
||
_, err = cache.GetPortal(testPortal2.Name) | ||
require.IsType(t, trace.NotFound(""), err) | ||
} | ||
|
||
const ( | ||
unnamedStatement = "" | ||
unnamedPortal = "" | ||
) | ||
|
||
var ( | ||
testQuery1 = "select * from test" | ||
testUnnamedPortal1 = &Portal{ | ||
Name: unnamedPortal, | ||
Query: testQuery1, | ||
Parameters: []string{}, | ||
} | ||
testUnnamedStatement1 = &Statement{ | ||
Name: unnamedStatement, | ||
Query: testQuery1, | ||
Portals: map[string]*Portal{ | ||
unnamedPortal: testUnnamedPortal1, | ||
}, | ||
} | ||
|
||
testQuery2 = "select * from test where id = $1" | ||
testUnnamedPortal2 = &Portal{ | ||
Name: unnamedPortal, | ||
Query: testQuery2, | ||
Parameters: []string{"123"}, | ||
} | ||
testUnnamedStatement2 = &Statement{ | ||
Name: unnamedStatement, | ||
Query: testQuery2, | ||
Portals: map[string]*Portal{ | ||
unnamedPortal: testUnnamedPortal2, | ||
}, | ||
} | ||
|
||
testQuery3 = "update test set value = $1 where id = $2" | ||
testPortal1 = &Portal{ | ||
Name: "P_1", | ||
Query: testQuery3, | ||
Parameters: []string{"abc", "123"}, | ||
} | ||
testPortal2 = &Portal{ | ||
Name: "P_2", | ||
Query: testQuery3, | ||
Parameters: []string{"def", "456"}, | ||
} | ||
testStatement = &Statement{ | ||
Name: "S_1", | ||
Query: testQuery3, | ||
Portals: map[string]*Portal{ | ||
"P_1": testPortal1, | ||
"P_2": testPortal2, | ||
}, | ||
} | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters