waf.go 52.3 KB
Newer Older
qiuqunfeng's avatar
qiuqunfeng committed
1 2 3
package service

import (
qiuqunfeng's avatar
qiuqunfeng committed
4
	"bytes"
qiuqunfeng's avatar
qiuqunfeng committed
5
	"context"
qiuqunfeng's avatar
commit  
qiuqunfeng committed
6
	"crypto/tls"
qiuqunfeng's avatar
qiuqunfeng committed
7
	"encoding/json"
qiuqunfeng's avatar
commit  
qiuqunfeng committed
8
	"fmt"
9
	"io"
qiuqunfeng's avatar
qiuqunfeng committed
10
	"net/http"
11
	"net/url"
qiuqunfeng's avatar
commit  
qiuqunfeng committed
12
	"os"
qiuqunfeng's avatar
qiuqunfeng committed
13 14
	"strconv"
	"strings"
15
	"sync"
16
	"time"
qiuqunfeng's avatar
qiuqunfeng committed
17

18 19
	jsoniter "github.com/json-iterator/go"
	"github.com/olivere/elastic/v7"
qiuqunfeng's avatar
commit  
qiuqunfeng committed
20
	"github.com/rs/zerolog/log"
qiuqunfeng's avatar
commit  
qiuqunfeng committed
21
	"gitlab.com/tensorsecurity-rd/waf-console/internal/model"
qiuqunfeng's avatar
qiuqunfeng committed
22
	"gitlab.com/tensorsecurity-rd/waf-console/internal/utils"
qiuqunfeng's avatar
qiuqunfeng committed
23 24
	"gitlab.com/tensorsecurity-rd/waf-console/pkg/apis/waf.security.io/v1alpha1"
	"gorm.io/gorm"
25
	corev1 "k8s.io/api/core/v1"
qiuqunfeng's avatar
qiuqunfeng committed
26
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
27
	"k8s.io/apimachinery/pkg/util/sets"
qiuqunfeng's avatar
qiuqunfeng committed
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
var DefAttackClass = []AttackClasses{{1, "Remote Command Execution", "远程代码执行", "RCE_OS"},
	{2, "SQL Injection", "SQL注入", "SQLI"},
	{3, "Cross-Site Scripting", "跨站脚本攻击", "XSS"},
	{4, "Access of Internal Components", "内部组件访问", "AOIC"},
	{5, "Directory Traversal", "路径穿越", "DT"},
	{6, "Data Leakage", "数据泄露", "DL"},
	{7, "Source Code Disclosure", "源码泄露", "SCD"},
	{8, "Php remote code execution", "PHP远程代码执行", "RCE_PHP"},
	{9, "Java remote code execution", "JAVA远程代码执行", "RCE_JAVA"},
	{10, "Local file include", "本地文件包含", "LFI"},
	{11, "Remote file include", "远程文件包含", "RFI"},
	{12, "Url Redirect", "URL重定向(CVE)", "UR"},
	{13, "DOS", "DOS攻击", "DOS"},
	{14, "Unauthorized File Upload", "未授权文件上传", "UFL"},
	{15, "General Rule", "一般文件规则", "GR"},
	{16, "Site Scanning/Probing", "网站扫描/探测", "SS"},
	{17, "Server-side request forgery", "跨站请求伪造", "SSRF"},
	{18, "Famous application vulnerable", "针对知名应用的针对性规则", "FAPPV"},
	{19, "Other", "其它", "Other"},
	{20, "blacklist", "黑名单", "black"},
	{21, "whitelist", "白名单", "white"},
	{22, "strong whitelist", "强白名单", "force-white"}}

qiuqunfeng's avatar
qiuqunfeng committed
53
type wafService struct {
qiuqunfeng's avatar
qiuqunfeng committed
54 55
	clusterClientManager *utils.ClusterClientManager
	db                   *gorm.DB
56
	gatewayUrl           string
57
	elasticClient        *elastic.Client
qiuqunfeng's avatar
qiuqunfeng committed
58 59
}

60 61
func NewWafService(clusterClientManager *utils.ClusterClientManager, db *gorm.DB, gatewayUrl string, elasticClient *elastic.Client) Service {
	return &wafService{clusterClientManager: clusterClientManager, db: db, gatewayUrl: gatewayUrl, elasticClient: elasticClient}
qiuqunfeng's avatar
qiuqunfeng committed
62 63
}

64 65 66 67 68
func getEnabledRuleNum(db *gorm.DB, wafService *model.WafService) (int, error) {
	// Get total number of rule categories
	var totalCategories int64
	if err := db.Model(&model.WafRuleCategory{}).Where("status = ?", 0).Count(&totalCategories).Error; err != nil {
		return 0, fmt.Errorf("failed to get rule categories: %v", err)
69
	}
70 71 72 73 74 75 76 77 78

	// If no rule category status is set, all categories are enabled
	if wafService.RuleCategoryStatus == nil {
		return int(totalCategories), nil
	}

	// If status is 0, all categories are enabled
	if wafService.RuleCategoryStatus.Status == 0 {
		return int(totalCategories), nil
79 80
	}

81 82 83 84 85
	// If status is 1, count only enabled categories
	disabledCount := len(wafService.RuleCategoryStatus.CategoryID)
	enabledCount := int(totalCategories) - disabledCount

	return enabledCount, nil
86 87
}

qiuqunfeng's avatar
qiuqunfeng committed
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
func (s *wafService) GetWaf(ctx context.Context, regionCode, namespace, gatewayName string) (*WafService, error) {
	wafService := &model.WafService{}
	err := s.db.Model(&model.WafService{}).Where("gateway_name = ? AND region_code = ? AND namespace = ?", gatewayName, regionCode, namespace).First(wafService).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			// Create new WAF service record if not found
			wafService = &model.WafService{
				RegionCode:  regionCode,
				Namespace:   namespace,
				GatewayName: gatewayName,
				Mode:        string(WafModeAlert),
			}
			if err := s.db.Create(wafService).Error; err != nil {
				return nil, fmt.Errorf("failed to create WAF service: %v", err)
			}
		} else {
			return nil, fmt.Errorf("failed to query WAF service: %v", err)
		}
qiuqunfeng's avatar
qiuqunfeng committed
106
	}
107 108 109 110 111 112 113 114 115 116 117 118 119
	listenerWafs, err := s.ListListenerWafStatus(ctx, &GatewateInfo{
		GatewayName: gatewayName,
		Namespace:   namespace,
		RegionCode:  regionCode,
	})
	if err != nil {
		return nil, fmt.Errorf("failed to list listener WAF status: %v", err)
	}
	listeners := []string{}
	for _, listener := range listenerWafs {
		hosts := strings.Join(listener.Hosts, "@")
		listeners = append(listeners, fmt.Sprintf("%s-%d", hosts, listener.Port))
	}
120 121 122 123
	ruleNum, err := getEnabledRuleNum(s.db, wafService)
	if err != nil {
		return nil, fmt.Errorf("failed to get enabled rule count: %v", err)
	}
124

125
	// Count attack logs for current day
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
	// now := time.Now()
	// startOfDay := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
	// endOfDay := startOfDay.Add(24 * time.Hour)

	// boolQuery := elastic.NewBoolQuery()
	// boolQuery.Must(elastic.NewTermQuery("service_id", wafService.ID))
	// boolQuery.Filter(elastic.NewRangeQuery("attack_time").
	// 	Gte(startOfDay.UnixMilli()).
	// 	Lt(endOfDay.UnixMilli()))
	// boolQuery.Filter(elastic.NewBoolQuery().MustNot(elastic.NewTermQuery("action", "pass")))

	// result, err := s.elasticClient.Count("waf-detections*").
	// 	Query(boolQuery).
	// 	Do(ctx)
	// if err != nil {
	// 	return nil, fmt.Errorf("failed to count attack logs: %v", err)
	// }

	// wafService.AttackNum = int(result)
qiuqunfeng's avatar
qiuqunfeng committed
145
	return &WafService{
146
		ID:          wafService.ID,
qiuqunfeng's avatar
qiuqunfeng committed
147 148
		GatewayName: wafService.GatewayName,
		Mode:        wafService.Mode,
149
		RuleNum:     ruleNum,
qiuqunfeng's avatar
qiuqunfeng committed
150
		AttackNum:   wafService.AttackNum,
151
		Listeners:   listeners,
qiuqunfeng's avatar
qiuqunfeng committed
152
	}, nil
qiuqunfeng's avatar
qiuqunfeng committed
153 154
}

155
func (s *wafService) CountAttackLogs(ctx context.Context, regionCode string, serviceID uint32) (int64, error) {
qunfeng qiu's avatar
qunfeng qiu committed
156 157 158 159 160 161
	now := time.Now()
	startOfDay := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
	endOfDay := startOfDay.Add(24 * time.Hour)

	boolQuery := elastic.NewBoolQuery()
	boolQuery.Must(elastic.NewTermQuery("service_id", serviceID))
162
	boolQuery.Filter(elastic.NewTermQuery("cluster_key", regionCode))
qunfeng qiu's avatar
qunfeng qiu committed
163 164 165 166 167 168 169 170 171 172
	boolQuery.Filter(elastic.NewRangeQuery("attack_time").
		Gte(startOfDay.UnixMilli()).
		Lt(endOfDay.UnixMilli()))
	boolQuery.Filter(elastic.NewBoolQuery().MustNot(elastic.NewTermQuery("action", "pass")))

	result, err := s.elasticClient.Count("waf-detections*").
		Query(boolQuery).
		Do(ctx)
	if err != nil {
		log.Err(fmt.Errorf("failed to count attack logs: %v", err))
173
		return 0, err
qunfeng qiu's avatar
qunfeng qiu committed
174 175
	}

176
	return result, nil
qunfeng qiu's avatar
qunfeng qiu committed
177 178
}

