-
Notifications
You must be signed in to change notification settings - Fork 0
/
auditlog.go
941 lines (851 loc) · 27.1 KB
/
auditlog.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
/*
Copyright 2015-2019 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 events
import (
"bufio"
"bytes"
"compress/gzip"
"context"
"encoding/json"
"fmt"
"io"
"math"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"github.com/gravitational/teleport"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/session"
"github.com/gravitational/teleport/lib/utils"
"github.com/gravitational/trace"
"github.com/jonboulle/clockwork"
"github.com/prometheus/client_golang/prometheus"
log "github.com/sirupsen/logrus"
)
const (
// SessionLogsDir is a subdirectory inside the eventlog data dir
// where all session-specific logs and streams are stored, like
// in /var/lib/teleport/logs/sessions
SessionLogsDir = "sessions"
// PlaybacksDir is a directory for playbacks
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"
// sessionsMigratedEvent is a sessions migration event used internally
sessionsMigratedEvent = "sessions.migrated"
)
var (
auditOpenFiles = prometheus.NewGauge(
prometheus.GaugeOpts{
Name: "audit_server_open_files",
Help: "Number of open audit files",
},
)
)
func init() {
// Metrics have to be registered to be exposed:
prometheus.MustRegister(auditOpenFiles)
}
// AuditLog is a new combined facility to record Teleport events and
// sessions. It implements IAuditLog
type AuditLog struct {
sync.Mutex
*log.Entry
AuditLogConfig
// playbackDir is a directory used for unpacked session recordings
playbackDir string
// fileTime is a rounded (to a day, by default) timestamp of the
// currently opened file
fileTime time.Time
// activeDownloads helps to serialize simultaneous downloads
// from the session record server
activeDownloads map[string]context.Context
// ctx signals close of the audit log
ctx context.Context
// cancel triggers closing of the signal context
cancel context.CancelFunc
// localLog is a local events log used
// to emit audit events if no external log has been specified
localLog *FileLog
}
// AuditLogConfig specifies configuration for AuditLog server
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
// RecordSessions controls if sessions are recorded along with audit events.
RecordSessions bool
// RotationPeriod defines how frequently to rotate the log file
RotationPeriod time.Duration
// SessionIdlePeriod defines the period after which sessions will be considered
// idle (and audit log will free up some resources)
SessionIdlePeriod 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 userownership 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 UploadHandler
// ExternalLog is a pluggable external log service
ExternalLog IAuditLog
// EventC is evnets channel for testing purposes, not used if empty
EventsC chan *AuditLogEvent
}
// AuditLogEvent is an internal audit log event
type AuditLogEvent struct {
// Type is an event type
Type string
// Error is an event error
Error error
}
// CheckAndSetDefaults checks and sets defaults
func (a *AuditLogConfig) CheckAndSetDefaults() error {
if a.DataDir == "" {
return trace.BadParameter("missing parameter DataDir")
}
if a.ServerID == "" {
return trace.BadParameter("missing parameter ServerID")
}
if a.Clock == nil {
a.Clock = clockwork.NewRealClock()
}
if a.UIDGenerator == nil {
a.UIDGenerator = utils.NewRealUID()
}
if a.RotationPeriod == 0 {
a.RotationPeriod = defaults.LogRotationPeriod
}
if a.SessionIdlePeriod == 0 {
a.SessionIdlePeriod = defaults.SessionIdlePeriod
}
if a.DirMask == nil {
mask := os.FileMode(teleport.DirMaskSharedGroup)
a.DirMask = &mask
}
if (a.GID != nil && a.UID == nil) || (a.UID != nil && a.GID == nil) {
return trace.BadParameter("if UID or GID is set, both should be specified")
}
if a.PlaybackRecycleTTL == 0 {
a.PlaybackRecycleTTL = defaults.PlaybackRecycleTTL
}
return nil
}
// Creates and returns a new Audit Log object whish will store its logfiles in
// a given directory. Session recording can be disabled by setting
// recordSessions to false.
func NewAuditLog(cfg AuditLogConfig) (*AuditLog, error) {
if err := cfg.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
ctx, cancel := context.WithCancel(context.TODO())
al := &AuditLog{
playbackDir: filepath.Join(cfg.DataDir, PlaybackDir, SessionLogsDir, defaults.Namespace),
AuditLogConfig: cfg,
Entry: log.WithFields(log.Fields{
trace.Component: teleport.ComponentAuditLog,
}),
activeDownloads: make(map[string]context.Context),
ctx: ctx,
cancel: cancel,
}
// create a directory for audit logs, audit log does not create
// session logs before migrations are run in case if the directory
// has to be moved
auditDir := filepath.Join(cfg.DataDir, cfg.ServerID)
if err := os.MkdirAll(auditDir, *cfg.DirMask); err != nil {
return nil, trace.ConvertSystemError(err)
}
// create a directory for session logs:
sessionDir := filepath.Join(cfg.DataDir, cfg.ServerID, SessionLogsDir, defaults.Namespace)
if err := os.MkdirAll(sessionDir, *cfg.DirMask); err != nil {
return nil, trace.ConvertSystemError(err)
}
// create a directory for uncompressed playbacks
if err := os.MkdirAll(filepath.Join(al.playbackDir), *cfg.DirMask); err != nil {
return nil, trace.ConvertSystemError(err)
}
if cfg.UID != nil && cfg.GID != nil {
err := os.Chown(cfg.DataDir, *cfg.UID, *cfg.GID)
if err != nil {
return nil, trace.ConvertSystemError(err)
}
err = os.Chown(sessionDir, *cfg.UID, *cfg.GID)
if err != nil {
return nil, trace.ConvertSystemError(err)
}
err = os.Chown(al.playbackDir, *cfg.UID, *cfg.GID)
if err != nil {
return nil, trace.ConvertSystemError(err)
}
}
if al.ExternalLog == nil {
var err error
al.localLog, err = NewFileLog(FileLogConfig{
RotationPeriod: al.RotationPeriod,
Dir: auditDir,
SymlinkDir: cfg.DataDir,
Clock: al.Clock,
UIDGenerator: al.UIDGenerator,
SearchDirs: al.auditDirs,
})
if err != nil {
return nil, trace.Wrap(err)
}
}
go al.periodicCleanupPlaybacks()
return al, nil
}
func (l *AuditLog) WaitForDelivery(context.Context) error {
return nil
}
// SessionRecording is a recording of a live session
type SessionRecording struct {
// Namespace is a session namespace
Namespace string
// SessionID is a session ID
SessionID session.ID
// Recording is a packaged tarball recording
Recording io.Reader
}
// CheckAndSetDefaults checks and sets default parameters
func (l *SessionRecording) CheckAndSetDefaults() error {
if l.Recording == nil {
return trace.BadParameter("missing parameter Recording")
}
if l.SessionID.IsZero() {
return trace.BadParameter("missing parameter session ID")
}
if l.Namespace == "" {
l.Namespace = defaults.Namespace
}
return nil
}
// UploadSessionRecording persists the session recording locally or to third
// party storage.
func (l *AuditLog) UploadSessionRecording(r SessionRecording) error {
if err := r.CheckAndSetDefaults(); err != nil {
return trace.Wrap(err)
}
// This function runs on the Auth Server. If no upload handler is defined
// (for example, not going to S3) then unarchive it to Auth Server disk.
if l.UploadHandler == nil {
err := utils.Extract(r.Recording, filepath.Join(l.DataDir, l.ServerID, SessionLogsDir, r.Namespace))
return trace.Wrap(err)
}
// Upload session recording to endpoint defined in file configuration. Like S3.
start := time.Now()
url, err := l.UploadHandler.Upload(context.TODO(), r.SessionID, r.Recording)
if err != nil {
l.WithFields(log.Fields{"duration": time.Now().Sub(start), "session-id": r.SessionID}).Warningf("Session upload failed: %v", trace.DebugReport(err))
return trace.Wrap(err)
}
l.WithFields(log.Fields{"duration": time.Now().Sub(start), "session-id": r.SessionID}).Debugf("Session upload completed.")
return l.EmitAuditEvent(SessionUploadEvent, EventFields{
SessionEventID: string(r.SessionID),
URL: url,
EventIndex: math.MaxInt32,
})
}
// PostSessionSlice submits slice of session chunks to the audit log server.
func (l *AuditLog) PostSessionSlice(slice SessionSlice) error {
if slice.Namespace == "" {
return trace.BadParameter("missing parameter Namespace")
}
if len(slice.Chunks) == 0 {
return trace.BadParameter("missing session chunks")
}
if l.ExternalLog != nil {
return l.ExternalLog.PostSessionSlice(slice)
}
if slice.Version < V3 {
return trace.BadParameter("audit log rejected %v log entry, upgrade your components.", slice.Version)
}
// V3 API does not write session log to local session directory,
// instead it writes locally, this internal method captures
// non-print events to the global audit log
return l.processSlice(nil, &slice)
}
func (l *AuditLog) processSlice(sl SessionLogger, slice *SessionSlice) error {
for _, chunk := range slice.Chunks {
if chunk.EventType == SessionPrintEvent || chunk.EventType == "" {
continue
}
fields, err := EventFromChunk(slice.SessionID, chunk)
if err != nil {
return trace.Wrap(err)
}
if err := l.EmitAuditEvent(chunk.EventType, fields); err != nil {
return trace.Wrap(err)
}
}
return nil
}
func (l *AuditLog) getAuthServers() ([]string, error) {
// scan the log directory:
df, err := os.Open(l.DataDir)
if err != nil {
return nil, trace.Wrap(err)
}
defer df.Close()
entries, err := df.Readdir(-1)
if err != nil {
return nil, trace.Wrap(err)
}
var authServers []string
for i := range entries {
fi := entries[i]
if fi.IsDir() {
fileName := filepath.Base(fi.Name())
// TODO: this is not the best solution because these names
// can be colliding with customer-picked names, so consider
// moving the folders to a folder level up and keep the servers
// one small
if fileName != PlaybackDir && fileName != teleport.ComponentUpload {
authServers = append(authServers, fileName)
}
}
}
return authServers, nil
}
type sessionIndex struct {
dataDir string
namespace string
sid session.ID
events []indexEntry
chunks []indexEntry
indexFiles []string
}
func (idx *sessionIndex) fileNames() []string {
files := make([]string, 0, len(idx.indexFiles)+len(idx.events)+len(idx.chunks))
files = append(files, idx.indexFiles...)
for i := range idx.events {
files = append(files, idx.eventsFileName(i))
}
for i := range idx.chunks {
files = append(files, idx.chunksFileName(i))
}
return files
}
func (idx *sessionIndex) sort() {
sort.Slice(idx.events, func(i, j int) bool {
return idx.events[i].Index < idx.events[j].Index
})
sort.Slice(idx.chunks, func(i, j int) bool {
return idx.chunks[i].Offset < idx.chunks[j].Offset
})
}
func (idx *sessionIndex) eventsFileName(index int) string {
entry := idx.events[index]
return filepath.Join(idx.dataDir, entry.authServer, SessionLogsDir, idx.namespace, entry.FileName)
}
func (idx *sessionIndex) eventsFile(afterN int) (int, error) {
for i := len(idx.events) - 1; i >= 0; i-- {
entry := idx.events[i]
if int64(afterN) >= entry.Index {
return i, nil
}
}
return -1, trace.NotFound("%v not found", afterN)
}
// chunkFileNames returns file names of all session chunk files
func (idx *sessionIndex) chunkFileNames() []string {
fileNames := make([]string, len(idx.chunks))
for i := 0; i < len(idx.chunks); i++ {
fileNames[i] = idx.chunksFileName(i)
}
return fileNames
}
func (idx *sessionIndex) chunksFile(offset int64) (string, int64, error) {
for i := len(idx.chunks) - 1; i >= 0; i-- {
entry := idx.chunks[i]
if offset >= entry.Offset {
return idx.chunksFileName(i), entry.Offset, nil
}
}
return "", 0, trace.NotFound("%v not found", offset)
}
func (idx *sessionIndex) chunksFileName(index int) string {
entry := idx.chunks[index]
return filepath.Join(idx.dataDir, entry.authServer, SessionLogsDir, idx.namespace, entry.FileName)
}
func (l *AuditLog) readSessionIndex(namespace string, sid session.ID) (*sessionIndex, error) {
authServers, err := l.getAuthServers()
if err != nil {
return nil, trace.Wrap(err)
}
if l.UploadHandler == nil {
return readSessionIndex(l.DataDir, authServers, namespace, sid)
}
return readSessionIndex(l.DataDir, []string{PlaybackDir}, namespace, sid)
}
func readSessionIndex(dataDir string, authServers []string, namespace string, sid session.ID) (*sessionIndex, error) {
index := sessionIndex{
sid: sid,
dataDir: dataDir,
namespace: namespace,
}
for _, authServer := range authServers {
indexFileName := filepath.Join(dataDir, authServer, SessionLogsDir, namespace, fmt.Sprintf("%v.index", sid))
indexFile, err := os.OpenFile(indexFileName, os.O_RDONLY, 0640)
err = trace.ConvertSystemError(err)
if err != nil {
if !trace.IsNotFound(err) {
return nil, trace.Wrap(err)
}
continue
}
index.indexFiles = append(index.indexFiles, indexFileName)
events, chunks, err := readIndexEntries(indexFile, authServer)
if err != nil {
return nil, trace.Wrap(err)
}
index.events = append(index.events, events...)
index.chunks = append(index.chunks, chunks...)
err = indexFile.Close()
if err != nil {
return nil, trace.Wrap(err)
}
}
index.sort()
return &index, nil
}
func readIndexEntries(file *os.File, authServer string) (events []indexEntry, chunks []indexEntry, err error) {
scanner := bufio.NewScanner(file)
for lineNo := 0; scanner.Scan(); lineNo++ {
var entry indexEntry
if err := json.Unmarshal(scanner.Bytes(), &entry); err != nil {
return nil, nil, trace.Wrap(err)
}
entry.authServer = authServer
switch entry.Type {
case fileTypeEvents:
events = append(events, entry)
case fileTypeChunks:
chunks = append(chunks, entry)
default:
return nil, nil, trace.BadParameter("unsupported type: %q", entry.Type)
}
}
return
}
// createOrGetDownload creates a new download sync entry for a given session,
// if there is no active download in progress, or returns an existing one.
// if the new context has been created, cancel function is returned as a
// second argument. Caller should call this function to signal that download has been
// completed or failed.
func (l *AuditLog) createOrGetDownload(path string) (context.Context, context.CancelFunc) {
l.Lock()
defer l.Unlock()
ctx, ok := l.activeDownloads[path]
if ok {
return ctx, nil
}
ctx, cancel := context.WithCancel(context.TODO())
l.activeDownloads[path] = ctx
return ctx, func() {
cancel()
l.Lock()
defer l.Unlock()
delete(l.activeDownloads, path)
}
}
func (l *AuditLog) downloadSession(namespace string, sid session.ID) error {
tarballPath := filepath.Join(l.playbackDir, string(sid)+".tar")
ctx, cancel := l.createOrGetDownload(tarballPath)
// means that another download is in progress, so simply wait until
// it finishes
if cancel == nil {
l.Debugf("Another download is in progress for %v, waiting until it gets completed.", sid)
select {
case <-ctx.Done():
return nil
case <-l.ctx.Done():
return trace.BadParameter("audit log is closing, aborting the download")
}
}
defer cancel()
_, err := os.Stat(tarballPath)
err = trace.ConvertSystemError(err)
if err == nil {
l.Debugf("Recording %v is already downloaded and unpacked to %v.", sid, tarballPath)
return nil
}
if !trace.IsNotFound(err) {
return trace.Wrap(err)
}
start := time.Now()
l.Debugf("Starting download of %v.", sid)
tarball, err := os.OpenFile(tarballPath, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0640)
if err != nil {
return trace.ConvertSystemError(err)
}
defer tarball.Close()
if err := l.UploadHandler.Download(l.ctx, sid, tarball); err != nil {
// remove partially downloaded tarball
os.Remove(tarball.Name())
return trace.Wrap(err)
}
l.WithFields(log.Fields{"duration": time.Now().Sub(start)}).Debugf("Downloaded %v to %v.", sid, tarballPath)
start = time.Now()
_, err = tarball.Seek(0, 0)
if err != nil {
return trace.ConvertSystemError(err)
}
if err := utils.Extract(tarball, l.playbackDir); err != nil {
return trace.Wrap(err)
}
// Extract every chunks file on disk while holding the context,
// otherwise parallel downloads will try to unpack the file at the same time.
idx, err := l.readSessionIndex(namespace, sid)
if err != nil {
return trace.Wrap(err)
}
for _, fileName := range idx.chunkFileNames() {
reader, err := l.unpackFile(fileName)
if err != nil {
return trace.Wrap(err)
}
if err := reader.Close(); err != nil {
l.Warningf("Failed to close file: %v.", err)
}
}
l.WithFields(log.Fields{"duration": time.Now().Sub(start)}).Debugf("Unpacked %v to %v.", tarballPath, l.playbackDir)
return nil
}
// 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 (l *AuditLog) GetSessionChunk(namespace string, sid session.ID, offsetBytes, maxBytes int) ([]byte, error) {
if l.UploadHandler != nil {
if err := l.downloadSession(namespace, sid); err != nil {
return nil, trace.Wrap(err)
}
}
var data []byte
for {
out, err := l.getSessionChunk(namespace, sid, offsetBytes, maxBytes)
if err != nil {
if err == io.EOF {
return data, nil
}
return nil, trace.Wrap(err)
}
data = append(data, out...)
if len(data) == maxBytes || len(out) == 0 {
return data, nil
}
maxBytes = maxBytes - len(out)
offsetBytes = offsetBytes + len(out)
}
}
func (l *AuditLog) cleanupOldPlaybacks() error {
// scan the log directory and clean files last
// accessed after an hour
df, err := os.Open(l.playbackDir)
if err != nil {
return trace.ConvertSystemError(err)
}
defer df.Close()
entries, err := df.Readdir(-1)
if err != nil {
return trace.ConvertSystemError(err)
}
for i := range entries {
fi := entries[i]
if fi.IsDir() {
continue
}
fd := fi.ModTime().UTC()
diff := l.Clock.Now().UTC().Sub(fd)
if diff <= l.PlaybackRecycleTTL {
continue
}
fileToRemove := filepath.Join(l.playbackDir, fi.Name())
err := os.Remove(fileToRemove)
if err != nil {
l.Warningf("Failed to remove file %v: %v.", fileToRemove, err)
}
l.Debugf("Removed unpacked session playback file %v after %v.", fileToRemove, diff)
}
return nil
}
type readSeekCloser interface {
io.Reader
io.Seeker
io.Closer
}
func (l *AuditLog) unpackFile(fileName string) (readSeekCloser, error) {
basename := filepath.Base(fileName)
unpackedFile := filepath.Join(l.playbackDir, strings.TrimSuffix(basename, filepath.Ext(basename)))
// If client has called GetSessionChunk before session is over
// this could lead to cases when not all data will be returned,
// because unpackFile will be called concurrently with the unfinished write
unpackedInfo, err := os.Stat(unpackedFile)
err = trace.ConvertSystemError(err)
switch {
case err != nil && !trace.IsNotFound(err):
return nil, trace.Wrap(err)
case err == nil:
packedInfo, err := os.Stat(fileName)
if err != nil {
return nil, trace.ConvertSystemError(err)
}
// no new data has been added
if unpackedInfo.ModTime().Unix() >= packedInfo.ModTime().Unix() {
return os.OpenFile(unpackedFile, os.O_RDONLY, 0640)
}
}
start := l.Clock.Now()
dest, err := os.OpenFile(unpackedFile, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0640)
if err != nil {
return nil, trace.ConvertSystemError(err)
}
source, err := os.OpenFile(fileName, os.O_RDONLY, 0640)
if err != nil {
return nil, trace.ConvertSystemError(err)
}
defer source.Close()
reader, err := gzip.NewReader(source)
if err != nil {
return nil, trace.Wrap(err)
}
defer reader.Close()
if _, err := io.Copy(dest, reader); err != nil {
// Unexpected EOF is returned by gzip reader
// when the file has not been closed yet,
// ignore this error
if err != io.ErrUnexpectedEOF {
dest.Close()
return nil, trace.Wrap(err)
}
}
if _, err := dest.Seek(0, 0); err != nil {
dest.Close()
return nil, trace.Wrap(err)
}
l.Debugf("Uncompressed %v into %v in %v", fileName, unpackedFile, l.Clock.Now().Sub(start))
return dest, nil
}
func (l *AuditLog) getSessionChunk(namespace string, sid session.ID, offsetBytes, maxBytes int) ([]byte, error) {
if namespace == "" {
return nil, trace.BadParameter("missing parameter namespace")
}
idx, err := l.readSessionIndex(namespace, sid)
if err != nil {
return nil, trace.Wrap(err)
}
fileName, fileOffset, err := idx.chunksFile(int64(offsetBytes))
if err != nil {
return nil, trace.Wrap(err)
}
reader, err := l.unpackFile(fileName)
if err != nil {
return nil, trace.Wrap(err)
}
defer reader.Close()
// seek to 'offset' from the beginning
reader.Seek(int64(offsetBytes)-fileOffset, 0)
// copy up to maxBytes from the offset position:
var buff bytes.Buffer
_, err = io.Copy(&buff, io.LimitReader(reader, int64(maxBytes)))
return buff.Bytes(), err
}
// 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 (l *AuditLog) GetSessionEvents(namespace string, sid session.ID, afterN int, includePrintEvents bool) ([]EventFields, error) {
l.WithFields(log.Fields{"sid": string(sid), "afterN": afterN, "printEvents": includePrintEvents}).Debugf("GetSessionEvents.")
if namespace == "" {
return nil, trace.BadParameter("missing parameter namespace")
}
// Print events are stored in the context of the downloaded session
// so pull them
if !includePrintEvents && l.ExternalLog != nil {
events, err := l.ExternalLog.GetSessionEvents(namespace, sid, afterN, includePrintEvents)
// some loggers (e.g. FileLog) do not support retrieving session only print events,
// in this case rely on local fallback to download the session,
// unpack it and use local search
if !trace.IsNotImplemented(err) {
return events, err
}
}
// If code has to fetch print events (for playback) it has to download
// the playback from external storage first
if l.UploadHandler != nil {
if err := l.downloadSession(namespace, sid); err != nil {
return nil, trace.Wrap(err)
}
}
idx, err := l.readSessionIndex(namespace, sid)
if err != nil {
return nil, trace.Wrap(err)
}
fileIndex, err := idx.eventsFile(afterN)
if err != nil {
return nil, trace.Wrap(err)
}
events := make([]EventFields, 0, 256)
for i := fileIndex; i < len(idx.events); i++ {
skip := 0
if i == fileIndex {
skip = afterN
}
out, err := l.fetchSessionEvents(idx.eventsFileName(i), skip)
if err != nil {
return nil, trace.Wrap(err)
}
events = append(events, out...)
}
return events, nil
}
func (l *AuditLog) fetchSessionEvents(fileName string, afterN int) ([]EventFields, error) {
logFile, err := os.OpenFile(fileName, os.O_RDONLY, 0640)
if err != nil {
// no file found? this means no events have been logged yet
if os.IsNotExist(err) {
return nil, nil
}
return nil, trace.Wrap(err)
}
defer logFile.Close()
reader, err := gzip.NewReader(logFile)
if err != nil {
return nil, trace.Wrap(err)
}
defer reader.Close()
retval := make([]EventFields, 0, 256)
// read line by line:
scanner := bufio.NewScanner(reader)
for lineNo := 0; scanner.Scan(); lineNo++ {
if lineNo < afterN {
continue
}
var fields EventFields
if err = json.Unmarshal(scanner.Bytes(), &fields); err != nil {
log.Error(err)
return nil, trace.Wrap(err)
}
fields[EventCursor] = lineNo
retval = append(retval, fields)
}
return retval, nil
}
// EmitAuditEvent adds a new event to the log. Part of auth.IAuditLog interface.
func (l *AuditLog) EmitAuditEvent(eventType string, fields EventFields) error {
if l.ExternalLog != nil {
return l.ExternalLog.EmitAuditEvent(eventType, fields)
}
return l.localLog.EmitAuditEvent(eventType, fields)
}
// emitEvent emits event for test purposes
func (l *AuditLog) emitEvent(e AuditLogEvent) {
if l.EventsC == nil {
return
}
select {
case l.EventsC <- &e:
return
default:
l.Warningf("Blocked on the events channel.")
}
}
// auditDirs returns directories used for audit log storage
func (l *AuditLog) auditDirs() ([]string, error) {
authServers, err := l.getAuthServers()
if err != nil {
return nil, trace.Wrap(err)
}
var out []string
for _, serverID := range authServers {
out = append(out, filepath.Join(l.DataDir, serverID))
}
return out, nil
}
// SearchEvents finds events. Results show up sorted by date (newest first),
// limit is used when set to value > 0
func (l *AuditLog) SearchEvents(fromUTC, toUTC time.Time, query string, limit int) ([]EventFields, error) {
l.Debugf("SearchEvents(%v, %v, query=%v, limit=%v)", fromUTC, toUTC, query, limit)
if limit <= 0 {
limit = defaults.EventsIterationLimit
}
if limit > defaults.EventsMaxIterationLimit {
return nil, trace.BadParameter("limit %v exceeds max iteration limit %v", limit, defaults.MaxIterationLimit)
}
if l.ExternalLog != nil {
return l.ExternalLog.SearchEvents(fromUTC, toUTC, query, limit)
}
return l.localLog.SearchEvents(fromUTC, toUTC, query, limit)
}
// SearchSessionEvents searches for session related events. Used to find completed sessions.
func (l *AuditLog) SearchSessionEvents(fromUTC, toUTC time.Time, limit int) ([]EventFields, error) {
l.Debugf("SearchSessionEvents(%v, %v, %v)", fromUTC, toUTC, limit)
if l.ExternalLog != nil {
return l.ExternalLog.SearchSessionEvents(fromUTC, toUTC, limit)
}
return l.localLog.SearchSessionEvents(fromUTC, toUTC, limit)
}
// Closes the audit log, which inluces closing all file handles and releasing
// all session loggers
func (l *AuditLog) Close() error {
if l.ExternalLog != nil {
if err := l.ExternalLog.Close(); err != nil {
log.Warningf("Close failure: %v", err)
}
}
l.cancel()
l.Lock()
defer l.Unlock()
if l.localLog != nil {
if err := l.localLog.Close(); err != nil {
log.Warningf("Close failure: %v", err)
}
l.localLog = nil
}
return nil
}
func (l *AuditLog) periodicCleanupPlaybacks() {
ticker := time.NewTicker(5 * time.Minute)
defer ticker.Stop()
for {
select {
case <-ticker.C:
if err := l.cleanupOldPlaybacks(); err != nil {
l.Warningf("Error while cleaning up playback files: %v.", err)
}
}
}
}