/
handler.go
150 lines (134 loc) · 5.29 KB
/
handler.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
package main
import (
"context"
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/sqs"
"github.com/ca-risken/aws/pkg/common"
"github.com/ca-risken/aws/pkg/message"
awsClient "github.com/ca-risken/aws/proto/aws"
"github.com/ca-risken/common/pkg/logging"
mimosasqs "github.com/ca-risken/common/pkg/sqs"
"github.com/ca-risken/core/proto/alert"
"github.com/ca-risken/core/proto/finding"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"
)
type sqsHandler struct {
findingClient finding.FindingServiceClient
alertClient alert.AlertServiceClient
awsClient awsClient.AWSServiceClient
// cloudsploit
resultDir string
configDir string
cloudsploitDir string
awsRegion string
maxMemSizeMB int
}
func (s *sqsHandler) HandleMessage(ctx context.Context, sqsMsg *sqs.Message) error {
msgBody := aws.StringValue(sqsMsg.Body)
appLogger.Infof("got message. message: %v", msgBody)
// Parse message
msg, err := message.ParseMessage(msgBody)
if err != nil {
appLogger.Errorf("Invalid message. message: %v, error: %v", msg, err)
return mimosasqs.WrapNonRetryable(err)
}
requestID, err := appLogger.GenerateRequestID(fmt.Sprint(msg.ProjectID))
if err != nil {
appLogger.Warnf("Failed to generate requestID: err=%+v", err)
requestID = fmt.Sprint(msg.ProjectID)
}
appLogger.Infof("start Scan, RequestID=%s", requestID)
status := common.InitScanStatus(msg)
// check AccountID matches Arn for Scan
if !common.IsMatchAccountIDArn(msg.AccountID, msg.AssumeRoleArn) {
appLogger.Warnf("AccountID doesn't match AssumeRoleArn, accountID: %v, ARN: %v", msg.AccountID, msg.AssumeRoleArn)
return s.handleErrorWithUpdateStatus(ctx, &status, fmt.Errorf("AssumeRoleArn for CloudSploit must be created in AWS AccountID: %v", msg.AccountID))
}
cloudsploitConf := &CloudsploitConfig{
ResultDir: s.resultDir,
ConfigDir: s.configDir,
CloudsploitDir: s.cloudsploitDir,
AWSRegion: s.awsRegion,
MaxMemSizeMB: s.maxMemSizeMB,
}
err = cloudsploitConf.generate(ctx, msg.AssumeRoleArn, msg.ExternalID, msg.AWSID, msg.AccountID)
if err != nil {
appLogger.Errorf("Error occured when configure: %v, error: %v", msg, err)
return mimosasqs.WrapNonRetryable(err)
}
// Run cloudsploit
tspan, _ := tracer.StartSpanFromContext(ctx, "runCloudSploit")
appLogger.Infof("start cloudsploit scan, RequestID=%s", requestID)
cloudsploitResult, err := cloudsploitConf.run(msg.AccountID)
tspan.Finish(tracer.WithError(err))
if err != nil {
appLogger.Errorf("Failed to exec cloudsploit, error: %v", err)
return s.handleErrorWithUpdateStatus(ctx, &status, err)
}
appLogger.Infof("end cloudsploit scan, RequestID=%s", requestID)
// Clear finding score
if _, err := s.findingClient.ClearScore(ctx, &finding.ClearScoreRequest{
DataSource: msg.DataSource,
ProjectId: msg.ProjectID,
Tag: []string{msg.AccountID},
}); err != nil {
appLogger.Errorf("Failed to clear finding score. AWSID: %v, error: %v", msg.AWSID, err)
return s.handleErrorWithUpdateStatus(ctx, &status, err)
}
// Put Finding and Tag Finding
if err := s.putFindings(ctx, cloudsploitResult, msg); err != nil {
appLogger.Errorf("Faild to put findings. AWSID: %v, error: %v", msg.AWSID, err)
return s.handleErrorWithUpdateStatus(ctx, &status, err)
}
// Update status
if err := s.updateScanStatusSuccess(ctx, &status); err != nil {
appLogger.Errorf("Faild to update scan status. AWSID: %v, error: %v", msg.AWSID, err)
return mimosasqs.WrapNonRetryable(err)
}
appLogger.Infof("end Scan, RequestID=%s", requestID)
if msg.ScanOnly {
return nil
}
// Call AnalyzeAlert
if err := s.CallAnalyzeAlert(ctx, msg.ProjectID); err != nil {
appLogger.Notifyf(logging.ErrorLevel, "Failed to analyzeAlert, project_id=%d, err=%+v", msg.ProjectID, err)
return mimosasqs.WrapNonRetryable(err)
}
return nil
}
func (s *sqsHandler) handleErrorWithUpdateStatus(ctx context.Context, scanStatus *awsClient.AttachDataSourceRequest, err error) error {
if updateErr := s.updateScanStatusError(ctx, scanStatus, err.Error()); updateErr != nil {
appLogger.Warnf("Failed to update scan status error: err=%+v", updateErr)
}
return mimosasqs.WrapNonRetryable(err)
}
func (s *sqsHandler) updateScanStatusError(ctx context.Context, status *awsClient.AttachDataSourceRequest, statusDetail string) error {
status.AttachDataSource.Status = awsClient.Status_ERROR
if len(statusDetail) > 200 {
statusDetail = statusDetail[:200] + " ..." // cut long text
}
status.AttachDataSource.StatusDetail = statusDetail
return s.attachAWSStatus(ctx, status)
}
func (s *sqsHandler) updateScanStatusSuccess(ctx context.Context, status *awsClient.AttachDataSourceRequest) error {
status.AttachDataSource.Status = awsClient.Status_OK
status.AttachDataSource.StatusDetail = ""
return s.attachAWSStatus(ctx, status)
}
func (s *sqsHandler) attachAWSStatus(ctx context.Context, status *awsClient.AttachDataSourceRequest) error {
resp, err := s.awsClient.AttachDataSource(ctx, status)
if err != nil {
return err
}
appLogger.Infof("Success to update AWS status, response=%+v", resp)
return nil
}
func (s *sqsHandler) CallAnalyzeAlert(ctx context.Context, projectID uint32) error {
_, err := s.alertClient.AnalyzeAlert(ctx, &alert.AnalyzeAlertRequest{ProjectId: projectID})
if err != nil {
return err
}
appLogger.Info("Success to analyze alert.")
return nil
}