179 180 181 182 183 184 185 186 187 188 189
func (s *wafService) ListWafs(ctx context.Context) ([]WafService, error) {
	var wafs []WafService
	if err := s.db.Model(&model.WafService{}).Find(&wafs).Error; err != nil {
		return nil, err
	}
	for i, waf := range wafs {
		wafs[i].Name = waf.GatewayName
	}
	return wafs, nil
}

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
func (s *wafService) GetWafGatewayInfo(ctx context.Context, req *GetWafGatewayInfoReq) (*WafService, error) {
	wafService := &model.WafService{}
	err := s.db.Model(&model.WafService{}).Where("gateway_name = ? AND namespace = ? AND region_code = ?", req.GatewayName, req.Namespace, req.RegionCode).First(wafService).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			httpRequst := http.Request{
				Method: http.MethodPost,
				URL:    &url.URL{Scheme: "https", Host: "console.tensorsecurity.com", Path: "/api/v1/waf/gateway"},
				Header: http.Header{
					"Cookie": []string{req.Cookie},
				},
				Body: io.NopCloser(strings.NewReader(fmt.Sprintf(`{"gateway_name": "%s", "namespace": "%s", "region_code": "%s"}`, req.GatewayName, req.Namespace, req.RegionCode))),
			}
			resp, err := http.DefaultClient.Do(&httpRequst)
			if err != nil {
				return nil, fmt.Errorf("failed to get WAF service: %v", err)
			}
			defer resp.Body.Close()
			body, err := io.ReadAll(resp.Body)
			if err != nil {
				return nil, fmt.Errorf("failed to read WAF service: %v", err)
			}
			var wafService model.WafService
			err = json.Unmarshal(body, &wafService)
			if err != nil {
				return nil, fmt.Errorf("failed to unmarshal WAF service: %v", err)
			}
			wafService.ID = 0
			wafService.RuleCategoryStatus = nil
			wafService.RuleNum = 0
			wafService.AttackNum = 0
			// wafService.Host = model.HostList([]string{"*"})
			wafService.Mode = string(WafModeAlert)
			err = s.db.Create(wafService).Error
			if err != nil {
				return nil, fmt.Errorf("failed to create WAF service: %v", err)
			}
		} else {
			return nil, fmt.Errorf("failed to query WAF service: %v", err)
		}
	}
	return &WafService{
		GatewayName: wafService.GatewayName,
		Mode:        wafService.Mode,
		RuleNum:     wafService.RuleNum,
		AttackNum:   wafService.AttackNum,
	}, nil
}

qiuqunfeng's avatar
commit  
qiuqunfeng committed
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
func (s *wafService) getRulesForService(req *CreateWafReq) ([]v1alpha1.Rule, error) {
	rules := []v1alpha1.Rule{}
	ruleCategories := []model.WafRuleCategory{}
	if err := s.db.Model(&model.WafRuleCategory{}).Where("status = ?", 0).Find(&ruleCategories).Error; err != nil {
		return nil, fmt.Errorf("failed to get rule categories: %v", err)
	}

	// Get existing WAF service config if any
	wafService := &model.WafService{}
	err := s.db.Model(&model.WafService{}).Where("gateway_name = ? AND namespace = ? AND region_code = ?", req.GatewayName, req.Namespace, req.RegionCode).First(wafService).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			// Create new WAF service record if not found
			wafService = &model.WafService{
				RegionCode:  req.RegionCode,
				Namespace:   req.Namespace,
				GatewayName: req.GatewayName,
				Mode:        string(WafModeAlert),
			}
			if err := s.db.Create(wafService).Error; err != nil {
				return nil, fmt.Errorf("failed to create WAF service: %v", err)
			}
		} else {
			return nil, fmt.Errorf("failed to query WAF service: %v", err)
		}
	}

	// Determine which rule categories to enable
	var enabledCategories []model.WafRuleCategory

269
	if wafService.RuleCategoryStatus != nil && len(wafService.RuleCategoryStatus.CategoryID) == 1 {
qiuqunfeng's avatar
commit  
qiuqunfeng committed
270 271
		// Only include categories not already enabled
		for _, category := range ruleCategories {
272 273
			if s.isCategoryEnabled(category.CategoryID, wafService.RuleCategoryStatus) {
				enabledCategories = append(enabledCategories, category)
qiuqunfeng's avatar
commit  
qiuqunfeng committed
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
			}
		}
	} else {
		// Enable all categories if none specified
		enabledCategories = ruleCategories
	}

	for _, category := range enabledCategories {
		for _, rule := range category.Rules {
			rules = append(rules, v1alpha1.Rule{
				ID:          rule.ID,
				Level:       rule.Level,
				Name:        rule.Name,
				Type:        rule.Type,
				Description: rule.Description,
				Expr:        rule.Expr,
				Mode:        rule.Mode,
			})
		}
	}

	return rules, nil
}

qiuqunfeng's avatar
qiuqunfeng committed
298
func (s *wafService) CreateWaf(ctx context.Context, req *CreateWafReq) (*WafService, error) {
299
	var errMsg string
300
	var status int = 0 // Success by default
301

qiuqunfeng's avatar
qiuqunfeng committed
302
	name := fmt.Sprintf("%s-%d", req.GatewayName, req.Port)
303 304

	defer func() {
305
		_ = s.addListenerHistory(ctx, name, req.ListenerName, req.GatewayName, req.Namespace, req.RegionCode, errMsg, status, model.OperationCreate)
306 307 308
	}()

	// Create the WAF service resource
qiuqunfeng's avatar
qiuqunfeng committed
309 310
	service := &v1alpha1.Service{
		ObjectMeta: metav1.ObjectMeta{
qiuqunfeng's avatar
qiuqunfeng committed
311
			Name:      name,
qiuqunfeng's avatar
qiuqunfeng committed
312
			Namespace: req.Namespace,
qiuqunfeng's avatar
qiuqunfeng committed
313 314 315
			Labels: map[string]string{
				"apigateway_name": req.GatewayName,
			},
qiuqunfeng's avatar
qiuqunfeng committed
316 317 318
		},
		Spec: v1alpha1.ServiceSpec{
			HostNames:   req.Host,
319
			ServiceName: req.ListenerName,
qiuqunfeng's avatar
qiuqunfeng committed
320 321
			Port:        req.Port,
			Workload: v1alpha1.WorkloadRef{
322
				Kind:       req.GatewayName,
323
				Name:       req.GatewayName,
324 325
				Namespace:  req.Namespace,
				ClusterKey: req.RegionCode,
qiuqunfeng's avatar
qiuqunfeng committed
326
			},
qiuqunfeng's avatar
qiuqunfeng committed
327 328 329 330 331 332 333
			Uri: &v1alpha1.StringMatch{
				Prefix: "/",
			},
			LogConfig: &v1alpha1.LogConfig{
				Enable: 1,
				Level:  "info",
			},
334 335
			Mode:      string(req.Mode),
			ServiceID: req.ServiceID,
qiuqunfeng's avatar
qiuqunfeng committed
336 337
		},
	}
qiuqunfeng's avatar
qiuqunfeng committed
338

339
	rules, err := s.getRulesForService(req)
qiuqunfeng's avatar
qiuqunfeng committed
340
	if err != nil {
341
		status = 1 // Failure
342 343
		errMsg = fmt.Sprintf("failed to get rules for service: %v", err)
		return nil, fmt.Errorf("%s", errMsg)
qiuqunfeng's avatar
qiuqunfeng committed
344
	}
345
	service.Spec.Rules = rules
qiuqunfeng's avatar
qiuqunfeng committed
346

347
	if len(service.Spec.Rules) == 0 {
348
		status = 1 // Failure
349 350
		errMsg = "cannot create WAF service with no rules"
		return nil, fmt.Errorf("%s", errMsg)
351 352
	}

qiuqunfeng's avatar
qiuqunfeng committed
353 354 355
	// Create the WAF service in Kubernetes
	client := s.clusterClientManager.GetClient(req.RegionCode)
	if client == nil {
356
		status = 1 // Failure
357 358
		errMsg = fmt.Sprintf("failed to get cluster client for region %s", req.RegionCode)
		return nil, fmt.Errorf("%s", errMsg)
qiuqunfeng's avatar
qiuqunfeng committed
359
	}
360
	if _, err := client.Versioned.WafV1alpha1().Services(req.Namespace).Create(ctx, service, metav1.CreateOptions{}); err != nil {
361
		status = 1 // Failure
362 363
		errMsg = fmt.Sprintf("failed to create WAF service: %v", err)
		return nil, fmt.Errorf("%s", errMsg)
qiuqunfeng's avatar
qiuqunfeng committed
364 365
	}

366 367 368 369 370 371
	return &WafService{
		GatewayName: req.GatewayName,
		Mode:        service.Spec.Mode,
		RuleNum:     len(service.Spec.Rules),
		AttackNum:   0,
	}, nil
qiuqunfeng's avatar
qiuqunfeng committed
372
}
qiuqunfeng's avatar
commit  
qiuqunfeng committed
373

