log_consumer.go 13.1 KB
Newer Older
1 2 3 4
package service

import (
	"context"
5
	"encoding/json"
6
	"errors"
7 8
	"fmt"
	"time"
9 10 11

	"github.com/rs/zerolog/log"
	"github.com/segmentio/kafka-go"
12
	"github.com/segmentio/kafka-go/sasl/scram"
13
	"gitlab.com/tensorsecurity-rd/waf-console/internal/config"
14 15 16 17 18
	"gitlab.com/tensorsecurity-rd/waf-console/internal/model"
	"gitlab.com/tensorsecurity-rd/waf-console/internal/utils/id"

	es "github.com/olivere/elastic/v7"
	esStore "gitlab.com/tensorsecurity-rd/waf-console/internal/store"
19 20 21
	"gorm.io/gorm"
)

22 23 24 25 26 27
const (
	KafkaTopicIvanWafDetections       = "ivan_waf_detections"
	KafkaGroupIvanWafDetectionsPalace = "ivan_waf_detections_palace"

	EsIndexWafDetections      = "waf-detections*"
	EsIndexWafDetectionsAlias = "waf-detections"
28
	ESIndexEvents             = "events"
29
	ESIndexSignals            = "signals"
30 31
)

32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
var scramAlgo = map[string]scram.Algorithm{
	"SHA512": scram.SHA512,
	"SHA256": scram.SHA256,
}

var ErrMissingBrokers = errors.New("no KAFKA_BROKERS env variable set")
var ErrMissingAuthInfo = errors.New("no username or passwrod set when auth is enabled")
var ErrUnsupportedAuthMethod = errors.New("unsupported auth method")

const (
	EnvKafkaAuthMethod   = "KAFKA_AUTH_METHOD"
	EnvKafkaAuthUsername = "KAFKA_AUTH_USERNAME"
	EnvKafkaAuthPassword = "KAFKA_AUTH_PASSWORD"
	EnvKafkaScramAlgo    = "KAFKA_SCRAM_ALGO"
	EnvKafkaBrokers      = "KAFKA_BROKERS"
	KafkaAuthPlain       = "plain"
	KafkaAuthScram       = "scram"
)

qiuqunfeng's avatar
qiuqunfeng committed
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
type AttackClassDesp struct {
	En string
	Zh string
}

var AttackClassDespMap = map[string]AttackClassDesp{
	"RCE_OS":      {En: "Remote Command Execution", Zh: "远程代码执行"},
	"SQLI":        {En: "SQL Injection", Zh: "SQL注入"},
	"XSS":         {En: "Cross-Site Scripting", Zh: "跨站脚本攻击"},
	"AOIC":        {En: "Access of Internal Components", Zh: "内部组件访问"},
	"DT":          {En: "Directory Traversal", Zh: "路径穿越"},
	"DL":          {En: "Data Leakage", Zh: "数据泄露"},
	"SCD":         {En: "Source Code Disclosure", Zh: "源码泄露"},
	"RCE_PHP":     {En: "Php remote code execution", Zh: "PHP远程代码执行"},
	"RCE_JAVA":    {En: "Java remote code execution", Zh: "JAVA远程代码执行"},
	"LFI":         {En: "Local file include", Zh: "本地文件包含"},
	"RFI":         {En: "Remote file include", Zh: "远程文件包含"},
	"UR":          {En: "Url Redirect", Zh: "URL重定向(CVE)"},
	"DOS":         {En: "DOS", Zh: "DOS攻击"},
	"UFL":         {En: "Unauthorized File Upload", Zh: "未授权文件上传"},
	"GR":          {En: "General Rule", Zh: "一般文件规则"},
	"SS":          {En: "Site Scanning/Probing", Zh: "网站扫描/探测"},
	"SSRF":        {En: "Server-side request forgery", Zh: "跨站请求伪造"},
	"FAPPV":       {En: "Famous application vulnerable", Zh: "针对知名应用的针对性规则"},
	"Other":       {En: "Other", Zh: "其它"},
	"black":       {En: "blacklist", Zh: "黑名单"},
	"white":       {En: "whitelist", Zh: "白名单"},
	"force-white": {En: "strong whitelist", Zh: "强白名单"},
}

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
// func getSASLMechanismByEnv() (sasl.Mechanism, bool, error) {
// 	authMethod := os.Getenv(EnvKafkaAuthMethod)
// 	username := os.Getenv(EnvKafkaAuthUsername)
// 	password := os.Getenv(EnvKafkaAuthPassword)
// 	var mechanism sasl.Mechanism
// 	switch authMethod {
// 	case KafkaAuthPlain:
// 		if username == "" || password == "" {
// 			return nil, true, ErrMissingAuthInfo
// 		}
// 		mechanism = &plain.Mechanism{
// 			Username: username,
// 			Password: password,
// 		}
// 	case KafkaAuthScram:
// 		if username == "" || password == "" {
// 			return nil, true, ErrMissingAuthInfo
// 		}
// 		algoKey := os.Getenv(EnvKafkaScramAlgo)
// 		algo := scram.SHA512
// 		algoTmp, exist := scramAlgo[algoKey]
// 		if exist {
// 			algo = algoTmp
// 		}
// 		var err error
// 		mechanism, err = scram.Mechanism(algo, username, password)
// 		if err != nil {
// 			return nil, true, err
// 		}
// 	}
// 	return mechanism, mechanism != nil, nil
// }
113

