File: main.go

package info (click to toggle)
golang-github-landlock-lsm-go-landlock 0.0~git20250303.1544bcc-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 276 kB
  • sloc: makefile: 9
file content (71 lines) | stat: -rw-r--r-- 1,707 bytes parent folder | download
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
// landlock-restrict-net executes a process with Landlock network restrictions
//
// This is an example tool which does not provide backwards
// compatibility guarantees.
package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"strconv"
	"syscall"

	"github.com/landlock-lsm/go-landlock/landlock"
)

func usage() {
	var (
		out  = flag.CommandLine.Output()
		name = os.Args[0]
	)
	fmt.Fprintf(out, "Usage of %s:\n", name)
	flag.PrintDefaults()
	fmt.Fprintf(out, "\nExample usages:\n")
	fmt.Fprintf(out, "  %s -tcp.bind 8080 /usr/bin/nc -l 127.0.0.1 8080\n", name)
	fmt.Fprintf(out, "  %s -tcp.connect 8080 /usr/bin/nc 127.0.0.1 8080\n", name)
}

func main() {
	flag.Usage = usage

	var rules []landlock.Rule
	flag.Func("tcp.bind", "A TCP port where bind(2) should be permitted", func(s string) error {
		p, err := strconv.ParseUint(s, 10, 16)
		if err != nil {
			return err
		}
		log.Println("PERMIT TCP bind on port", p)
		rules = append(rules, landlock.BindTCP(uint16(p)))
		return nil
	})
	flag.Func("tcp.connect", "A TCP port where connect(2) should be permitted", func(s string) error {
		p, err := strconv.ParseUint(s, 10, 16)
		if err != nil {
			return err
		}
		log.Println("PERMIT TCP connect to port", p)
		rules = append(rules, landlock.ConnectTCP(uint16(p)))
		return nil
	})

	flag.Parse()

	var cmd []string
	if flag.NArg() > 1 {
		cmd = flag.Args()
	} else {
		log.Println("missing command to call, using /bin/bash")
		cmd = []string{"/bin/bash"}
	}

	if err := landlock.V4.RestrictNet(rules...); err != nil {
		log.Fatalf("landlock RestrictNet: %v", err)
	}

	log.Printf("Starting %v", cmd)
	if err := syscall.Exec(cmd[0], cmd, os.Environ()); err != nil {
		log.Fatalf("execve: %v", err)
	}
}