Commit e8027610 authored by qiuqunfeng's avatar qiuqunfeng
Browse files

Initial commit

parents
package config
const (
WeibuUrl = "https://api.threatbook.cn/v3/ip/query?apikey=d625206f5fdb49eeb98b0c30f46f4310a444f76d392540e8a0bb160d8a7d02c4&resource="
)
var Conf Config
type Config struct {
Debug bool
}
func init() {}
package controller
import (
"time"
"github.com/gin-gonic/gin"
"gitlab.com/tensorsecurity-rd/waf-console/internal/model"
"gitlab.com/tensorsecurity-rd/waf-console/internal/service"
"gitlab.com/tensorsecurity-rd/waf-console/internal/utils"
)
type IpInfoController struct {
service service.Service
// controller.Api
}
var isMock bool
// func NewIpInfoController(apiKey string) *IpInfoController {
// mock := os.Getenv("MOCK")
// // var isMock bool
// if mock == "true" {
// isMock = true
// }
// useCachedIPInfo := os.Getenv("USE_IPINFO_CACHE")
// mode := os.Getenv("MODE")
// if mode == "private" {
// return &IpInfoController{
// service: service.NewIpServicePrivate(config.WeibuUrl, apiKey, useCachedIPInfo == "true"),
// }
// } else {
// return &IpInfoController{
// service: service.NewIpService(config.WeibuUrl, apiKey, useCachedIPInfo == "true"),
// }
// }
// }
func mockResponse(ctx *gin.Context) {
ipInfo := model.IPInfo{
Location: model.Location{
Country: "United States",
Province: "New York",
City: "New York City",
Longitude: -74.006,
Latitude: 40.713,
CountryCode: "US",
},
Carrier: "China mobile",
OSSIntelligences: []model.Intelligence{
{
Source: "ThreatBook Labs",
Confidence: 70,
Expired: false,
FindTime: time.Now().UnixMilli(),
UpdateTime: time.Now().UnixMilli(),
IntelTypes: []string{},
IntelTags: []model.TagsClass{},
},
},
OnlineIntelligences: []model.Intelligence{
{
Source: "ThreatBook Labs",
Confidence: 90,
Expired: true,
FindTime: time.Now().UnixMilli(),
UpdateTime: time.Now().UnixMilli(),
IntelTypes: []string{"aaa"},
IntelTags: []model.TagsClass{
{
TagsType: "industry",
Tags: "aaaa",
},
},
},
},
Ports: []model.Port{
{
Port: 80,
Module: "ddd",
Product: "test",
Version: "4",
Detail: "none",
},
},
Samples: []model.Sample{
{
Hash: "12344",
ScanTime: time.Now().UnixMilli(),
Ratio: "19/25",
MalwareType: "attck",
MalwareFamily: "wwww",
},
},
Cas: []model.CAS{
{
Protocol: "ssl",
Port: 443,
Period: 122,
DigitalCertificate: model.Certificate{
Subject: "CloudFlare Origin Certificate",
Fingerprint: "857b7363019f1bf550375d56fa1f483ffb72bdef",
Purpose: "SSL client|SSL server|Netscape SSL server|Any Purpose|Any Purpose CA|OCSP helper",
},
},
},
Rdnses: []model.RDNS{
{
RDNS: "aa",
GetTime: "",
},
},
TagsClasses: []model.TagsClass{
{
TagsType: "hijacked",
Tags: "",
},
},
Scene: "测试",
IsMalicious: true,
}
resp := &utils.SingleRespData{
Item: ipInfo,
}
utils.AssembleResponse(ctx, resp, nil)
}
// func (c *IpInfoController) QueryIP(ctx *gin.Context) {
// ip := ctx.Param("ip")
// if isMock {
// logging.Get().Info().Msg("mock data")
// mockResponse(ctx)
// return
// }
// ipInfo, err := c.service.QueryIP(ip)
// if err != nil {
// logging.Get().Err(err).Msgf("query ip info")
// utils.AssembleResponse(ctx, nil, err)
// // ctx.JSON(http.StatusInternalServerError, err)
// return
// }
// resp := &utils.SingleRespData{
// Item: ipInfo,
// }
// utils.AssembleResponse(ctx, resp, nil)
// }
package controller
import (
"time"
"github.com/gin-gonic/gin"
)
type SystemController struct {
// service service.Service
// controller.Api
}
func NewSystemController() *SystemController {
return &SystemController{
// service: service.NewI pService(config.WeibuUrl, apiKey),
}
}
func (c *SystemController) SystemInfo(ctx *gin.Context) {
ctx.JSON(200, gin.H{
"model": "B7b-xxx",
"description": "test",
"latestLearning": time.Now().UnixMilli(),
"learningPeriod": time.Duration(time.Hour + time.Minute*12 + time.Second*11).String(),
"modelTime": time.Now().UnixMilli(),
})
}
package controller
import (
"context"
"time"
"github.com/gin-gonic/gin"
"gitlab.com/tensorsecurity-rd/waf-console/internal/service"
"gitlab.com/tensorsecurity-rd/waf-console/internal/utils"
"gitlab.com/tensorsecurity-rd/waf-console/pkg/generated/clientset/versioned"
"gorm.io/gorm"
)
type WafController struct {
service service.Service
}
func NewWafController(client *versioned.Clientset, db *gorm.DB) *WafController {
return &WafController{
service: service.NewWafService(client, db),
}
}
func (c *WafController) Waf(ctx *gin.Context) {
ctx1, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
gatewayName := ctx.Param("gateway_name")
waf, err := c.service.GetWaf(ctx1, gatewayName)
if err != nil {
// logging.Get().Err(err).Msgf("get waf")
utils.AssembleResponse(ctx, nil, err)
return
}
resp := &utils.SingleRespData{
Item: waf,
}
utils.AssembleResponse(ctx, resp, nil)
}
func (c *WafController) CreateWaf(ctx *gin.Context) {
ctx1, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
var req []service.CreateWafReq
if err := ctx.BindJSON(&req); err != nil {
utils.AssembleResponse(ctx, nil, err)
return
}
for _, r := range req {
c.service.CreateWaf(ctx1, &r)
}
utils.AssembleResponse(ctx, nil, nil)
}
package model
// type TagsType string
const (
// C2 TagsType = "C2"
// Hijacked TagsType = "Hijacked"
)
type Port struct {
Port int16 `json:"port"`
Module string `json:"module"`
Product string `json:"product"`
Version string `json:"version"`
Detail string `json:"detail"`
}
type Location struct {
Country string `json:"country"`
CountryCode string `json:"countryCode"`
Province string `json:"province"`
City string `json:"city"`
Longitude float64 `json:"longitude"`
Latitude float64 `json:"latitude"`
}
type Sample struct {
Hash string `json:"hash"`
ScanTime int64 `json:"scanTime"`
Ratio string `json:"ratio"`
MalwareType string `json:"malwareType"`
MalwareFamily string `json:"malwareFamily"`
}
type CAS struct {
Protocol string `json:"protocol"`
Port int16 `json:"port"`
Period int `json:"period"`
DigitalCertificate Certificate `json:"digitalCertificate"`
}
type Certificate struct {
Subject string `json:"subject"`
Issuer string `json:"issuer"`
Fingerprint string `json:"fingerprint"`
Purpose string `json:"purpose"`
Verify string `json:"verify"`
Status string `json:"status"`
Revoked bool `json:"revoked"`
Begin string `json:"begin"`
End string `json:"end"`
StatusDesc string `json:"statusDesc"`
SerialNumber string `json:"serialNumber"`
RevokedTime string `json:"revokedTime"`
}
type TagsClass struct {
TagsType string `json:"tagsType"` //标签类别,如"industry(行业)"、"gangs(团伙)"、"virus_family(家族)"等
Tags string `json:"tags"` //具体的攻击团伙或安全事件标签,例如:APT、海莲花等。
}
type ASN struct {
Number int `json:"number"` //ASN号码
Name string `json:"name"`
Company string `json:"Company"`
Region string `json:"region"`
Info string `json:"info"` // ASN名称 + ASN归属公司 + RIR登记区域
RiskRank int `json:"riskRank"` //风险值(0~4,越大代表风险越高)
}
type Intelligence struct {
Source string `json:"source"`
FindTime int64 `json:"findTime"`
UpdateTime int64 `json:"updateTime"`
Confidence int `json:"confidence"`
Expired bool `json:"expired"`
IntelTypes []string `json:"intelTypes"` //威胁类型
IntelTags []TagsClass `json:"intelTags"` //情报的标签信息
}
type RDNS struct {
RDNS string `json:"rdns"`
GetTime string `json:"getTime"`
}
type IPInfo struct {
Carrier string `json:"carrier"` // 运营商
Location Location `json:"location"` // 位置信息
OSSIntelligences []Intelligence `json:"ossIntelligences"` // 开源情报
OnlineIntelligences []Intelligence `json:"onlineIntelligences"` // 在线情报
Ports []Port `json:"ports"` //开发端口
Samples []Sample `json:"samples"` // 相关样本
Cas []CAS `json:"cas"` // SSL相关证书信息
Rdnses []RDNS `json:"rdnses"` // Rdns记录
TagsClasses []TagsClass `json:"tagsClasses"` //相关攻击团伙或安全事件信息
Scene string `json:"scene"` //应用场景
Asn ASN `json:"asn"` //asn信息
SumCurDomains int `json:"sumCurDomains"` //反查当前域名数量
IsMalicious bool `json:"isMalicious"` //是否恶意
Judgments []string `json:"judgments"` // 威胁类型
}
package model
import (
"database/sql/driver"
"encoding/json"
"strings"
)
type HostList []string
func (h HostList) Value() (driver.Value, error) {
return strings.Join(h, ","), nil
}
func (h *HostList) Scan(src interface{}) error {
*h = strings.Split(src.(string), ",")
return nil
}
type Waf struct {
ID uint `gorm:"column:id;primaryKey;autoIncrement"`
GatewayName string `gorm:"column:gateway_name"`
Port int `gorm:"column:port"`
Namespace string `gorm:"column:namespace"`
RegionCode string `gorm:"column:region_code"`
Host HostList `gorm:"column:host"`
}
func (Waf) TableName() string {
return "waf"
}
type WafRule struct {
ID int `json:"id"`
CategoryID string `gorm:"column:category_id"`
Level int `json:"level"`
Status int `gorm:"column:status"`
Name string `json:"name"`
Type string `json:"type"`
Description string `json:"description"`
Expr string `json:"expr"`
Mode string `json:"mode"`
}
func (WafRule) TableName() string {
return "waf_rules"
}
type WafRuleCategory struct {
ID string `gorm:"column:id;primaryKey;autoIncrement"`
CategoryID string `gorm:"column:category_id"`
CategoryEN string `gorm:"column:category_en"`
CategoryZH string `gorm:"column:category_zh"`
DescriptionEN string `gorm:"column:description_en"`
DescriptionZH string `gorm:"column:description_zh"`
Status int `gorm:"column:status"`
Rules []WafRule `gorm:"column:rules"`
}
func (WafRuleCategory) TableName() string {
return "waf_rule_categories"
}
func (r *WafRuleCategory) Scan(src interface{}) error {
err := json.Unmarshal(src.([]byte), r)
if err != nil {
return err
}
return nil
}
func (r WafRuleCategory) Value() (driver.Value, error) {
return json.Marshal(r)
}
{
"item": {
"gatewayname": "example-gateway",
"mode": "active",
"rule_num": 10,
"attack_num": 5
}
}
{
"region_code": "lf-tst7",
"gateway_name": "zqrtest",
"port": 9999,
"host": "*"
}
[
{
"region_code": "lf-tst7",
"gateway_name": "zqrtest",
"port": 9999,
"host": "*",
"namespace": "test"
},
{
"region_code": "lf-tst7",
"gateway_name": "zqrtest",
"port": 9999,
"host": "*",
"namespace": "test"
}
]
\ No newline at end of file
This diff is collapsed.
package service
import (
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"gitlab.com/tensorsecurity-rd/waf-console/internal/model"
)
var fakePrivateData = `{
"data": [
{
"ioc": "159.203.93.255",
"host": "10.65.135.204",
"intelligence": [
{
"judgments": [
"Exploit"
],
"severity": "low",
"ban": {
"banned": 1,
"reason": "The IP address belongs to DigitalOcean, LLC, it is recommended to assess and handle it accordingly."
},
"basic": {
"carrier": "DigitalOcean, LLC",
"location": {
"country": "美国",
"country_code": "US",
"province": "新泽西州",
"city": "克利夫顿",
"lng": -74.16366,
"lat": 40.858402
}
},
"asn": {
"number": "14061",
"info": "DIGITALOCEAN-ASN - DigitalOcean, LLC, US"
},
"ioc_type": "ipv4",
"confidence_level": "low",
"is_malicious": true,
"source_name": "微步在线-IP信誉",
"update_time": 1719268503000
}
]
}
],
"response_code": 0,
"verbose_msg": "success"
}`
type ipServicePrivate struct {
URL string
ApiKey string
// ipQueryUrl string
ipReputationUrl string
// ipInfoMap map[string]IpInfo
// useCachedIPInfo bool
// ipInfoCache *expirable.LRU[string, IPInfoPrivate]
}
// func NewIpServicePrivate(url, apiKey string, useCachedIPInfo bool) Service {
// var ipReputationUrl string
// reputationUrl := os.Getenv("IP_REPUTATION_URL")
// logging.Get().Info().Msgf("reputationUrl: %s", reputationUrl)
// if reputationUrl != "" {
// ipReputationUrl = reputationUrl
// } else {
// ipReputationUrl = fmt.Sprintf("%s?apikey=%s&resource=", ipReputation, apiKey)
// }
// logging.Get().Info().Msgf("ipReputationUrl: %s", ipReputationUrl)
// return &ipServicePrivate{
// URL: url,
// ApiKey: apiKey,
// ipReputationUrl: ipReputationUrl,
// }
// }
func (s *ipServicePrivate) QueryIP(ip string) (*model.IPInfo, error) {
url := s.ipReputationUrl + ip
respData, err := http.DefaultClient.Get(url)
if err != nil {
return nil, err
}
defer respData.Body.Close()
body, err := io.ReadAll(respData.Body)
if err != nil {
return nil, fmt.Errorf("query ip info failed: %w", err)
}
var resp IPInfoPrivateResp
if err := json.Unmarshal(body, &resp); err != nil {
return nil, fmt.Errorf("unmarshal response failed: %w", err)
}
if len(resp.Data) == 0 || len(resp.Data[0].Intelligence) == 0 {
return nil, fmt.Errorf("no data found for ip %s", ip)
}
info := resp.Data[0].Intelligence[0]
tagsClasses := make([]model.TagsClass, 0, 5)
for k, v := range info.TagsClasses {
for _, tag := range v {
tagsClasses = append(tagsClasses, model.TagsClass{
TagsType: k,
Tags: tag,
})
}
}
return &model.IPInfo{
Carrier: info.Basic.Carrier,
Location: model.Location{
Country: info.Basic.Location.Country,
CountryCode: info.Basic.Location.CountryCode,
Province: info.Basic.Location.Province,
City: info.Basic.Location.City,
Longitude: info.Basic.Location.Longitude,
Latitude: info.Basic.Location.Latitude,
},
Asn: model.ASN{
Number: func() int { n, _ := strconv.Atoi(info.ASN.Number); return n }(),
Info: info.ASN.Info,
},
Scene: info.Scene,
IsMalicious: info.IsMalicious,
Judgments: info.Judgments,
TagsClasses: tagsClasses,
}, nil
}
package service
import (
"encoding/json"
"fmt"
"reflect"
"testing"
"gitlab.com/tensorsecurity-rd/waf-console/internal/model"
)
func TestIPService_QueryIP(t *testing.T) {
type fields struct {
URL string
ApiKey string
}
type args struct {
ip string
}
tests := []struct {
name string
fields fields
args args
want *model.IPInfo
wantErr bool
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s := &ipService{
URL: tt.fields.URL,
ApiKey: tt.fields.ApiKey,
}
got, err := s.QueryIP(tt.args.ip)
if (err != nil) != tt.wantErr {
t.Errorf("IPService.QueryIP() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("IPService.QueryIP() = %v, want %v", got, tt.want)
}
})
}
}
func TestParseIPInfo(t *testing.T) {
t.Run("test 1", func(t *testing.T) {
var respData RespData
err := json.Unmarshal([]byte(fakeData), &respData)
if err != nil {
t.Errorf("Unmarshal err %v", err)
}
if info, ok := respData.Data["87.236.176.199"]; ok {
var ipInfo IpInfo
d, err := info.MarshalJSON()
if err != nil {
t.Error(err)
}
err = json.Unmarshal(d, &ipInfo)
if err != nil {
t.Error(err)
}
fmt.Println(ipInfo.Judgments)
}
fmt.Println("ddddd")
})
}
func TestParseIPInfoPrivate(t *testing.T) {
t.Run("test 1", func(t *testing.T) {
var respData IPInfoPrivateResp
err := json.Unmarshal([]byte(fakePrivateData), &respData)
if err != nil {
t.Errorf("Unmarshal err %v", err)
}
if len(respData.Data) > 0 {
for _, v := range respData.Data {
fmt.Println(v)
}
}
fmt.Println("ddddd")
})
}
package service
import "context"
type Service interface {
// QueryIP(ip string) (*model.IPInfo, error)
GetWaf(ctx context.Context, gatewayName string) (*Waf, error)
CreateWaf(ctx context.Context, req *CreateWafReq) (*Waf, error)
}
package service
import "encoding/json"
type Intelligence struct {
Source string `json:"source"`
Confidence int `json:"confidence"`
Expired bool `json:"expired"`
IntelTags []TagsClass `json:"intel_tags"`
FindTime string `json:"find_time"`
IntelTypes []string `json:"intel_types"`
UpdateTime string `json:"update_time"`
}
type OpenSource struct {
Source string `json:"source"`
Confidence int `json:"confidence"`
Expired bool `json:"expired"`
IntelTags []TagsClass `json:"intel_tags"`
FindTime string `json:"find_time"`
IntelTypes []string `json:"intel_types"`
UpdateTime string `json:"update_time"`
}
type Location struct {
Country string `json:"country"`
Province string `json:"province"`
City string `json:"city"`
Longitude string `json:"lng"`
Latitude string `json:"lat"`
CountryCode string `json:"country_code"`
}
type Basic struct {
Carrier string `json:"carrier"`
Location Location `json:"location"`
}
type ASN struct {
Rank int `json:"rank"`
Info string `json:"info"`
Number int `json:"number"`
}
type Port struct {
Port int `json:"port"`
Module string `json:"module"`
Product string `json:"product"`
Version string `json:"version"`
Detail string `json:"detail"`
}
type RDNS struct {
RDNS string `json:"rdns"`
GetTime string `json:"get_time"`
}
type Intelligences struct {
ThreatbookLab []Intelligence `json:"threatbook_lab"`
XReward []interface{} `json:"x_reward"`
OpenSource []OpenSource `json:"open_source"`
}
type Sample struct {
Hash string `json:"sha256"`
ScanTime string `json:"scan_time"`
Ratio string `json:"ratio"`
MalwareType string `json:"malware_type"`
MalwareFamily string `json:"malware_family"`
}
type TagsClass struct {
TagsType string `json:"tags_type"` //标签类别,如"industry(行业)"、"gangs(团伙)"、"virus_family(家族)"等
Tags []string `json:"tags"` //具体的攻击团伙或安全事件标签,例如:APT、海莲花等。
}
type CAS struct {
Protocol string `json:"protocol"`
Port int16 `json:"port"`
Period int `json:"period"`
DigitalCertificate Certificate `json:"digital_certificate"`
}
type Certificate struct {
Subject string `json:"subject"`
Issuer string `json:"issuer"`
Fingerprint string `json:"fingerprint"`
Purpose string `json:"purpose"`
Verify string `json:"verify"`
Status string `json:"status"`
Revoked bool `json:"revoked"`
Begin string `json:"begin"`
End string `json:"end"`
StatusDesc string `json:"status_desc"`
SerialNumber string `json:"serial_number"`
RevokedTime string `json:"revoked_time"`
}
type IpInfo struct {
Samples []Sample `json:"samples"`
TagsClasses []TagsClass `json:"tags_classes"`
Judgments []string `json:"judgments"`
Intelligences Intelligences `json:"intelligences"`
Scene string `json:"scene"`
Basic Basic `json:"basic"`
ASN ASN `json:"asn"`
Ports []Port `json:"ports"`
CAS []CAS `json:"cas"`
UpdateTime string `json:"update_time"`
RDNSList []RDNS `json:"rdns_list"`
SumCurDomains string `json:"sum_cur_domains"`
}
type RespData struct {
Data map[string]json.RawMessage `json:"data"`
ResponseCode int `json:"response_code"`
VerboseMsg string `json:"verbose_msg"`
}
type Reputation struct {
IsMalicious bool `json:"is_malicious"`
}
type ASNPrivate struct {
Rank int `json:"rank"`
Info string `json:"info"`
Number string `json:"number"`
}
type LocationPrivate struct {
Country string `json:"country"`
Province string `json:"province"`
City string `json:"city"`
Longitude float64 `json:"lng"`
Latitude float64 `json:"lat"`
CountryCode string `json:"country_code"`
}
type BasicPrivate struct {
Carrier string `json:"carrier"`
Location LocationPrivate `json:"location"`
}
type TagsClassPrivate map[string][]string
type IPInfoPrivate struct {
Judgments []string `json:"judgments"`
Basic BasicPrivate `json:"basic"`
ASN ASNPrivate `json:"asn"`
Scene string `json:"scene"`
IsMalicious bool `json:"is_malicious"`
TagsClasses TagsClassPrivate `json:"tags_classes"`
}
type IPInfoPrivateRespData struct {
IOC string `json:"ioc"`
Intelligence []IPInfoPrivate `json:"intelligence"`
}
type IPInfoPrivateResp struct {
Data []IPInfoPrivateRespData `json:"data"`
ResponseCode int `json:"response_code"`
VerboseMsg string `json:"verbose_msg"`
}
type Waf struct {
GatewayName string `json:"gateway_name"`
Mode string `json:"mode"`
RuleNum int `json:"rule_num"`
AttackNum int `json:"attack_num"`
} // WAF configuration details
type CreateWafReq struct {
RegionCode string `json:"region_code"`
Namespace string `json:"namespace"`
GatewayName string `json:"gateway_name"`
Port uint32 `json:"port"`
Host []string `json:"host"`
}
type RuleRequest struct {
CategoryID []string `json:"category_id"`
Status int `json:"status"`
}
package service
import (
"context"
"gitlab.com/tensorsecurity-rd/waf-console/pkg/apis/waf.security.io/v1alpha1"
"gitlab.com/tensorsecurity-rd/waf-console/pkg/generated/clientset/versioned"
"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) {
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,
},
},
}
_, err := s.client.WafV1alpha1().Services(req.Namespace).Create(context.Background(), service, metav1.CreateOptions{})
if err != nil {
return nil, err
}
return nil, nil
}
package utils
type ResponseDataOptionFunc func(ev *SuccessResponse)
type SuccessResponse struct {
APIVersion string `json:"apiVersion"`
Data interface{} `json:"data"`
}
type FailResponse struct {
APIVersion string `json:"apiVersion"`
Error RespErr `json:"error"`
}
type RespErr struct {
Code int `json:"code"`
Message string `json:"message"`
}
type ListRespData struct {
Items interface{} `json:"items"`
ItemsPerPage int `json:"itemsPerPage"`
TotalItems int `json:"totalItems"`
}
type SingleRespData struct {
Item interface{} `json:"item"`
}
package utils
import (
"net/http"
"github.com/gin-gonic/gin"
"gitlab.com/security-rd/go-pkg/logging"
)
const APIVersion = "v1"
func AssembleResponse(c *gin.Context, data interface{}, err error, opts ...ResponseDataOptionFunc) {
code := http.StatusOK
if err != nil {
logging.Get().Err(err)
code = http.StatusInternalServerError
c.JSON(code, FailResponse{
APIVersion: APIVersion,
Error: RespErr{
Code: code,
Message: err.Error(),
},
})
return
}
resp := SuccessResponse{
APIVersion: APIVersion,
Data: data,
}
for _, opt := range opts {
opt(&resp)
}
c.JSON(code, resp)
}
// Package v1alpha1 contains API Schema definitions for the defense v1 API group
// +k8s:deepcopy-gen=package,register
// +k8s:conversion-gen=open-cluster-management.io/api/cluster
// +k8s:defaulter-gen=TypeMeta
// +k8s:openapi-gen=true
// +kubebuilder:validation:Optional
// +groupName=waf.security.io
package v1alpha1
package v1alpha1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
)
var (
GroupName = "waf.security.io"
GroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1alpha1"}
schemeBuilder = runtime.NewSchemeBuilder(addKnownTypes)
// Install is a function which adds this version to a scheme
Install = schemeBuilder.AddToScheme
// SchemeGroupVersion generated code relies on this name
// Deprecated
SchemeGroupVersion = GroupVersion
// AddToScheme exists solely to keep the old generators creating valid code
// DEPRECATED
AddToScheme = schemeBuilder.AddToScheme
)
// Resource generated code relies on this being here, but it logically belongs to the group
// DEPRECATED
func Resource(resource string) schema.GroupResource {
return schema.GroupResource{Group: GroupName, Resource: resource}
}
// Adds the list of known types to api.Scheme.
func addKnownTypes(scheme *runtime.Scheme) error {
scheme.AddKnownTypes(GroupVersion,
&Service{},
&ServiceList{},
)
metav1.AddToGroupVersion(scheme, GroupVersion)
return nil
}
package v1alpha1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
)
// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN!
// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized.
type SelectorOperator string
type StringMatch struct {
Prefix string `json:"prefix,omitempty"`
Exact string `json:"exact,omitempty"`
}
type MatchExpression struct {
ID uint32 `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Mode string `json:"mode,omitempty"`
Scope string `json:"scope,omitempty"`
Expr string `json:"expr,omitempty"`
Status int32 `json:"status,omitempty"`
}
type LogConfig struct {
Enable int `json:"attack_enable,omitempty"`
Level string `json:"level,omitempty"`
}
type WorkloadRef struct {
ClusterKey string `json:"clusterKey"`
Namespace string `json:"namespace"`
Kind string `json:"kind"`
Name string `json:"name"`
}
type Rule struct {
ID int `json:"id"`
Level int `json:"level"`
Type string `json:"type"`
Description string `json:"description"`
Expr string `json:"expr"`
Mode string `json:"mode"`
Name string `json:"name"`
}
// ServiceSpec defines the desired state of Service
type ServiceSpec struct {
// INSERT ADDITIONAL SPEC FIELDS - desired state of cluster
// Important: Run "make" to regenerate code after modifying this file
HostNames []string `json:"hostNames,omitempty"`
Uri *StringMatch `json:"uri,omitempty"`
Mode string `json:"mode"`
LogConfig *LogConfig `json:"logConfig,omitempty"`
BlackWhireLists []MatchExpression `json:"blackWhireLists,omitempty"`
ExcludedFileTypes []string `json:"excludedFileTypes,omitempty"`
DetectHeaders []string `json:"detect_headers,omitempty"`
Workload WorkloadRef `json:"workload"`
Secret string `json:"secret,omitempty"`
ServiceName string `json:"serviceName"`
ServiceID uint32 `json:"serviceId"`
Rules []Rule `json:"rules,omitempty"`
Port uint32 `json:"port"`
}
type ServicePort struct {
Port int32 `json:"port"`
TargetPort intstr.IntOrString `json:"targetPort"`
HttpsPort int32 `json:"httpsPort"`
}
// ServiceStatus defines the observed state of Service
type ServiceStatus struct {
// INSERT ADDITIONAL STATUS FIELD - define observed state of cluster
// Important: Run "make" to regenerate code after modifying this file
SecretVervision string `json:"secretRevision,omitempty"`
ObservedGeneration int64 `json:"observedGeneration,omitempty"`
Labels map[string]string `json:"labels,omitempty"`
KubeServices map[string][]ServicePort `json:"kubeSerices,omitempty"`
BwListVervision string `json:"bwListVersion,omitempty"`
CoreServiceVersion int64 `json:"coreServiceVersion,omitempty"`
}
// +kubebuilder:object:root=true
// +kubebuilder:subresource:status
// +genclient
// Service is the Schema for the services API
type Service struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec ServiceSpec `json:"spec,omitempty"`
Status ServiceStatus `json:"status,omitempty"`
}
//+kubebuilder:object:root=true
// ServiceList contains a list of Service
type ServiceList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []Service `json:"items"`
}
//go:build !ignore_autogenerated
// +build !ignore_autogenerated
/*
Copyright 2021.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by controller-gen. DO NOT EDIT.
package v1alpha1
import (
runtime "k8s.io/apimachinery/pkg/runtime"
)
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *LogConfig) DeepCopyInto(out *LogConfig) {
*out = *in
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LogConfig.
func (in *LogConfig) DeepCopy() *LogConfig {
if in == nil {
return nil
}
out := new(LogConfig)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *MatchExpression) DeepCopyInto(out *MatchExpression) {
*out = *in
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MatchExpression.
func (in *MatchExpression) DeepCopy() *MatchExpression {
if in == nil {
return nil
}
out := new(MatchExpression)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Rule) DeepCopyInto(out *Rule) {
*out = *in
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Rule.
func (in *Rule) DeepCopy() *Rule {
if in == nil {
return nil
}
out := new(Rule)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Service) DeepCopyInto(out *Service) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
in.Status.DeepCopyInto(&out.Status)
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Service.
func (in *Service) DeepCopy() *Service {
if in == nil {
return nil
}
out := new(Service)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *Service) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ServiceList) DeepCopyInto(out *ServiceList) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ListMeta.DeepCopyInto(&out.ListMeta)
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]Service, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ServiceList.
func (in *ServiceList) DeepCopy() *ServiceList {
if in == nil {
return nil
}
out := new(ServiceList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ServiceList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ServicePort) DeepCopyInto(out *ServicePort) {
*out = *in
out.TargetPort = in.TargetPort
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ServicePort.
func (in *ServicePort) DeepCopy() *ServicePort {
if in == nil {
return nil
}
out := new(ServicePort)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ServiceSpec) DeepCopyInto(out *ServiceSpec) {
*out = *in
if in.HostNames != nil {
in, out := &in.HostNames, &out.HostNames
*out = make([]string, len(*in))
copy(*out, *in)
}
if in.Uri != nil {
in, out := &in.Uri, &out.Uri
*out = new(StringMatch)
**out = **in
}
if in.LogConfig != nil {
in, out := &in.LogConfig, &out.LogConfig
*out = new(LogConfig)
**out = **in
}
if in.BlackWhireLists != nil {
in, out := &in.BlackWhireLists, &out.BlackWhireLists
*out = make([]MatchExpression, len(*in))
copy(*out, *in)
}
if in.ExcludedFileTypes != nil {
in, out := &in.ExcludedFileTypes, &out.ExcludedFileTypes
*out = make([]string, len(*in))
copy(*out, *in)
}
if in.DetectHeaders != nil {
in, out := &in.DetectHeaders, &out.DetectHeaders
*out = make([]string, len(*in))
copy(*out, *in)
}
out.Workload = in.Workload
if in.Rules != nil {
in, out := &in.Rules, &out.Rules
*out = make([]Rule, len(*in))
copy(*out, *in)
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ServiceSpec.
func (in *ServiceSpec) DeepCopy() *ServiceSpec {
if in == nil {
return nil
}
out := new(ServiceSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ServiceStatus) DeepCopyInto(out *ServiceStatus) {
*out = *in
if in.Labels != nil {
in, out := &in.Labels, &out.Labels
*out = make(map[string]string, len(*in))
for key, val := range *in {
(*out)[key] = val
}
}
if in.KubeServices != nil {
in, out := &in.KubeServices, &out.KubeServices
*out = make(map[string][]ServicePort, len(*in))
for key, val := range *in {
var outVal []ServicePort
if val == nil {
(*out)[key] = nil
} else {
in, out := &val, &outVal
*out = make([]ServicePort, len(*in))
copy(*out, *in)
}
(*out)[key] = outVal
}
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ServiceStatus.
func (in *ServiceStatus) DeepCopy() *ServiceStatus {
if in == nil {
return nil
}
out := new(ServiceStatus)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *StringMatch) DeepCopyInto(out *StringMatch) {
*out = *in
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new StringMatch.
func (in *StringMatch) DeepCopy() *StringMatch {
if in == nil {
return nil
}
out := new(StringMatch)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *WorkloadRef) DeepCopyInto(out *WorkloadRef) {
*out = *in
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkloadRef.
func (in *WorkloadRef) DeepCopy() *WorkloadRef {
if in == nil {
return nil
}
out := new(WorkloadRef)
in.DeepCopyInto(out)
return out
}
/*
Copyright 2021.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by client-gen. DO NOT EDIT.
package versioned
import (
"fmt"
wafv1alpha1 "gitlab.com/tensorsecurity-rd/waf-console/pkg/generated/clientset/versioned/typed/waf.security.io/v1alpha1"
discovery "k8s.io/client-go/discovery"
rest "k8s.io/client-go/rest"
flowcontrol "k8s.io/client-go/util/flowcontrol"
)
type Interface interface {
Discovery() discovery.DiscoveryInterface
WafV1alpha1() wafv1alpha1.WafV1alpha1Interface
}
// Clientset contains the clients for groups. Each group has exactly one
// version included in a Clientset.
type Clientset struct {
*discovery.DiscoveryClient
wafV1alpha1 *wafv1alpha1.WafV1alpha1Client
}
// WafV1alpha1 retrieves the WafV1alpha1Client
func (c *Clientset) WafV1alpha1() wafv1alpha1.WafV1alpha1Interface {
return c.wafV1alpha1
}
// Discovery retrieves the DiscoveryClient
func (c *Clientset) Discovery() discovery.DiscoveryInterface {
if c == nil {
return nil
}
return c.DiscoveryClient
}
// NewForConfig creates a new Clientset for the given config.
// If config's RateLimiter is not set and QPS and Burst are acceptable,
// NewForConfig will generate a rate-limiter in configShallowCopy.
func NewForConfig(c *rest.Config) (*Clientset, error) {
configShallowCopy := *c
if configShallowCopy.RateLimiter == nil && configShallowCopy.QPS > 0 {
if configShallowCopy.Burst <= 0 {
return nil, fmt.Errorf("burst is required to be greater than 0 when RateLimiter is not set and QPS is set to greater than 0")
}
configShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst)
}
var cs Clientset
var err error
cs.wafV1alpha1, err = wafv1alpha1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
return &cs, nil
}
// NewForConfigOrDie creates a new Clientset for the given config and
// panics if there is an error in the config.
func NewForConfigOrDie(c *rest.Config) *Clientset {
var cs Clientset
cs.wafV1alpha1 = wafv1alpha1.NewForConfigOrDie(c)
cs.DiscoveryClient = discovery.NewDiscoveryClientForConfigOrDie(c)
return &cs
}
// New creates a new Clientset for the given RESTClient.
func New(c rest.Interface) *Clientset {
var cs Clientset
cs.wafV1alpha1 = wafv1alpha1.New(c)
cs.DiscoveryClient = discovery.NewDiscoveryClient(c)
return &cs
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment