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

import (
	"context"
qiuqunfeng's avatar
commit  
qiuqunfeng committed
5 6
	"fmt"
	"os"
qiuqunfeng's avatar
commit  
qiuqunfeng committed
7
	"slices"
qiuqunfeng's avatar
qiuqunfeng committed
8

qiuqunfeng's avatar
commit  
qiuqunfeng committed
9
	"gitlab.com/tensorsecurity-rd/waf-console/internal/model"
qiuqunfeng's avatar
qiuqunfeng committed
10 11
	"gitlab.com/tensorsecurity-rd/waf-console/pkg/apis/waf.security.io/v1alpha1"
	"gitlab.com/tensorsecurity-rd/waf-console/pkg/generated/clientset/versioned"
qiuqunfeng's avatar
commit  
qiuqunfeng committed
12
	"gopkg.in/yaml.v3"
qiuqunfeng's avatar
qiuqunfeng committed
13 14 15 16 17 18 19 20 21 22 23 24 25
	"gorm.io/gorm"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

type wafService struct {
	client *versioned.Clientset
	db     *gorm.DB
}

func NewWafService(client *versioned.Clientset, db *gorm.DB) Service {
	return &wafService{client: client, db: db}
}

qiuqunfeng's avatar
commit  
qiuqunfeng committed
26
func (s *wafService) GetWaf(ctx context.Context, regionCode, namespace, gatewayName string) (*WafService, error) {
qiuqunfeng's avatar
commit  
qiuqunfeng committed
27
	wafService := &model.WafService{}
qiuqunfeng's avatar
commit  
qiuqunfeng committed
28
	err := s.db.Model(&model.WafService{}).Where("gateway_name = ? AND region_code = ? AND namespace = ?", gatewayName, regionCode, namespace).First(wafService).Error
qiuqunfeng's avatar
commit  
qiuqunfeng committed
29 30 31 32
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			// Create new WAF service record if not found
			wafService = &model.WafService{
qiuqunfeng's avatar
commit  
qiuqunfeng committed
33 34
				RegionCode:  regionCode,
				Namespace:   namespace,
qiuqunfeng's avatar
commit  
qiuqunfeng committed
35 36 37 38 39 40 41 42 43
				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
44
	}
qiuqunfeng's avatar
commit  
qiuqunfeng committed
45 46 47 48 49 50
	return &WafService{
		GatewayName: wafService.GatewayName,
		Mode:        wafService.Mode,
		RuleNum:     wafService.RuleNum,
		AttackNum:   wafService.AttackNum,
	}, nil
qiuqunfeng's avatar
qiuqunfeng committed
51 52
}

qiuqunfeng's avatar
commit  
qiuqunfeng committed
53
func (s *wafService) CreateWaf(ctx context.Context, req *CreateWafReq) (*WafService, error) {
qiuqunfeng's avatar
commit  
qiuqunfeng committed
54
	// Create the WAF service resource
qiuqunfeng's avatar
commit  
qiuqunfeng committed
55
	name := fmt.Sprintf("%s-%d", req.GatewayName, req.Port)
qiuqunfeng's avatar
qiuqunfeng committed
56 57
	service := &v1alpha1.Service{
		ObjectMeta: metav1.ObjectMeta{
qiuqunfeng's avatar
commit  
qiuqunfeng committed
58
			Name:      name,
qiuqunfeng's avatar
qiuqunfeng committed
59 60 61 62 63 64 65 66 67 68 69
			Namespace: req.Namespace,
		},
		Spec: v1alpha1.ServiceSpec{
			HostNames:   req.Host,
			ServiceName: req.GatewayName,
			Port:        req.Port,
			Workload: v1alpha1.WorkloadRef{
				Kind:      "Deployment",
				Name:      req.GatewayName,
				Namespace: req.Namespace,
			},
qiuqunfeng's avatar
commit  
qiuqunfeng committed
70 71 72 73 74 75 76 77
			Uri: &v1alpha1.StringMatch{
				Prefix: "/",
			},
			LogConfig: &v1alpha1.LogConfig{
				Enable: 1,
				Level:  "info",
			},
			Mode: "block",
qiuqunfeng's avatar
qiuqunfeng committed
78 79
		},
	}
qiuqunfeng's avatar
commit  
qiuqunfeng committed
80 81 82

	// Get enabled rule categories from DB
	var ruleCategories []model.WafRuleCategory
qiuqunfeng's avatar
commit  
qiuqunfeng committed
83
	if err := s.db.Model(&model.WafRuleCategory{}).Where("status = ?", 0).Find(&ruleCategories).Error; err != nil {
qiuqunfeng's avatar
commit  
qiuqunfeng committed
84 85 86 87 88 89
		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 = ?", req.GatewayName).First(wafService).Error
qiuqunfeng's avatar
commit  
qiuqunfeng committed
90 91 92 93
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			// Create new WAF service record if not found
			wafService = &model.WafService{
qiuqunfeng's avatar
commit  
qiuqunfeng committed
94 95
				RegionCode:  req.RegionCode,
				Namespace:   req.Namespace,
qiuqunfeng's avatar
commit  
qiuqunfeng committed
96 97 98 99 100 101 102 103 104
				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)
		}
qiuqunfeng's avatar
commit  
qiuqunfeng committed
105 106 107 108
	}

	// Determine which rule categories to enable
	var enabledCategories []model.WafRuleCategory
qiuqunfeng's avatar
commit  
qiuqunfeng committed
109 110

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

	// Add rules from enabled categories
	for _, category := range enabledCategories {
		for _, rule := range category.Rules {
			service.Spec.Rules = append(service.Spec.Rules, v1alpha1.Rule{
				ID:          rule.ID,
				Level:       rule.Level,
				Name:        rule.Name,
				Type:        rule.Type,
				Description: rule.Description,
				Expr:        rule.Expr,
				Mode:        rule.Mode,
			})
		}
	}

	// Create the WAF service in Kubernetes
	if _, err := s.client.WafV1alpha1().Services(req.Namespace).Create(ctx, service, metav1.CreateOptions{}); err != nil {
		return nil, fmt.Errorf("failed to create WAF service: %v", err)
qiuqunfeng's avatar
qiuqunfeng committed
140 141 142 143
	}

	return nil, nil
}
qiuqunfeng's avatar
commit  
qiuqunfeng committed
144

