Script: openbsd_privdrop.py

Set least privilege on OpenBSD.
Author: Alvar Penning — Version: 0.1.0 — License: ISC
For WeeChat ≥ 1.3.
Tags: openbsd, privileges, py3
Added: 2022-09-18

Download GitHub Repository

  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
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# Copyright (c) 2022 Alvar Penning <post@0x21.biz>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

# The openbsd_privdrop.py script tries to achieve the principle of least
# privilege for a WeeChat running on OpenBSD by restricting both the available
# system operations as well as the available file system paths by pledge(2) and
# unveil(2). As those functions are OpenBSD-specific, this script does not work
# on any other operating system.
#
# The respective filters are set by configuration variables. On first run or in
# the absence of configuration entries, sane defaults are set. These should be
# sufficient for a normal WeeChat installation, but would have to be adjusted,
# for example, when using other scripts or plugins. So the default does not
# allow the execution of other programs and assumes a home directory under
# /home/$USERNAME for unveil(2).
#
# - https://man.openbsd.org/pledge.2
# - https://man.openbsd.org/unveil.2

# History:
#
# 2022-09-18, Alvar Penning <post@0x21.biz>
#   version 0.1.0: initial release


import ctypes
import os
import sys
import weechat


SCRIPT_NAME    = "openbsd_privdrop"
SCRIPT_AUTHOR  = "Alvar Penning <post@0x21.biz>"
SCRIPT_VERSION = "0.1.0"
SCRIPT_LICENSE = "ISC"
SCRIPT_DESC    = "Drop WeeChat's privileges through OpenBSD's pledge(2) and unveil(2)."

SETTINGS = {
        "pledge_promises": (
            "stdio rpath wpath cpath dpath inet flock unix dns sendfd recvfd tty proc error",
            "List of promises for pledge(2).",
            ),
        "pledge_execpromises": (
            "",
            "List of promises to executed processes; requires exec in pledge_promises.",
            ),
        "unveil": (
            "~:rwc;/home:r;/usr/local/lib:r",  # WeeChat `stat`s /home while building the path to /home/$USER/...
            "List of path and permissions for unveil(2). Format: /a/path:rwc;/another/path:rw",
            ),
}


def libc_func(name):
    """ Returns a libc function, e.g., pledge or unveil.
        Inspired by https://nullprogram.com/blog/2021/09/15/
    """
    f = ctypes.CDLL(None, use_errno=True)[name]

    def _call_f(*args):
        weechat.prnt("", f"*\t{name}{args}")
        if f(*args) == -1:
            errno = ctypes.get_errno()
            raise OSError(errno, os.strerror(errno))

    return _call_f


def config_get(key):
    """ Fetch a stored configuration value and normalize the returned string
        for libc usage by replacing empty strings through None and converting
        non-empty strings to bytes.
    """
    value = weechat.config_get_plugin(key)
    return value.encode() if value != "" else None


def weechat_pledge():
    """ Execute pledge(2) for the configured promise.
    """
    pledge = libc_func("pledge")

    promises = config_get("pledge_promises")
    execpromises = config_get("pledge_execpromises")

    pledge(promises, execpromises)


def weechat_unveil():
    """ Execute unveil(2) for the configured paths.
        Unveil should be called before pledge unless "unveil" is promised.
    """
    unveil = libc_func("unveil")

    for path_part in config_get("unveil").split(b";"):
        path, permissions = path_part.split(b":")
        path = weechat.string_eval_path_home(path.decode(), {}, {}, {}).encode()
        unveil(path, permissions)

    unveil(None, None)


def main():
    """ Main function to load the script and apply the restrictions.
    """
    reg = weechat.register(
            SCRIPT_NAME,
            SCRIPT_AUTHOR,
            SCRIPT_VERSION,
            SCRIPT_LICENSE,
            SCRIPT_DESC,
            "", "")
    if not reg:
        return

    if not sys.platform.startswith("openbsd"):
        weechat.prnt("", f"{SCRIPT_NAME} is only supported on OpenBSD")
        return

    for key, value in SETTINGS.items():
        if not weechat.config_is_set_plugin(key):
            weechat.config_set_plugin(key, value[0])
            weechat.config_set_desc_plugin(key, f"{value[1]} (default: \"{value[0]}\")")

    weechat_unveil()
    weechat_pledge()


if __name__ == "__main__":
    main()