waf.go 6.21 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 26 27 28 29 30 31 32 33 34 35 36
	"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}
}

func (s *wafService) GetWaf(ctx context.Context, gatewayName string) (*Waf, error) {
	waf := &Waf{
		GatewayName: gatewayName,
		Mode:        "block",
		RuleNum:     100,
		AttackNum:   100,
	}
	return waf, nil
}

func (s *wafService) CreateWaf(ctx context.Context, req *CreateWafReq) (*Waf, error) {
qiuqunfeng's avatar
commit  
qiuqunfeng committed
37
	// Create the WAF service resource
qiuqunfeng's avatar
qiuqunfeng committed
38 39 40 41 42 43 44 45 46 47 48 49 50 51
	service := &v1alpha1.Service{
		ObjectMeta: metav1.ObjectMeta{
			Name:      req.GatewayName,
			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
52 53 54 55 56 57 58 59
			Uri: &v1alpha1.StringMatch{
				Prefix: "/",
			},
			LogConfig: &v1alpha1.LogConfig{
				Enable: 1,
				Level:  "info",
			},
			Mode: "block",
qiuqunfeng's avatar
qiuqunfeng committed
60 61
		},
	}
qiuqunfeng's avatar
commit  
qiuqunfeng committed
62 63 64

	// Get enabled rule categories from DB
	var ruleCategories []model.WafRuleCategory
qiuqunfeng's avatar
commit  
qiuqunfeng committed
65
	if err := s.db.Model(&model.WafRuleCategory{}).Where("status = ?", 0).Find(&ruleCategories).Error; err != nil {
qiuqunfeng's avatar
commit  
qiuqunfeng committed
66 67 68 69 70 71
		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
72 73 74 75 76 77 78 79 80 81 82 83 84
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			// Create new WAF service record if not found
			wafService = &model.WafService{
				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
85 86 87 88
	}

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

	if wafService.RuleCategoryStatus != nil && len(wafService.RuleCategoryStatus.CategoryID) > 0 {
qiuqunfeng's avatar
commit  
qiuqunfeng committed
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
		// 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
120 121 122 123
	}

	return nil, nil
}
qiuqunfeng's avatar
commit  
qiuqunfeng committed
124 125

func (s *wafService) UpdateMode(ctx context.Context, req *UpdateModeReq) (*Waf, error) {
qiuqunfeng's avatar
commit  
qiuqunfeng committed
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
	// 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{
				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
148 149
	return nil, nil
}
qiuqunfeng's avatar
commit  
qiuqunfeng committed
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179

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
180
	yamlFile, err := os.ReadFile("rules/waf-rules.yaml")
qiuqunfeng's avatar
commit  
qiuqunfeng committed
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
	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
213 214 215 216
		err = s.db.Table("waf_rule_categories").Create(&model).Error
		if err != nil {
			return err
		}
qiuqunfeng's avatar
commit  
qiuqunfeng committed
217 218 219 220
	}

	return nil
}