Debian Codegraph @

cmd/landlock-restrict-net/main.go

raw
1 // landlock-restrict-net executes a process with Landlock network restrictions.
2 //
3 // This is an example tool which does not provide backwards compatibility guarantees.
4 package main
5
6 import (
7 "flag"
8 "fmt"
9 "log"
10 "os"
11 "strconv"
12 "syscall"
13
14 "github.com/landlock-lsm/go-landlock/landlock"
15 )
16
17 func usage() {
18 var (
19 out = flag.CommandLine.Output()
20 name = os.Args[0]
21 )
22 fmt.Fprintf(out, "Usage of %s:\n", name)
23 flag.PrintDefaults()
24 fmt.Fprintf(out, "\nExample usages:\n")
25 fmt.Fprintf(out, " %s -tcp.bind 8080 /usr/bin/nc -l 127.0.0.1 8080\n", name)
26 fmt.Fprintf(out, " %s -tcp.connect 8080 /usr/bin/nc 127.0.0.1 8080\n", name)
27 fmt.Fprintln(out)
28 fmt.Fprintln(out, "\033[31;1m** This is a demo tool for go-landlock and will not provide backwards compatibility. **\033[0m")
29 }
30
31 func main() {
32 flag.Usage = usage
33
34 var rules []landlock.Rule
35 flag.Func("tcp.bind", "A TCP port where bind(2) should be permitted", func(s string) error {
36 p, err := strconv.ParseUint(s, 10, 16)
37 if err != nil {
38 return err
39 }
40 log.Println("PERMIT TCP bind on port", p)
41 rules = append(rules, landlock.BindTCP(uint16(p)))
42 return nil
43 })
44 flag.Func("tcp.connect", "A TCP port where connect(2) should be permitted", func(s string) error {
45 p, err := strconv.ParseUint(s, 10, 16)
46 if err != nil {
47 return err
48 }
49 log.Println("PERMIT TCP connect to port", p)
50 rules = append(rules, landlock.ConnectTCP(uint16(p)))
51 return nil
52 })
53
54 flag.Parse()
55
56 var cmd []string
57 if flag.NArg() > 1 {
58 cmd = flag.Args()
59 } else {
60 log.Println("missing command to call, using /bin/bash")
61 cmd = []string{"/bin/bash"}
62 }
63
64 if err := landlock.V9.RestrictNet(rules...); err != nil {
65 log.Fatalf("landlock RestrictNet: %v", err)
66 }
67
68 log.Printf("Starting %v", cmd)
69 if err := syscall.Exec(cmd[0], cmd, os.Environ()); err != nil {
70 log.Fatalf("execve: %v", err)
71 }
72 }