sftp.go 14.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
package logic

import (
	"errors"
	"fmt"
	"log"
	"net"
	"os"
	"regexp"
liming6's avatar
liming6 committed
10
	"slices"
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
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/samber/mo"
	"github.com/shirou/gopsutil/v4/process"
)

var (
	RegParsePid     = regexp.MustCompile(`^\[([0-9]+)\]:\s*(.*)$`)
	RegParseSession = regexp.MustCompile(`(?i)^session\s+(opened|closed)\s+for\s+local\s+user\s+(.*)\s+from\s+\[(.*)\]`)

	SftpLogMap  = make(map[int32]*SftpLogSet) // 全局的,用于记录sftp信息的map,key为进程id,value为日志集
	SftpLogLock = sync.RWMutex{}              // 保护SftpLogMap的锁
)

type GetSLA interface {
	GetFfileAction() SftpLogAction
	SetPid(pid int32)
	GetPid() int32
}

type SftpLogAction string

const (
	SLAUnknown      SftpLogAction = ""
	SLAOpen         SftpLogAction = "open "
	SLAClose        SftpLogAction = "close "
	SLARemove       SftpLogAction = "remove name "
	SLARename       SftpLogAction = "rename old "
	SLAForceClose   SftpLogAction = "forced close "
	SLAOpenSession  SftpLogAction = "session opened"
	SLACloseSession SftpLogAction = "session closed"
)

func parseSLA(s string, t time.Time) GetSLA {
	prev := ""
liming6's avatar
liming6 committed
49
50
	switch {
	case strings.HasPrefix(s, string(SLAOpen)):
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
		fields := strings.Fields(s)
		result := SftpLogOpen{Time: t}
		for i, v := range fields[1:] {
			if i == 0 {
				result.Path = strings.Trim(v, `"`)
				continue
			}
			switch v {
			case "flags", "mode":
				prev = v
			default:
				switch prev {
				case "flags":
					result.Flags = strings.Split(v, ",")
				case "mode":
					p, err := strconv.ParseUint(v, 8, 32)
					if err == nil {
						result.Mode = mo.None[uint32]()
					} else {
						result.Mode = mo.Some(uint32(p))
					}
				}
			}
		}
		return &result
liming6's avatar
liming6 committed
76
	case strings.HasPrefix(s, string(SLAClose)):
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
		fields := strings.Fields(s)
		result := SftpLogClose{Time: t}
		for k, v := range fields[1:] {
			if k == 0 {
				result.Path = strings.Trim(v, `"`)
			}
			switch v {
			case "bytes", "read", "written":
				prev = v
			default:
				switch prev {
				case "read":
					read, err := strconv.ParseUint(v, 10, 64)
					if err != nil {
						result.Read = mo.None[uint64]()
					} else {
						result.Read = mo.Some(read)
					}
				case "written":
					read, err := strconv.ParseUint(v, 10, 64)
					if err != nil {
						result.Write = mo.None[uint64]()
					} else {
						result.Write = mo.Some(read)
					}
				}
			}
		}
		return &result
liming6's avatar
liming6 committed
106
	case strings.HasPrefix(s, string(SLARemove)):
107
108
109
110
		fields := strings.Fields(s)
		result := SftpLogRemove{Time: t}
		result.Path = fields[2]
		return &result
liming6's avatar
liming6 committed
111
	case strings.HasPrefix(s, string(SLARename)):
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
		fields := strings.Fields(s)
		result := SftpLogRename{Time: t}
		for _, v := range fields[1:] {
			switch v {
			case "old", "new":
				prev = v
			default:
				switch prev {
				case "old":
					result.Old = strings.Trim(v, `"`)
				case "new":
					result.New = strings.Trim(v, `"`)
				}
			}
		}
		return &result
liming6's avatar
liming6 committed
128
	case strings.HasPrefix(s, string(SLAForceClose)):
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
		fields := strings.Fields(s)
		result := SftpLogForceClose{Time: t}
		for k, v := range fields[2:] {
			if k == 0 {
				result.Path = strings.Trim(v, `"`)
			}
			switch v {
			case "bytes", "read", "written":
				prev = v
			default:
				switch prev {
				case "read":
					read, err := strconv.ParseUint(v, 10, 64)
					if err != nil {
						result.Read = mo.None[uint64]()
					} else {
						result.Read = mo.Some(read)
					}
				case "written":
					read, err := strconv.ParseUint(v, 10, 64)
					if err != nil {
						result.Write = mo.None[uint64]()
					} else {
						result.Write = mo.Some(read)
					}
				}
			}
		}
		return &result
liming6's avatar
liming6 committed
158
	case strings.HasPrefix(s, string(SLAOpenSession)):
159
160
161
162
163
		result := SftpLogOpenSession{Time: t}
		items := RegParseSession.FindStringSubmatch(s)
		result.User = items[2]
		result.From = items[3]
		return &result
liming6's avatar
liming6 committed
164
	case strings.HasPrefix(s, string(SLACloseSession)):
165
166
167
168
169
		result := SftpLogCloseSession{Time: t}
		items := RegParseSession.FindStringSubmatch(s)
		result.User = items[2]
		result.From = items[3]
		return &result
liming6's avatar
liming6 committed
170
171
	default:
		return nil
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
	}
}