qiuqunfeng's avatar
qiuqunfeng committed
374
func (s *wafService) DeleteListenerWaf(ctx context.Context, req *DeleteListenerReq) error {
375
	var errMsg string
376
	var status int = 0 // Success by default
377
	var listenerName string
378 379 380

	name := fmt.Sprintf("%s-%d", req.GatewayName, req.Port)

qiuqunfeng's avatar
qiuqunfeng committed
381 382
	client := s.clusterClientManager.GetClient(req.RegionCode)
	if client == nil {
383
		status = 1 // Failure
384 385
		errMsg = fmt.Sprintf("failed to get cluster client for region %s", req.RegionCode)
		return fmt.Errorf("%s", errMsg)
qiuqunfeng's avatar
qiuqunfeng committed
386
	}
387

qiuqunfeng's avatar
fix  
qiuqunfeng committed
388 389
	service, err := client.Versioned.WafV1alpha1().Services(req.Namespace).Get(ctx, name, metav1.GetOptions{})
	if err != nil {
390 391 392 393
		status = 1 // Failure
		errMsg = fmt.Sprintf("failed to get WAF service: %v", err)
		return fmt.Errorf("%s", errMsg)
	}
394
	listenerName = service.Spec.ServiceName
qiuqunfeng's avatar
fix  
qiuqunfeng committed
395
	log.Info().Msgf("listenerName: %s", listenerName)
396

397 398 399 400
	defer func() {
		_ = s.addListenerHistory(ctx, name, listenerName, req.GatewayName, req.Namespace, req.RegionCode, errMsg, status, model.OperationDelete)
	}()

401
	if err := client.Versioned.WafV1alpha1().Services(req.Namespace).Delete(ctx, name, metav1.DeleteOptions{}); err != nil {
402
		status = 1 // Failure
403 404
		errMsg = fmt.Sprintf("failed to delete WAF service: %v", err)
		return fmt.Errorf("%s", errMsg)
qiuqunfeng's avatar
qiuqunfeng committed
405
	}
406

qiuqunfeng's avatar
qiuqunfeng committed
407 408 409 410 411 412
	return nil
}

func (s *wafService) UpdateMode(ctx context.Context, req *UpdateModeReq) (*WafService, error) {
	// Check if WAF service exists
	wafService := &model.WafService{}
413
	err := s.db.Model(&model.WafService{}).Where("gateway_name = ? and namespace = ? and region_code = ?", req.GatewayName, req.Namespace, req.RegionCode).First(wafService).Error
qiuqunfeng's avatar
qiuqunfeng committed
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			// Create new WAF service record if not found
			wafService = &model.WafService{
				RegionCode:  req.RegionCode,
				Namespace:   req.Namespace,
				GatewayName: req.GatewayName,
				Mode:        string(req.Mode),
			}
			if err := s.db.Create(wafService).Error; err != nil {
				return nil, fmt.Errorf("failed to create WAF service: %v", err)
			}
		} else {
			return nil, fmt.Errorf("failed to query WAF service: %v", err)
		}
	} else {
		// Update mode if service exists
		if err := s.db.Model(wafService).Update("mode", string(req.Mode)).Error; err != nil {
			return nil, fmt.Errorf("failed to update WAF service mode: %v", err)
		}
	}
435 436 437 438 439
	// Update mode for each listener
	client := s.clusterClientManager.GetClient(req.RegionCode)
	if client == nil {
		return nil, fmt.Errorf("failed to get cluster client for region %s", req.RegionCode)
	}
440
	listenerList, err := client.Versioned.WafV1alpha1().Services(req.Namespace).List(ctx, metav1.ListOptions{LabelSelector: fmt.Sprintf("apigateway_name=%s", req.GatewayName)})
441 442 443
	if err != nil {
		return nil, fmt.Errorf("failed to get listener list: %v", err)
	}
444
	var wg sync.WaitGroup
445
	for _, listener := range listenerList.Items {
446
		wg.Add(1)
447
		listener := listener // Create new variable for goroutine
448
		listener.Spec.Mode = string(req.Mode)
449
		go func() {
450
			defer wg.Done()
451
			log.Info().Msgf("update WAF service mode: %v", listener.Name)
452
			_, err := client.Versioned.WafV1alpha1().Services(req.Namespace).Update(ctx, &listener, metav1.UpdateOptions{})
453 454 455 456 457
			if err != nil {
				log.Error().Msgf("failed to update WAF service mode: %v", err)
			}
		}()
	}
458
	wg.Wait()
459 460 461 462
	return &WafService{
		GatewayName: req.GatewayName,
		Mode:        string(req.Mode),
	}, nil
qiuqunfeng's avatar
commit  
qiuqunfeng committed
463
}
qiuqunfeng's avatar
commit  
qiuqunfeng committed
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484

func (s *wafService) GetRules(ctx context.Context, categoryID string) ([]WafRule, error) {
	var rules []WafRule
	err := s.db.Table("waf_rules").Where("category_id = ?", categoryID).Find(&rules).Error
	if err != nil {
		return nil, err
	}
	return rules, nil
}

func (s *wafService) GetRule(ctx context.Context, ruleID int) (*WafRule, error) {
	var rule WafRule
	err := s.db.Table("waf_rules").Where("id = ?", ruleID).First(&rule).Error
	if err != nil {
		return nil, err
	}
	return &rule, nil
}

func (s *wafService) SaveRuleCategoryToDB(ctx context.Context) error {
	var categories []WafRuleCategory
485
	jsonFile, err := os.ReadFile("rules/waf-rules.json")
qiuqunfeng's avatar
commit  
qiuqunfeng committed
486 487 488 489
	if err != nil {
		return fmt.Errorf("error reading yaml file: %v", err)
	}

490 491
	// err = yaml.Unmarshal(yamlFile, &categories)
	err = json.Unmarshal(jsonFile, &categories)
qiuqunfeng's avatar
commit  
qiuqunfeng committed
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
	if err != nil {
		return fmt.Errorf("error unmarshaling yaml: %v", err)
	}

	for _, category := range categories {
		rules := []model.WafRule{}
		for _, rule := range category.Rules {
			rules = append(rules, model.WafRule{
				ID:          rule.ID,
				CategoryID:  category.CategoryID,
				Level:       rule.Level,
				Name:        rule.Name,
				Type:        rule.Type,
				Description: rule.Description,
				Expr:        rule.Expr,
				Mode:        rule.Mode,
			})
		}
		model := model.WafRuleCategory{
			CategoryID:    category.CategoryID,
			Status:        category.Status,
513 514
			CategoryEN:    category.Category.EN,
			CategoryZH:    category.Category.Zh,
qiuqunfeng's avatar
commit  
qiuqunfeng committed
515 516 517 518
			DescriptionEN: category.Description.EN,
			DescriptionZH: category.Description.Zh,
			Rules:         model.RuleList(rules),
		}
qiuqunfeng's avatar
commit  
qiuqunfeng committed
519 520 521 522
		err = s.db.Table("waf_rule_categories").Create(&model).Error
		if err != nil {
			return err
		}
qiuqunfeng's avatar
commit  
qiuqunfeng committed
523 524 525 526
	}

	return nil
}
qiuqunfeng's avatar
qiuqunfeng committed
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542

func (s *wafService) DeleteListener(ctx context.Context, req *DeleteListenerReq) error {
	listener := &model.GatewayListener{}
	err := s.db.Model(&model.GatewayListener{}).Where("gateway_name = ? AND namespace = ? AND region_code = ?", req.GatewayName, req.Namespace, req.RegionCode).First(listener).Error
	if err != nil {
		return err
	}

	err = s.db.Model(&model.GatewayListener{}).Where("gateway_name = ? AND namespace = ? AND region_code = ?", req.GatewayName, req.Namespace, req.RegionCode).Delete(listener).Error
	if err != nil {
		return err
	}

	return nil
}

543 544 545 546 547 548
func (s *wafService) getServiceID(ctx context.Context, gatewayName, namespace, regionCode string) (uint32, error) {
	service := &model.WafService{}
	err := s.db.WithContext(ctx).Model(&model.WafService{}).Where("gateway_name = ? AND namespace = ? AND region_code = ?", gatewayName, namespace, regionCode).First(service).Error
	if err != nil {
		return 0, err
	}
qiuqunfeng's avatar
qiuqunfeng committed
549

550 551 552 553
	return uint32(service.ID), nil
}

