/
integritymonitor.go
204 lines (180 loc) · 5.3 KB
/
integritymonitor.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
package integritymonitor
import (
"bytes"
"context"
"errors"
"fmt"
"strconv"
"strings"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
"github.com/ScienceSoft-Inc/integrity-sum/internal/data"
"github.com/ScienceSoft-Inc/integrity-sum/internal/utils/process"
"github.com/ScienceSoft-Inc/integrity-sum/internal/walker"
"github.com/ScienceSoft-Inc/integrity-sum/internal/worker"
"github.com/ScienceSoft-Inc/integrity-sum/pkg/alerts"
"github.com/ScienceSoft-Inc/integrity-sum/pkg/k8s"
"github.com/ScienceSoft-Inc/integrity-sum/pkg/minio"
)
const (
IntegrityMessageNewFileFound = "new file found"
IntegrityMessageFileDeleted = "file deleted"
IntegrityMessageFileMismatch = "file content mismatch"
IntegrityMessageUnknownErr = "unknown integrity error"
)
func GetProcessPath(procName string, path string) (string, error) {
pid, err := process.GetPID(procName)
if err != nil {
return "", fmt.Errorf("failed build process path: %w", err)
}
return fmt.Sprintf("/proc/%d/root/%s", pid, path), nil
}
func CheckIntegrity(ctx context.Context, log *logrus.Logger, processName string, monitoringDirectories []string,
deploymentData *k8s.DeploymentData, kubeClient *k8s.KubeClient) error {
log.Debug("begin check integrity")
ctx, cancel := context.WithCancel(ctx)
defer cancel()
errC := make(chan error)
defer close(errC)
var err error
paths := make([]string, len(monitoringDirectories))
for i, p := range monitoringDirectories {
paths[i], err = GetProcessPath(processName, p)
if err != nil {
log.WithError(err).Error("failed build process path")
return err
}
}
comparedHashesChan := compareHashes(ctx, log, worker.WorkersPool(
viper.GetInt("count-workers"),
walker.ChanWalkDir(ctx, paths, log),
worker.NewWorker(ctx, viper.GetString("algorithm"), log),
), processName, viper.GetString("algorithm"), errC)
log.Trace("calculate & save hashes...")
select {
case <-ctx.Done():
log.Error(ctx.Err())
return ctx.Err()
case countHashes := <-comparedHashesChan:
log.WithField("countHashes", countHashes).Info("hashes compared successfully")
return nil
case err := <-errC:
integrityCheckFailed(log, err, deploymentData, kubeClient, processName)
return err
}
}
func compareHashes(
ctx context.Context,
log *logrus.Logger,
hashC <-chan worker.FileHash,
procName string,
algName string,
errC chan<- error) <-chan int {
doneC := make(chan int)
go func() {
defer close(doneC)
procDirs, err := GetProcessPath(procName, "")
if err != nil {
errC <- fmt.Errorf("failed get process path: %w", err)
return
}
ms := minio.Instance()
csFile := process.CheckSumFile(procName, algName)
log.Infof("getting check sums file %s", csFile)
hashData, err := ms.Load(ctx, viper.GetString("minio-bucket"), csFile)
if err != nil {
errC <- fmt.Errorf("cannot read hash data: %w", err)
return
}
expectedHashes, err := data.NewFileStorage(bytes.NewReader(hashData)).Get()
if err != nil {
errC <- fmt.Errorf("failed get hash data: %w", err)
return
}
//convert hashes to map
expectedHashesMap := make(map[string]string)
for _, h := range expectedHashes {
expectedHashesMap[h.FullFileName] = h.Hash
}
for v := range hashC {
select {
case <-ctx.Done():
return
default:
}
strippedPaths := strings.TrimPrefix(v.Path, procDirs)
if h, ok := expectedHashesMap[strippedPaths]; ok {
if h != v.Hash {
errC <- &IntegrityError{Type: ErrTypeFileMismatch, Path: strippedPaths, Hash: v.Hash}
return
}
delete(expectedHashesMap, strippedPaths)
} else {
errC <- &IntegrityError{Type: ErrTypeNewFile, Path: strippedPaths, Hash: v.Hash}
return
}
}
for p, h := range expectedHashesMap {
errC <- &IntegrityError{Type: ErrTypeFileDeleted, Path: p, Hash: h}
return
}
doneC <- len(expectedHashes)
}()
return doneC
}
func integrityCheckFailed(
log *logrus.Logger,
err error,
deploymentData *k8s.DeploymentData,
kubeClient *k8s.KubeClient,
procName string,
) {
log.WithError(err).Error("check integrity failed")
var (
mPath string
integrityError *IntegrityError
alertErr error
)
if errors.As(err, &integrityError) {
mPath = integrityError.Path
log.WithField("path", integrityError.Path)
alertErr = alerts.Send(alerts.New(fmt.Sprintf("Restart pod %v", deploymentData.NamePod),
err.Error(),
mPath,
procName,
))
if alertErr != nil {
log.WithError(alertErr).Error("Failed send alert")
}
kubeClient.RestartPod()
}
}
func ParseMonitoringOpts(opts string) (map[string][]string, error) {
if opts == "" {
return nil, fmt.Errorf("--%s %s", "monitoring-options", "is empty")
}
unOpts, err := strconv.Unquote(opts)
if err != nil {
unOpts = opts
}
processes := strings.Split(unOpts, " ")
if len(processes) < 1 {
return nil, fmt.Errorf("--%s %s", "monitoring-options", "is empty")
}
optsMap := make(map[string][]string)
for _, p := range processes {
procPaths := strings.Split(p, "=")
if len(procPaths) < 2 {
return nil, fmt.Errorf("%s", "application and monitoring paths should be represented as key=value pair")
}
if procPaths[1] == "" {
return nil, fmt.Errorf("%s", "monitoring path is required")
}
paths := strings.Split(strings.Trim(procPaths[1], ","), ",")
for i, v := range paths {
paths[i] = strings.TrimSpace(v)
}
optsMap[procPaths[0]] = paths
}
return optsMap, nil
}