type SftpLogOpen struct {
	Path  string
	Flags []string
	Mode  mo.Option[uint32]
	Time  time.Time
	Pid   int32
}

func (slo *SftpLogOpen) GetFfileAction() SftpLogAction {
	return SLAOpen
}

func (slo *SftpLogOpen) GetPid() int32 {
	return slo.Pid
}

func (slo *SftpLogOpen) SetPid(pid int32) {
	slo.Pid = pid
}

type SftpLogClose struct {
	Path        string
	Read, Write mo.Option[uint64]
	Time        time.Time
	Pid         int32
}

func (s *SftpLogClose) GetFfileAction() SftpLogAction {
	return SLAClose
}

func (s *SftpLogClose) GetPid() int32 {
	return s.Pid
}

func (s *SftpLogClose) SetPid(pid int32) {
	s.Pid = pid
}

type SftpLogRemove struct {
	Path string
	Time time.Time
	Pid  int32
}

func (slr *SftpLogRemove) GetFfileAction() SftpLogAction {
	return SLARemove
}

func (s *SftpLogRemove) GetPid() int32 {
	return s.Pid
}

func (s *SftpLogRemove) SetPid(pid int32) {
	s.Pid = pid
}

type SftpLogRename struct {
	Old, New string
	Time     time.Time
	Pid      int32
}

func (slr *SftpLogRename) GetFfileAction() SftpLogAction {
	return SLARename
}

func (s *SftpLogRename) GetPid() int32 {
	return s.Pid
}

func (s *SftpLogRename) SetPid(pid int32) {
	s.Pid = pid
}

type SftpLogForceClose struct {
	Path        string
	Read, Write mo.Option[uint64]
	Time        time.Time
	Pid         int32
}

func (slfc *SftpLogForceClose) GetFfileAction() SftpLogAction {
	return SLAForceClose
}

func (s *SftpLogForceClose) GetPid() int32 {
	return s.Pid
}

func (s *SftpLogForceClose) SetPid(pid int32) {
	s.Pid = pid
}

type SftpLogOpenSession struct {
	Time time.Time
	User string
	From string
	Pid  int32
}

func (slos *SftpLogOpenSession) GetFfileAction() SftpLogAction {
	return SLAOpenSession
}

func (s *SftpLogOpenSession) GetPid() int32 {
	return s.Pid
}

func (s *SftpLogOpenSession) SetPid(pid int32) {
	s.Pid = pid
}

type SftpLogCloseSession struct {
	Time time.Time
	User string
	From string
	Pid  int32
}

func (slos *SftpLogCloseSession) GetFfileAction() SftpLogAction {
	return SLACloseSession
}

func (s *SftpLogCloseSession) GetPid() int32 {
	return s.Pid
}

func (s *SftpLogCloseSession) SetPid(pid int32) {
	s.Pid = pid
}

// SftpLogSet 存储一个sftp进程的相关日志信息
type SftpLogSet struct {
	Pid          int32                // 进程pid
	User         string               // 用户名或uid
	From         string               // 连接地址
	SessionStart mo.Option[time.Time] // 对话开始时间
	SessionClose mo.Option[time.Time] // 会话断开时间
	OpenedFile   map[string]*FileInfo // 文件日志
	IsTabby      mo.Option[bool]      // 进程是否为tabby
	IsAlive      bool                 // 进程是否存活
	Lock         sync.RWMutex         // 保护OpenedFile读写的锁
}