func (s *wafService) EnableListenerWaf(ctx context.Context, req *EnableListenerWafReq) error {
554 555
	if req.Enable {
		log.Info().Msgf("Create WAF for listener %s", req.GatewayName)
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
		serviceID, err := s.getServiceID(ctx, req.GatewayName, req.Namespace, req.RegionCode)
		if err != nil {
			if err == gorm.ErrRecordNotFound {
				service := &model.WafService{
					GatewayName: req.GatewayName,
					Namespace:   req.Namespace,
					RegionCode:  req.RegionCode,
					Mode:        string(req.Mode),
				}
				if err := s.db.Model(&model.WafService{}).Create(&service).Error; err != nil {
					return err
				}
				serviceID = uint32(service.ID)
			} else {
				return err
			}
		}

		_, err = s.CreateWaf(ctx, &CreateWafReq{
qiuqunfeng's avatar
qiuqunfeng committed
575 576 577 578 579
			GatewateInfo: GatewateInfo{
				GatewayName: req.GatewayName,
				Namespace:   req.Namespace,
				RegionCode:  req.RegionCode,
			},
580 581 582 583
			Port:         uint32(req.Port),
			Host:         req.Hosts,
			Mode:         req.Mode,
			ListenerName: req.ListenerName,
584
			ServiceID:    serviceID,
qiuqunfeng's avatar
qiuqunfeng committed
585
		})
qiuqunfeng's avatar
commit  
qiuqunfeng committed
586 587 588
		if err != nil {
			return err
		}
qiuqunfeng's avatar
qiuqunfeng committed
589
	} else {
590 591
		log.Info().Msgf("Delete WAF for listener %s", req.GatewayName)
		err := s.DeleteListenerWaf(ctx, &DeleteListenerReq{
qiuqunfeng's avatar
qiuqunfeng committed
592 593 594 595 596
			GatewateInfo: GatewateInfo{
				GatewayName: req.GatewayName,
				Namespace:   req.Namespace,
				RegionCode:  req.RegionCode,
			},
597 598
			Port:         req.Port,
			ListenerName: req.ListenerName,
qiuqunfeng's avatar
qiuqunfeng committed
599
		})
qiuqunfeng's avatar
commit  
qiuqunfeng committed
600 601 602
		if err != nil {
			return err
		}
qiuqunfeng's avatar
qiuqunfeng committed
603 604 605 606
	}
	return nil
}

607 608 609 610 611 612
func getGatewayNameFromCrn(crn string) string {
	// crn:ucs::apigateway:lf-tst7:214613666997:instance/testaaa
	parts := strings.Split(crn, "/")
	return parts[len(parts)-1]
}

613
func (s *wafService) listListenerFromApiGateway(ctx context.Context, apiGatewayCrn string, regionCode string, cookie string) ([]GatewayRespListenerData, error) {
614 615 616 617 618 619 620
	body, err := json.Marshal(map[string]string{
		"apigateway_crn": apiGatewayCrn,
		"region_code":    regionCode,
	})
	if err != nil {
		return nil, fmt.Errorf("failed to marshal request body: %v", err)
	}
621
	request, err := http.NewRequestWithContext(ctx, "POST", "https://csm.console.test.tg.unicom.local/apigatewaymng/listener/lf-tst7/list_listeners", bytes.NewBuffer(body))
622 623 624 625
	if err != nil {
		return nil, fmt.Errorf("failed to create request: %v", err)
	}
	request.Header.Set("Cookie", cookie)
qiuqunfeng's avatar
commit  
qiuqunfeng committed
626 627 628 629 630 631 632 633
	// Create custom transport with TLS config
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{
			InsecureSkipVerify: true, // Skip certificate verification for test environment
		},
	}
	client := &http.Client{Transport: tr}
	resp, err := client.Do(request)
634 635 636 637 638
	if err != nil {
		return nil, fmt.Errorf("failed to get listener list: %v", err)
	}
	defer resp.Body.Close()

639
	log.Info().Msgf("resp: %v", resp)
640 641 642 643 644 645
	// Parse response
	var response GatewayListenerResponseList

	if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
		return nil, fmt.Errorf("failed to parse listener list: %v", err)
	}
646
	log.Info().Msgf("response: %v", response)
647 648 649
	return response.Data, nil
}

qiuqunfeng's avatar
qiuqunfeng committed
650 651
func (s *wafService) EnableGatewayWaf(ctx context.Context, req *EnableGatewayWafReq) error {
	if req.Enable {
652
		listeners, err := s.listListenerFromApiGateway(ctx, req.ApiGatewayCrn, req.RegionCode, req.Cookie)
qiuqunfeng's avatar
qiuqunfeng committed
653 654 655
		if err != nil {
			return fmt.Errorf("failed to get listener list: %v", err)
		}
qiuqunfeng's avatar
commit  
qiuqunfeng committed
656
		log.Info().Msgf("listeners: %v", listeners)
qiuqunfeng's avatar
qiuqunfeng committed
657 658
		// Create WAF for each listener
		for _, listener := range listeners {
qiuqunfeng's avatar
commit  
qiuqunfeng committed
659 660
			gatewayName := getGatewayNameFromCrn(listener.ApiGatewayCrn)
			namespace := fmt.Sprintf("%s-%s", listener.CreateAccountName, listener.CreateAccountID)
qiuqunfeng's avatar
qiuqunfeng committed
661 662
			if _, err := s.CreateWaf(ctx, &CreateWafReq{
				GatewateInfo: GatewateInfo{
qiuqunfeng's avatar
commit  
qiuqunfeng committed
663 664
					GatewayName: gatewayName,
					Namespace:   namespace,
qiuqunfeng's avatar
qiuqunfeng committed
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
					RegionCode:  req.RegionCode,
				},
				Port: uint32(listener.Port),
				Host: listener.Hosts,
			}); err != nil {
				return fmt.Errorf("failed to create WAF for listener %d: %v", listener.Port, err)
			}
		}
	} else {
		s.DeleteGatewayWaf(ctx, &GatewateInfo{
			GatewayName: req.GatewayName,
			Namespace:   req.Namespace,
			RegionCode:  req.RegionCode,
		})
	}
	return nil
}

func (s *wafService) DeleteGatewayWaf(ctx context.Context, req *GatewateInfo) error {
684 685 686 687 688 689
	var errMsg string
	var status int = 0 // Success by default

	defer func() {
		s.addListenerHistory(ctx, "", "", req.GatewayName, req.Namespace, req.RegionCode, errMsg, status, model.OperationDelete)
	}()
qiuqunfeng's avatar
qiuqunfeng committed
690 691
	client := s.clusterClientManager.GetClient(req.RegionCode)
	if client == nil {
692 693 694
		errMsg = "failed to get cluster client"
		status = 1
		return fmt.Errorf("%s", errMsg)
qiuqunfeng's avatar
qiuqunfeng committed
695 696
	}
	labelSelector := fmt.Sprintf("apigateway_name=%s", req.GatewayName)
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715

	// serviceList, err := client.Versioned.WafV1alpha1().Services(req.Namespace).List(ctx, metav1.ListOptions{LabelSelector: labelSelector})
	// if err != nil {
	// 	errMsg = "failed to get WAF service"
	// 	status = 1
	// 	return fmt.Errorf("%s", errMsg)
	// }
	// listenerNames := []string{}
	// wafNames := []string{}
	// for _, service := range serviceList.Items {
	// 	listenerNames = append(listenerNames, service.Spec.ServiceName)
	// 	wafNames = append(wafNames, fmt.Sprintf("%s-%d", service.Spec.ServiceName, service.Spec.Port))
	// }
	// defer func() {
	// 	for index, listenerName := range listenerNames {
	// 		s.addListenerHistory(ctx, wafNames[index], listenerName, req.GatewayName, req.Namespace, req.RegionCode, errMsg, status, model.OperationDelete)
	// 	}
	// }()

716
	if err := client.Versioned.WafV1alpha1().Services(req.Namespace).DeleteCollection(ctx, metav1.DeleteOptions{}, metav1.ListOptions{LabelSelector: labelSelector}); err != nil {
717 718 719
		errMsg = "failed to delete WAF service"
		status = 1
		return fmt.Errorf("%s", errMsg)
qiuqunfeng's avatar
qiuqunfeng committed
720 721 722 723
	}
	return nil
}

724 725 726 727 728 729 730 731 732 733 734 735
func (s *wafService) isCategoryEnabled(categoryID string, wafService *model.RuleCategoryStatus) bool {
	if wafService.Status == 0 {
		return true
	}
	for _, id := range wafService.CategoryID {
		if id == categoryID {
			return false
		}
	}
	return true
}

736 737 738 739 740 741 742 743 744 745
func (s *wafService) calculateCrdWafRules(ctx context.Context, req *RuleRequest, wafService *model.WafService) ([]v1alpha1.Rule, error) {
	rules := []v1alpha1.Rule{}
	ruleCategories := []model.WafRuleCategory{}
	if err := s.db.WithContext(ctx).Model(&model.WafRuleCategory{}).Where("status = ?", 0).Find(&ruleCategories).Error; err != nil {
		return nil, fmt.Errorf("failed to get rule categories: %v", err)
	}

	// Determine which rule categories to enable
	var enabledCategories []model.WafRuleCategory

qiuqunfeng's avatar
qiuqunfeng committed
746
	if wafService.RuleCategoryStatus != nil && len(wafService.RuleCategoryStatus.CategoryID) >= 1 {
747 748
		// Only include categories not already enabled
		for _, category := range ruleCategories {
749 750
			if s.isCategoryEnabled(category.CategoryID, wafService.RuleCategoryStatus) {
				enabledCategories = append(enabledCategories, category)
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
			}
		}
	} else {
		// Enable all categories if none specified
		enabledCategories = ruleCategories
	}

	for _, category := range enabledCategories {
		for _, rule := range category.Rules {
			rules = append(rules, v1alpha1.Rule{
				ID:          rule.ID,
				Level:       rule.Level,
				Name:        rule.Name,
				Type:        rule.Type,
				Description: rule.Description,
				Expr:        rule.Expr,
				Mode:        rule.Mode,
			})
		}
	}

	return rules, nil
}

