aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/fix_private-bin.py
blob: 961646aa4e75f45a574755c304b1fed1397fced4 (plain) (blame)
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
#!/usr/bin/env python3
__author__ = "KOLANICH"
__copyright__ = """This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to <https://unlicense.org/>"""
__license__ = "Unlicense"

import typing
import sys, os, re
from collections import OrderedDict
from pathlib import Path
from shutil import which

privRx = re.compile(r"^(#\s*)?(private-bin)(\s+)(.+)$")


def fixSymlinkedBins(files: typing.List[Path], replMap: typing.Dict[str, str]) -> None:
    """
    Used to add filenames to private-bin directives of files if the ones present are mentioned in replMap
    replMap is a dict where key is the marker filename and value is the filename to add
    """

    for filename in files:
        lines = filename.read_text(encoding="utf-8").split("\n")

        shouldUpdate = False
        for (i, line) in enumerate(lines):
            m = privRx.match(line)
            if m:
                lineUpdated = False
                mBins = OrderedDict((sb, sb) for sb in (b.strip() for b in m.group(4).split(",")))

                for (old, new) in replMap.items():
                    if old in mBins:
                        #print(old, "->", new)
                        if new not in mBins:
                            mBins[old] = old + "," + new
                            lineUpdated = True

                if lineUpdated:
                    comment = m.group(1)
                    if comment is None:
                        comment = ""
                    lines[i] = comment + m.group(2) + m.group(3) + ",".join(mBins.values())
                    shouldUpdate = True

        if shouldUpdate:
            filename.write_text("\n".join(lines), encoding="utf-8")


def createSetOfBinaries(files: typing.List[Path]) -> typing.Set[str]:
    """
    Creates a set of binaries mentioned in private-bin directives of files.
    """
    s = set()
    for filename in files:
        with open(filename, "r") as file:
            for line in file:
                m = privRx.match(line)
                if m:
                    bins = m.group(4).split(",")
                    bins = [n.strip() for n in bins]
                    s = s | set(bins)
    return s

def getExecutableNameFromLink(p: Path) -> str:
    return os.readlink(str(p)).split(" ")[0]


forbiddenExecutables= ["firejail"]

def populateForbiddenExecutables():
    forbiddenSymlinks = []
    for e in forbiddenExecutables:
        r = which(e)
        if r is not None:
            yield r

forbiddenSymlinks = set(populateForbiddenExecutables())


def createSymlinkTable(binDirs: typing.Iterable[Path], binariesSet: typing.Set[str]) -> typing.Mapping[str, str]:
    """
    creates a dict of symlinked binaries in the system where a key is a symlink name and value is a symlinked binary.
    binDirs are folders to look into for binaries symlinks
    binariesSet is a set of binaries to be checked if they are actually a symlinks
    """
    m = dict()
    toProcess = binariesSet
    while len(toProcess) != 0:
        additional = set()
        for binName in toProcess:
            for binaryDir in binDirs:
                p = binaryDir / binName
                if p.is_symlink():
                    res = []
                    nm = getExecutableNameFromLink(p)
                    if nm in forbiddenSymlinks:
                        continue
                    m[binName] = nm
                    additional.add(nm)
                    break

        toProcess = additional
    return m


def doTheFixes(profilesPath: Path, binDirs: typing.Iterable[Path]) -> None:
    """
    Fixes private-bin in .profiles for firejail. The pipeline is as follows:
    discover files -> discover mentioned binaries ->
    discover the ones which are symlinks ->
    make a look-up table for fix ->
    filter the ones can be fixed (we cannot fix the ones which are not in directories for binaries) ->
    apply fix
    """
    files = list(profilesPath.glob("**/*.profile"))
    bins = createSetOfBinaries(files)
    #print("The binaries used are:")
    #print(bins)
    stbl = createSymlinkTable(binDirs, bins)
    print("The replacement table is:")
    print(stbl)
    for k, v in tuple(stbl.items()):
        if k.find(os.path.sep) < 0 and v.find(os.path.sep) < 0:
            pass
        else:
            del stbl[k]

    print("Filtered replacement table is:")
    print(stbl)
    fixSymlinkedBins(files, stbl)


thisDir = Path(__file__).absolute().parent
defaultProfilesPath = (thisDir.parent / "etc")


def printHelp():
    print("python3 " + str(thisDir) +
          " <dir with .profile files>\nThe default dir is " +
          str(defaultProfilesPath) + "\n" + doTheFixes.__doc__)


def main() -> None:
    """The main function. Parses the commandline args, shows messages and calls the function actually doing the work."""
    if len(sys.argv) > 2 or (len(sys.argv) == 2 and
                             (sys.argv[1] == "-h" or sys.argv[1] == "--help")):
        printHelp()
        sys.exit(1)

    profilesPath = None
    if len(sys.argv) == 2:
        if os.path.isdir(sys.argv[1]):
            profilesPath = os.path.abspath(sys.argv[1])
        else:
            if os.path.exists(sys.argv[1]):
                print(sys.argv[1] + " is not a dir")
            else:
                print(sys.argv[1] + " does not exist")
            printHelp()
            sys.exit(1)
    else:
        print("Using default profiles dir: ", defaultProfilesPath)
        profilesPath = defaultProfilesPath

    binDirs = ("/bin", "/usr/bin", "/usr/bin", "/usr/sbin", "/usr/local/bin", "/usr/local/sbin")
    binDirs = type(binDirs)(Path(p) for p in binDirs)

    print("Binaries dirs are:")
    print(binDirs)
    doTheFixes(profilesPath, binDirs)


if __name__ == "__main__":
    main()