qiuqunfeng's avatar
commit  
qiuqunfeng committed
145
func (s *wafService) UpdateMode(ctx context.Context, req *UpdateModeReq) (*WafService, error) {
qiuqunfeng's avatar
commit  
qiuqunfeng committed
146 147 148 149 150 151 152
	// Check if WAF service exists
	wafService := &model.WafService{}
	err := s.db.Model(&model.WafService{}).Where("gateway_name = ?", req.GatewayName).First(wafService).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			// Create new WAF service record if not found
			wafService = &model.WafService{
qiuqunfeng's avatar
commit  
qiuqunfeng committed
153 154
				RegionCode:  req.RegionCode,
				Namespace:   req.Namespace,
qiuqunfeng's avatar
commit  
qiuqunfeng committed
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
				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)
		}
	}
qiuqunfeng's avatar
commit  
qiuqunfeng committed
170 171
	return nil, nil
}
qiuqunfeng's avatar
commit  
qiuqunfeng committed
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

func (s *wafService) GetRuleCategories(ctx context.Context) ([]WafRuleCategory, error) {
	var categories []WafRuleCategory
	err := s.db.Table("waf_rule_categories").Find(&categories).Error
	if err != nil {
		return nil, err
	}
	return categories, nil
}

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
qiuqunfeng's avatar
commit  
qiuqunfeng committed
202
	yamlFile, err := os.ReadFile("rules/waf-rules.yaml")
qiuqunfeng's avatar
commit  
qiuqunfeng committed
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
	if err != nil {
		return fmt.Errorf("error reading yaml file: %v", err)
	}

	err = yaml.Unmarshal(yamlFile, &categories)
	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,
			CategoryEN:    category.Catagory.EN,
			CategoryZH:    category.Catagory.Zh,
			DescriptionEN: category.Description.EN,
			DescriptionZH: category.Description.Zh,
			Rules:         model.RuleList(rules),
		}
qiuqunfeng's avatar
commit  
qiuqunfeng committed
235 236 237 238
		err = s.db.Table("waf_rule_categories").Create(&model).Error
		if err != nil {
			return err
		}
qiuqunfeng's avatar
commit  
qiuqunfeng committed
239 240 241 242
	}

	return nil
}