func (s *wafService) updateRulesForCrd(ctx context.Context, req *RuleRequest, wafService *model.WafService) error {
	client := s.clusterClientManager.GetClient(req.RegionCode)
	if client == nil {
		return fmt.Errorf("failed to get cluster client")
	}
	serviceList, err := client.Versioned.WafV1alpha1().Services(req.Namespace).List(ctx, metav1.ListOptions{LabelSelector: fmt.Sprintf("apigateway_name=%s", req.GatewayName)})
	if err != nil {
		return fmt.Errorf("failed to get WAF service: %v", err)
	}
	if len(serviceList.Items) == 0 {
		log.Info().Msgf("WAF service not found for gateway %s", req.GatewayName)
		return nil
	}
	rules, err := s.calculateCrdWafRules(ctx, req, wafService)
	if err != nil {
		return fmt.Errorf("failed to calculate WAF rules: %v", err)
	}

	for _, service := range serviceList.Items {
		service.Spec.Rules = rules
		_, err = client.Versioned.WafV1alpha1().Services(req.Namespace).Update(ctx, &service, metav1.UpdateOptions{})
		if err != nil {
			return fmt.Errorf("failed to update WAF service: %v", err)
		}
	}

	return nil
}

qiuqunfeng's avatar
qiuqunfeng committed
804 805
func (s *wafService) UpdateRule(ctx context.Context, req *RuleRequest) error {
	wafService := &model.WafService{}
806
	err := s.db.Model(&model.WafService{}).Where("gateway_name = ? and namespace = ? and region_code = ?", req.GatewayName, req.Namespace, req.RegionCode).First(wafService).Error
qiuqunfeng's avatar
qiuqunfeng committed
807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			// Create new WAF service record if not found
			wafService = &model.WafService{
				RegionCode:  req.RegionCode,
				Namespace:   req.Namespace,
				GatewayName: req.GatewayName,
				Mode:        string(WafModeAlert),
				RuleCategoryStatus: &model.RuleCategoryStatus{
					CategoryID: req.CategoryID,
					Status:     req.Status,
				},
			}
			if err := s.db.Create(wafService).Error; err != nil {
				return fmt.Errorf("failed to create WAF service: %v", err)
			}
		} else {
			return fmt.Errorf("failed to query WAF service: %v", err)
		}
	} else {
		// Update mode if service exists
828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
		if req.Status == 1 {
			if wafService.RuleCategoryStatus == nil {
				wafService.RuleCategoryStatus = &model.RuleCategoryStatus{
					CategoryID: req.CategoryID,
					Status:     req.Status,
				}
			} else {
				wafService.RuleCategoryStatus.CategoryID = append(wafService.RuleCategoryStatus.CategoryID, req.CategoryID...)
				wafService.RuleCategoryStatus.Status = req.Status
			}
		} else {
			if wafService.RuleCategoryStatus == nil {
				return nil
			}
			for i, id := range wafService.RuleCategoryStatus.CategoryID {
				for _, categoryID := range req.CategoryID {
					if id == categoryID {
845 846 847 848 849
						if i == len(wafService.RuleCategoryStatus.CategoryID)-1 {
							wafService.RuleCategoryStatus.CategoryID = wafService.RuleCategoryStatus.CategoryID[:i]
						} else {
							wafService.RuleCategoryStatus.CategoryID = append(wafService.RuleCategoryStatus.CategoryID[:i], wafService.RuleCategoryStatus.CategoryID[i+1:]...)
						}
850 851 852
					}
				}
			}
853
		}
854

855
		if err := s.db.Model(wafService).Update("rule_category_status", wafService.RuleCategoryStatus).Error; err != nil {
qiuqunfeng's avatar
qiuqunfeng committed
856 857 858
			return fmt.Errorf("failed to update WAF service mode: %v", err)
		}
	}
859 860 861 862
	err = s.updateRulesForCrd(ctx, req, wafService)
	if err != nil {
		return fmt.Errorf("failed to update WAF rules: %v", err)
	}
qiuqunfeng's avatar
qiuqunfeng committed
863 864 865 866 867 868 869 870 871
	return nil
}

func (s *wafService) ListListenerWafStatus(ctx context.Context, req *GatewateInfo) ([]*GatewayListener, error) {
	client := s.clusterClientManager.GetClient(req.RegionCode)
	if client == nil {
		return nil, fmt.Errorf("failed to get cluster client")
	}

872
	listenerList, err := client.Versioned.WafV1alpha1().Services(req.Namespace).List(ctx, metav1.ListOptions{LabelSelector: fmt.Sprintf("apigateway_name=%s", req.GatewayName)})
qiuqunfeng's avatar
qiuqunfeng committed
873 874 875 876 877 878 879 880
	if err != nil {
		return nil, fmt.Errorf("failed to get listener list: %v", err)
	}

	listenerStatusList := []*GatewayListener{}
	for _, listener := range listenerList.Items {
		n := strings.LastIndex(listener.Name, "-")
		if n == -1 {
qiuqunfeng's avatar
commit  
qiuqunfeng committed
881
			return nil, fmt.Errorf("failed to get listener port: %v", listener.Name)
qiuqunfeng's avatar
qiuqunfeng committed
882 883 884 885
		}
		listenerPort := listener.Name[n+1:]
		listenerPortInt, err := strconv.Atoi(listenerPort)
		if err != nil {
qiuqunfeng's avatar
commit  
qiuqunfeng committed
886
			return nil, fmt.Errorf("failed to parse listener port: %v", err)
qiuqunfeng's avatar
qiuqunfeng committed
887 888
		}

889 890
		// hosts := strings.Join(listener.Spec.HostNames, "@")
		// log.Info().Msgf("hosts: %v", hosts)
qiuqunfeng's avatar
qiuqunfeng committed
891 892 893 894
		listenerStatusList = append(listenerStatusList, &GatewayListener{
			GatewayName: req.GatewayName,
			Namespace:   req.Namespace,
			RegionCode:  req.RegionCode,
895 896
			Port:        listenerPortInt,
			Hosts:       listener.Spec.HostNames,
qiuqunfeng's avatar
qiuqunfeng committed
897 898 899
		})
	}

900 901 902 903 904 905 906 907 908 909
	// for _, port := range portList {
	// 	listenerStatusList = append(listenerStatusList, &GatewayListener{
	// 		GatewayName: req.GatewayName,
	// 		Namespace:   req.Namespace,
	// 		RegionCode:  req.RegionCode,
	// 		Port:        port,
	// 		Enable:      true,
	// 	})
	// }

qiuqunfeng's avatar
qiuqunfeng committed
910 911
	return listenerStatusList, nil
}
912 913 914 915 916 917 918 919

func (s *wafService) EnableListenerWafs(ctx context.Context, req *EnableListenerWafsReq) error {

	client := s.clusterClientManager.GetClient(req.RegionCode)
	if client == nil {
		return fmt.Errorf("failed to get cluster client")
	}

920
	listenerList, err := client.Versioned.WafV1alpha1().Services(req.Namespace).List(ctx, metav1.ListOptions{LabelSelector: fmt.Sprintf("apigateway_name=%s", req.GatewayName)})
921
	if err != nil {
922
		log.Error().Msgf("failed to get listener list: %v", err)
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
		return err
	}

	portList := []int{}
	for _, listener := range listenerList.Items {
		n := strings.LastIndex(listener.Name, "-")
		if n == -1 {
			return fmt.Errorf("failed to get listener port: %v", listener.Name)
		}
		listenerPort := listener.Name[n+1:]
		listenerPortInt, err := strconv.Atoi(listenerPort)
		if err != nil {
			return fmt.Errorf("failed to parse listener port: %v", err)
		}
		portList = append(portList, listenerPortInt)
	}
	currentPortSet := sets.NewInt(portList...)

	desiredPortSet := sets.NewInt()
942
	wafMap := map[int]ListenerWaf{}
943
	for _, listener := range req.Listeners {
944
		// get port from listener.HostsAndPort, like hosts1@127.0.0.1@abc.com-8080
945
		index := strings.LastIndex(listener.HostsAndPort, "-")
946 947 948
		if index == -1 {
			return fmt.Errorf("failed to get listener port: %v", listener)
		}
949
		port := listener.HostsAndPort[index+1:]
950 951 952 953 954
		portInt, err := strconv.Atoi(port)
		if err != nil {
			return fmt.Errorf("failed to parse listener port: %v", err)
		}
		desiredPortSet.Insert(portInt)
955
		log.Info().Msgf("listener: %v", listener.Name)
956

957
		hosts := strings.Split(listener.HostsAndPort[:index], "@")
958 959 960 961 962
		wafMap[portInt] = ListenerWaf{
			Hosts:        hosts,
			HostsAndPort: listener.HostsAndPort,
			Name:         listener.Name,
		}
963 964 965 966
	}

	// enable WAF for ports that are in the desired port set but not in the current port set
	addingPortSet := desiredPortSet.Difference(currentPortSet)
967 968 969 970 971 972 973 974 975 976 977 978

	// Get mode from waf_services table
	wafService := &model.WafService{}
	err = s.db.Model(&model.WafService{}).Where("gateway_name = ?", req.GatewayName).First(wafService).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return fmt.Errorf("waf service not found for gateway %s", req.GatewayName)
		}
		return fmt.Errorf("failed to query waf service: %v", err)
	}
	mode := WafMode(wafService.Mode)

