/
ports.go
94 lines (78 loc) Β· 1.76 KB
/
ports.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
package firewall
import (
"sync"
"time"
"github.com/safing/portbase/log"
"github.com/safing/portbase/rng"
)
type portStatus struct {
lastSeen time.Time
isMe bool
}
var (
portsInUse = make(map[uint16]*portStatus)
portsInUseLock sync.Mutex
cleanerTickDuration = 10 * time.Second
cleanTimeout = 10 * time.Minute
)
func getPortStatusAndMarkUsed(port uint16) *portStatus {
portsInUseLock.Lock()
defer portsInUseLock.Unlock()
ps, ok := portsInUse[port]
if ok {
ps.lastSeen = time.Now()
return ps
}
new := &portStatus{
lastSeen: time.Now(),
isMe: false,
}
portsInUse[port] = new
return new
}
// GetPermittedPort returns a local port number that is already permitted for communication.
// This bypasses the process attribution step to guarantee connectivity.
// Communication on the returned port is attributed to the Portmaster.
func GetPermittedPort() uint16 {
portsInUseLock.Lock()
defer portsInUseLock.Unlock()
for i := 0; i < 1000; i++ {
// generate port between 10000 and 65535
rN, err := rng.Number(55535)
if err != nil {
log.Warningf("filter: failed to generate random port: %s", err)
return 0
}
port := uint16(rN + 10000)
// check if free, return if it is
_, ok := portsInUse[port]
if !ok {
portsInUse[port] = &portStatus{
lastSeen: time.Now(),
isMe: true,
}
return port
}
}
return 0
}
func portsInUseCleaner() {
for {
select {
case <-interceptionModule.Stopping():
return
case <-time.After(cleanerTickDuration):
cleanPortsInUse()
}
}
}
func cleanPortsInUse() {
portsInUseLock.Lock()
defer portsInUseLock.Unlock()
threshold := time.Now().Add(-cleanTimeout)
for port, status := range portsInUse {
if status.lastSeen.Before(threshold) {
delete(portsInUse, port)
}
}
}