-
Notifications
You must be signed in to change notification settings - Fork 48
/
SecurityHandler.go
353 lines (295 loc) · 11.6 KB
/
SecurityHandler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
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
140
141
142
143
144
145
146
147
148
149
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
180
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
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
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
// Cloud Driver Interface of CB-Spider.
// The CB-Spider is a sub-Framework of the Cloud-Barista Multi-Cloud Project.
// The CB-Spider Mission is to connect all the clouds with a single interface.
//
// * Cloud-Barista: https://github.com/cloud-barista
//
// This is Resouces interfaces of Cloud Driver.
//
// by CB-Spider Team, 2019.06.
package resources
import (
"errors"
"strings"
call "github.com/cloud-barista/cb-spider/cloud-control-manager/cloud-driver/call-log"
idrv "github.com/cloud-barista/cb-spider/cloud-control-manager/cloud-driver/interfaces"
irs "github.com/cloud-barista/cb-spider/cloud-control-manager/cloud-driver/interfaces/resources"
"github.com/davecgh/go-spew/spew"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
vpc "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/vpc/v20170312"
)
type TencentSecurityHandler struct {
Region idrv.RegionInfo
Client *vpc.Client
}
//https://intl.cloud.tencent.com/document/product/213/34272
//https://intl.cloud.tencent.com/ko/document/api/215/36083
/*
@TODO 포트 다양하게 처리 가능해야 함. - 현재는 콤머는 에러 처리
사용가능 포트 규칙 : 콤머(,) / 대쉬(-) / ALL(전체)
Port: A single port number, or a port range in the format of “8000-8010”. The Port field is accepted only if the value of the Protocol field is TCP or UDP. Otherwise Protocol and Port are mutually exclusive.
Action : ACCEPT or DROP
*/
func (securityHandler *TencentSecurityHandler) CreateSecurity(securityReqInfo irs.SecurityReqInfo) (irs.SecurityInfo, error) {
cblogger.Infof("securityReqInfo : ", securityReqInfo)
//=================================================
// 동일 이름 생성 방지 추가(cb-spider 요청 필수 기능)
//=================================================
isExist, errExist := securityHandler.isExist(securityReqInfo.IId.NameId)
if errExist != nil {
cblogger.Error(errExist)
return irs.SecurityInfo{}, errExist
}
if isExist {
return irs.SecurityInfo{}, errors.New("A SecurityGroup with the name " + securityReqInfo.IId.NameId + " already exists.")
}
// logger for HisCall
callogger := call.GetLogger("HISCALL")
callLogInfo := call.CLOUDLOGSCHEMA{
CloudOS: call.TENCENT,
RegionZone: securityHandler.Region.Zone,
ResourceType: call.SECURITYGROUP,
ResourceName: securityReqInfo.IId.NameId,
CloudOSAPI: "CreateSecurityGroupWithPolicies()",
ElapsedTime: "",
ErrorMSG: "",
}
request := vpc.NewCreateSecurityGroupWithPoliciesRequest()
request.GroupName = common.StringPtr(securityReqInfo.IId.NameId)
request.GroupDescription = common.StringPtr(securityReqInfo.IId.NameId) //설명 없으면 에러
cblogger.Debug("보안 정책 처리")
securityGroupPolicySet := &vpc.SecurityGroupPolicySet{}
for _, curPolicy := range *securityReqInfo.SecurityRules {
securityGroupPolicy := new(vpc.SecurityGroupPolicy)
securityGroupPolicy.Protocol = common.StringPtr(curPolicy.IPProtocol)
//securityGroupPolicy.CidrBlock = common.StringPtr("0.0.0.0/0")
securityGroupPolicy.CidrBlock = common.StringPtr(curPolicy.CIDR)
securityGroupPolicy.Action = common.StringPtr("accept")
if curPolicy.ToPort != "" && curPolicy.ToPort != curPolicy.FromPort {
securityGroupPolicy.Port = common.StringPtr(curPolicy.FromPort + "-" + curPolicy.ToPort)
} else {
securityGroupPolicy.Port = common.StringPtr(curPolicy.FromPort)
}
if strings.EqualFold(curPolicy.Direction, "inbound") {
securityGroupPolicySet.Ingress = append(securityGroupPolicySet.Ingress, securityGroupPolicy)
} else {
securityGroupPolicySet.Egress = append(securityGroupPolicySet.Egress, securityGroupPolicy)
}
}
request.SecurityGroupPolicySet = securityGroupPolicySet
callLogStart := call.Start()
response, err := securityHandler.Client.CreateSecurityGroupWithPolicies(request)
callLogInfo.ElapsedTime = call.Elapsed(callLogStart)
if err != nil {
callLogInfo.ErrorMSG = err.Error()
callogger.Error(call.String(callLogInfo))
cblogger.Error(err)
spew.Dump(request)
return irs.SecurityInfo{}, err
}
//spew.Dump(response)
cblogger.Debug(response.ToJsonString())
callogger.Info(call.String(callLogInfo))
securityInfo, errSecurity := securityHandler.GetSecurity(irs.IID{SystemId: *response.Response.SecurityGroup.SecurityGroupId})
if errSecurity != nil {
cblogger.Error(errSecurity)
return irs.SecurityInfo{}, errSecurity
}
securityInfo.IId.NameId = securityReqInfo.IId.NameId
return securityInfo, nil
}
func (securityHandler *TencentSecurityHandler) ListSecurity() ([]*irs.SecurityInfo, error) {
// logger for HisCall
callogger := call.GetLogger("HISCALL")
callLogInfo := call.CLOUDLOGSCHEMA{
CloudOS: call.TENCENT,
RegionZone: securityHandler.Region.Zone,
ResourceType: call.SECURITYGROUP,
ResourceName: "ListSecurity()",
CloudOSAPI: "DescribeSecurityGroups()",
ElapsedTime: "",
ErrorMSG: "",
}
request := vpc.NewDescribeSecurityGroupsRequest()
request.Limit = common.StringPtr("100") //default : 20 / max : 100
callLogStart := call.Start()
response, err := securityHandler.Client.DescribeSecurityGroups(request)
callLogInfo.ElapsedTime = call.Elapsed(callLogStart)
if err != nil {
callLogInfo.ErrorMSG = err.Error()
callogger.Error(call.String(callLogInfo))
cblogger.Error(err)
return nil, err
}
//spew.Dump(response)
cblogger.Debug(response.ToJsonString())
callogger.Info(call.String(callLogInfo))
var results []*irs.SecurityInfo
for _, securityGroup := range response.Response.SecurityGroupSet {
// securityInfo := ExtractSecurityInfo(securityGroup)
securityInfo, errSecurity := securityHandler.GetSecurity(irs.IID{NameId: *securityGroup.SecurityGroupName, SystemId: *securityGroup.SecurityGroupId})
if errSecurity != nil {
cblogger.Error(errSecurity)
return nil, errSecurity
}
results = append(results, &securityInfo)
}
return results, nil
}
// cb-spider 정책상 이름 기반으로 중복 생성을 막아야 함.
func (securityHandler *TencentSecurityHandler) isExist(chkName string) (bool, error) {
cblogger.Debugf("chkName : %s", chkName)
request := vpc.NewDescribeSecurityGroupsRequest()
request.Filters = []*vpc.Filter{
&vpc.Filter{
Name: common.StringPtr("security-group-name"),
Values: common.StringPtrs([]string{chkName}),
},
}
response, err := securityHandler.Client.DescribeSecurityGroups(request)
if err != nil {
cblogger.Error(err)
return false, err
}
if *response.Response.TotalCount < 1 {
return false, nil
}
cblogger.Infof("보안그룹 정보 찾음 - VpcId:[%s] / VpcName:[%s]", *response.Response.SecurityGroupSet[0].SecurityGroupId, *response.Response.SecurityGroupSet[0].SecurityGroupName)
return true, nil
}
func (securityHandler *TencentSecurityHandler) GetSecurity(securityIID irs.IID) (irs.SecurityInfo, error) {
cblogger.Infof("securitySystemId : [%s]", securityIID.SystemId)
callogger := call.GetLogger("HISCALL")
callLogInfo := call.CLOUDLOGSCHEMA{
CloudOS: call.TENCENT,
RegionZone: securityHandler.Region.Zone,
ResourceType: call.SECURITYGROUP,
ResourceName: securityIID.SystemId,
CloudOSAPI: "DescribeSecurityGroupPolicies()",
ElapsedTime: "",
ErrorMSG: "",
}
request := vpc.NewDescribeSecurityGroupsRequest()
request.SecurityGroupIds = common.StringPtrs([]string{securityIID.SystemId})
callLogStart := call.Start()
response, err := securityHandler.Client.DescribeSecurityGroups(request)
callLogInfo.ElapsedTime = call.Elapsed(callLogStart)
if err != nil {
callLogInfo.ErrorMSG = err.Error()
callogger.Error(call.String(callLogInfo))
cblogger.Error(err)
return irs.SecurityInfo{}, err
}
//spew.Dump(response)
cblogger.Debug(response.ToJsonString())
callogger.Info(call.String(callLogInfo))
if *response.Response.TotalCount > 0 {
securityInfo := irs.SecurityInfo{}
securityInfo.IId = irs.IID{NameId: *response.Response.SecurityGroupSet[0].SecurityGroupName, SystemId: *response.Response.SecurityGroupSet[0].SecurityGroupId}
securityInfo.SecurityRules, err = securityHandler.GetSecurityRuleInfo(securityIID)
if err != nil {
cblogger.Error(err)
return irs.SecurityInfo{}, err
}
return securityInfo, nil
} else {
return irs.SecurityInfo{}, errors.New("InvalidSecurityGroupId.NotFound: The SecurityGroup " + securityIID.SystemId + " does not exist")
}
}
func (securityHandler *TencentSecurityHandler) GetSecurityRuleInfo(securityIID irs.IID) (*[]irs.SecurityRuleInfo, error) {
cblogger.Infof("securitySystemId : [%s]", securityIID.SystemId)
request := vpc.NewDescribeSecurityGroupPoliciesRequest()
request.SecurityGroupId = common.StringPtr(securityIID.SystemId)
response, err := securityHandler.Client.DescribeSecurityGroupPolicies(request)
if err != nil {
cblogger.Error(err)
return nil, err
}
//spew.Dump(response)
cblogger.Debug(response.ToJsonString())
var securityRuleInfos []irs.SecurityRuleInfo
var ingress []irs.SecurityRuleInfo
var egress []irs.SecurityRuleInfo
ingress, err = securityHandler.ExtractPolicyGroups(response.Response.SecurityGroupPolicySet.Ingress, "inbound")
if err != nil {
cblogger.Error(err)
return nil, err
}
egress, err = securityHandler.ExtractPolicyGroups(response.Response.SecurityGroupPolicySet.Egress, "outbound")
if err != nil {
cblogger.Error(err)
return nil, err
}
securityRuleInfos = append(ingress, egress...)
return &securityRuleInfos, nil
}
//@TODO Port에 콤머가 사용된 정책 처리해야 함.
//direction : inbound / outbound
func (securityHandler *TencentSecurityHandler) ExtractPolicyGroups(policyGroups []*vpc.SecurityGroupPolicy, direction string) ([]irs.SecurityRuleInfo, error) {
var results []irs.SecurityRuleInfo
var fromPort string
var toPort string
/*
var newDirection string
//ingress -> inbound
if strings.EqualFold(direction, "ingress") {
newDirection = "inbound"
} else if strings.EqualFold(direction, "egress") {
newDirection = "outbound"
} else { //UnKnown
newDirection = direction
}
*/
for _, curPolicy := range policyGroups {
if len(*curPolicy.Port) > 0 {
//WEB UI에서는 입력 자체가 불 가능한 것 같지만 혹시 몰라서 콤머 기반으로 파싱 후 대쉬(-)를 처리함.
portArr := strings.Split(*curPolicy.Port, ",")
for _, curPort := range portArr {
portRange := strings.Split(curPort, "-")
fromPort = portRange[0]
if len(portRange) > 1 {
toPort = portRange[len(portRange)-1]
} else {
toPort = ""
}
securityRuleInfo := irs.SecurityRuleInfo{
Direction: direction, // "inbound | outbound"
CIDR: *curPolicy.CidrBlock,
IPProtocol: *curPolicy.Protocol,
FromPort: fromPort,
ToPort: toPort,
}
results = append(results, securityRuleInfo)
}
}
}
return results, nil
}
func (securityHandler *TencentSecurityHandler) DeleteSecurity(securityIID irs.IID) (bool, error) {
cblogger.Infof("securityNameId : [%s]", securityIID.SystemId)
callogger := call.GetLogger("HISCALL")
callLogInfo := call.CLOUDLOGSCHEMA{
CloudOS: call.TENCENT,
RegionZone: securityHandler.Region.Zone,
ResourceType: call.SECURITYGROUP,
ResourceName: securityIID.SystemId,
CloudOSAPI: "DeleteSecurityGroup()",
ElapsedTime: "",
ErrorMSG: "",
}
request := vpc.NewDeleteSecurityGroupRequest()
request.SecurityGroupId = common.StringPtr(securityIID.SystemId)
callLogStart := call.Start()
response, err := securityHandler.Client.DeleteSecurityGroup(request)
callLogInfo.ElapsedTime = call.Elapsed(callLogStart)
if err != nil {
callLogInfo.ErrorMSG = err.Error()
callogger.Error(call.String(callLogInfo))
cblogger.Error(err)
return false, err
}
//spew.Dump(response)
cblogger.Debug(response.ToJsonString())
callogger.Info(call.String(callLogInfo))
return true, nil
}