979 980 981 982 983 984 985
	for _, port := range addingPortSet.List() {
		err := s.EnableListenerWaf(ctx, &EnableListenerWafReq{
			GatewateInfo: GatewateInfo{
				GatewayName: req.GatewayName,
				Namespace:   req.Namespace,
				RegionCode:  req.RegionCode,
			},
986 987 988 989 990
			Port:         port,
			Hosts:        wafMap[port].Hosts,
			Enable:       true,
			Mode:         mode,
			ListenerName: wafMap[port].Name,
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
		})
		if err != nil {
			return fmt.Errorf("failed to enable listener WAF: %v", err)
		}
	}

	// delete WAF for ports that are not in the desired port set
	deletingPortSet := currentPortSet.Difference(desiredPortSet)
	for _, port := range deletingPortSet.List() {
		err := s.DeleteListenerWaf(ctx, &DeleteListenerReq{
			GatewateInfo: GatewateInfo{
				GatewayName: req.GatewayName,
				Namespace:   req.Namespace,
				RegionCode:  req.RegionCode,
			},
			Port: port,
		})
		if err != nil {
			return fmt.Errorf("failed to delete listener WAF: %v", err)
		}
	}
	return nil
}
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051

func generateListToken(sort []interface{}) (string, error) {
	var token []string

	for _, v := range sort {
		switch v.(type) {
		case string:
			token = append(token, v.(string))
		case float64:
			token = append(token, strconv.FormatInt(int64(v.(float64)), 10))
		default:
			// json-iterator 和 encoding/json 的Decode,返回的都是 encoding/json 的 Number
			t, ok := jsoniter.CastJsonNumber(v)
			if !ok {
				return "", fmt.Errorf("unsupported sort field. value: %v, type: %T", v, v)
			}
			token = append(token, t)
		}
	}

	return strings.Join(token, ","), nil
}

func (s *wafService) ListAttackLogs(ctx context.Context, req *AttackLogFilter) ([]AttackLog, string, error) {
	boolQuery := elastic.NewBoolQuery()
	if req.ServiceId != 0 {
		boolQuery.Must(elastic.NewTermQuery("service_id", req.ServiceId))
	}
	if req.Cluster != "" {
		boolQuery.Filter(elastic.NewTermQuery("cluster_key", req.Cluster))
	}
	if req.AttackUrl != "" {
		boolQuery.Filter(elastic.NewMatchPhraseQuery("attacked_url", req.AttackUrl).Slop(0))
	}
	if req.AttackIp != "" {
		boolQuery.Filter(elastic.NewMatchPhraseQuery("attack_ip", req.AttackIp).Slop(0))
	}
	if req.AttackApp != "" {
1052
		boolQuery.Filter(elastic.NewMatchPhraseQuery("res_name", req.AttackApp).Slop(0))
1053
	}
1054
	if req.AttackListener != "" {
1055
		boolQuery.Filter(elastic.NewMatchPhraseQuery("attacked_app", req.AttackListener).Slop(0))
1056
	}
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
	if req.AttackType != "" {
		attackTypes := strings.Split(req.AttackType, ",")
		var terms []any
		for _, attackType := range attackTypes {
			terms = append(terms, attackType)
		}
		boolQuery.Filter(elastic.NewTermsQuery("attack_type", terms...))
	}
	if req.Action != "" {
		actions := strings.Split(req.Action, ",")
		var terms []interface{}
		for _, action := range actions {
			terms = append(terms, action)
		}
		boolQuery.Filter(elastic.NewTermsQuery("action", terms...))
	} else {
		boolQuery.Filter(elastic.NewBoolQuery().MustNot(elastic.NewTermQuery("action", "pass")))
	}

1076 1077
	hasStart := req.StartTime > 0
	hasEnd := req.EndTime > 0
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
	if hasStart || hasEnd {
		rangeQuery := elastic.NewRangeQuery("attack_time")
		if hasStart {
			rangeQuery.Gte(req.StartTime)
		}
		if hasEnd {
			rangeQuery.Lte(req.EndTime)
		}

		boolQuery.Filter(rangeQuery)
	}
	src, _ := boolQuery.Source()
1090
	log.Info().Interface("src", src.(map[string]interface{})).Msg("find waf detections src")
1091 1092 1093 1094 1095 1096 1097 1098

	ss := s.elasticClient.Search("waf-detections*")
	if req.Token != "" {
		for _, t := range strings.Split(req.Token, ",") {
			ss.SearchAfter(t)
		}
	}

qiuqunfeng's avatar
debug  
qiuqunfeng committed
1099
	log.Info().Interface("limit", req.Limit).Msg("limit")
1100
	result, err := ss.Query(boolQuery).Size(req.Limit).
1101 1102 1103 1104 1105 1106 1107 1108
		SortBy(elastic.NewFieldSort("attack_time").Order(false),
			elastic.NewFieldSort("id.digit").Order(false)).
		Do(ctx)

	if err != nil {
		return nil, "", fmt.Errorf("failed to search waf detections: %v", err)
	}

1109 1110
	list := make([]model.WafDetection, len(result.Hits.Hits))
	endIdx := len(result.Hits.Hits) - 1
1111
	pageToken := ""
1112 1113
	log.Info().Interface("res", result).Msg("list attack logs res")
	for i, hit := range result.Hits.Hits {
1114
		log.Info().Interface("hit source", hit.Source).Msg("hit")
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
		wafDetection := model.WafDetection{}
		if err = json.Unmarshal(hit.Source, &wafDetection); err != nil {
			return nil, "", fmt.Errorf("failed to unmarshal waf detection: %v", err)
		}

		list[i] = wafDetection
		if i == endIdx {
			pageToken, err = generateListToken(hit.Sort)
			if err != nil {
				return nil, "", fmt.Errorf("failed to generate list token: %v", err)
			}
		}
	}

	attackLogs := make([]AttackLog, len(list))
	for i, wafDetection := range list {
		attackLogs[i] = AttackLog{
1132 1133 1134
			Uuid:           wafDetection.ID,
			AttackTime:     wafDetection.AttackTime,
			AttackIp:       wafDetection.AttackIP,
1135
			AttackListener: wafDetection.AttackedApp,
1136 1137 1138 1139
			AttackType:     wafDetection.AttackType,
			Action:         wafDetection.Action,
			ClusterKey:     wafDetection.ClusterKey,
			AttackedAddr:   wafDetection.AttackedURL,
1140 1141 1142 1143 1144
		}
	}
	return attackLogs, pageToken, nil
}

1145
func (s *wafService) GetAttackLogDetails(ctx context.Context, uuid string) (*AttackLog, error) {
1146
	res, err := s.elasticClient.Search("waf-detections*").
1147
		Query(elastic.NewTermQuery("id.keyword", uuid)).Do(ctx)
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
	if err != nil {
		return nil, fmt.Errorf("failed to search waf detections: %v", err)
	}

	wafDetection := model.WafDetection{}
	if err = json.Unmarshal(res.Hits.Hits[0].Source, &wafDetection); err != nil {
		return nil, fmt.Errorf("failed to unmarshal waf detection: %v", err)
	}

	attackLog := &AttackLog{
		Uuid:           wafDetection.ID,
		AttackTime:     wafDetection.AttackTime,
		AttackIp:       wafDetection.AttackIP,
		AttackListener: wafDetection.AttackedApp,
1162
		AttackedApp:    wafDetection.AttackedApp,
1163 1164 1165 1166 1167 1168 1169 1170 1171
		AttackType:     wafDetection.AttackType,
		Action:         wafDetection.Action,
		RuleName:       wafDetection.RuleName,
		AttackLoad:     wafDetection.AttackLoad,
		RequestPkg:     wafDetection.ReqPkg,
	}
	return attackLog, nil
}

