forked from nccgroup/singularity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
firewall.go
67 lines (57 loc) · 1.61 KB
/
firewall.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
package singularity
import (
"fmt"
"log"
"os/exec"
"strconv"
)
//IPTablesRule is a struct representing a linux iptable firewall rule
type IPTablesRule struct {
srcAddr string
srcPort string
dstAddr string
dstPort string
srcPortRange string
}
//NewIPTableRule populate an iptables rule
func NewIPTableRule(srcAddr string, srcPort string,
dstAddr string, dstPort string) *IPTablesRule {
p := IPTablesRule{srcAddr: srcAddr, srcPort: srcPort,
dstAddr: dstAddr, dstPort: dstPort}
p.generateSourcePortRange(10)
return &p
}
// TODO Experimental
func (ipt *IPTablesRule) generateSourcePortRange(max int) {
i, err := strconv.Atoi(ipt.srcPort)
if err != nil {
log.Fatal(err)
}
if (i < 0) || (i > 65535) {
log.Fatal("Source port is not within an expected range")
}
maxPort := i + max
var maxPortString string
if maxPort > 65535 {
maxPortString = "65535"
} else {
maxPortString = strconv.Itoa(maxPort)
}
ipt.srcPortRange = fmt.Sprintf("%v:%v", ipt.srcPort, maxPortString)
}
func (ipt *IPTablesRule) makeAndRunRule(command string) {
rule := exec.Command("/sbin/iptables",
command, "INPUT", "-p", "tcp", "-j", "REJECT", "--reject-with", "tcp-reset",
"--source", ipt.srcAddr, //"--sport" srcPortRange,
"--destination", ipt.dstAddr, "--destination-port", ipt.dstPort)
err := rule.Run()
log.Printf("Firewall: `iptables` finished with return code: %v", err)
}
//AddRule adds an iptables rule in Linux iptable
func (ipt *IPTablesRule) AddRule() {
ipt.makeAndRunRule("-A")
}
//RemoveRule removes an iptables rule in Linux iptable
func (ipt *IPTablesRule) RemoveRule() {
ipt.makeAndRunRule("-D")
}