~qbit/protect

ref: v1.1.0 protect/protect.go -rw-r--r-- 1.8 KiB
c48b0e8fAaron Bieber Add ReducePledges for easier reduction of pledges 2 months ago
                                                                                
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
/*
Package protect is a wrapper for OpenBSD's pledge(2) and unveil(2) system
calls.

This library is trivial, but I found myself writing it often enough that I
figure it should be a package.
*/
package protect

import (
	"regexp"
	"strings"
)

// Unveil is a wrapper for OpenBSD's unveil(2). unveil can be used to limit
// a processes view of the filesystem.
//
// The first call to Unveil removes a processes visibility to everything
// except 'path'. Any subsequent calls expand the view to contain those
// paths. Finally a call to UnveilBlock will lock the view in place.
// Preventing access to anything else.
//
// On non-OpenBSD machines this call is a noop.
func Unveil(path string, flags string) error {
	return unveil(path, flags)
}

// UnveilBlock locks the Unveil'd paths. Preventing further changes to a
// processes filesystem view.
//
// On non-OpenBSD machines this call is a noop.
func UnveilBlock() error {
	return unveilBlock()
}

// Pledge wraps OpenBSD's pledge(2) system call. One can use this to limit
// the system calls a process can make.
//
// On non-OpenBSD machines this call is a noop.
func Pledge(promises string) error {
	return pledge(promises)
}

// ReducePledges takes the current list of plpedges and a list of pledges that
// should be removed. The new list is returned and Pledge() will be called
// with the reduced set of pledges.
func ReducePledges(current, toRemove string) (string, error) {
	newPledges, err := reduce(current, toRemove)
	if err != nil {
		return "", err
	}

	return newPledges, pledge(newPledges)
}

func reduce(a, b string) (string, error) {
	var newList []string
	currentList := strings.Split(a, " ")

	for _, s := range currentList {
		match, err := regexp.MatchString(s, b)
		if err != nil {
			return "", err
		}

		if !match {
			newList = append(newList, s)
		}
	}

	return strings.Join(newList, " "), nil
}