func NewSftpLogSet(pid int32, user *string, startTime *time.Time) *SftpLogSet {
	result := &SftpLogSet{
		Pid:          pid,
		User:         "",
		SessionStart: mo.None[time.Time](),
		SessionClose: mo.None[time.Time](),
		OpenedFile:   make(map[string]*FileInfo),
		IsTabby:      mo.None[bool](),
		IsAlive:      true,
		Lock:         sync.RWMutex{},
	}
	if user != nil {
		result.User = *user
	} else {
		p, err := process.NewProcess(pid)
		if err == nil {
			user, err := p.Username()
			if err == nil {
				result.User = user
liming6's avatar
liming6 committed
339
340
341
342
343
			} else {
				uids, err := p.Uids()
				if err == nil && len(uids) > 0 {
					result.User = fmt.Sprintf("UID: %d", uids[0])
				}
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
			}
		}
	}
	if startTime != nil {
		result.SessionStart = mo.Some(*startTime)
	}
	return result
}

// CheckAlive 检查进程是否存活
func (sls *SftpLogSet) CheckAlive() (bool, error) {
	p, err := process.NewProcess(sls.Pid)
	if err != nil {
		sls.IsAlive = false
		return false, err
	}
	if p == nil {
		sls.IsAlive = false
		return false, nil
	}
	cmd, err := p.Cmdline()
	if err != nil {
		sls.IsAlive = false
		return false, err
	}
	alive := strings.Contains(cmd, "sftp-server")
	sls.IsAlive = alive
	return alive, nil
}

type FileInfo struct {
liming6's avatar
liming6 committed
375
376
377
378
	Path    string       // 文件路径,对于tabby等中途会修改的sftp客户端,这里记录有后缀的名称
	Log     []GetSLA     // 文件操作日志
	LogLock sync.RWMutex // 保护Log的读写
	LogSet  *SftpLogSet  // 这个文件信息所属的日志集,用于获取用户名和pid
379
380
381
382
383
384
385
}

func NewFileInfo(path string, ls *SftpLogSet) *FileInfo {
	return &FileInfo{
		Path:    path,
		Log:     make([]GetSLA, 0, 4),
		LogSet:  ls,
liming6's avatar
liming6 committed
386
		LogLock: sync.RWMutex{},
387
388
389
390
391
392
	}
}

// CheckNeedScan 检查是否需要扫描文件
func (fi *FileInfo) CheckNeedScan() {
	// 检查最后一个日志的种类
liming6's avatar
liming6 committed
393
394
	rl := fi.LogLock.RLocker()
	rl.Lock()
395
396
397
398
399
	l := len(fi.Log)
	if l == 0 {
		return
	}
	last := fi.Log[l-1]
liming6's avatar
liming6 committed
400
401
	userName := fi.LogSet.User
	rl.Unlock()
402
403
	switch act := last.(type) {
	case *SftpLogClose:
liming6's avatar
liming6 committed
404
		if strings.HasSuffix(act.Path, ".tabby-upload") {
405
406
			return
		}
liming6's avatar
liming6 committed
407
408
409
410
		fi.LogSet.Lock.Lock()
		delete(fi.LogSet.OpenedFile, act.Path)
		fi.LogSet.Lock.Unlock()
		log.Printf("user %s upload file: %s, scanning...\n", userName, act.Path)
411
412
		have, _ := ScanFile(act.Path)
		if have {
liming6's avatar
liming6 committed
413
			log.Printf("user %s upload file %s containing viruses\n", userName, act.Path)
414
		} else {
liming6's avatar
liming6 committed
415
			log.Printf("user %s upload file %s not find virus\n", userName, act.Path)
416
		}
liming6's avatar
liming6 committed
417
		return
418
	case *SftpLogRename:
liming6's avatar
liming6 committed
419
420
		if strings.HasSuffix(act.Old, ".tabby-upload") {
			log.Printf("user %s upload file: %s, scanning...\n", userName, act.New)
421
422
			have, _ := ScanFile(act.New)
			if have {
liming6's avatar
liming6 committed
423
				log.Printf("user %s upload file %s containing viruses\n", userName, act.New)
424
			} else {
liming6's avatar
liming6 committed
425
				log.Printf("user %s upload file %s not find virus\n", userName, act.New)
426
			}
liming6's avatar
liming6 committed
427
428
429
430
			fi.LogSet.Lock.Lock()
			delete(fi.LogSet.OpenedFile, act.Old)
			delete(fi.LogSet.OpenedFile, act.New)
			fi.LogSet.Lock.Unlock()
431
		}
liming6's avatar
liming6 committed
432
		return
433
	case *SftpLogForceClose:
liming6's avatar
liming6 committed
434
		log.Printf("user %s upload file: %s, scanning...\n", userName, act.Path)
435
436
		have, _ := ScanFile(act.Path)
		if have {
liming6's avatar
liming6 committed
437
			log.Printf("user %s upload file %s containing viruses\n", userName, act.Path)
438
		} else {
liming6's avatar
liming6 committed
439
			log.Printf("user %s upload file %s not find virus\n", userName, act.Path)
440
		}
liming6's avatar
liming6 committed
441
442
443
444
		fi.LogSet.Lock.Lock()
		delete(fi.LogSet.OpenedFile, act.Path)
		fi.LogSet.Lock.Unlock()
		return
445
446
447
448
449
450
451
452
453
454
455
	}
}

