-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoutbound.go
574 lines (504 loc) · 17.3 KB
/
outbound.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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/containernetworking/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/types"
current "github.com/containernetworking/cni/pkg/types/100"
"github.com/containernetworking/cni/pkg/version"
"github.com/containernetworking/plugins/pkg/utils"
bv "github.com/containernetworking/plugins/pkg/utils/buildversion"
"github.com/ncode/cni-outbound/pkg/iptables"
"io"
"log/slog"
"os"
"strings"
"time"
)
type LogConfig struct {
Enable bool `json:"enable"`
Directory string `json:"directory"`
}
type PluginConf struct {
types.NetConf
MainChainName string `json:"mainChainName"`
DefaultAction string `json:"defaultAction"`
OutboundRules []iptables.OutboundRule `json:"outboundRules"`
Logging LogConfig `json:"logging"`
}
var logger *slog.Logger
var newIPTablesManager = func(conf *PluginConf) (iptables.Manager, error) {
return iptables.NewIPTablesManager(conf.MainChainName, conf.DefaultAction)
}
func setupLogging(conf *PluginConf) error {
if !conf.Logging.Enable {
logger = slog.New(slog.NewTextHandler(io.Discard, nil))
return nil
}
var logWriter *os.File
if conf.Logging.Directory == "" {
conf.Logging.Directory = "/var/log/cni"
}
currentDate := time.Now().Format("2006-01-02")
logFileName := fmt.Sprintf("%s/outbound-%s.log", strings.TrimSuffix(conf.Logging.Directory, "/"), currentDate)
file, err := os.OpenFile(logFileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return fmt.Errorf("failed to open log file: %v", err)
}
logWriter = file
opts := slog.HandlerOptions{
AddSource: true,
Level: slog.LevelInfo,
}
handler := slog.NewJSONHandler(logWriter, &opts)
logger = slog.New(handler)
return nil
}
func generateChainName(netName, containerID string) string {
return utils.MustFormatChainNameWithPrefix(netName, containerID, "OUT-")
}
func parseAdditionalRules(args, containerID string) ([]iptables.OutboundRule, error) {
logger.Log(context.Background(), slog.LevelInfo,
"Parsing additional rules from args",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", containerID),
slog.String("details", args),
)
if args == "" {
logger.Log(context.Background(), slog.LevelInfo,
"No additional args provided",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", containerID),
)
return nil, nil // Return nil
}
var additionalRules []iptables.OutboundRule // Initialize as nil
kvs := strings.Split(args, ";")
for _, kv := range kvs {
parts := strings.SplitN(kv, "=", 2)
if len(parts) != 2 || parts[0] != "outbound.additional_rules" {
continue
}
logger.Log(context.Background(), slog.LevelInfo,
"Found outbound.additional_rules",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", containerID),
slog.String("rules", parts[1]),
)
if err := json.Unmarshal([]byte(parts[1]), &additionalRules); err != nil {
logger.Log(context.Background(), slog.LevelError,
"Failed to parse additional rules",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", containerID),
slog.Any("error", err),
)
return nil, fmt.Errorf("failed to parse additional rules from CNI args: %v", err)
}
break
}
logger.Log(context.Background(), slog.LevelInfo,
"Parsed additional rules",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", containerID),
slog.Int("ruleCount", len(additionalRules)),
)
return additionalRules, nil
}
func parseConfig(stdin []byte, args, containerID string) (*PluginConf, error) {
conf := PluginConf{}
if err := json.Unmarshal(stdin, &conf); err != nil {
logger.Log(context.Background(), slog.LevelError,
"Failed to parse network configuration",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", containerID),
slog.Any("error", err),
)
return nil, fmt.Errorf("failed to parse network configuration: %v", err)
}
if err := setupLogging(&conf); err != nil {
logger.Log(context.Background(), slog.LevelError,
"Failed to setup logging",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", containerID),
slog.Any("error", err),
)
return nil, fmt.Errorf("failed to setup logging: %v", err)
}
logger.Log(context.Background(), slog.LevelInfo,
"Parsing configuration",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", containerID),
)
// Parse prevResult if it exists
if conf.RawPrevResult != nil {
if err := version.ParsePrevResult(&conf.NetConf); err != nil {
logger.Log(context.Background(), slog.LevelError,
"Could not parse prevResult",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", containerID),
slog.Any("error", err),
)
return nil, fmt.Errorf("could not parse prevResult: %v", err)
}
// Convert prevResult to current.Result
result, err := current.NewResultFromResult(conf.PrevResult)
if err != nil {
logger.Log(context.Background(), slog.LevelError,
"Failed to convert prevResult to current.Result",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", containerID),
slog.Any("error", err),
)
return nil, fmt.Errorf("failed to convert prevResult to current.Result: %v", err)
}
// Check for required fields
if len(result.Interfaces) == 0 {
return nil, fmt.Errorf("invalid prevResult structure: missing interfaces")
}
if len(result.IPs) == 0 {
return nil, fmt.Errorf("invalid prevResult structure: missing ips")
}
conf.PrevResult = result
}
if conf.MainChainName == "" {
logger.Log(context.Background(), slog.LevelInfo,
"Using default MainChainName: CNI-OUTBOUND",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", containerID),
)
conf.MainChainName = "CNI-OUTBOUND"
}
if conf.DefaultAction == "" {
logger.Log(context.Background(), slog.LevelInfo,
"Using default DefaultAction: DROP",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", containerID),
)
conf.DefaultAction = "DROP"
}
logger.Log(context.Background(), slog.LevelInfo,
"Base configuration",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", containerID),
slog.String("MainChainName", conf.MainChainName),
slog.String("DefaultAction", conf.DefaultAction),
)
// Parse and append additional rules from CNI args, if any
additionalRules, err := parseAdditionalRules(args, containerID)
if err != nil {
return nil, err
}
if len(additionalRules) > 0 {
logger.Log(context.Background(), slog.LevelInfo,
"Appending additional rules",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", containerID),
slog.Int("ruleCount", len(additionalRules)),
)
conf.OutboundRules = append(conf.OutboundRules, additionalRules...)
}
logger.Log(context.Background(), slog.LevelInfo,
"Total outbound rules",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", containerID),
slog.Int("totalRules", len(conf.OutboundRules)),
)
return &conf, nil
}
func cmdAdd(args *skel.CmdArgs) error {
conf, err := parseConfig(args.StdinData, args.Args, args.ContainerID)
if err != nil {
logger.Log(context.Background(), slog.LevelError,
"Failed to parse config",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
slog.Any("error", err),
)
return err
}
logger.Log(context.Background(), slog.LevelInfo,
"CNI ADD called",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
)
logger.Log(context.Background(), slog.LevelInfo,
"Creating IPTablesManager",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
)
iptManager, err := newIPTablesManager(conf)
if err != nil {
logger.Log(context.Background(), slog.LevelError,
"Failed to create IPTablesManager",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
slog.Any("error", err),
)
return fmt.Errorf("failed to create IPTablesManager: %v", err)
}
logger.Log(context.Background(), slog.LevelInfo,
"Ensuring main chain exists",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
)
if err := iptManager.EnsureMainChainExists(); err != nil {
logger.Log(context.Background(), slog.LevelError,
"Failed to ensure main chain exists",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
slog.Any("error", err),
)
return fmt.Errorf("failed to ensure main chain exists: %v", err)
}
logger.Log(context.Background(), slog.LevelInfo,
"Creating container chain",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
)
containerChain := generateChainName(conf.Name, args.ContainerID)
if err := iptManager.CreateContainerChain(containerChain); err != nil {
logger.Log(context.Background(), slog.LevelError,
"Failed to create container chain",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
slog.Any("error", err),
)
return fmt.Errorf("failed to create container chain: %v", err)
}
logger.Log(context.Background(), slog.LevelInfo,
"Adding rules to container chain",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
)
for _, rule := range conf.OutboundRules {
logger.Log(context.Background(), slog.LevelInfo,
"Adding rule",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
slog.Any("rule", rule),
)
if err := iptManager.AddRule(containerChain, rule); err != nil {
logger.Log(context.Background(), slog.LevelError,
"Failed to add rule to container chain",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
slog.Any("error", err),
slog.Any("rule", rule),
)
return fmt.Errorf("failed to add rule to container chain: %v", err)
}
}
logger.Log(context.Background(), slog.LevelInfo,
"Adding jump rule to main chain",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
)
var result *current.Result
if conf.PrevResult == nil {
// If there's no previous result, return an error
return fmt.Errorf("no prevResult found")
}
result, err = current.NewResultFromResult(conf.PrevResult)
if err != nil {
logger.Log(context.Background(), slog.LevelError,
"Failed to parse prevResult",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
slog.Any("error", err),
)
return fmt.Errorf("failed to parse prevResult: %v", err)
}
containerIP := result.IPs[0].Address.IP.String()
logger.Log(context.Background(), slog.LevelInfo,
"Container IP obtained",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
slog.String("ip", containerIP),
)
if err := iptManager.AddJumpRule(containerIP, containerChain); err != nil {
logger.Log(context.Background(), slog.LevelError,
"Failed to add jump rule to main chain",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
slog.Any("error", err),
)
return fmt.Errorf("failed to add jump rule to main chain: %v", err)
}
logger.Log(context.Background(), slog.LevelInfo,
"CNI ADD completed successfully",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
)
return types.PrintResult(result, conf.CNIVersion)
}
func cmdDel(args *skel.CmdArgs) error {
conf, err := parseConfig(args.StdinData, args.Args, args.ContainerID)
if err != nil {
logger.Log(context.Background(), slog.LevelError,
"Failed to parse config",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
slog.Any("error", err),
)
return err
}
logger.Log(context.Background(), slog.LevelInfo,
"CNI DEL called",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
)
logger.Log(context.Background(), slog.LevelInfo,
"Creating IPTablesManager",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
)
iptManager, err := newIPTablesManager(conf)
if err != nil {
logger.Log(context.Background(), slog.LevelError,
"Failed to create IPTablesManager",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
slog.Any("error", err),
)
return fmt.Errorf("failed to create IPTablesManager: %v", err)
}
logger.Log(context.Background(), slog.LevelInfo,
"Removing container chain",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
)
containerChain := generateChainName(conf.Name, args.ContainerID)
if err := iptManager.RemoveJumpRuleByTargetChain(containerChain); err != nil {
logger.Log(context.Background(), slog.LevelWarn,
"Failed to remove jump rule from main chain",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
slog.Any("error", err),
)
}
logger.Log(context.Background(), slog.LevelInfo,
"Clearing and deleting container chain",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
)
if err := iptManager.ClearAndDeleteChain(containerChain); err != nil {
logger.Log(context.Background(), slog.LevelError,
"Failed to clear and delete container chain",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
slog.Any("error", err),
)
return fmt.Errorf("failed to clear and delete container chain: %v", err)
}
logger.Log(context.Background(), slog.LevelInfo,
"CNI DEL completed successfully",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
)
return nil
}
func cmdCheck(args *skel.CmdArgs) error {
conf, err := parseConfig(args.StdinData, args.Args, args.ContainerID)
if err != nil {
logger.Log(context.Background(), slog.LevelError,
"Failed to parse config",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
slog.Any("error", err),
)
return err
}
logger.Log(context.Background(), slog.LevelInfo,
"CNI CHECK called",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
)
logger.Log(context.Background(), slog.LevelInfo,
"Creating IPTablesManager",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
)
iptManager, err := newIPTablesManager(conf)
if err != nil {
logger.Log(context.Background(), slog.LevelError,
"Failed to create IPTablesManager",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
slog.Any("error", err),
)
return fmt.Errorf("failed to create IPTablesManager: %v", err)
}
logger.Log(context.Background(), slog.LevelInfo,
"Checking if main chain exists",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
)
exists, err := iptManager.ChainExists(conf.MainChainName)
if err != nil {
logger.Log(context.Background(), slog.LevelError,
"Failed to check if main chain exists",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
slog.Any("error", err),
)
return fmt.Errorf("failed to check if main chain exists: %v", err)
}
if !exists {
logger.Log(context.Background(), slog.LevelError,
"Main chain does not exist",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
slog.String("chain", conf.MainChainName),
)
return fmt.Errorf("main chain %s does not exist", conf.MainChainName)
}
logger.Log(context.Background(), slog.LevelInfo,
"Checking container chain",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
)
containerChain := generateChainName(conf.Name, args.ContainerID)
exists, err = iptManager.ChainExists(containerChain)
if err != nil {
logger.Log(context.Background(), slog.LevelError,
"Failed to check if container chain exists",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
slog.Any("error", err),
)
return fmt.Errorf("failed to check if container chain exists: %v", err)
}
if !exists {
logger.Log(context.Background(), slog.LevelError,
"Container chain does not exist",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
slog.String("chain", containerChain),
)
return fmt.Errorf("container chain %s does not exist", containerChain)
}
logger.Log(context.Background(), slog.LevelInfo,
"Verifying rules in container chain",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
)
if err := iptManager.VerifyRules(containerChain, conf.OutboundRules); err != nil {
logger.Log(context.Background(), slog.LevelError,
"Rule verification failed",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
slog.Any("error", err),
)
return fmt.Errorf("rule verification failed: %v", err)
}
logger.Log(context.Background(), slog.LevelInfo,
"CNI CHECK completed successfully",
slog.String("component", "CNI-Outbound"),
slog.String("containerID", args.ContainerID),
)
return nil
}
func main() {
skel.PluginMain(cmdAdd, cmdCheck, cmdDel, version.All, bv.BuildString("outbound"))
}