1172
func (s *wafService) GetAttackLogRsp(ctx context.Context, uuid string, length uint32) (*AttackRsp, error) {
1173
	res, err := s.elasticClient.Search("waf-detections*").
1174
		Query(elastic.NewTermQuery("id.keyword", uuid)).Do(ctx)
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
	if err != nil {
		return nil, fmt.Errorf("failed to search waf detections: %v", err)
	}

	wafDetection := model.WafDetection{}
	if err = json.Unmarshal(res.Hits.Hits[0].Source, &wafDetection); err != nil {
		return nil, fmt.Errorf("failed to unmarshal waf detection: %v", err)
	}

	rspData := wafDetection.RspPkg
	intact := true

	if length != 0 && length < uint32(len(rspData)) {
		rspData = wafDetection.RspPkg[0:length]
		intact = false
	}
1191 1192 1193 1194 1195
	contentType := wafDetection.RspContentType
	if contentType == "" {
		contentType = "text/html"
	}

1196 1197 1198
	attackRsp := &AttackRsp{
		Uuid:        wafDetection.ID,
		Intact:      intact,
1199
		ContentType: contentType,
1200 1201 1202 1203 1204
		RspPkg:      rspData,
	}
	return attackRsp, nil
}

1205 1206
func (s *wafService) ListRules(ctx context.Context, regionCode, namespace, gatewayName, language, name string) ([]RuleGroupResp, error) {
	ruleCategories := []model.WafRuleCategory{}
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
	db := s.db.Model(&model.WafRuleCategory{})
	if name != "" {
		col := "category_zh"
		switch language {
		case "zh":
			col = "category_zh"
		case "en":
			col = "category_en"
		}
		like := fmt.Sprintf("%s LIKE ?", col)
		db = db.Where(like, "%"+name+"%")
	}
	err := db.Find(&ruleCategories).Error
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
	if err != nil {
		return nil, fmt.Errorf("failed to get waf service: %v", err)
	}

	ruleGroupResp := []RuleGroupResp{}
	wafService := &model.WafService{}
	err = s.db.Model(&model.WafService{}).Where("gateway_name = ? and namespace = ? and region_code = ?", gatewayName, namespace, regionCode).First(wafService).Error
	if err != nil {
		return nil, fmt.Errorf("failed to get waf service: %v", err)
	}
1230
	if wafService.RuleCategoryStatus != nil && wafService.RuleCategoryStatus.Status == 1 {
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
		for _, category := range ruleCategories {
			for _, categoryID := range wafService.RuleCategoryStatus.CategoryID {
				if category.CategoryID == categoryID {
					category.Status = 1
				}
			}
			if language == "en" {
				ruleGroupResp = append(ruleGroupResp, RuleGroupResp{
					CategoryID:  category.CategoryID,
					Status:      category.Status,
					Category:    category.CategoryEN,
					Description: category.DescriptionEN,
				})
			} else {
				ruleGroupResp = append(ruleGroupResp, RuleGroupResp{
					CategoryID:  category.CategoryID,
					Status:      category.Status,
					Category:    category.CategoryZH,
					Description: category.DescriptionZH,
				})
			}
		}
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
	} else {
		for _, category := range ruleCategories {
			if language == "en" {
				ruleGroupResp = append(ruleGroupResp, RuleGroupResp{
					CategoryID:  category.CategoryID,
					Status:      category.Status,
					Category:    category.CategoryEN,
					Description: category.DescriptionEN,
				})
			} else {
				ruleGroupResp = append(ruleGroupResp, RuleGroupResp{
					CategoryID:  category.CategoryID,
					Status:      category.Status,
					Category:    category.CategoryZH,
					Description: category.DescriptionZH,
				})
			}
		}
1271 1272 1273
	}
	return ruleGroupResp, nil
}
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292

func (s *wafService) getWafServiceMap(ctx context.Context, req *MatcherExpr) (map[string][]model.WafService, error) {
	svcMap := make(map[string][]model.WafService)
	wafServices := []model.WafService{}
	if req.Global {
		if err := s.db.WithContext(ctx).Model(&model.WafService{}).Find(&wafServices).Error; err != nil {
			return nil, err
		}
	} else {
		if err := s.db.WithContext(ctx).Model(&model.WafService{}).Where("id in ?", req.Scope).Find(&wafServices).Error; err != nil {
			return nil, err
		}
	}
	for _, wafService := range wafServices {
		svcMap[wafService.RegionCode] = append(svcMap[wafService.RegionCode], wafService)
	}
	return svcMap, nil
}

qiuqunfeng's avatar
debug  
qiuqunfeng committed
1293 1294 1295 1296 1297 1298 1299 1300
func groupWafServicesByNamespace(wafServices []model.WafService) map[string][]model.WafService {
	svcMap := make(map[string][]model.WafService)
	for _, wafService := range wafServices {
		svcMap[wafService.Namespace] = append(svcMap[wafService.Namespace], wafService)
	}
	return svcMap
}

1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
func (s *wafService) createConfigMap(ctx context.Context, req *MatcherExpr, regionCode string, wafSvc []model.WafService) error {
	client := s.clusterClientManager.GetClient(regionCode)
	if client == nil {
		return fmt.Errorf("failed to get cluster client")
	}

	gatewayNames := []string{}
	for _, wafSvc := range wafSvc {
		gatewayNames = append(gatewayNames, wafSvc.GatewayName)
	}
	scope := strings.Join(gatewayNames, ",")
	matchExpr := v1alpha1.MatchExpression{
		ID:     req.ID,
		Name:   req.Name,
		Scope:  scope,
		Mode:   req.Mode,
		Expr:   req.Expr,
		Status: req.Status,
	}
	matchExprJson, err := json.Marshal(matchExpr)
	if err != nil {
		return fmt.Errorf("failed to marshal match expression: %v", err)
	}
	name := fmt.Sprintf("waf-black-white-list-%d", req.ID)
1325
	log.Info().Interface("name", name).Msg("create config map")
1326 1327
	_, err = client.Clientset.CoreV1().ConfigMaps(wafSvc[0].Namespace).Create(ctx, &corev1.ConfigMap{
		ObjectMeta: metav1.ObjectMeta{
1328 1329
			Name:   name,
			Labels: map[string]string{"waf.security.io/black-white-list": "true"},
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
		},
		Data: map[string]string{
			"match-expression": string(matchExprJson),
		},
	}, metav1.CreateOptions{})
	if err != nil {
		return fmt.Errorf("failed to create config map: %v", err)
	}
	return nil
}

1341 1342 1343 1344 1345 1346 1347 1348 1349 1350
func (s *wafService) updateConfigMap(ctx context.Context, req *MatcherExpr, regionCode string, wafSvc []model.WafService) error {
	client := s.clusterClientManager.GetClient(regionCode)
	if client == nil {
		return fmt.Errorf("failed to get cluster client")
	}
	name := fmt.Sprintf("waf-black-white-list-%d", req.ID)
	configMap, err := client.Clientset.CoreV1().ConfigMaps(wafSvc[0].Namespace).Get(ctx, name, metav1.GetOptions{})
	if err != nil {
		return fmt.Errorf("failed to get config map: %v", err)
	}
1351 1352 1353 1354

	gatewayNames := []string{}
	for _, wafSvc := range wafSvc {
		gatewayNames = append(gatewayNames, wafSvc.GatewayName)
1355 1356 1357 1358
	}
	matchExpr := v1alpha1.MatchExpression{
		ID:     req.ID,
		Name:   req.Name,
1359
		Scope:  strings.Join(gatewayNames, ","),
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
		Mode:   req.Mode,
		Expr:   req.Expr,
		Status: req.Status,
	}

	matchExprJson, err := json.Marshal(matchExpr)
	if err != nil {
		return fmt.Errorf("failed to marshal match expression: %v", err)
	}

	newConfigMap := configMap.DeepCopy()
	newConfigMap.Data["match-expression"] = string(matchExprJson)
	_, err = client.Clientset.CoreV1().ConfigMaps(wafSvc[0].Namespace).Update(ctx, newConfigMap, metav1.UpdateOptions{})
	if err != nil {
		return fmt.Errorf("failed to update config map: %v", err)
	}
	return nil
}

1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
func (s *wafService) CreateBlackWhiteList(ctx context.Context, req *MatcherExpr) error {
	tErr := s.db.Transaction(func(tx *gorm.DB) error {
		matcherExpr := model.MatcherExpr{
			Name:   req.Name,
			Scope:  req.Scope,
			Mode:   req.Mode,
			Expr:   req.Expr,
			Global: req.Global,
		}
		err := s.db.WithContext(ctx).Create(&matcherExpr).Error
		if err != nil {
			return err
		}

		req.ID = matcherExpr.ID
		svcMap, err := s.getWafServiceMap(ctx, req)
		if err != nil {
			return err
		}
1398
		log.Info().Interface("svcMap", svcMap).Msg("svcMap")
1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
		for regionCode, wafServices := range svcMap {
			err := s.createConfigMap(ctx, req, regionCode, wafServices)
			if err != nil {
				return err
			}
		}

		return nil
	})
	return tErr
}