114 115 116
type LogConsumerService struct {
	consumer *kafka.Reader
	db       *gorm.DB
117
	esStore  *esStore.ESStore
118 119
}

120 121 122 123 124 125 126 127 128
func NewLogConsumerService(db *gorm.DB, esStore *esStore.ESStore, config *config.KafkaConfig) *LogConsumerService {
	// mechanism, _, err := getSASLMechanismByEnv()
	// if err != nil {
	// 	log.Fatal().Err(err).Msg("failed to get SASL mechanism")
	// }
	// brokers := strings.Split(os.Getenv(EnvKafkaBrokers), ",")
	// if len(brokers) == 0 {
	// 	log.Fatal().Msg("no KAFKA_BROKERS env variable set")
	// }
129

130 131 132 133 134 135 136 137 138 139 140
	// consumer := kafka.NewReader(kafka.ReaderConfig{
	// 	Brokers: brokers,
	// 	GroupID: KafkaGroupIvanWafDetectionsPalace,
	// 	Topic:   KafkaTopicIvanWafDetections,
	// 	Dialer: &kafka.Dialer{
	// 		SASLMechanism: mechanism,
	// 		Timeout:       10 * time.Second,
	// 		DualStack:     true,
	// 	},
	// })
	consumer := NewKafkaReader(config)
141

142 143 144
	return &LogConsumerService{
		consumer: consumer,
		db:       db,
145
		esStore:  esStore,
146 147 148 149
	}
}

func (s *LogConsumerService) Consume() {
150
	log.Info().Msg("start consume kafka message")
151 152 153 154 155 156 157 158 159 160 161 162 163
	for {
		m, err := s.consumer.ReadMessage(context.Background())
		if err != nil {
			log.Error().Err(err).Msg("failed to read message")
			continue
		}
		log.Info().Msgf("message: %s", string(m.Value))
		go s.processMessage(m)
	}
}

func (s *LogConsumerService) processMessage(m kafka.Message) {
	log.Info().Msgf("processing message: %s", string(m.Value))
164 165 166
	s.Handle(context.Background(), m.Value)
}

167 168 169 170
func (s *LogConsumerService) genWafDetection(wafDetectionMessage model.WafDetectionMessage, attackedLog model.WafDetectionAttackedLog) (model.WafDetection, error) {
	if attackedLog.AttackIP == "" {
		return model.WafDetection{}, errors.New("attack_ip is empty")
	}
171

172 173 174 175 176 177 178 179 180
	wafDetection := model.WafDetection{
		WafDetectionMessageBasic: wafDetectionMessage.WafDetectionMessageBasic,
		WafDetectionAttackedLog:  attackedLog,
		CreatedAt:                wafDetectionMessage.CreatedAt,
	}
	wafDetection.WafDetectionAttackedLog.ID = id.Str()
	return wafDetection, nil
}

181 182 183 184 185 186 187 188 189 190 191 192 193
func serverityFromAttackAction(action string) int {
	switch action {
	case "warn":
		return 5
	case "block":
		return 3
	case "pass":
		return 7
	default:
		return 7
	}
}