func InsertAction(action GetSLA) {
	if action == nil {
		return
	}
	pid := action.GetPid()
	switch act := action.(type) {
	case *SftpLogOpenSession:
		// 新建
liming6's avatar
liming6 committed
456
		SftpLogLock.Lock()
457
458
459
		sls := NewSftpLogSet(pid, &act.User, &act.Time)
		sls.From = act.From
		SftpLogMap[pid] = sls
liming6's avatar
liming6 committed
460
		SftpLogLock.Unlock()
461
462
		return
	case *SftpLogCloseSession:
liming6's avatar
liming6 committed
463
		SftpLogLock.Lock()
464
		delete(SftpLogMap, pid)
liming6's avatar
liming6 committed
465
		SftpLogLock.Unlock()
466
467
		return
	case *SftpLogOpen:
liming6's avatar
liming6 committed
468
469
470
471
472
		if slices.Contains(act.Flags, "READ") {
			// 是读文件,不理会
			return
		}
		SftpLogLock.Lock()
473
474
475
476
477
		ls, have := SftpLogMap[pid]
		if !have {
			ls = NewSftpLogSet(pid, nil, &act.Time)
			SftpLogMap[pid] = ls
		}
liming6's avatar
liming6 committed
478
		SftpLogLock.Unlock()
479
480
481
482
483
484
485
		istabby := strings.HasSuffix(act.Path, ".tabby-upload")
		ls.IsTabby = mo.Some(istabby)
		ls.Lock.Lock()
		finfo, have := ls.OpenedFile[act.Path]
		if !have {
			finfo = NewFileInfo(act.Path, ls)
			ls.OpenedFile[act.Path] = finfo
liming6's avatar
liming6 committed
486
487
			ls.Lock.Unlock()
			finfo.LogLock.Lock()
488
			finfo.Log = append(finfo.Log, act)
liming6's avatar
liming6 committed
489
			finfo.LogLock.Unlock()
490
491
		} else {
			// 发生重复了???
liming6's avatar
liming6 committed
492
			ls.Lock.Unlock()
493
		}
liming6's avatar
liming6 committed
494

495
496
		return
	case *SftpLogClose:
liming6's avatar
liming6 committed
497
498
499
500
501
		if num, have := act.Write.Get(); have && num == 0 {
			// 没有写入数据,不处理
			return
		}
		SftpLogLock.Lock()
502
503
504
505
506
		ls, have := SftpLogMap[pid]
		if !have {
			ls = NewSftpLogSet(pid, nil, &act.Time)
			SftpLogMap[pid] = ls
		}
liming6's avatar
liming6 committed
507
		SftpLogLock.Unlock()
508
		ls.Lock.Lock()
liming6's avatar
liming6 committed
509
510
511
		if strings.HasSuffix(act.Path, ".tabby-upload") {
			ls.IsTabby = mo.Some(true)
		}
512
513
514
515
516
517
		finfo, have := ls.OpenedFile[act.Path]
		if !have {
			finfo = NewFileInfo(act.Path, ls)
			ls.OpenedFile[act.Path] = finfo
		}
		ls.Lock.Unlock()
liming6's avatar
liming6 committed
518
519
520
521
		finfo.LogLock.Lock()
		finfo.Log = append(finfo.Log, act)
		finfo.LogLock.Unlock()
		go finfo.CheckNeedScan()
522
523
524
525
		return
	case *SftpLogRemove:
		// 查看是否为tabby,如果是tabby,需要检查是否为上传的文件
		// 如果没有,不创建日志
liming6's avatar
liming6 committed
526
		SftpLogLock.Lock()
527
528
529
530
531
		ls, have := SftpLogMap[pid]
		if !have {
			ls = NewSftpLogSet(pid, nil, &act.Time)
			SftpLogMap[pid] = ls
		}
liming6's avatar
liming6 committed
532
		SftpLogLock.Unlock()
533
534
535
536
537
538
539
540
541
		a, b := ls.IsTabby.Get()
		if a && b {
			delete(ls.OpenedFile, act.Path)
		}
		return
	case *SftpLogRename:
		// 查看是否为tabby,如果是tabby,需要检查是否为上传的文件
		istabby := strings.HasSuffix(act.Old, ".tabby-upload")
		if istabby {
liming6's avatar
liming6 committed
542
543
544
545
546
547
548
549
			SftpLogLock.Lock()
			ls, have := SftpLogMap[pid]
			if !have {
				ls = NewSftpLogSet(pid, nil, &act.Time)
				SftpLogMap[pid] = ls
			}
			SftpLogLock.Unlock()
			ls.IsTabby = mo.Some(istabby)
550
551
552
553
554
555
556
557
			// 是tabby上传的文件,需要记录日志
			ls.Lock.Lock()
			finfo, have := ls.OpenedFile[act.Old]
			if !have {
				finfo = NewFileInfo(act.Old, ls)
				ls.OpenedFile[act.Old] = finfo
			}
			ls.Lock.Unlock()
liming6's avatar
liming6 committed
558
559
560
561
			finfo.LogLock.Lock()
			finfo.Log = append(finfo.Log, act)
			finfo.LogLock.Unlock()
			go finfo.CheckNeedScan()
562
563
564
		}
		return
	case *SftpLogForceClose:
liming6's avatar
liming6 committed
565
566
567
568
		if num, have := act.Write.Get(); have && num == 0 {
			return
		}
		SftpLogLock.Lock()
569
570
571
572
573
574
		// 是强制中断,需要检查是否为上传的文件
		ls, have := SftpLogMap[pid]
		if !have {
			ls = NewSftpLogSet(pid, nil, &act.Time)
			SftpLogMap[pid] = ls
		}
liming6's avatar
liming6 committed
575
		SftpLogLock.Unlock()
576
577
578
579
580
581
582
		ls.Lock.Lock()
		finfo, have := ls.OpenedFile[act.Path]
		if !have {
			finfo = NewFileInfo(act.Path, ls)
			ls.OpenedFile[act.Path] = finfo
		}
		ls.Lock.Unlock()
liming6's avatar
liming6 committed
583
584
585
586
		finfo.LogLock.Lock()
		finfo.Log = append(finfo.Log, act)
		finfo.LogLock.Unlock()
		go finfo.CheckNeedScan()
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
		return
	}
}

