aboutsummaryrefslogtreecommitdiffhomepage
path: root/firectl.py
blob: 020efd4e39d81856bc4d44716ba0a259cf96aa75 (plain)
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
# -*- coding: utf-8 -*-
__version__ = "0.1"

import os
from difflib import get_close_matches

import click


profile_path = "/etc/firejail/"
application_path = "/usr/share/applications/"
config = "/etc/firejail/firectl.conf"

profiles = [os.path.splitext(f)[0] for f in os.listdir(profile_path)]
applications = [os.path.splitext(f)[0] for f in os.listdir(application_path)]
installed = [p for p in profiles if p in applications]


@click.version_option()
@click.group()
def cli():
    pass


def get_config():
    """Get header and config."""
    header = "# list of enforced firejail profiles\n"
    try:
        with open(config, 'r') as f:
            conf = [l.strip() for l in f.readlines() if not l.startswith('#')]
    except FileNotFoundError:
        conf = []
    return header, conf


def write_config(programs, test, combine):
    """Write config to disk if necessary. Uses test to check if a program has to
    be added/removed from the config. Programs and conf are combined with
    combine.
    """
    header, conf = get_config()
    programs = [os.path.splitext(os.path.basename(p))[0] for p in programs]

    write = False
    for p in programs:
        if test(p, conf):
            write = True
            continue

    if write:
        lines = header + "\n".join(sorted(combine(programs, conf)))
        with open(config, 'w') as f:
            f.writelines(lines)


def add_config(programs):
    """Add programs to config."""
    write_config(programs,
                 lambda program, conf: program not in conf,
                 lambda programs, conf: set(conf + programs))


def remove_config(programs):
    """Remove programs from config."""
    write_config(programs,
                 lambda program, conf: program in conf,
                 lambda programs, conf: set(conf) - set(programs))


def get_desktop(program):
    """Get path to program's desktop file."""
    path = os.path.join(application_path, program + ".desktop")
    if os.path.isfile(path):
        return path
    else:
        message = "Desktop file for %s does not exist." % program

        typo = get_close_matches(program, installed, n=1)
        if len(typo) > 0:
            message += "\n\nDid you mean %s?" % typo[0]

        raise click.ClickException(message)


def replace(filename, condition, transform):
    """Replace lines in filename for which condition is true with transform."""
    newfile = []
    with open(filename, 'r') as f:
        for line in f:
            if condition(line):
                newfile.append(transform(line))
            else:
                newfile.append(line)

    with open(filename, 'w') as f:
        f.writelines(newfile)


def get_programs(program):
    """Return list of programs to enable / disable."""
    if len(program) == 0:
        raise click.ClickException("No program specified.")

    # Check if we have permission to modify global desktop files.
    if not os.access(get_desktop(installed[0]), os.W_OK):
        raise click.UsageError(
            message="Can't modify desktop files, please execute as root.")

    if program[0] == "all":
        program = installed

    return [get_desktop(p) for p in program]


@cli.command(help="enable firejail for program")
@click.argument("program", type=click.STRING, nargs=-1)
def enable(program, update_config=True):
    """Enable firejail for program. Program is tuple/list of program names."""
    programs = get_programs(program)

    for p in programs:
        replace(p,
                lambda l: l.startswith("Exec=") and "firejail" not in l,
                lambda l: "Exec=firejail " + l[l.find('=') + 1:])

    if update_config:
        add_config(programs)


@cli.command(help="disable firejail for program")
@click.argument("program", type=click.STRING, nargs=-1)
def disable(program):
    """Disable firejail for program. Program is tuple/list of program names."""
    programs = get_programs(program)

    for p in programs:
        replace(p,
                lambda line: line.startswith("Exec=firejail"),
                lambda line: "Exec=" + line[14:])

    remove_config(programs)


@cli.command(help="show status of firejail profiles")
def status():
    """Display status of available firejail profiles."""
    enabled = []
    disabled = []
    for p in installed:
        with open(get_desktop(p), 'r') as f:
            if "Exec=firejail" in f.read():
                enabled.append(p)
            else:
                disabled.append(p)

    click.echo("{:<2} firejail profiles are enabled".format(len(enabled)))
    for p in sorted(enabled):
        click.echo("   %s" % p)
    print()

    click.echo("{:<2} firejail profiles are disabled and available"
               .format(len(disabled)))
    for p in sorted(disabled):
        click.echo("   %s" % p)

    header, conf = get_config()
    disabled = [p for p in conf if p not in enabled]
    if len(disabled) > 0:
        click.secho("\n{} firejail profiles are disabled by updates"
                    .format(len(disabled)), fg="red")
        click.echo("Please run: sudo firectl restore")


@cli.command(help="restore firejail profiles from config")
def restore():
    """Re-enable firejail profiles for when desktop files get updated."""
    header, conf = get_config()
    if len(conf) > 1:
        enable.callback(conf, update_config=False)