194 195 196
func (s *LogConsumerService) genWafDetectionSignal(wafDetectionMessage model.WafDetectionMessage, attackedLog model.WafDetectionAttackedLog, eventID string) (model.Signal, error) {
	signal := model.Signal{
		ID:      id.Str(),
197
		RuleKey: &model.RuleKey{Name: attackedLog.AttackType, Category: "WAF"},
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
		Scope: &map[string]model.Scope{
			"cluster": {
				Kind: "cluster",
				ID:   wafDetectionMessage.WafDetectionMessageBasic.ClusterKey,
				Name: wafDetectionMessage.WafDetectionMessageBasic.ClusterKey,
			},
			"namespace": {
				Kind: "namespace",
				ID:   wafDetectionMessage.WafDetectionMessageBasic.Namespace,
				Name: wafDetectionMessage.WafDetectionMessageBasic.Namespace,
			},
			"resource": {
				Kind: "resource",
				ID:   "",
				Name: fmt.Sprintf("%s(%s)", wafDetectionMessage.WafDetectionMessageBasic.ResName, wafDetectionMessage.WafDetectionMessageBasic.ResKind),
			},
		},
215
		Severity: serverityFromAttackAction(attackedLog.Action),
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
		Tags:     []string{"waf"},
		EventIDs: []string{eventID},
		Context: map[string]interface{}{
			"attack_ip":   attackedLog.AttackIP,
			"attack_time": attackedLog.AttackTime,
			"attack_url":  attackedLog.AttackedURL,
			"attack_app":  attackedLog.AttackedApp,
			"attack_load": attackedLog.AttackLoad,
			"rule_name":   attackedLog.RuleName,
			"action":      attackedLog.Action,
			"waf_body": map[string]interface{}{
				"type": "code",
				"request": map[string]interface{}{
					"action":  attackedLog.Action,
					"req_pkg": attackedLog.ReqPkg,
				},
				"response": map[string]interface{}{
					"content_type": attackedLog.RspContentType,
					"res_pkg":      attackedLog.RspPkg,
				},
			},
		},
		CreatedAt:         attackedLog.AttackTime,
		IsWhitelistFilter: false,
	}
	return signal, nil
}

244
func (s *LogConsumerService) genWafDetectionEvent(wafDetectionMessage model.WafDetectionMessage, attackedLog model.WafDetectionAttackedLog) (model.Event, error) {
qiuqunfeng's avatar
qiuqunfeng committed
245 246 247 248 249
	// attackClass := AttackClassDespMap[attackedLog.AttackType]
	// attackClassDesp := attackClass.Zh
	// if lang == "en" {
	// 	attackClassDesp = attackClass.En
	// }
250 251
	event := model.Event{
		ID:          id.Str(),
252
		Type:        "ruleScope",
qiuqunfeng's avatar
qiuqunfeng committed
253
		Description: attackedLog.AttackType,
254 255 256
		RuleKeys: []model.RuleKey{
			{
				Version1: 0,
257
				Name:     attackedLog.AttackType,
258 259 260
				Category: "WAF",
			},
		},
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
		Scopes: map[string][]model.Scope{
			"cluster": {
				{
					Kind: "cluster",
					ID:   wafDetectionMessage.WafDetectionMessageBasic.ClusterKey,
					Name: wafDetectionMessage.WafDetectionMessageBasic.ClusterKey,
				},
			},
			"namespace": {
				{
					Kind: "namespace",
					ID:   wafDetectionMessage.WafDetectionMessageBasic.Namespace,
					Name: wafDetectionMessage.WafDetectionMessageBasic.Namespace,
				},
			},
			"resource": {
				{
					Kind: "resource",
					ID:   "",
					Name: fmt.Sprintf("%s(%s)", wafDetectionMessage.WafDetectionMessageBasic.ResName, wafDetectionMessage.WafDetectionMessageBasic.ResKind),
				},
			},
		},
		Resources: []map[string]model.Scope{
			{
				"cluster": {
					Kind: "cluster",
					ID:   wafDetectionMessage.WafDetectionMessageBasic.ClusterKey,
					Name: wafDetectionMessage.WafDetectionMessageBasic.ClusterKey,
				},
				"namespace": {
					Kind: "namespace",
					ID:   wafDetectionMessage.WafDetectionMessageBasic.Namespace,
					Name: wafDetectionMessage.WafDetectionMessageBasic.Namespace,
				},
				"resource": {
					Kind: "resource",
					ID:   "",
					Name: fmt.Sprintf("%s(%s)", wafDetectionMessage.WafDetectionMessageBasic.ResName, wafDetectionMessage.WafDetectionMessageBasic.ResKind),
				},
			},
		},
		Relation: model.Relation{
304
			Type: "Discovery",
305
		},
306 307
		CreatedAt: attackedLog.AttackTime,
		UpdatedAt: attackedLog.AttackTime,
308
		Severity:  serverityFromAttackAction(attackedLog.Action),
309 310
		Timestamp: time.Now(),
		Context: map[string]interface{}{
311 312
			"attack_ip":   attackedLog.AttackIP,
			"attack_time": attackedLog.AttackTime,
313
			"attack_url":  attackedLog.AttackedURL,
314 315 316
			"attack_app":  attackedLog.AttackedApp,
			"attack_load": attackedLog.AttackLoad,
			"rule_name":   attackedLog.RuleName,
317
			"action":      attackedLog.Action,
318
			"waf_body": map[string]interface{}{
319 320 321 322 323 324 325 326 327
				"type": "code",
				"request": map[string]interface{}{
					"action":  attackedLog.Action,
					"req_pkg": attackedLog.ReqPkg,
				},
				"response": map[string]interface{}{
					"content_type": attackedLog.RspContentType,
					"res_pkg":      attackedLog.RspPkg,
				},
328
			},
329
		},
330 331 332
		SignalsCount: map[int]int{
			6: 1,
		},
333 334 335 336
	}
	return event, nil
}