func ParseSftpLog(s string) (GetSLA, error) {
	if !strings.Contains(s, "sftp-server") {
		// 不是sftp日志
		return nil, nil
	}
	items := strings.SplitN(s, "sftp-server", 2)
	if len(items) != 2 {
		return nil, errors.New("parse error")
	}
	fs := strings.Split(strings.Trim(items[0], " "), " ")
	if len(fs) != 4 {
		return nil, errors.New("parse error")
	}
	t, err := time.Parse(time.Stamp, strings.Join(fs[:3], " "))
	t = t.AddDate(time.Now().Year(), 0, 0)
	if err != nil {
		return nil, err
	}
	if !RegParsePid.MatchString(items[1]) {
		return nil, errors.New("parse error")
	}
	fs = RegParsePid.FindStringSubmatch(items[1])
	if len(fs) != 3 {
		return nil, errors.New("parse error")
	}
	pid, err := strconv.ParseInt(fs[1], 10, 32)
	if err != nil {
		return nil, err
	}
	fta := parseSLA(fs[2], t)
	if fta == nil {
		return nil, nil
	}
	fta.SetPid(int32(pid))
	return fta, nil
}

func StartSftpMonitor() {
	regRemove := regexp.MustCompile(`^<\d+>(.*)$`)
	os.Remove("/tmp/rsyslog.sock")
	conn, err := net.ListenPacket("unixgram", "/tmp/rsyslog.sock")
	if err != nil {
		log.Fatal(err)
	}
liming6's avatar
liming6 committed
635
	defer os.Remove("/tmp/rsyslog.sock")
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
	buffer := make([]byte, 16384)
	for {
		n, _, err := conn.ReadFrom(buffer)
		if err != nil {
			break
		}
		content := string(buffer[:n])
		items := regRemove.FindStringSubmatch(content)
		if len(items) == 0 {
			continue
		}
		if strings.Contains(items[1], "sftp-server") {
			l, err := ParseSftpLog(items[1])
			if err != nil {
				log.Println(err)
			} else {
liming6's avatar
liming6 committed
652
653
654
				if l != nil {
					InsertAction(l)
				}
655
656
657
658
			}
		}
	}
}