Debian Codegraph @

landlock/net_opt.go

raw
1 package landlock
2
3 import (
4 "fmt"
5
6 ll "github.com/landlock-lsm/go-landlock/landlock/syscall"
7 )
8
9 type NetRule struct {
10 access AccessNetSet
11 port uint16
12 }
13
14 // ConnectTCP is a [Rule] which grants the right to connect a socket
15 // to a given TCP port.
16 //
17 // In Go, the connect(2) operation is usually run as part of
18 // [net.Dial].
19 func ConnectTCP(port uint16) NetRule {
20 return NetRule{
21 access: ll.AccessNetConnectTCP,
22 port: port,
23 }
24 }
25
26 // BindTCP is a [Rule] which grants the right to bind a socket to a
27 // given TCP port.
28 //
29 // In Go, the bind(2) operation is usually run as part of
30 // [net.Listen]. Since Go 1.24, [net.Listen] defaults to Multipath
31 // TCP, see the discussion in the package documentation.
32 func BindTCP(port uint16) NetRule {
33 return NetRule{
34 access: ll.AccessNetBindTCP,
35 port: port,
36 }
37 }
38
39 func (n NetRule) String() string {
40 return fmt.Sprintf("ALLOW %v on TCP port %v", n.access, n.port)
41 }
42
43 func (n NetRule) compatibleWithConfig(c Config) bool {
44 return n.access.isSubset(c.handledAccessNet)
45 }
46
47 func (n NetRule) addToRuleset(rulesetFD int, c Config) error {
48 if n.access == 0 {
49 // Adding this to the ruleset would be a no-op
50 // and result in an error.
51 return nil
52 }
53 flags := 0
54 attr := &ll.NetPortAttr{
55 AllowedAccess: uint64(n.access),
56 Port: uint64(n.port),
57 }
58 return ll.LandlockAddNetPortRule(rulesetFD, attr, flags)
59 }
60
61 func (n NetRule) downgrade(c Config) (out Rule, ok bool) {
62 return NetRule{
63 access: n.access.intersect(c.handledAccessNet),
64 port: n.port,
65 }, true
66 }