-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgo-docker-iptables.go
321 lines (258 loc) · 7.29 KB
/
go-docker-iptables.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
package main
import (
"github.com/vishvananda/netns"
"gopkg.in/alecthomas/kingpin.v2"
"encoding/json"
"strings"
"runtime"
"os"
"os/exec"
"net"
// "bufio"
"bytes"
"log"
"fmt"
"io/ioutil"
// "reflect"
"strconv"
// "syscall"
)
const (
iptablesPath = "/usr/sbin/iptables"
)
type Container struct {
Command string
Created int
Id string
Image string
Names []string
Ports []string
Status string
Labels map[string]string
}
type firewall struct {
Input struct {
Rules []rules
}
Output struct {
Rules []rules
}
Forward struct {
Rules []rules
}
}
type rules struct {
Source string
SourcePort string
Destination string
DestinationPort string
Proto string
Type string
}
var (
app = kingpin.New("go-docker-iptables", "A tool to manage iptables inside containers from the host")
Debug = app.Flag("debug","Enable verbose loggin").Bool()
LabelDef = app.Flag("label", "Iptables search label").Default("com.iptables").String()
)
func main() {
kingpin.MustParse(app.Parse(os.Args[1:]))
if *Debug {
log.Printf("Go docker iptables started")
log.Printf("Using %s as search label", *LabelDef)
}
// for {
containers, _:= get_containers()
for _, c:= range containers {
Firewall := &firewall{ }
Firewall.Input.Rules = make([]rules, 100)
Firewall.Output.Rules = make([]rules, 100)
Firewall.Forward.Rules = make([]rules, 100)
if *Debug {
log.Printf("Focus on Container: %s = %s", c.Id, c.PrimaryName())
}
c.GetRules( *Firewall )
err := c.ApplyRules( *Firewall )
if err != nil {
log.Println("Error Applying Rules")
}
if *Debug {
// Firewall.PrintRules()
}
}
// }
}
func get_containers() ([]Container, error) {
c, err := net.Dial("unix", "/var/run/docker.sock")
if err != nil {
return nil, err
}
if *Debug {
log.Println("Sending request...")
}
_, err = c.Write([]byte("GET /containers/json HTTP/1.0\r\n\r\n"))
if err != nil {
return nil, err
}
var result []byte
var in_bytes = make([]byte, 102400)
for {
num, err := c.Read(in_bytes)
result = append(result, in_bytes...)
if err != nil || num < len(in_bytes) {
break
}
}
result = bytes.Trim(result, "\x00")
results := bytes.SplitN(result, []byte{'\r', '\n', '\r', '\n'}, 2)
jsonBlob := results[1]
if *Debug {
log.Println("Got response:")
log.Println(string(jsonBlob))
}
var containers []Container
err = json.Unmarshal(jsonBlob, &containers)
return containers, err
}
func (c Container) PrimaryName() string {
primary_name := c.Names[0]
if primary_name == "" {
return ""
}
primary_name = strings.Trim(primary_name, "/")
return primary_name
}
func (c Container) tasksFile() string {
return fmt.Sprintf("/sys/fs/cgroup/memory/system.slice/docker-%s.scope/tasks", c.Id)
}
func (c Container) firstPid() (int, error) {
data, err := ioutil.ReadFile(c.tasksFile())
if err != nil {
return -1, err
}
value, err := strconv.Atoi(strings.SplitN(string(data), "\n", 2)[0])
if err != nil {
return -1, err
}
return value, nil
}
func (c Container) GetRules(fw firewall) {
for k, v := range c.Labels {
if strings.HasPrefix(k, *LabelDef ) {
// pull the chain from the LabelDef
chain := strings.SplitAfter(k, *LabelDef )[1]
// Loop over the possible chains
switch {
case strings.Contains((strings.ToLower(chain)), "input"): {
chainpos := strings.SplitAfter(chain, "input.")[1]
if *Debug {
log.Printf( "Input Chain : %s on position %s", v, chainpos )
}
pos, err := strconv.Atoi(chainpos)
if err != nil {
log.Println("Illegal position defined for %s and %s",k,v)
}
fw.AddInputRule(pos ,v)
}
case strings.Contains((strings.ToLower(chain)), "output"): {
chainpos := strings.SplitAfter(chain, "output.")[1]
if *Debug {
log.Printf( "Output Chain : %s on position %s", v, chainpos )
}
}
case strings.Contains((strings.ToLower(chain)), "forward"): {
chainpos := strings.SplitAfter(chain, "forward.")[1]
if *Debug {
log.Printf( "Forward Chain : %s on position %s", v, chainpos )
}
}
}
// if *Debug {
// log.Printf( "Key : %s Value %s" ,k,v )
// }
}
}
}
func (c Container) ApplyRules(fw firewall) error {
// Lock the OS Thread so we don't accidentally switch namespaces
runtime.LockOSThread()
defer runtime.UnlockOSThread()
// Save the current network namespace
origns, _ := netns.Get()
defer origns.Close()
// Create a new network namespace
pid, _ := c.firstPid()
log.Printf( "pid %v", pid)
newns, _ := netns.GetFromPid(pid)
defer newns.Close()
// Switch to the container namespace
netns.Set(newns)
// Input
cmd := append([]string{"-t", "filter", "-F", "INPUT"})
err := exec.Command(iptablesPath, cmd...).Run()
if err != nil {
log.Println("Couldn't apply clear rule")
}
for pos , rule := range fw.Input.Rules {
if rule.Type != "" {
sport, _ := strconv.Atoi(rule.SourcePort)
dport, _ := strconv.Atoi(rule.DestinationPort)
if *Debug {
log.Printf( "ApplyRules - Source : %s SourcePort %v Destination : %s DestinationPort : %v Proto : %s Type : %s" , rule.Source , sport , rule.Destination, dport , rule.Proto, rule.Type )
}
ippos := pos+1
args := []string{"-t", "filter", "-I", "INPUT", strconv.Itoa( ippos ) , "-p" , rule.Proto , "--source" , rule.Source , "--destination-port" , rule.DestinationPort, "-j", strings.ToUpper(rule.Type) , "--wait"}
if *Debug {
log.Printf( "ApplyRules cmd %s - args : %s", iptablesPath, args )
}
cmd := exec.Cmd{Path: iptablesPath, Args: append([]string{iptablesPath}, args...)}
err := cmd.Run()
if err != nil {
log.Println("Couldn't apply rule %v", pos )
}
}
}
// Switch back to the original namespace
netns.Set(origns)
runtime.UnlockOSThread()
return nil
}
func (f firewall) AddInputRule(pos int, rule string) {
if *Debug {
log.Printf( "AddInputRule - Pos : %v Rule %s" ,pos,rule )
}
var R rules
err := json.Unmarshal([]byte(rule), &R )
if err != nil {
log.Println("Couldn't convert json label to rule")
}
f.Input.Rules[pos] = R
}
func (f firewall) PrintRules() {
for _ , rule := range f.Input.Rules {
if rule.Type != "" {
sport, _ := strconv.Atoi(rule.SourcePort)
dport, _ := strconv.Atoi(rule.DestinationPort)
if *Debug {
log.Printf( "PrintRules Input Source : %s SourcePort %v Destination : %s DestinationPort : %v Proto : %s Type : %s" , rule.Source , sport , rule.Destination, dport , rule.Proto, rule.Type )
}
}
}
for _ , rule := range f.Output.Rules {
if rule.Type != "" {
sport, _ := strconv.Atoi(rule.SourcePort)
dport, _ := strconv.Atoi(rule.DestinationPort)
if *Debug {
log.Printf( "PrintRules Output Source : %s SourcePort %v Destination : %s DestinationPort : %v Proto : %s Type : %s" , rule.Source , sport , rule.Destination, dport , rule.Proto, rule.Type )
}
}
}
for _ , rule := range f.Forward.Rules {
if rule.Type != "" {
sport, _ := strconv.Atoi(rule.SourcePort)
dport, _ := strconv.Atoi(rule.DestinationPort)
if *Debug {
log.Printf( "PrintRules Forward Source : %s SourcePort %v Destination : %s DestinationPort : %v Proto : %s Type : %s" , rule.Source , sport , rule.Destination, dport , rule.Proto, rule.Type )
}
}
}
}