337 338 339 340 341 342 343 344 345
func (s *LogConsumerService) Handle(ctx context.Context, message []byte) error {
	WafDetectionMessage := model.WafDetectionMessage{}
	err := json.Unmarshal(message, &WafDetectionMessage)
	if err != nil {
		log.Err(err).Str("message.Value", string(message)).Msg("unmarshal kafka message fails")
		return err
	}

	bulkableRequests := make([]es.BulkableRequest, 0)
346
	// WafDetections := make([]model.WafDetection, len(WafDetectionMessage.AttackedLog))
347 348 349 350 351 352 353 354 355 356

	unPassCount := 0
	for i := range WafDetectionMessage.AttackedLog {
		if WafDetectionMessage.AttackedLog[i].AttackIP == "" {
			log.Err(err).Str("message.Value", string(message)).Msg("WafDetectionMessage.AttackedLog[i].AttackIP empty")
			continue
		}
		if WafDetectionMessage.AttackedLog[i].Action != "pass" {
			unPassCount++
		}
357 358 359 360
		// WafDetections[i].WafDetectionMessageBasic = WafDetectionMessage.WafDetectionMessageBasic
		// WafDetections[i].WafDetectionAttackedLog = WafDetectionMessage.AttackedLog[i]
		// WafDetections[i].WafDetectionAttackedLog.ID = id.Str()
		// WafDetections[i].CreatedAt = WafDetectionMessage.CreatedAt
361 362 363 364 365
		wafDetection, err := s.genWafDetection(WafDetectionMessage, WafDetectionMessage.AttackedLog[i])
		if err != nil {
			log.Err(err).Str("message.Value", string(message)).Msg("gen waf detection fails")
			continue
		}
366

367 368
		bulkIndexWaflog := es.NewBulkIndexRequest().Index(EsIndexWafDetectionsAlias)
		bulkableRequests = append(bulkableRequests, bulkIndexWaflog.Id(wafDetection.WafDetectionAttackedLog.ID).Doc(wafDetection))
369 370 371 372 373 374

		event, err := s.genWafDetectionEvent(WafDetectionMessage, WafDetectionMessage.AttackedLog[i])
		if err != nil {
			log.Err(err).Str("message.Value", string(message)).Msg("gen waf detection event fails")
			continue
		}
375
		log.Info().Msgf("waf event: %+v", event)
376 377
		bulkIndexEvent := es.NewBulkIndexRequest().Index(ESIndexEvents)
		bulkableRequests = append(bulkableRequests, bulkIndexEvent.Id(event.ID).Doc(event))
378 379 380 381 382 383 384 385

		signal, err := s.genWafDetectionSignal(WafDetectionMessage, WafDetectionMessage.AttackedLog[i], event.ID)
		if err != nil {
			log.Err(err).Str("message.Value", string(message)).Msg("gen waf detection signal fails")
			continue
		}
		bulkIndexSignal := es.NewBulkIndexRequest().Index(ESIndexSignals)
		bulkableRequests = append(bulkableRequests, bulkIndexSignal.Id(signal.ID).Doc(signal))
386 387 388 389
	}

	s.esStore.Save(ctx, bulkableRequests)

390 391 392 393 394
	// err = s.db.WithContext(ctx).Model(&model.WafService{}).Where("id = ?", WafDetectionMessage.ServiceID).Update("attack_num", gorm.Expr("attack_num + ?", 1)).Error
	// if err != nil {
	// 	log.Err(err).Int64("WafDetectionMessage.ServiceID", WafDetectionMessage.ServiceID).Msg("update waf_service attack_number fails")
	// 	return err
	// }
395 396

	return nil
397
}