func (s *wafService) UpdateBlackWhiteList(ctx context.Context, req *MatcherExpr) error {
1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449
	tErr := s.db.Transaction(func(tx *gorm.DB) error {
		matcherExpr := model.MatcherExpr{}
		err := tx.WithContext(ctx).Where("id = ?", req.ID).First(&matcherExpr).Error
		if err != nil {
			return err
		}

		matcherExpr.Name = req.Name
		matcherExpr.Scope = req.Scope
		matcherExpr.Mode = req.Mode
		matcherExpr.Expr = req.Expr
		matcherExpr.Global = req.Global
		err = tx.WithContext(ctx).Save(&matcherExpr).Error
		if err != nil {
			return err
		}

		svcMap, err := s.getWafServiceMap(ctx, &MatcherExpr{
			ID:     req.ID,
			Name:   matcherExpr.Name,
			Scope:  matcherExpr.Scope,
			Mode:   matcherExpr.Mode,
			Expr:   matcherExpr.Expr,
			Global: matcherExpr.Global,
		})
		if err != nil {
			return err
		}
		for regionCode, wafSvc := range svcMap {
			err = s.updateConfigMap(ctx, req, regionCode, wafSvc)
			if err != nil {
				return err
			}
		}

		return nil
	})
	return tErr
1450 1451 1452
}

func (s *wafService) EnableBlackWhiteList(ctx context.Context, req *MatcherExpr) error {
1453 1454 1455 1456 1457
	matcherExpr := model.MatcherExpr{}
	err := s.db.WithContext(ctx).Where("id = ?", req.ID).First(&matcherExpr).Error
	if err != nil {
		return err
	}
1458 1459 1460 1461
	// if status is the same, do nothing
	if req.Status == int32(matcherExpr.Status) {
		return nil
	}
1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490

	svcMap, err := s.getWafServiceMap(ctx, &MatcherExpr{
		ID:     req.ID,
		Name:   matcherExpr.Name,
		Scope:  matcherExpr.Scope,
		Mode:   matcherExpr.Mode,
		Expr:   matcherExpr.Expr,
		Global: matcherExpr.Global,
	})
	if err != nil {
		return err
	}

	if req.Status == 1 {
		matcherExpr.Status = 1
		for regionCode, wafServices := range svcMap {
			err := s.deleteConfigMap(ctx, req.ID, regionCode, wafServices)
			if err != nil {
				return err
			}
		}
	} else {
		for regionCode, wafServices := range svcMap {
			err := s.createConfigMap(ctx, req, regionCode, wafServices)
			if err != nil {
				return err
			}
		}
	}
1491
	err = s.db.WithContext(ctx).Model(&model.MatcherExpr{}).Where("id = ?", req.ID).Update("status", req.Status).Error
1492 1493 1494
	if err != nil {
		return err
	}
1495 1496 1497
	return nil
}

1498 1499 1500 1501 1502 1503 1504 1505 1506 1507
func (s *wafService) deleteConfigMap(ctx context.Context, id uint32, regionCode string, wafSvc []model.WafService) error {
	client := s.clusterClientManager.GetClient(regionCode)
	if client == nil {
		return fmt.Errorf("failed to get cluster client")
	}
	name := fmt.Sprintf("waf-black-white-list-%d", id)
	return client.Clientset.CoreV1().ConfigMaps(wafSvc[0].Namespace).Delete(ctx, name, metav1.DeleteOptions{})
}

func (s *wafService) DeleteBlackWhiteList(ctx context.Context, ID uint32) error {
qiuqunfeng's avatar
debug  
qiuqunfeng committed
1508
	log.Info().Interface("delete black white list", ID).Msg("delete black white list")
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525
	matcherExpr := model.MatcherExpr{}
	err := s.db.WithContext(ctx).Where("id = ?", ID).First(&matcherExpr).Error
	if err != nil {
		return err
	}

	svcMap, err := s.getWafServiceMap(ctx, &MatcherExpr{
		ID:     ID,
		Name:   matcherExpr.Name,
		Scope:  matcherExpr.Scope,
		Mode:   matcherExpr.Mode,
		Expr:   matcherExpr.Expr,
		Global: matcherExpr.Global,
	})
	if err != nil {
		return err
	}
qiuqunfeng's avatar
debug  
qiuqunfeng committed
1526
	log.Info().Interface("delete svcMap", svcMap).Msg("delete svcMap")
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537
	for regionCode, wafServices := range svcMap {
		err := s.deleteConfigMap(ctx, ID, regionCode, wafServices)
		if err != nil {
			return err
		}
	}
	err = s.db.WithContext(ctx).Delete(&model.MatcherExpr{}, ID).Error
	if err != nil {
		return err
	}

1538 1539 1540
	return nil
}

1541 1542 1543 1544 1545 1546 1547 1548
func GetLikeExpr(s string) string {
	sb := strings.Builder{}
	sb.WriteByte('%')
	sb.WriteString(s)
	sb.WriteByte('%')
	return sb.String()
}

1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561
func getScopeName(ctx context.Context, db *gorm.DB, scope []uint32) ([]string, error) {
	var results []model.WafService
	err := db.WithContext(ctx).Raw("select gateway_name from waf_services where id in ? ", scope).Scan(&results).Error
	if err != nil {
		return nil, err
	}
	names := []string{}
	for _, r := range results {
		names = append(names, r.GatewayName)
	}
	return names, nil
}

1562
func (s *wafService) GetBlackWhiteLists(ctx context.Context, query *MatchExprQueryOption, limit int, offset int) ([]MatcherExpr, int, error) {
1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
	oneCtx, oneCancel := context.WithTimeout(ctx, 750*time.Millisecond)
	defer oneCancel()

	exprs := []model.MatcherExpr{}
	db := s.db.WithContext(oneCtx).Model(&model.MatcherExpr{})

	if len(query.whereEqCondition) > 0 {
		db = db.Where(query.whereEqCondition)
	}
	for column, val := range query.WhereLikeCondition {
		db = db.Where(fmt.Sprintf("%s LIKE ?", column), GetLikeExpr(val))
	}
	for column, val := range query.whereInCondition {
		db = db.Where(fmt.Sprintf("%s in ?", column), val)
	}
1578 1579 1580 1581 1582 1583
	var total int64
	err := db.Count(&total).Error
	if err != nil {
		return nil, 0, err
	}

1584 1585 1586
	if limit > 0 && offset >= 0 {
		db = db.Offset(offset).Limit(limit)
	}
1587
	err = db.Order("updated_at DESC").Find(&exprs).Error
1588
	if err != nil {
1589
		return nil, 0, err
1590 1591 1592
	}
	exprsResp := []MatcherExpr{}
	for _, expr := range exprs {
1593 1594 1595 1596
		scopeNames, err := getScopeName(ctx, s.db, expr.Scope)
		if err != nil {
			return nil, 0, err
		}
1597
		exprsResp = append(exprsResp, MatcherExpr{
1598 1599 1600 1601 1602 1603 1604 1605
			ID:        expr.ID,
			Name:      expr.Name,
			Scope:     expr.Scope,
			ScopeName: scopeNames,
			Mode:      expr.Mode,
			Expr:      expr.Expr,
			Status:    int32(expr.Status),
			Global:    expr.Global,
1606 1607
		})
	}
1608
	return exprsResp, int(total), nil
1609
}
1610 1611 1612 1613 1614 1615 1616

func (s *wafService) ListListenerHistory(ctx context.Context, query *WafListenerHistoryOption, limit int, offset int) ([]model.WafListenerHistory, int, error) {
	listenerHistories := []model.WafListenerHistory{}
	db := s.db.WithContext(ctx).Model(&model.WafListenerHistory{})
	if len(query.WhereEqCondition) > 0 {
		db = db.Where(query.WhereEqCondition)
	}
1617
	for _, val := range query.WhereLikeCondition {
qiuqunfeng's avatar
fix  
qiuqunfeng committed
1618 1619
		expr := GetLikeExpr(val)
		db = db.Where(fmt.Sprintf("%s LIKE ?", "name"), expr).Or("listener_name LIKE ?", expr).Or("gateway_name LIKE ?", expr)
1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635
	}
	if limit > 0 && offset >= 0 {
		db = db.Offset(offset).Limit(limit)
	}
	err := db.Order("created_at DESC").Find(&listenerHistories).Error
	if err != nil {
		return nil, 0, err
	}
	var total int64
	err = db.Count(&total).Error
	if err != nil {
		return nil, 0, err
	}
	return listenerHistories, int(total), nil
}

1636
func (s *wafService) addListenerHistory(ctx context.Context, name, listenerName, gatewayName, namespace, regionCode, description string, status int, operation model.Operation) error {
1637 1638 1639 1640 1641 1642 1643
	listenerHistory := model.WafListenerHistory{
		Name:         name,
		GatewayName:  gatewayName,
		ListenerName: listenerName,
		Namespace:    namespace,
		RegionCode:   regionCode,
		Description:  description,
1644 1645
		Status:       model.Status(status),
		Operation:    operation,
1646 1647 1648 1649 1650 1651 1652
	}
	err := s.db.WithContext(ctx).Create(&listenerHistory).Error
	if err != nil {
		return err
	}
	return nil
}
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674

func (s *wafService) ListAttackClasses(ctx context.Context, lang string) []AttackClasses {
	var attackClass []AttackClasses

	isEn := true
	if lang == "zh" {
		isEn = false
	}

	for i := 0; i < len(DefAttackClass); i++ {
		value := AttackClasses{
			Id:         DefAttackClass[i].Id,
			Describe:   DefAttackClass[i].Describe,
			AttackType: DefAttackClass[i].AttackType,
		}
		if isEn {
			value.Describe = DefAttackClass[i].En
		}
		attackClass = append(attackClass, value)
	}
	return attackClass
}