2
0
mirror of https://gitlab.com/apparmor/apparmor synced 2025-08-31 22:35:35 +00:00

Compare commits

...

376 Commits

Author SHA1 Message Date
intrigeri
c0815d0e0f dirtest.sh: don't rely on apparmor_parser -N's output sort order to be deterministic
I've seen this test fail because "apparmor_parser -N" returned the expected
lines, but in a different order than what's expected (dirtest.out).

To fix this, sort both the expected and actual output.
2022-07-25 10:14:31 +00:00
Christian Boltz
c0b5d90848 Merge Resolve "Python: Ensure opened files are closed."
This MR closes #239. In the temporary file commit, `tempfile.NamedTemporaryFile` is preferred over `tempfile.mkstemp` because it allows for simpler use of context managers and lets you choose what mode to open the file in. Also in this commit, note that in `aa.py` and `easyprof.py` destination files are now written directly, instead of writing to temp files and then renaming them.

Closes #239
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/898
Approved-by: Christian Boltz <apparmor@cboltz.de>
Merged-by: Christian Boltz <apparmor@cboltz.de>
2022-07-20 19:34:16 +00:00
Mark Grassi
e6cbdef4ab Implement code review comments. 2022-07-19 20:32:03 -04:00
Christian Boltz
ea0dc96050 Merge Support setuptools >= 61.2 in Python tests
Fix for #253, by mirroring the change from 1c23f5e1e4

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/897
Approved-by: Christian Boltz <apparmor@cboltz.de>
Merged-by: Christian Boltz <apparmor@cboltz.de>
2022-07-19 20:29:38 +00:00
Ben Greiner
d442584a0a reviewed edits 2022-07-19 21:47:02 +02:00
Mark Grassi
cf6606d380 Ensure opened temporary files are closed. 2022-07-17 21:52:55 -04:00
Ben Greiner
85734c3bac add setuptools to test-utils CI job 2022-07-16 20:42:07 +02:00
Ben Greiner
47d68dac0f use new build_platlib path with setuptools >= 61.2 2022-07-16 17:47:18 +02:00
Mark Grassi
0c1eb3ec92 Ensure opened files are closed. 2022-07-12 18:34:29 -04:00
Christian Boltz
97bd86c7c6 Merge Remove Python 2 support.
Per the discussion in #243, this MR removes Python 2 compatibility. Namely, this merge request:
- removes code behind `sys` and `platform` interpreter version checks
- removes `unicode` vs. `str` handling
- removes unnecessary `__future__` imports
- removes unnecessary `object` inheritance
- removes unnecessary `super()` arguments
- uncomments commented-out code with "uncomment when python3 only" notes or some variant of that message

Regarding the `unicode` vs. `str` handling, it's arguably more Pythonic to check `isinstance(x, str)` as opposed to `type(x) is str`, but I didn't want to alter code behavior.

A change needs to be made to the `INCOMPLETE_COVERAGE` setting in `utils/test/Makefile` to get the pipeline to pass. I didn't get anywhere tweaking the setting myself, so someone else with more AppArmor experience will have to make that change.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/894
Approved-by: Christian Boltz <apparmor@cboltz.de>
Merged-by: Christian Boltz <apparmor@cboltz.de>
2022-07-12 18:26:29 +00:00
Steve Beattie
0859b42ba2 profiles: merge Update syslogd for inetutils-syslogd
The inetutils syslogd implementation integrates the kmsg support in the
main server, it has support for syslog.d configuration fragment files.
and it uses a slightly different pid filename.

Signed-off-by: Guillem Jover <guillem@hadrons.org>

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/888
Approved-by: Steve Beattie <gitlab@nxnw.org>
Merged-by: Steve Beattie <gitlab@nxnw.org>
2022-07-08 05:12:46 +00:00
Christian Boltz
e1011d646d Merge rc.apparmor.functions: only use systemd-detect-virt if it's present
This is a follow-up on !812, which added a call to systemd-detect-virt.
Everywhere else we don't assume that program is present,
and first check if it's there before we run it.
Let's do the same here.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/896
Approved-by: Christian Boltz <apparmor@cboltz.de>
Approved-by: Jon Tourville <jon.tourville@canonical.com>
Merged-by: Christian Boltz <apparmor@cboltz.de>
2022-07-06 21:45:39 +00:00
Mark Grassi
db4939cf6a Improve variable name. 2022-07-06 13:51:57 -04:00
Mark Grassi
44c814e76c Update code coverage settings. 2022-07-06 13:29:32 -04:00
intrigeri
06f86e2a02 rc.apparmor.functions: only use systemd-detect-virt if it's present
This is a follow-up on !812, which added a call to systemd-detect-virt.
Everywhere else we don't assume that program is present,
and first check if it's there before we run it.
Let's do the same here.
2022-07-06 06:41:35 +00:00
Mark Grassi
df97cf89bd Remove Python 2 support. 2022-06-29 20:41:38 -04:00
Christian Boltz
57eebd6cdb Merge zgrep: allow executing egrep and fgrep
egrep and fgrep also need to execute grep and write to /dev/tty in the
helper child profile.

Fixes: https://progress.opensuse.org/issues/113108

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/892
Approved-by: Jon Tourville <jon.tourville@canonical.com>
Merged-by: Christian Boltz <apparmor@cboltz.de>
2022-06-29 13:25:14 +00:00
Christian Boltz
df37c299e1 zgrep: allow executing egrep and fgrep
egrep and fgrep also need to execute grep and write to /dev/tty in the
helper child profile.

Fixes: https://progress.opensuse.org/issues/113108
2022-06-28 23:27:10 +02:00
Christian Boltz
08da556e4e Merge Fix inconsistent return length.
Correct issue discussed in !889.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/890
Approved-by: Christian Boltz <apparmor@cboltz.de>
Merged-by: Christian Boltz <apparmor@cboltz.de>
2022-06-28 18:59:37 +00:00
Mark Grassi
728dbde5e4 Fix inconsistent return length. 2022-06-28 08:30:31 -04:00
Christian Boltz
43f419458e Merge Speed up list creations, and change lists to tuples where appropriate.
Tuples [are quite a bit faster than lists](https://stackoverflow.com/a/22140115). If you don't need mutability, a tuple is almost always the better collection to choose. This merge request changes lists to tuples where appropriate, and speeds up some list creations by changing `list()` calls into `[]` literals. It also changes a few function calls to use tuple unpacking, i.e. `func(*tup)`, as opposed to `func(tup[0], tup[1], ...)`. This yields yet another performance improvement, as well as a readability improvement.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/889
Approved-by: Christian Boltz <apparmor@cboltz.de>
Merged-by: Christian Boltz <apparmor@cboltz.de>
2022-06-27 18:56:10 +00:00
Mark Grassi
7581c9e113 Speed up list creations, and change lists to tuples where appropriate.. 2022-06-26 22:18:56 -04:00
Christian Boltz
36c704ce04 Merge Avoid unnecessary memory copies when enlarging lists.
This merge request addresses issue #240.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/886
Approved-by: Christian Boltz <apparmor@cboltz.de>
Merged-by: Christian Boltz <apparmor@cboltz.de>
2022-06-26 12:06:22 +00:00
Mark Grassi
ca9920cf92 Avoid unnecessary memory copies when enlarging lists. 2022-06-26 12:06:22 +00:00
Guillem Jover
8175d26cc3 Update syslogd for inetutils-syslogd
The inetutils syslogd implementation integrates the kmsg support in the
main server, it has support for syslog.d configuration fragment files.
and it uses a slightly different pid filename.

Signed-off-by: Guillem Jover <guillem@hadrons.org>
2022-06-25 21:15:51 +02:00
Christian Boltz
50a45c6a39 Merge Ensure opened files are closed.
This partially addresses issue #239. There are still some remaining instances where opened files are not properly closed, e.g. the `NamedTemporaryFile` in `utils/apparmor/config.py`.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/885
Approved-by: Christian Boltz <apparmor@cboltz.de>
Merged-by: Christian Boltz <apparmor@cboltz.de>
2022-06-22 17:20:49 +00:00
Christian Boltz
df1ca957d6 Merge Fix spelling and grammar errors.
I found a few spelling and grammar errors while working on my other merge requests. I figured it'd be wise to separate these fixes from the code changes.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/887
Approved-by: Christian Boltz <apparmor@cboltz.de>
Merged-by: Christian Boltz <apparmor@cboltz.de>
2022-06-22 17:09:42 +00:00
Mark Grassi
c255968e63 Fix spelling and grammar errors. 2022-06-18 16:14:45 -04:00
Mark Grassi
bf819bc8e6 Ensure opened files are closed. 2022-06-18 14:40:58 -04:00
John Johansen
d7e3f33aa8 Merge abstraction/exo-open: Remove dbus deny rule
Abstractions should not generally include deny rules as this can unduly
constrain profiles which include them due to the precedent matching rules
between deny vs allow rules. Also as per the comment, this is not required
for exo-open to work, so simply omit it from the abstraction for
now. Finally, in Ubuntu, the evince profile includes the exo-open
abstraction and this deny rule causes evince to fail to initialise
correctly as it then assumes it cannot use gvfs.

Signed-off-by: Alex Murray <alex.murray@canonical.com>

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/884
Approved-by: John Johansen <john@jjmx.net>
Merged-by: John Johansen <john@jjmx.net>
2022-06-16 17:08:11 +00:00
Alex Murray
cd91492d53 abstraction/exo-open: Remove dbus deny rule
Abstractions should not generally include deny rules as this can unduly
constrain profiles which include them due to the precedent matching rules
between deny vs allow rules. Also as per the comment, this is not required
for exo-open to work, so simply omit it from the abstraction for
now. Finally, in Ubuntu, the evince profile includes the exo-open
abstraction and this deny rule causes evince to fail to initialise
correctly as it then assumes it cannot use gvfs.

Signed-off-by: Alex Murray <alex.murray@canonical.com>
2022-06-15 14:54:19 +09:30
Christian Boltz
48fc233d05 Merge samba profiles: support paths used by Arch Linux
On Arch Linux `rpcd_classic`, `rpcd_epmapper`, `rpcd_fsrvp`, `rpcd_lsad`, `rpcd_mdssvc`, `rpcd_rpcecho`, `rpcd_spoolss`, `rpcd_winreg`, `samba-bgqd`, `samba-dcerpcd` and `smbspool_krb5_wrapper` are in `/usr/lib/samba/samba/`.

See https://archlinux.org/packages/extra/x86_64/samba/files/ and https://bugs.archlinux.org/task/74614.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/883
Approved-by: Christian Boltz <apparmor@cboltz.de>
Merged-by: Christian Boltz <apparmor@cboltz.de>
2022-06-06 10:53:53 +00:00
nl6720
deadcc0d11 samba profiles: support paths used by Arch Linux
On Arch Linux rpcd_classic, rpcd_epmapper, rpcd_fsrvp, rpcd_lsad, rpcd_mdssvc, rpcd_rpcecho, rpcd_spoolss, rpcd_winreg, samba-bgqd, samba-dcerpcd and smbspool_krb5_wrapper are in /usr/lib/samba/samba/.
See https://archlinux.org/packages/extra/x86_64/samba/files/ and https://bugs.archlinux.org/task/74614.
2022-06-06 11:57:14 +03:00
John Johansen
2a3140cb93 parser: fix min length calculation for inverse character sets
The inverse character set lists the characters it doesn't match. If
the inverse character set contains an oob then that is NOT considered
a match. So length should be one.

However because of oobs are handle not containing an oob doesn't mean
there is a match either. Currently the only way to match an oob is
via a positive express (no inverse matches are possible).

Signed-off-by: John Johansen <john.johansen@canonical.com>
2022-05-23 15:39:14 -07:00
John Johansen
6e0b660709 Merge Update for the mesa abstraction
I noticed that some apps return the following errors when launched:

```
  kernel: audit: type=1400 audit(1651244478.255:5501): apparmor="DENIED" operation="open" profile="some_app" name="/sys/devices/pci0000:00/0000:00:02.0/revision" pid=1877976 comm="some_app" requested_mask="r" denied_mask="r" fsuid=1000 ouid=0
  kernel: audit: type=1400 audit(1651244478.255:5502): apparmor="DENIED" operation="open" profile="some_app" name="/sys/devices/pci0000:00/0000:00:02.0/config" pid=1877976 comm="some_app" requested_mask="r" denied_mask="r" fsuid=1000 ouid=0
```

Blocking the files results in the following errors when the app is executed in a terminal:

```
  MESA: error: Failed to query drm device.
  libGL error: failed to create dri screen
  libGL error: failed to load driver: crocus
  MESA: error: Failed to query drm device.
  libGL error: failed to create dri screen
  libGL error: failed to load driver: crocus
```

Since they have something to do with MESA, I think the mesa abstraction should
be updated to fix the issue.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/879
Approved-by: John Johansen <john@jjmx.net>
Merged-by: John Johansen <john@jjmx.net>
2022-05-23 22:35:59 +00:00
John Johansen
8490fa1db5 Merge Add missing permissions for dovecot-{imap,lmtp,pop3}
References: https://bugzilla.opensuse.org/show_bug.cgi?id=1199535

I propose this patch for 3.0 and master. (2.13 and older have more different dovecot profiles which might make backporting a bit harder.)

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/881
Approved-by: John Johansen <john@jjmx.net>
Merged-by: John Johansen <john@jjmx.net>
2022-05-23 22:33:36 +00:00
John Johansen
a61ae7b2f0 Merge parser/capability.h: add missing <cstdint> include
Without the change apparmor build fails on this week's gcc-13 snapshot as:

    capability.h:66:6: error: variable or field '__debug_capabilities' declared void
       66 | void __debug_capabilities(uint64_t capset, const char *name);
          |      ^~~~~~~~~~~~~~~~~~~~
    capability.h:66:27: error: 'uint64_t' was not declared in this scope
       66 | void __debug_capabilities(uint64_t capset, const char *name);
          |                           ^~~~~~~~
    capability.h:23:1: note: 'uint64_t' is defined in header '<cstdint>'; did you forget to '#include <cstdint>'?
       22 | #include <linux/capability.h>
      +++ |+#include <cstdint>
       23 |

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/882
Approved-by: John Johansen <john@jjmx.net>
Merged-by: John Johansen <john@jjmx.net>
2022-05-23 22:24:53 +00:00
Sergei Trofimovich
64a64be7ff parser/capability.h: add missing <cstdint> include
Without the change apparmor build fails on this week's gcc-13 snapshot as:

    capability.h:66:6: error: variable or field '__debug_capabilities' declared void
       66 | void __debug_capabilities(uint64_t capset, const char *name);
          |      ^~~~~~~~~~~~~~~~~~~~
    capability.h:66:27: error: 'uint64_t' was not declared in this scope
       66 | void __debug_capabilities(uint64_t capset, const char *name);
          |                           ^~~~~~~~
    capability.h:23:1: note: 'uint64_t' is defined in header '<cstdint>'; did you forget to '#include <cstdint>'?
       22 | #include <linux/capability.h>
      +++ |+#include <cstdint>
       23 |
2022-05-23 23:13:14 +01:00
Christian Boltz
ad8df7f88f Add missing permissions for dovecot-{imap,lmtp,pop3}
References: https://bugzilla.opensuse.org/show_bug.cgi?id=1199535
2022-05-15 20:53:35 +02:00
Christian Boltz
ab19f5599d Merge profiles/apparmor.d: update samba-dceprpc & samba-rpcd-* profiles
aarch64 needs some additional rules on tumbleweed to handle for
example

apparmor="DENIED" operation="file_mmap" profile="samba-dcerpcd" name="/usr/lib64/samba/samba-dcerpcd" pid=897 comm="samba-dcerpcd" requested_mask="m" denied_mask="m" fsuid=0 ouid=0

The other new rpcd_* services exhibit similar errors

Fixes: https://bugzilla.opensuse.org/show_bug.cgi?id=1198309

Signed-off-by: Noel Power <noel.power@suse.com>

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/880
Approved-by: Christian Boltz <apparmor@cboltz.de> for 3.0 and master
Merged-by: Christian Boltz <apparmor@cboltz.de>
2022-05-11 19:44:43 +00:00
Noel Power
6a621616d9 profiles/apparmor.d: update samba-dceprpc & samba-rpcd-* profiles
aarch64 needs some additional rules on tumbleweed to handle for
example

apparmor="DENIED" operation="file_mmap" profile="samba-dcerpcd" name="/usr/lib64/samba/samba-dcerpcd" pid=897 comm="samba-dcerpcd" requested_mask="m" denied_mask="

The other new rpcd_* services exhibit similar errors

Fixes: https://bugzilla.opensuse.org/show_bug.cgi?id=1198309

Signed-off-by: Noel Power <noel.power@suse.com>
2022-05-11 15:55:01 +01:00
Mikhail Morfikov
a54409eb94 Update for the mesa abstraction
I noticed that some apps return the following errors when launched:

  kernel: audit: type=1400 audit(1651244478.255:5501): apparmor="DENIED" operation="open" profile="some_app" name="/sys/devices/pci0000:00/0000:00:02.0/revision" pid=1877976 comm="some_app" requested_mask="r" denied_mask="r" fsuid=1000 ouid=0
  kernel: audit: type=1400 audit(1651244478.255:5502): apparmor="DENIED" operation="open" profile="some_app" name="/sys/devices/pci0000:00/0000:00:02.0/config" pid=1877976 comm="some_app" requested_mask="r" denied_mask="r" fsuid=1000 ouid=0

Blocking the files results in the following errors when the app is executed in a terminal:

  MESA: error: Failed to query drm device.
  libGL error: failed to create dri screen
  libGL error: failed to load driver: crocus
  MESA: error: Failed to query drm device.
  libGL error: failed to create dri screen
  libGL error: failed to load driver: crocus

Since they have something to do with MESA, I think the mesa abstraction should
be updated to fix the issue.
2022-04-29 22:58:37 +02:00
Christian Boltz
62bf2f773b Merge zgrep profile: also allow zstd
openSUSE works on extending zgrep to also support zstd-compressed files.

References: http://bugzilla.opensuse.org/show_bug.cgi?id=1198922

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/878
Approved-by: Jon Tourville <jon.tourville@canonical.com>
Merged-by: Christian Boltz <apparmor@cboltz.de>
2022-04-28 23:01:21 +00:00
Christian Boltz
c5a51a080f zgrep profile: also allow zstd
openSUSE works on extending zgrep to also support zstd-compressed files.

References: http://bugzilla.opensuse.org/show_bug.cgi?id=1198922
2022-04-27 22:15:17 +02:00
John Johansen
c7d060a7dd Merge Add some empty and cut-off bad abi rules
Credits go to Seth who proposed these tests in
https://gitlab.com/apparmor/apparmor/merge_requests/196#note_108500403

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/875
Approved-by: John Johansen <john@jjmx.net>
Merged-by: John Johansen <john@jjmx.net>
2022-04-19 18:54:51 +00:00
John Johansen
3083ce7a39 Merge Allow reading all of /etc/php[578]/** in abstractions/php
... and with that, make a rule in the php-fpm profile (which missed
php8) superfluous.

Fixes: https://gitlab.com/apparmor/apparmor/-/issues/229
Fixes: https://bugzilla.opensuse.org/show_bug.cgi?id=1186267#c11
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/876
Approved-by: John Johansen <john@jjmx.net>
Merged-by: John Johansen <john@jjmx.net>
2022-04-19 18:43:19 +00:00
John Johansen
bfa67b369d Merge profiles: update snap_browsers permissions
The snap_browsers abstraction requires more permissions
due to updates on snaps.
    
Some of the permissions are not required in older versions of
Ubuntu that use 2.12 and 2.13, but are introduced for unification
and ease of maintenance purposes. These include:
```
    all dbus permissions,
    @{PROC}/sys/kernel/random/uuid r,
    owner @{PROC}/@{pid}/cgroup r,
    /var/lib/snapd/sequence/{chromium,firefox,opera}.json r,
```


I also propose a cherry-pick of this commit to 2.12, 2.13 and 3.0

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/877
Approved-by: John Johansen <john@jjmx.net>
Merged-by: John Johansen <john@jjmx.net>
2022-04-19 18:35:52 +00:00
Georgia Garcia
eb828dde6f profiles: update snap_browsers permissions
The snap_browsers abstraction requires more permissions
due to updates on snaps.

Some of the permissions are not required in older versions of
Ubuntu that use 2.12 and 2.13, but are introduced for unification
and ease of maintenance purposes. These include:
all dbus permissions,
@{PROC}/sys/kernel/random/uuid r,
owner @{PROC}/@{pid}/cgroup r,
/var/lib/snapd/sequence/{chromium,firefox,opera}.json r,

Signed-off-by: Georgia Garcia <georgia.garcia@canonical.com>
2022-04-18 21:18:26 -03:00
Christian Boltz
c946f0bf75 Allow reading all of /etc/php[578]/** in abstractions/php
... and with that, make a rule in the php-fpm profile (which missed
php8) superfluous.

Fixes: https://gitlab.com/apparmor/apparmor/-/issues/229

Fixes: https://bugzilla.opensuse.org/show_bug.cgi?id=1186267#c11
2022-04-18 20:52:39 +02:00
Christian Boltz
69302067b0 Merge tools.py: inline check_profile_dir() into __init__()
... which was the only caller of this tiny function.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/874
Approved-by: Jon Tourville <jon.tourville@canonical.com>
Merged-by: Christian Boltz <apparmor@cboltz.de>
2022-04-18 11:47:22 +00:00
Christian Boltz
a2ff041e98 Merge zgrep profile: allow executing /usr/bin/expr
expr is used for parsing commandline options in zgrep.

Fixes: https://bugzilla.opensuse.org/show_bug.cgi?id=1198531

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/873
Approved-by: Jon Tourville <jon.tourville@canonical.com>
Merged-by: Christian Boltz <apparmor@cboltz.de>
2022-04-18 11:46:52 +00:00
Christian Boltz
8cb81ec25f Add some empty and cut-off bad abi rules
Credits go to Seth who proposed these tests in
https://gitlab.com/apparmor/apparmor/merge_requests/196#note_108500403
2022-04-17 00:38:18 +02:00
Christian Boltz
484247355e tools.py: inline check_profile_dir() into __init__()
... which was the only caller of this tiny function.
2022-04-16 23:38:17 +02:00
Christian Boltz
ad8c5f0be3 zgrep profile: allow executing /usr/bin/expr
expr is used for parsing commandline options in zgrep.

Fixes: https://bugzilla.opensuse.org/show_bug.cgi?id=1198531
2022-04-16 22:32:01 +02:00
Christian Boltz
3d27977b1c Merge profiles/apparmor.d: Add new profiles needed for samba-4.16
samba-4.16 has a completely new dcerpc subsystem, services that
used to be built into the smbd daemon itself (and deployed in forked
instances) are now hosted in standalone binaries. The following new
binaries now need new profiles

  rpcd_classic
  rpcd_epmapper
  rpcd_fsrvp
  rpcd_lsad
  rpcd_mdssvc
  rpcd_rpcecho
  rpcd_spoolss
  rpcd_winreg
  samba-dcerpcd

Additionally smbd & winbindd need new entries because the exec
samba-dcerpcd

Signed-off-by: Noel Power <noel.power@suse.com>

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/871
Approved-by: Christian Boltz <apparmor@cboltz.de>
Merged-by: Christian Boltz <apparmor@cboltz.de>
2022-04-15 12:52:19 +00:00
Noel Power
c785bcbe47 profiles/apparmor.d: Add new profiles needed for samba-4.16
samba-4.16 has a completely new dcerpc subsystem, services that
used to be built into the smbd daemon itself (and deployed in forked
instances) are now hosted in standalone binaries. The following new
binaries now need new profiles

  rpcd_classic
  rpcd_epmapper
  rpcd_fsrvp
  rpcd_lsad
  rpcd_mdssvc
  rpcd_rpcecho
  rpcd_spoolss
  rpcd_winreg
  samba-dcerpcd

Mostly these are captured in a single common profile 'samba-rpcd'

Additionally smbd & winbindd need new entries because they exec
samba-dcerpcd

Fixes: https://bugzilla.opensuse.org/show_bug.cgi?id=1198309

Signed-off-by: Noel Power <noel.power@suse.com>
2022-04-15 12:10:07 +01:00
John Johansen
41b4436710 Merge Add zgrep and xzgrep profile
This prevents exploiting https://www.openwall.com/lists/oss-security/2022/04/08/2
aka CVE-2022-1271 (file write and code execution via "funny" filenames)

I propose this addition for 3.0 and master.

(Tested on openSUSE Tumbleweed - tests on other distros welcome ;-)

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/870
Approved-by: Georgia Garcia <georgia.garcia@canonical.com>
Merged-by: John Johansen <john@jjmx.net>
2022-04-12 05:18:11 +00:00
John Johansen
52e82516d7 Merge add a common reload_profile() function to aa.py
This function is based on reload_profile() in tools.py, but also
replaces most of reload_base() in aa.py.

For bonus points, we get rid of shell=True when calling apparmor_parser.

Note: This slightly changes the behaviour of aa-logprof and aa-genprof -
if the parser errors out ($? > 0), the output no longer gets hidden.
However, this will not raise an exception, and aa-logprof and aa-genprof
won't abort on parser errors.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/855
Approved-by: John Johansen <john@jjmx.net>
Merged-by: John Johansen <john@jjmx.net>
2022-04-12 05:17:50 +00:00
John Johansen
103603277a Merge sbin.rpc.statd: add hosts_access abstraction, /etc/nfs.conf{,.d/}
Observed these denials on an Ubuntu jammy system, when a user with an NFS homedir logs in:
```
Mar 29 06:57:14 darkstar kernel: [ 5988.206958] audit: type=1400 audit(1648551434.502:72): apparmor="DENIED" operation="open" profile="rpc.statd" name="/etc/nfs.conf" pid=3195 comm="rpc.statd" requested_mask="r" denied_mask="r" fsuid=0 ouid=0
Mar 29 06:57:14 darkstar kernel: [ 5988.207023] audit: type=1400 audit(1648551434.502:73): apparmor="DENIED" operation="open" profile="rpc.statd" name="/etc/nfs.conf.d/" pid=3195 comm="rpc.statd" requested_mask="r" denied_mask="r" fsuid=0 ouid=0
Mar 29 10:48:49 darkstar kernel: [19883.319957] audit: type=1400 audit(1648565329.710:74): apparmor="DENIED" operation="open" profile="rpc.statd" name="/etc/hosts.allow" pid=3196 comm="rpc.statd" requested_mask="r" denied_mask="r" fsuid=111 ouid=0
Mar 29 10:48:49 darkstar kernel: [19883.320016] audit: type=1400 audit(1648565329.710:75): apparmor="DENIED" operation="open" profile="rpc.statd" name="/etc/hosts.deny" pid=3196 comm="rpc.statd" requested_mask="r" denied_mask="r" fsuid=111 ouid=0
Mar 29 17:07:33 darkstar kernel: [  162.642366] audit: type=1400 audit(1648588053.026:72): apparmor="DENIED" operation="file_lock" profile="rpc.statd" name="/etc/nfs.conf" pid=1697 comm="rpc.statd" requested_mask="k" denied_mask="k" fsuid=0 ouid=0
```

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/866
Approved-by: John Johansen <john@jjmx.net>
Merged-by: John Johansen <john@jjmx.net>
2022-04-12 05:16:23 +00:00
John Johansen
4537a5014b Merge profiles/apparmor.d/abstraction: Squash noisey setsockopt calls.
systemd will attempt to force socket buffer size using setsockopt
and param SO_SNDBUFFORCE (which require net_admin cap) if it's previous
attempt to set size was clipped by kernel limit.

- Silence 'type=AVC msg=audit(1648725005.727:201): apparmor="DENIED" operation="capable" profile="smbd" pid=3054 comm="smbd" capability=12  capname="net_admin"'

type entries.

Signed-off-by: Noel Power <noel.power@suse.com>

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/867
Approved-by: John Johansen <john@jjmx.net>
Merged-by: John Johansen <john@jjmx.net>
2022-04-12 05:14:24 +00:00
Christian Boltz
4c853dc74d Add zgrep and xzgrep profile
This prevents exploiting https://www.openwall.com/lists/oss-security/2022/04/08/2
aka CVE-2022-1271 (file write and code execution via "funny" filenames)
2022-04-12 00:04:22 +02:00
Christian Boltz
52b6b97c98 Merge dirtest.sh: error out on unexpected success
... if a test is expected to fail, but succeeds.

Also fix the copyright year - the test was created in 2022, not in 2013.

This fixes my comments on
bd78b6b292

The original MR !850 was merged into 3.0 and master, therefore I also propose this patch for 3.0 and master.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/868
Approved-by: Jon Tourville <jon.tourville@canonical.com>
Merged-by: Christian Boltz <apparmor@cboltz.de>
2022-04-04 11:14:15 +00:00
Christian Boltz
2036f6fa9d dirtest.sh: error out on unexpected success
... if a test is expected to fail, but succeeds.

Also fix the copyright year - the test was created in 2022, not in 2013.

This fixes my comments on
bd78b6b292
2022-04-03 17:45:24 +02:00
Noel Power
90f97357af profiles/apparmor.d/abstraction: Squash noisey setsockopt calls.
systemd will attempt to force socket buffer size using setsockopt
and param SO_SNDBUFFORCE (which require net_admin cap) if it's previous
attempt to set size was clipped by kernel limit.

- Silence 'type=AVC msg=audit(1648725005.727:201): apparmor="DENIED" operation="capable" profile="smbd" pid=3054 comm="smbd" capability=12  capname="net_admin"'

type entries.

Signed-off-by: Noel Power <noel.power@suse.com>
2022-03-31 12:23:00 +01:00
Daniel Richard G
8e845c2e7f sbin.rpc.statd: add hosts_access abstraction, /etc/nfs.conf{,.d/}
Also update to use @{run}
2022-03-30 01:04:26 -04:00
Christian Boltz
83685ba703 Merge Allow dovecot to use all signals
similar to commit 2f9d172c64
we discovered that there was a service outage
when dovecot tried to send a usr1 signal

type=AVC msg=audit(1648024138.249:184964): apparmor="DENIED" operation="signal" profile="dovecot" pid=1690 comm="dovecot" requested_mask="send" denied_mask="send" signal=usr1 peer="dovecot-imap-login"

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/865
Approved-by: Christian Boltz <apparmor@cboltz.de>
Merged-by: Christian Boltz <apparmor@cboltz.de>
2022-03-25 20:52:49 +00:00
Christian Boltz
ff9e457189 Merge abstractions/ssh_certs: extend pki/trust directories
- add pki/blacklist and pki/blocklist
- add /usr/share/pki/ in adddition to /etc/pki/

pki/blocklist was suggested by @darix, the other changes are things I noticed while adding it.

I propose this patch for 3.0 and master. (`abstractions/ssl_certs` on 2.x branches is quite different and needs a manual backport (or more cherry-picks) if you want to backport this MR.)

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/864
Approved-by: Jon Tourville <jon.tourville@canonical.com>
Merged-by: Christian Boltz <apparmor@cboltz.de>
2022-03-23 20:34:02 +00:00
Bernhard M. Wiedemann
f0919f83f1 Allow dovecot to use all signals
similar to commit 2f9d172c64
we discovered that there was a service outage
when dovecot tried to send a usr1 signal

type=AVC msg=audit(1648024138.249:184964): apparmor="DENIED" operation="signal" profile="dovecot" pid=1690 comm="dovecot" requested_mask="send" denied_mask="send" signal=usr1 peer="dovecot-imap-login"
2022-03-23 14:27:13 +01:00
Christian Boltz
32cd90eb88 abstractions/ssh_certs: extend pki/trust directories
- add pki/blacklist and pki/blocklist
- add /usr/share/pki/ in adddition to /etc/pki/

pki/blocklist was suggested by @darix, the other changes are things I noticed while adding it.
2022-03-22 12:36:42 +01:00
Christian Boltz
e2319167d0 Merge profiles/apparmor.d: Fix read access denied on /proc/*/fd bsc#1196850
- Fix "type=AVC msg=audit(1646702374.347:182): apparmor="DENIED"
       operation="open" profile="samba-bgqd" name="/proc/1933/fd/"
       pid=1933 comm="samba-bgqd" requested_mask="r" denied_mask="r"
       fsuid=0 ouid=0"

entries appearing in SLE15-SP4

Signed-off-by: Noel Power <noel.power@suse.com>

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/860
Merged-by: Christian Boltz <apparmor@cboltz.de>
2022-03-14 12:16:20 +00:00
Noel Power
6b83ba91c1 profiles/apparmor.d: Fix read access denied on /proc/*/fd bsc#1196850
- Fix "type=AVC msg=audit(1646702374.347:182): apparmor="DENIED"
       operation="open" profile="samba-bgqd" name="/proc/1933/fd/"
       pid=1933 comm="samba-bgqd" requested_mask="r" denied_mask="r"
       fsuid=0 ouid=0"

entries appearing in SLE15-SP4

Signed-off-by: Noel Power <noel.power@suse.com>
2022-03-14 10:30:03 +00:00
John Johansen
c3f64513f2 Merge smbd, samba-bgqd: allow reading openssl.cnf
References: https://bugzilla.opensuse.org/show_bug.cgi?id=1195463#c10

I propose this patch for 3.0 and master. (<= 2.13 don't have the samba-bgpd profile - if we want to backport to 2.x, we'll have to pick only the smbd part.)

Fixes: https://bugzilla.opensuse.org/show_bug.cgi?id=1195463#c10
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/862
Approved-by: John Johansen <john@jjmx.net>
Merged-by: John Johansen <john@jjmx.net>
2022-03-13 15:05:46 +00:00
Christian Boltz
16444e9c29 smbd, samba-bgqd: allow reading openssl.cnf
References: https://bugzilla.opensuse.org/show_bug.cgi?id=1195463#c10
2022-03-13 11:24:35 +01:00
John Johansen
8f7768cd02 Merge abstractions/nss-systemd: Allow access for systemd-machined names
See downstream bug at
https://bugs.launchpad.net/ubuntu/+source/apparmor/+bug/1964325

Signed-off-by: Alex Murray <alex.murray@canonical.com>

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/861
Approved-by: John Johansen <john@jjmx.net>
Merged-by: John Johansen <john@jjmx.net>
2022-03-10 04:07:56 +00:00
Alex Murray
9e260a8d79 abstractions/nss-systemd: Allow access for systemd-machined names
See downstream bug at
https://bugs.launchpad.net/ubuntu/+source/apparmor/+bug/1964325

Signed-off-by: Alex Murray <alex.murray@canonical.com>
2022-03-10 11:57:13 +10:30
John Johansen
bd78b6b292 parser: dirtest that was supposed to be part of the previous commit
libapparmor: fix handling of failed symlink traversal, fixed a couple
of directory walk issues that could cause failures. The test included
in this commit was supposed to be included in the previous commit,
but was accidentally dropped. Even worse the make file changes did
make it causing the previous commit to break the CI.

Fixes: MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/85
Signed-off-by: John Johansen <john.johansen@canonical.com>
2022-02-27 01:03:22 -08:00
John Johansen
acc6ba1cb7 libapparmor: fix handling of failed symlink traversal
Ideally we would have a flag or something so the caller could choose
to handle symlinks, or traverse them. But since all callers currently
don't handle symlinks just handle them in the iterator.

Beyond fixing the early termination due to a failed symlink this also
fixes another case of failure in one job cause dir based loads to
terminate early. Which can result in partial loads.

Fixes: https://gitlab.com/apparmor/apparmor/-/issues/215
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/850
Signed-off-by: John Johansen <john.johansen@canonical.com>
Approved-by: Georgia Garcia <georgia.garcia@canonical.com>
2022-02-27 00:55:41 -08:00
John Johansen
6f18326232 Merge GTK abstraction: add support for gtk4.
The recently added gtk abstraction (!825) lack the support for the new gtk4.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/857
Approved-by: Jon Tourville <jon.tourville@canonical.com>
Merged-by: John Johansen <john@jjmx.net>
2022-02-22 19:53:48 +00:00
Alexandre Pujol
8074ff4fd1 GTK abstraction: add support for gtk4. 2022-02-22 19:34:59 +00:00
Christian Boltz
7c725782a3 Merge aa-genprof: reduce and improve subprocess calls
Get rid of subprocess with shell=True

Simplify logmark used in syslog.

Instead of using `date | md5sum` and parsing the output to get the actual md5sum (without the stdin filename), use the current unixtime with a `logmark-` prefix.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/856
Acked-by: Seth Arnold <seth.arnold@gmail.com>
Merged-by: Christian Boltz <apparmor@cboltz.de>
2022-02-21 22:10:27 +00:00
Christian Boltz
95d89dfbac Simplify logmark used in syslog
Instead of using `date | md5sum` and parsing the output to get the
actual md5sum (without the stdin filename), use the current unixtime
with a `logmark-` prefix.
2022-02-21 22:52:14 +01:00
Christian Boltz
c0734411ee aa-genprof: get rid of subprocess with shell=True 2022-02-21 22:43:29 +01:00
Christian Boltz
c6dabdf1e8 add a common reload_profile() function to aa.py
This function is based on reload_profile() in tools.py, but also
replaces most of reload_base() in aa.py.

For bonus points, we get rid of shell=True when calling apparmor_parser.

Note: This slightly changes the behaviour of aa-logprof and aa-genprof -
if the parser errors out ($? > 0), the output no longer gets hidden.
However, this will not raise an exception, and aa-logprof and aa-genprof
won't abort on parser errors.
2022-02-21 22:05:59 +01:00
John Johansen
6e5fdb5c05 Merge smbd: allow reading under /usr/share/samba
Today, a normal user connected and did something (dunno what) that caused smbd to try to `/usr/share/samba/mdssvc/elasticsearch_mappings.json`:

Samba logs:

```
root@smb:~# journalctl -b0 -u smbd
-- Logs begin at Fri 2022-01-21 14:17:01 UTC, end at Thu 2022-02-17 23:56:02 UTC. --
Feb 17 14:01:20 smb systemd[1]: Starting Samba SMB Daemon...
Feb 17 14:01:26 smb smbd[113]: [2022/02/17 14:01:26.904865,  0] ../../lib/util/become_daemon.c:135(daemon_ready)
Feb 17 14:01:26 smb systemd[1]: Started Samba SMB Daemon.
Feb 17 14:01:26 smb smbd[113]:   daemon_ready: daemon 'smbd' finished starting up and ready to serve connections
Feb 17 21:05:35 smb smbd[3084]: pam_unix(samba:session): session opened for user jdoe by (uid=0)
Feb 17 21:05:37 smb smbd[3084]: [2022/02/17 21:05:37.735182,  0] ../../source3/rpc_server/mdssvc/mdssvc_es.c:92(mdssvc_es_init)
Feb 17 21:05:37 smb smbd[3084]:   mdssvc_es_init: Opening mapping file [/usr/share/samba/mdssvc/elasticsearch_mappings.json] failed: unable to open /usr/share/samba/mdssvc/elasticsearch_mappings.json: Permission denied
Feb 17 21:05:37 smb smbd[3084]: [2022/02/17 21:05:37.735436,  0] ../../source3/rpc_server/mdssvc/mdssvc.c:1490(mdssvc_init)
Feb 17 21:05:37 smb smbd[3084]:   mdssvc_init: backend init failed
Feb 17 21:05:37 smb smbd[3084]: [2022/02/17 21:05:37.735562,  0] ../../source3/rpc_server/mdssvc/srv_mdssvc_nt.c:152(_mdssvc_open)
Feb 17 21:05:37 smb smbd[3084]:   _mdssvc_open: Couldn't create policy handle for partage
Feb 17 23:56:02 smb smbd[3084]: pam_unix(samba:session): session closed for user jdoe
```

Since the 'smb' machine is a container, the Apparmor denial ended up in the host's log:

```
$ journalctl -o cat --grep samba -k --since today | cat
audit: type=1400 audit(1645131937.730:98): apparmor="DENIED" operation="open" namespace="root//lxd-smb_<var-snap-lxd-common-lxd>" profile="smbd" name="/usr/share/samba/mdssvc/elasticsearch_mappings.json" pid=35359 comm="smbd" requested_mask="r" denied_mask="r" fsuid=166549 ouid=165536

```

It is the first time it occurs in years of use but it seems legitimate as:

1) this file is installed by the package
2) `git grep -F elasticsearch_mappings` in Debian samba's source shows many hits:
```
$ git grep -F elasticsearch_mappings
debian/samba.install:usr/share/samba/mdssvc/elasticsearch_mappings.json
docs-xml/manpages/mdsearch.1.xml:         <filename>/usr/share/samba/mdssvc/elasticsearch_mappings.json</filename>
docs-xml/smbdotconf/misc/elasticsearchmappings.xml:  <value type="default">&pathconfig.SAMBA_DATADIR;/elasticsearch_mappings.json</value>
docs/manpages/mdfind.1:/usr/share/samba/mdssvc/elasticsearch_mappings\&.json
docs/manpages/smb.conf.5:\fI\fIelasticsearch:mappings\fR\fR\fI = \fR\fI${prefix}/var/samba/elasticsearch_mappings\&.json\fR\fI \fR
selftest/selftest.pl:   elasticsearch:mappings = $srcdir_abs/source3/rpc_server/mdssvc/elasticsearch_mappings.json
selftest/target/Samba3.pm:      elasticsearch:mappings = $srcdir_abs/source3/rpc_server/mdssvc/elasticsearch_mappings.json
source3/rpc_server/mdssvc/es_parser_test.c:             "%s/mdssvc/elasticsearch_mappings.json",
source3/rpc_server/mdssvc/mdssvc_es.c:          "%s/mdssvc/elasticsearch_mappings.json",
source3/rpc_server/wscript_build:                          'mdssvc/elasticsearch_mappings.json')
```

While only the `mdssvc` sub-dir could be authorized, the whole dir content seemed OK for read access anyway:

```
root@smb:~# ll /usr/share/samba/
total 53
drwxr-xr-x  5 root root   10 Feb  1 14:08 ./
drwxr-xr-x 67 root root   67 Jun 22  2021 ../
-rwxr-xr-x  1 root root 1163 Jan 31 13:11 addshare.py*
drwxr-xr-x  3 root root    4 Feb  1 14:08 admx/
drwxr-xr-x  2 root root    3 Feb  1 14:08 mdssvc/
-rwxr-xr-x  1 root root 2059 Jan 31 13:11 panic-action*
-rwxr-xr-x  1 root root 1333 Jan 31 13:11 setoption.py*
drwxr-xr-x  5 root root   57 Feb  1 14:08 setup/
-rw-r--r--  1 root root 8942 Jan 31 13:11 smb.conf
-rwxr-xr-x  1 root root 2682 Jan 31 13:11 update-apparmor-samba-profile*
```

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/853
Approved-by: John Johansen <john@jjmx.net>
Merged-by: John Johansen <john@jjmx.net>
2022-02-21 20:04:49 +00:00
John Johansen
40402e2436 Merge Revert "gitlab: testing: temporarily disable secret-detect"
It appears secret detection is failing if the master branch in the tree a merge request is being made from is too (some unknown value) far behind the branch of the tree it is being merged into.

This is problematic as it is not started practice to refresh the upstream branches of forked trees, but to keep multiple remotes in a single local tree, branch from mainline master, work on the branch and push to the fork for the merge request. This will require contributors to refresh their forked trees in secret-detection fails. Which may be problematic for some contributors, but since we don't know how bad this is going to be, for now re-enable secret detection.

This reverts commit 8b4344c17b.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/854
Approved-by: Christian Boltz <apparmor@cboltz.de>
Merged-by: John Johansen <john@jjmx.net>
2022-02-21 19:58:36 +00:00
John Johansen
51615755f8 Revert "gitlab: testing: temporarily disable secret-detect"
This reverts commit 8b4344c17b.
2022-02-21 11:31:44 -08:00
John Johansen
8b4344c17b gitlab: testing: temporarily disable secret-detect
Unfortunately secret detection is failing with
   fatal: error in object: unshallow sha1

and blocking merge requests. Unfortuntely all suggested work arounds
from https://gitlab.com/gitlab-org/gitlab/-/issues/351976 failed to
work.

Signed-off-by: John Johansen <john.johansen@canonical.com>
2022-02-18 00:19:31 -08:00
Simon Deziel
9e0adcfd07 smbd: allow reading under /usr/share/samba
Signed-off-by: Simon Deziel <simon@sdeziel.info>
2022-02-17 18:54:54 -05:00
Georgia Garcia
5001431cdf Merge parser: fix building with link time optimization (lto)
Libapparmor was fixed for lto builds on commit 7cde91f5 but
the parser was also failing due to the same reasons when lto
was enabled.

Fixes: https://gitlab.com/apparmor/apparmor/-/issues/214
Signed-off-by: Georgia Garcia <georgia.garcia@canonical.com>

Closes #214
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/851
Acked-by: Approved-by: John Johansen <john@jjmx.net>
Merged-by: Georgia Garcia <georgia.garcia@canonical.com>
2022-02-17 17:09:13 +00:00
John Johansen
6fa2d528e9 Merge Update apache2-common so that other processes can trace the hats that include...
Update apache2-common so that other processes can trace the hats that include this file. The main `usr.sbin.apache2` profile includes `abstractions/base` which has these lines in it, which is why `ss -tnlp` sometimes fails and sometimes works.

See also: [Debian Bug #1003153](https://bugs.debian.org/1003153) for more details about how this occurs.

Fixes: https://bugs.debian.org/1003153
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/852
Approved-by: John Johansen <john@jjmx.net>
Merged-by: John Johansen <john@jjmx.net>
2022-02-17 09:16:20 +00:00
Craig Small
071935b914 Update apache2-common so that other processes can trace the hats that include this file. The main includes abstractions/base which has these lines in it, which is why ss -tnlp sometimes fails.
See also: https://bugs.debian.org/1003153 for more details about how this occurs.
2022-02-17 07:57:55 +00:00
Georgia Garcia
b6d3daa715 parser: fix building with link time optimization (lto)
Libapparmor was fixed for lto builds on commit 7cde91f5 but
the parser was also failing due to the same reasons when lto
was enabled.

Fixes: https://gitlab.com/apparmor/apparmor/-/issues/214
Signed-off-by: Georgia Garcia <georgia.garcia@canonical.com>
2022-02-16 20:49:42 -03:00
John Johansen
e71e27c574 Merge smbd: include snippet generated at runtime on Debian and openSUSE
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/838
Approved-by: John Johansen <john@jjmx.net>
Merged-by: John Johansen <john@jjmx.net>
2022-02-15 21:29:02 +00:00
Christian Boltz
19abc66425 smbd: include snippet generated at runtime on openSUSE 2022-02-15 21:52:15 +01:00
John Johansen
ba14227bb5 Merge make test-aa-notify test_help_contents () less strict
Python 3.10 generates a slightly different --help output.

Fixes https://gitlab.com/apparmor/apparmor/-/issues/220

Closes #220
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/848
Acked-by: Approved-by: John Johansen <john@jjmx.net>
Merged-by: John Johansen <john@jjmx.net>
2022-02-15 19:17:30 +00:00
Christian Boltz
39f4132ab9 make test-aa-notify test_help_contents () less strict
Python 3.10 generates a slightly different --help output.

Fixes https://gitlab.com/apparmor/apparmor/-/issues/220
2022-02-15 19:39:32 +01:00
John Johansen
583e1905e9 Merge profile-load: use safer and less ambiguous shell constructs
Thanks to @cboltz for noticing this on https://gitlab.com/apparmor/apparmor/-/merge_requests/841#note_842436025.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/849
Acked-by: John Johansen <john@jjmx.net>
Merged-by: John Johansen <john@jjmx.net>
2022-02-15 08:16:38 +00:00
intrigeri
322b3f4d3e profile-load: use less ambiguous if/then construct
As shellcheck taught me
today (https://github.com/koalaman/shellcheck/wiki/SC2015),
"A && B || C is not if-then-else. C may run when A is true".

It does not matter here in practice, because worst case we would run "true" once
too many, but still.
2022-02-15 07:34:17 +00:00
intrigeri
35f23a6da1 profile-load: use safer "read" construct
In this case it does not matter, we're merely testing if we can actually
read from that file, but let's make this robust (and shellcheck happy)
for future's sake.

Reference: https://www.shellcheck.net/wiki/SC2162
2022-02-15 07:28:27 +00:00
John Johansen
5a41024bbe Merge Make the systemd unit a no-op in containers with no internal policy
In 73e124d4fb I've upstreamed the `is_container_with_internal_policy()` function, but so far it was not used anywhere upstream. This is the missing bit.

I could trace the history of that patch back to 2012 (2.7.102-0ubuntu3):

    * debian/apparmor.init: do nothing in a container.  This can be
      removed once stacked profiles are supported and used by lxc.
      (LP: #978297)

Context: I lack both knowledge and motivation to keep maintaining this as part of the Debian delta. I'd rather see upstream, and in particular folks more knowledgeable than me about LXC/LXD, or with external motivation factors to work on this part of the stack, take care of it.

Note: Debian has similar code in its [sysvinit script](https://salsa.debian.org/apparmor-team/apparmor/-/blob/debian/master/debian/apparmor.init). I'm not touching that one.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/840
Acked-by: John Johansen <john@jjmx.net>
Merged-by: John Johansen <john@jjmx.net>
2022-02-14 22:11:28 +00:00
John Johansen
26b7ddee36 Merge Allow access to socket directory used by recent ibus-daemon
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/837
Acked-by: John Johansen <john@jjmx.net>
Merged-by: John Johansen <john@jjmx.net>
2022-02-14 22:07:19 +00:00
John Johansen
4300953dc8 Merge CI: enable Secret-Detection and a few SAST analyzers
This MR depends on !843, mostly for convenience and to avoid having to rework it once !843 is merged. If this turns out to be a blocker, I can rebase it `--onto` master.

It's based on the draft from !584 and !716, but on top of copying'n'pasting the examples from the GitLab documentation, which was necessary but not sufficient, in this MR I tried my best to make these features work in our context: it actually passes CI, it does not clutter the CI UI with jobs that are not applicable here, and it yields a manageable amount of output (as opposed to hundreds of "OMG you're using format strings", that I don't think any of us is going to triage one by one any time soon).

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/844
Acked-by: Approved-by: John Johansen <john@jjmx.net>
Merged-by: John Johansen <john@jjmx.net>
2022-02-14 08:38:33 +00:00
John Johansen
6f0e361c8e Merge CI: parallelize across multiple jobs, only install necessary dependencies
This makes the pipeline run time about 30% shorter and, perhaps more importantly, this gives us more direct access to test failures: they are not hidden in the middle of the huge `test-all` log anymore.

As a bonus, this gives us much faster feedback for tests with a short duration.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/843
Acked-by: Approved-by: John Johansen <john@jjmx.net>
Merged-by: John Johansen <john@jjmx.net>
2022-02-14 08:17:47 +00:00
John Johansen
6a54d59172 Merge Import profile-load script from Debian
This script is used at least by LXC upstream and MySQL in Debian:
https://codesearch.debian.net/search?q=%2Flib%2Fapparmor%2Fprofile-load

Presumably it could be useful elsewhere if it was more readily available.

Similarly to !840, this is another user of the `is_container_with_internal_policy()` function. I'd like all the callers of this function to live in harmony under the same roof, upstream.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/841
Acked-by: John Johansen <john@jjmx.net>
Merged-by: John Johansen <john@jjmx.net>
2022-02-14 06:23:51 +00:00
John Johansen
046442741f Merge Add .desktop file for aa-notify
This allows distributions to start aa-notify automatically, should they wish so, by installing that file in a suitable location, such as `/etc/xdg/autostart`.

This file was introduced in Ubuntu 2.8.95~2430-0ubuntu3 package in 2014, replacing the `/etc/X11/Xsession.d` snippet that Ubuntu had added in 2010.

I'd like to stop having to care about this file as part of the Debian delta and to enable greater collaboration.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/839
Acked-by: John Johansen <john@jjmx.net>
Merged-by: John Johansen <john@jjmx.net>
2022-02-14 06:21:22 +00:00
Christian Boltz
1bb684b474 Merge shellcheck: skip files generated during libapparmor build
libtool generates horrible shell code, you don't want to see the
shellcheck results for it ;-)

This is only relevant for local testing (not in CI) because these files
don't exist in git and therefore don't exist when the shellcheck CI job
runs.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/847
Acked-by: Approved-by: intrigeri <intrigeri@boum.org>
Merged-by: Christian Boltz <apparmor@cboltz.de>
2022-02-13 21:21:37 +00:00
intrigeri
bf4134e705 Provide examples of how to disable a Bandit SAST analyzer warning 2022-02-13 21:05:54 +00:00
intrigeri
8c8965a720 CI: don't run the Bandit SAST analyzer on our test suites
Let's focus for now on code that runs on our users' systems.
2022-02-13 21:05:54 +00:00
intrigeri
086fb04f21 CI: disable SemGrep SAST analyzer
It runs the flawfinder checks, so let's disable this one for the same reason
we disabled flawfinder.
2022-02-13 21:05:54 +00:00
intrigeri
9bbbcd8447 CI: disable ESLint SAST analyzer
We have no JavaScript code, let's make the GitLab CI user interface leaner.
2022-02-13 21:05:54 +00:00
intrigeri
8655cf162a CI: disable flawfinder SAST analyzer
It reports hundreds of issues, lots of them with critical severity.
The GitLab UI allows dismissing them one-by-one very quickly,
but I'm not a good person to do that.
Let's try to have a better signal/noise ratio for this first iteration.
2022-02-13 21:05:54 +00:00
intrigeri
9240e12e73 CI: disable Dependency Scanning
According to
https://docs.gitlab.com/ee/user/application_security/dependency_scanning/,
"dependency scanning lets you know if your application uses an external (open
source) library that is known to be vulnerable".

AppArmor is not the kind of project that benefits from it: we don't link
statically against our dependencies, nor bundle them into released
artifacts.
2022-02-13 21:05:54 +00:00
intrigeri
7d69e55074 CI: disable spotbugs SAST analyzer
It requires building our Ant projects, which have not been touched in years.
2022-02-13 21:05:54 +00:00
intrigeri
9f8c0d25e3 CI: only run Debian'ish commands on jobs run on Debian'ish systems 2022-02-13 21:05:52 +00:00
Eric Rosenberg
2a7bd3aa9e CI: enable SAST, Secret-Detection, and Dependency Scanning 2022-02-13 21:04:18 +00:00
intrigeri
099f99a395 CI: ensure test-utils runs all intended tests 2022-02-13 21:02:58 +00:00
intrigeri
368625a9d3 utils/test/README.md: document not-totally-obvious cross-tree semi-dependency
Thanks to @cboltz for the explanation.
2022-02-13 21:02:58 +00:00
intrigeri
f0ff344e2a CI: normalize indentation 2022-02-13 21:02:58 +00:00
intrigeri
694b3348da CI: parallelize across multiple jobs, only install necessary dependencies 2022-02-13 21:02:56 +00:00
intrigeri
3c1163825b CI: don't install unneeded python-all-dev (Python 2) 2022-02-13 21:01:24 +00:00
Christian Boltz
6ae7b1566c shellcheck: skip files generated during libapparmor build
libtool generates horrible shell code, you don't want to see the
shellcheck results for it ;-)

This is only relevant for local testing (not in CI) because these files
don't exist in git and therefore don't exist when the shellcheck CI job
runs.
2022-02-13 21:41:54 +01:00
Christian Boltz
73c24a8b12 Merge Lint shell code and add shellcheck CI job
This should avoid unconsciously introducing regressions wrt. best practices for shell code.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/842
Acked-by: Christian Boltz <apparmor@cboltz.de>
Merged-by: Christian Boltz <apparmor@cboltz.de>
2022-02-13 20:06:55 +00:00
intrigeri
56dd267a24 Mark variables as dummy in a way that shellcheck 0.7.0 supports
The "_" prefix is only supported in shellcheck > 0.7.2.
2022-02-13 19:43:48 +00:00
intrigeri
529d386775 CI: enable all shellcheck severity levels
The few previous commits make this pass, let's profit.
2022-02-13 19:43:48 +00:00
intrigeri
6db9ebfd15 aa-decode: "fix" all remaining shellcheck style violations 2022-02-13 19:43:48 +00:00
intrigeri
985f9ca788 CI: set shellcheck minimum severity to info
The few previous commits make this pass, let's profit.
2022-02-13 19:43:48 +00:00
intrigeri
825f761c77 aa-decode, aa-remove-unknown: fix remaining shellcheck info-level violations
For details, see:

- https://www.shellcheck.net/wiki/SC2086
- https://www.shellcheck.net/wiki/SC2162
2022-02-13 19:43:48 +00:00
intrigeri
e55a9b3735 CI: set shellcheck minimum severity to warning
The few previous commits make this pass, let's profit.
2022-02-13 19:43:48 +00:00
intrigeri
af76d98fce utils/test/: drop support for running with Python 2 2022-02-13 19:43:48 +00:00
intrigeri
8d219e1f31 aa-remove-unknown: mark dummy variable as such
For details, see https://www.shellcheck.net/wiki/SC2034.
2022-02-13 19:43:48 +00:00
intrigeri
cfcc271b3c aa-remove-unknown: prefer [ p ] && [ q ] as [ p -a q ] is not well defined.
For details, see https://www.shellcheck.net/wiki/SC2166.
2022-02-13 19:43:48 +00:00
intrigeri
804e8f94a6 CI: prepare for enabling shellcheck warnings and info
- Assume /bin/sh has dash's features and ignore corresponding false positives

- Exclude parser/tst, tests and utils/test directories: they have tons
  of shellcheck violations but they don't *directly* impact our users.
  Let's first focus on code that runs on production systems.

- Exclude rc.apparmor.slackware: I don't know anything about Slackware's
  /bin/sh.
2022-02-13 19:43:48 +00:00
intrigeri
5a6f6c2fc8 CI: add shellcheck job, with minimum severity set to error
We have way too many warnings to enable lower severity levels,
but let's at least we don't introduce new errors.
2022-02-13 19:43:48 +00:00
intrigeri
398f584710 Test suite: don't use fragile "-e with globs" construction
For details, see https://github.com/koalaman/shellcheck/wiki/SC2144.
2022-02-13 19:43:48 +00:00
intrigeri
14d35c651c Test suite: don't use fragile shell construct mixing string and array
The previous code happened to work only because we always pass either 0 or 1
arguments to these functions. If we ever passed them 2+ arguments,
unexpected things would happen.

For details, see https://www.shellcheck.net/wiki/SC2145
2022-02-13 19:43:48 +00:00
intrigeri
fb94661937 rc.apparmor.functions: mark intentionally unused variable as dummy
Thanks, shellcheck!
2022-02-13 19:43:48 +00:00
intrigeri
2e0fb86a94 rc.apparmor.functions: check command exit status directly
Thanks, shellcheck!
2022-02-13 19:43:48 +00:00
intrigeri
0bae8bf82a rc.apparmor.functions: disable shellcheck false positive 2022-02-13 19:43:48 +00:00
intrigeri
8eeb8c48c5 rc.apparmor.functions: quote to prevent word splitting and syntax error on empty output
Thanks, shellcheck!
2022-02-13 19:43:48 +00:00
Christian Boltz
0f194ca1a0 Merge Remove unused init scripts, minor improvement to Slackware init script output
Based on !418, where all these changes have been discussed already.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/845
Acked-by: Christian Boltz <apparmor@cboltz.de>
Merged-by: Christian Boltz <apparmor@cboltz.de>
2022-02-13 18:39:23 +00:00
Christian Boltz
a744564fa4 Merge Drop superfluous shebang from python module
Found by rpmlint.

I propose this fix for 3.0 and master to keep the file in sync.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/846
Acked-by: Approved-by: intrigeri <intrigeri@boum.org> for 3.0 and master
Merged-by: Christian Boltz <gitlab2@cboltz.de>
2022-02-13 18:34:56 +00:00
Christian Boltz
749234f5a1 Drop superfluous shebang from python module
Found by rpmlint.
2022-02-13 18:29:34 +01:00
intrigeri
2019519e34 Delete Red Hat initscript
Even if there are Red Hat / Fedora systems that use AppArmor, chances are that
they use systemd, and not an initscript. And even if somehow they do use an
initscript, chances are that it's not this one, as last time it has seen
a non-cosmetic change was in 2007.
2022-02-13 16:53:44 +00:00
Chris Novakovic
7f64db1f19 Display improvements in rc.apparmor.functions
* Don't call aa_log_action_end after calling aa_log_failure_msg, because
  a generic "failure" message will be outputted twice by the Red Hat and
  Slackware init scripts.
* Don't append a space to the initial output from apparmor_stop, in line
  with other usages of aa_log_daemon_msg.
2022-02-13 16:53:27 +00:00
Chris Novakovic
2f2eab3b21 Remove Debian init script
Debian doesn't use the init script provided in parser/rc.apparmor.debian,
instead preferring to patch parser/rc.apparmor.functions and call its
functions directly in an init script they maintain themselves (something
they have done since 2006). Since this script is no longer used, and
currently doesn't work correctly anyway because it lacks definitions for
several functions that are relied upon in parser/rc.apparmor.functions,
it can be removed.
2022-02-13 16:53:22 +00:00
intrigeri
c7e68d7009 Import profile-load script from Debian
This script is used at least by LXC upstream and MySQL in Debian:
https://codesearch.debian.net/search?q=%2Flib%2Fapparmor%2Fprofile-load

Presumably it could be useful elsewhere if it was more readily available.
2022-02-12 10:34:38 +00:00
intrigeri
c44e93d856 Make the systemd unit a no-op in containers with no internal policy 2022-02-12 10:23:39 +00:00
intrigeri
bd06a9d214 Add .desktop file for aa-notify
This allows distributions to start aa-notify automatically,
should they wish so.
2022-02-12 09:34:26 +00:00
Jamie Strandboge
9505724d72 Allow access to socket directory used by recent ibus-daemon 2022-02-12 08:38:23 +00:00
intrigeri
9af832f48a smbd: include snippet generated at runtime on Debian 2022-02-12 08:36:10 +00:00
John Johansen
fb35ee4efc Merge aa-remove-unknown: abort on parser failure
If `apparmor_parser -N` (in `profiles_names_list()`) fails,
`aa-remove-unknown` possibly gets an incomplete list of profiles in
`/etc/apparmor.d/` and therefore might remove more profiles than it
should.

Replace the `profiles_names_list()` call with a direct `apparmor_parser`
call, and abort aa-remove-unknown if it exits with $? != 0

Before:
```
aa-remove-unknown -n
AppArmor parser error for /etc/apparmor.d/broken in profile /etc/apparmor.d/broken at line 1: syntax error, unexpected TOK_ID, expecting TOK_OPEN
Would remove 'delete_me'
```

After:
```
./aa-remove-unknown -n
AppArmor parser error for /etc/apparmor.d in profile /etc/apparmor.d/zbroken at line 1: syntax error, unexpected TOK_ID, expecting TOK_OPEN
apparmor_parser exited with failure, aborting.
```

And of course, after fixing the broken profile:
```
./aa-remove-unknown -n
Would remove 'delete_me'
```

Also drop the now-unused profiles_names_list() from rc.apparmor.functions - the only user was aa-remove-unknown.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/836
Acked-by:  John Johansen <john@jjmx.net>
Merged-by: John Johansen <john@jjmx.net>
2022-02-11 22:55:41 +00:00
Christian Boltz
db0a8aacd5 Drop now-unused profiles_names_list() from rc.apparmor.functions
The only user was aa-remove-unknown - until the previous commit.
2022-02-11 22:59:01 +01:00
Christian Boltz
5053a01d84 aa-remove-unknown: abort on parser failure
If apparmor_parser -N (in profiles_names_list()) fails,
aa-remove-unknown possibly gets an incomplete list of profiles in
/etc/apparmor.d/ and therefore might remove more profiles than it
should.

Replace the profiles_names_list() call with a direct apparmor_parser
call, and abort aa-remove-unknown if it exits with $? != 0

Before:
```
aa-remove-unknown -n
AppArmor parser error for /etc/apparmor.d/broken in profile /etc/apparmor.d/broken at line 1: syntax error, unexpected TOK_ID, expecting TOK_OPEN
Would remove 'delete_me'
```

After:
```
./aa-remove-unknown -n
AppArmor parser error for /etc/apparmor.d in profile /etc/apparmor.d/zbroken at line 1: syntax error, unexpected TOK_ID, expecting TOK_OPEN
apparmor_parser exited with failure, aborting.
```

And of course, after fixing the broken profile:
```
./aa-remove-unknown -n
Would remove 'delete_me'
```
2022-02-11 22:59:01 +01:00
John Johansen
e726ebe376 Merge Drop unused failstop_system() from rc.apparmor.functions
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/835
Acked-by: John Johansen <john@jjmx.net>
Merged-by: John Johansen <john@jjmx.net>
2022-02-11 08:28:07 +00:00
John Johansen
872747f173 Merge Simplify profiles_names_list()
... which is used by aa-remove-unknown.

apparmor_parser can read a whole directory, therefore we don't need to
do the directory listing, excluding *.rpmnew etc. ourself.

Also drop the now-unused skip_profile()

Related to https://gitlab.com/apparmor/apparmor/-/issues/148

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/834
Acked-by: John Johansen <john@jjmx.net>
Merged-by: John Johansen <john@jjmx.net>
2022-02-11 08:27:07 +00:00
Christian Boltz
8e1a4924d5 Drop unused failstop_system() from rc.apparmor.functions 2022-02-10 23:45:20 +01:00
John Johansen
2ba5575f7b libapparmor: sync library version change with the 3.0.4 release
Library versioning requires we keep these changes in sync. Since the
3.0.4 release bumped revision we need to do it here as well.

Signed-off-by: John Johansen <john.johansen@canonical.com>
2022-02-10 14:20:06 -08:00
Christian Boltz
8476786252 Drop skip_profile()
Its last user was profiles_names_list(), but since the previous commit
it lets apparmor_parser do this job.

Related to https://gitlab.com/apparmor/apparmor/-/issues/148
2022-02-10 22:56:16 +01:00
Christian Boltz
d38376c9c4 Simplify profiles_names_list()
... which is used by aa-remove-unknown.

apparmor_parser can read a whole directory, therefore we don't need to
do the directory listing, excluding *.rpmnew etc. ourself.

Related to https://gitlab.com/apparmor/apparmor/-/issues/148
2022-02-10 22:53:48 +01:00
John Johansen
9aa1a5b492 Merge Drop now-obsolete comment about skip_profile()
... which became superfluous after dropping use of xargs as fallback
when loading profiles in 0b8ea047e8

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/833
Acked-by: Approved-by: Jon Tourville <jon.tourville@canonical.com>
Merged-by: John Johansen <john@jjmx.net>
2022-02-09 18:32:44 +00:00
Christian Boltz
5527c20833 Drop now-obsolete comment about skip_profile()
... which became superfluous after dropping use of xargs as fallback
when loading profiles in 0b8ea047e8
2022-02-09 18:32:51 +01:00
John Johansen
5041a6235a Merge Add 'mctp' network domain keyword
Reported as comment on https://build.opensuse.org/request/show/951354
(update to glibc 2.35)

I propose this patch for at least 3.0 and master. Backporting it to older releases can't hurt, even if seeing a new-enough glibc or kernel with them is less likely.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/832
Acked-by: John Johansen <john@jjmx.net>
Merged-by: John Johansen <john@jjmx.net>
2022-02-08 18:20:59 +00:00
Christian Boltz
977af8c5ac Add 'mctp' network domain keyword
Reported as comment on https://build.opensuse.org/request/show/951354
(update to glibc 2.35)
2022-02-08 19:09:24 +01:00
John Johansen
7cde91f57f libapparmor: fix building with link time optimization (lto)
Currently libapparmor fails to build when lto is used because it uses
the asm directive to provide different version of some symbols.
Unfortunately gcc does not recognize this and the symbols defined by
asm are lost and optimized out by lto and then the link fails.

Fixes: https://gitlab.com/apparmor/apparmor/-/issues/214
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/831
Signed-off-by: John Johansen <john.johansen@canonical.com>
2022-02-04 15:01:36 -08:00
John Johansen
72c06c4d35 Merge Enable AppArmor to run properly under WSL/systemd
The AppArmor systemd scripts correctly detect the Windows Subsystem for Linux as a container, since all Linux distros executing under WSL 2 are containerized; however, unlike the majority of containers (since there is no accessible host distribution above them trying to set AppArmor policies that might interfere), AppArmor itself functions without problems in the WSL environment.

This patch adds WSL detection to the is_container_with_internal_policy function, allowing AppArmor to be started and operate normally in a WSL-plus-systemd environment.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/812
Acked-by: John Johansen <john@jjmx.net>
2022-02-04 10:25:14 +00:00
John Johansen
0b8ea047e8 rc.apparmor: drop use of xargs as fallback when loading profiles
LP:1377338 <https://bugs.launchpad.net/ubuntu/+source/apparmor/+bug/1377338>

has been fixed for quite awhile and we don't need to call xargs as
a fallback when loading policy fails.

In addition we really don't want to be doing this because we want to
be moving to atomic profile loads where if one profile fails the
whole load fails. This is a step in that direction.

Signed-off-by: John Johansen <john.johansen@canonical.com>
Acked-by: Christian Boltz <apparmor@cboltz.de>
2022-02-04 02:22:39 -08:00
John Johansen
08f32ac703 Merge Fix: Opening links with Chrome
Permission denied when Evince tries to use Chrome to open link.

In config is missing the bin: `/opt/google/chrome/crashpad_handler`.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/830
Acked-by: John Johansen <john@jjmx.net>
2022-02-04 10:14:31 +00:00
Cristiano Nunes
f0d3d6748f Fix: Opening links with Chrome 2022-02-03 09:42:36 -03:00
Georgia Garcia
64703c7158 Merge tests: add attach_disconnected tests
This test uses unix_fd_server to open a file and pass
its file descriptor to the attach_disconnected tests, which
then mounts, pivots root and then tries to open the file.

Since the server execs the client, this MR also inverts the order
of the parameters to allow the server to forward the client's args
along with the unix_socket path.

I'm also refactoring out the unix_fd_client logic into unix_fd_common,
so we can use this implementation when creating other clients, which is the case
for the test binary attach_disconnected

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/810
Acked-by: Approved-by: John Johansen <john@jjmx.net>
Merged-by: Georgia Garcia <georgia.garcia@canonical.com>
2022-01-27 13:48:18 +00:00
Georgia Garcia
cb4a397b1e tests: add attach_disconnected tests
This test uses unix_fd_server to open a file and pass
its file descriptor to the attach_disconnected tests, which
then mounts, pivots root and then tries to open the file.

Since the server execs the client, this commit also inverts the order
of the parameters to allow the server to forward the client's args
along with the unix_socket path.

Signed-off-by: Georgia Garcia <georgia.garcia@canonical.com>
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/810
Acked-by: John Johansen <john.johansen@canonical.com>
2022-01-27 10:36:14 -03:00
Georgia Garcia
b07a532a6f unix_fd_common tests: refactor out unix_fd_client code into common
The code from unix_fd_client can be used by other clients which
will receive the fd of a file using SCM rights.

Signed-off-by: Georgia Garcia <georgia.garcia@canonical.com>
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/810
Acked-by: John Johansen <john.johansen@canonical.com>
2022-01-27 10:35:29 -03:00
John Johansen
a19ff53674 Merge tests: disable file query test for kernels that don't provide the query feature
The file query test on query_label.sh fails on kernels
before 4.4 because of the lack of support. Since there
is no feature file to examine for this feature, we
needed to check for the kernel version. Refer to [qa-regression-testing](https://git.launchpad.net/qa-regression-testing/tree/scripts/test-apparmor.py#n1653).

As discussed on !767, we might need a more complicated test than
only checking for the kernel version, since this feature might
be available in out-of-tree Ubuntu kernels such as saucy (3.13).

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/769
Acked-by: John Johansen <john@jjmx.net>
2022-01-27 08:38:46 +00:00
John Johansen
d9afe25a0d Merge add snap-browsers profile
Whenever the evince deb package tries to open a snap browser which was
selected as the default, we get the following denial:

audit[2110]: AVC apparmor="DENIED" operation="exec" profile="/usr/bin/evince" name="/usr/bin/snap" pid=2110 comm="env" requested_mask="x" denied_mask="x" fsuid=1000 ouid=0

As a short-term solution, we are adding a snap-browsers profile
which restricts what snaps opened by evince can do.
The long-term solution is currently not available, but could be
accomplished by using enhanced environment variable filtering/mediation
and delegation of open fds.

Bug: https://launchpad.net/bugs/1794064

Signed-off-by: Georgia Garcia <georgia.garcia@canonical.com>
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/806
Acked-by: John Johansen <john@jjmx.net>
2022-01-27 08:35:05 +00:00
John Johansen
c67681a5a9 Merge Add the GTK abstraction
GTK/QT apps need to read some config files in order to properly render their windows in a graphical session. There are some `qt5` abstractions already, but it looks like the `gtk` abstraction is missing.

The `*gtk*` rules are basically the location of the GTK config files I found on the internet when I was trying to compose this abstraction. Some of the paths are missing in Debian, but different distros can use (or were using) them. Since GTK apps use themes, the abstraction also include the whole `/usr/share/themes/` , `@{HOME}/.themes/` and `@{HOME}/.local/share/themes/` dirs. I'm not sure whether this should be tightened. The `.Xauthority` file is generally needed when you deal with GUI apps under Xserver. Also since all GUI apps redirect output/error to the `~/.xsession-errors` file, this file also was included here.

Fixes: https://gitlab.com/apparmor/apparmor/-/issues/65
Fixes: https://gitlab.com/apparmor/apparmor/-/issues/168
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/825
Acked-by: John Johansen <john.johansen@canonical.com>
2022-01-27 08:23:59 +00:00
John Johansen
6154925c62 Merge tests: add built test files to gitignore
The following files generated during the build were not ignored by git: aa_policy_cache at_secure dbus_common.o dbus_eavesdrop dbus_message dbus_service dbus_unrequested_reply fd_inheritance fd_inheritor introspect pivot_root query_label socketpair syscall_ioperm syscall_iopl transition unix_socket unix_socket_client unix_socket_common.o uservars.inc xattrs_profile

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/826
Signed-off-by: Georgia Garcia <georgia.garcia@canonical.com>
Acked-by: John Johansen <john.johansen@canonical.com>
2022-01-27 08:19:27 +00:00
John Johansen
1ca30e35b0 libapparmor: Fix ruby 3.1 build for libapparmor
The Hack used to build the libapparmor swig interface for ruby fails
with ruby 3.1.  Instead of trying to do black magic in ruby to rename
the generated Makefile to Makefile.new, just save off the Makefile
and restore after ruby's setup has been called.

Fixes: https://gitlab.com/apparmor/apparmor/-/issues/206
Signed-off-by: John Johansen <john.johansen@canonical.com>
Acked-by: Christian Boltz <apparmor@cboltz.de>
2022-01-26 23:12:27 -08:00
John Johansen
0e52b555ae Merge init: make xargs invocation busybox-compatible
busybox xargs does not have -d nor long --max-procs options, instead use -0 (and separate arguments with printf "%s\\0") and -P which are more portable. While we are here, also add -r (--no-run-if-empty, which also has no long equivalent for busybox) as we likely don't want to run anything if no profile were found

This is useful for alpine systems where findutils is not installed by default, but busybox xargs is available.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/828
Acked-by: John Johansen <john.johansen@canoical.com>
2022-01-27 03:23:50 +00:00
Dominique Martinet
76163f801d init: make xargs invocation busybox-compatible
busybox xargs does not have -d nor long --max-procs options,
instead use -0 (and separate arguments with printf "%s\0")
and -P which are more portable.
While we are here, also add -r (--no-run-if-empty, which also has
no long equivalent for busybox) as we likely don't want to run
anything if no profile were found

This is useful for alpine systems where findutils is not installed by
default, but busybox xargs is available.
2022-01-27 11:48:05 +09:00
Georgia Garcia
c0ee4a9a8a tests: add built test files to gitignore
The following files generated during the build were not ignored by git:
  aa_policy_cache
  at_secure
  dbus_common.o
  dbus_eavesdrop
  dbus_message
  dbus_service
  dbus_unrequested_reply
  fd_inheritance
  fd_inheritor
  introspect
  pivot_root
  query_label
  socketpair
  syscall_ioperm
  syscall_iopl
  transition
  unix_socket
  unix_socket_client
  unix_socket_common.o
  uservars.inc
  xattrs_profile

Signed-off-by: Georgia Garcia <georgia.garcia@canonical.com>
2022-01-26 11:00:41 -03:00
Mikhail Morfikov
93d49a3945 add the GTK abstraction 2022-01-21 18:37:22 +01:00
John Johansen
457ab38b93 aa-status: fix crash due to \n in profile name
This fixes a crash when a profile name contains a \n character which
breaks profile name parsing. The fix is minimal in that it ignores
the bad profile name and continues processing.

Ideally this name would not exist and is indicative of a bug in the kernel.

Fixes: https://gitlab.com/apparmor/apparmor/-/issues/211
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/824
Signed-off-by: John Johansen <john.johansen@canonical.com>
Acked-by: Christian Boltz <apparmor@cboltz.de>
2022-01-20 13:40:02 -08:00
Christian Boltz
90b312c55a Merge branch 'cboltz-samba-lmb2' into 'master'
abstractions/samba: allow ldb2 paths

See merge request apparmor/apparmor!821

Note: https://bugzilla.opensuse.org/show_bug.cgi?id=1192684 was made public in the meantime.

Acked-by: Jon Tourville <jon.tourville@canonical.com>
2022-01-18 12:53:52 +00:00
John Johansen
2b270216aa Merge abstractions/openssl: allow /etc/ssl/{engdef,engines}.d/
These directories were introduced in openssl in https://patchwork.ozlabs.org/project/openwrt/patch/20210429153530.10020-2-cotequeiroz@gmail.com/

I propose this patch for 3.0 and master. Optionally also for older branches, even if it's unlikely that systems using 2.13.x or older get a new-enough openssl to need this ;-)

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/818
Acked-by: John Johansen <john.johansen@canonical.com>
2022-01-17 20:07:29 +00:00
Christian Boltz
901f2ea9cd abstractions/samba: allow ldb2 paths
libldb packaging in openSUSE changes to use "ldb2" in the path, adjust
the abstraction accordingly.

Patch by Samuel Cabrero <scabrero@suse.de>
via https://build.opensuse.org/request/show/947009

References:
- https://bugzilla.opensuse.org/show_bug.cgi?id=1192684 (non-public)
- https://build.opensuse.org/request/show/946250 (ldb packaging change)
- https://build.opensuse.org/request/show/946251 (samba packaging change)
2022-01-17 20:03:13 +01:00
Christian Boltz
cf35cfe8c2 Merge branch 'cboltz-tunables-order' into 'master'
Define @{HOMEDIRS} before using it in @{HOME}

See merge request apparmor/apparmor!820

Acked-by: Georgia Garcia  <georgia.garcia@canonical.com>
2022-01-06 12:22:58 +00:00
Christian Boltz
867d32950e Define @{HOMEDIRS} before using it in @{HOME}
The old order is not really wrong / a bug because the order doesn't
matter, but defining the variables it in the "right" order helps to
prevent confusion.

Fixes: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=1003158
2022-01-05 21:00:50 +01:00
Christian Boltz
fc4d1f76fa Merge branch 'bsc1192336' into 'master'
profiles/apparmor.d: Fix file_mmap violation for bsc#1192336.

See merge request apparmor/apparmor!819

Acked-by: Christian Boltz <apparmor@cboltz.de> for 3.0 and master
2021-12-20 18:06:40 +00:00
Noel Power
e19abd3bdf profiles/apparmor.d: Fix file_mmap violation for bsc#1192336.
- Fix 'apparmor="DENIED" operation="file_mmap" profile="samba-bgqd"
      name="/usr/lib64/samba/samba-bgqd" pid=2876 comm="samba-bgqd"
      requested_mask="m" denied_mask="m" fsuid=0 ouid=0'

entries appearing in SLE15-SP4

Signed-off-by: Noel Power <noel.power@suse.com>
2021-12-20 15:01:19 +00:00
Christian Boltz
e58dd798f0 abstractions/openssl: allow /etc/ssl/{engdef,engines}.d/
These directories were introduced in openssl in
https://patchwork.ozlabs.org/project/openwrt/patch/20210429153530.10020-2-cotequeiroz@gmail.com/
2021-12-19 22:36:05 +01:00
Christian Boltz
4cbd2684b8 Merge branch 'cboltz-aa-dict' into 'master'
Change 'aa' from hasher to dict

See merge request apparmor/apparmor!817

Acked-by: Jon Tourville <jon.tourville@canonical.com>
2021-12-14 18:21:35 +00:00
Christian Boltz
529c408d9e Merge branch 'cboltz-abstractions-python' into 'master'
abstractions/python: merge /usr/ and /usr/local/ rules, and add some new rules

See merge request apparmor/apparmor!814

Acked-by: Georgia Garcia <georgia.garcia@canonical.com>
2021-12-13 17:02:46 +00:00
Christian Boltz
32acb228f9 Change 'aa' from hasher to dict
If there's still some code left that tries to access an uninitialized
item in 'aa' (reading or writing), this will result in a very visible
crash instead of silently seeming to work.

Testing shows that we seem to correctly initialize each item in 'aa' (no
crashes), therefore let's hope the best ;-)
2021-12-11 20:24:41 +01:00
Christian Boltz
ebd4143ca2 Merge branch 'cboltz-parser-typo' into 'master'
Fix comment typo in parser/lib.c

See merge request apparmor/apparmor!815

Acked-by: Jon Tourville <jon.tourville@canonical.com>
2021-12-07 18:45:01 +00:00
Christian Boltz
854cbae52e Fix comment typo in parser/lib.c 2021-12-05 18:16:53 +01:00
Christian Boltz
cac848e240 abstractions/python: add several permissions
- allow reading *.so.*
- allow directory listings in .../site-packages/
- allow reading various metadata files

These additions are based on denials seen on openSUSE Leap 15.3 with
python 3.9.
2021-12-04 20:54:52 +01:00
Christian Boltz
5491b75872 abstractions/python: merge /usr/ and /usr/local/ rules
This keeps all existing permissions, and adds a few that were out of
sync:
- /usr/lib*/python3.*/lib-dynload/*.so missed 3.1[0-9]
- /usr/lib/python3/... was missing, only /usr/local/python3/ was allowed
2021-12-04 20:09:52 +01:00
Georgia Garcia
21e5a721ab replace deprecated distutils with setuptools
Adds python3 setuptools as a build dependency for libapparmor

Fixes: https://gitlab.com/apparmor/apparmor/-/issues/202
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/813
Signed-off-by: Georgia Garcia <georgia.garcia@canonical.com>
Acked-by: Christian Boltz <apparmor@cboltz.de>
2021-11-11 20:23:35 -03:00
Alistair Young
a6360d9db2 Add explicit WSL detection to is_container_with_internal_policy 2021-11-08 21:21:09 +00:00
John Johansen
ca276d2bfd Merge Add support for reading s390x and aarch64 wtmp file
Both aarch64 and s390x have a bigger wtmp record size (16 bytes more than x86_64, 400 bytes total).

The byte position of the timestamp is also different on each architecture. To make things even more interesting, s390x is big endian.

Note that this MR includes more things, like
* moving `get_last_login_timestamp()` to the new `apparmor/notify.py` file
* add unit tests for it
* add wtmp example files from various architectures, including a hand-edited one claiming to be from 1999
* fixing a bug in `get_last_login_timestamp()` that unpacked `type` from too many bytes - which accidently worked on x86_64
* detecting from which architecture the wtmp file comes (luckily the timestamps are located at different locations)

See the individual commits for details.

Fixes: https://bugzilla.opensuse.org/show_bug.cgi?id=1181155
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/809
Acked-by: John Johansen <john.johansen@canonical.com>
2021-11-08 20:50:34 +00:00
John Johansen
ee9e61aad2 Merge Add missing /proc permissions to avahi-daemon profile
Fixes: https://gitlab.com/apparmor/apparmor/-/issues/203

MR:https://gitlab.com/apparmor/apparmor/-/merge_requests/811
Acked-by: John Johansen <john.johansen@canonical.com>
2021-10-30 09:16:37 +00:00
Christian Boltz
8c1243e43f Add missing /proc permissions to avahi-daemon profile
Fixes: https://gitlab.com/apparmor/apparmor/-/issues/203
2021-10-26 13:54:51 +02:00
Christian Boltz
1da0305c89 Add tests for sane_timestamp
Ensure that pre-2000 and post-2050 dates get rejected, and something in
between gets accepted.

This also extends coverage to 100% - before, the post-2050 branch was
not covered.
2021-10-24 17:24:43 +02:00
Christian Boltz
63f1a58bef Add truncated and ancient wtmp example to tests
A too-small file can't contain something useful.

Also, a wtmp file with a timestamp from pre-2000 is beyond what you'd
expect on a 2021 system.
2021-10-24 17:24:43 +02:00
Christian Boltz
255716b90a Add support for reading s390x and aarch64 wtmp file
Both aarch64 and s390x have a bigger wtmp record size (16 bytes more
than x86_64, 400 bytes total).

The byte position of the timestamp is also different on each
architecture. To make things even more interesting, s390x is big endian.

Fixes: https://bugzilla.opensuse.org/show_bug.cgi?id=1181155
2021-10-24 17:24:43 +02:00
Christian Boltz
f79b335b6c fix reading 'type' from wtmp
'type' is a short (see "ut_type" in wtmp(5)), therefore only read two
bytes and unpack them as short. Afterwards read two padding bytes to
/dev/null.

This accidently worked on x86_64 because it's little endian, but will
fail on big endian architectures.
2021-10-24 17:24:43 +02:00
Christian Boltz
905b89a5c7 Add unittest for get_last_login_timestamp
... starting with a x86_64 wtmp example file
2021-10-24 14:23:53 +02:00
Christian Boltz
6dc9884c8e Move get_last_login_timestamp() into apparmor.notify
This is a preparation to make adding tests easier.
2021-10-24 14:23:15 +02:00
John Johansen
b6551618d8 Merge Generate af_names.h similar to cap_names.h
This adds a base_af_names.h file similar to base_cap_names.h to support newer address families in policy when built against older headers.

Fixes: https://gitlab.com/apparmor/apparmor/-/issues/195
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/808
Acked-by: John Johansen <john.johansen@canonical.com>
2021-10-20 21:16:24 +00:00
Jon Tourville
90620cb64f Generate af_names.h similar to cap_names.h 2021-10-18 15:55:57 -05:00
Georgia Garcia
fb3283f37e add snap-browsers profile
Whenever the evince deb package tries to open a snap browser which was
selected as the default, we get the following denial:

audit[2110]: AVC apparmor="DENIED" operation="exec" profile="/usr/bin/evince" name="/usr/bin/snap" pid=2110 comm="env" requested_mask="x" denied_mask="x" fsuid=1000 ouid=0

As a short-term solution, we are adding a snap-browsers profile
which restricts what snaps opened by evince can do.
The long-term solution is currently not available, but could be
accomplished by using enhanced environment variable filtering/mediation
and delegation of open fds.

Bug: https://launchpad.net/bugs/1794064

Signed-off-by: Georgia Garcia <georgia.garcia@canonical.com>
2021-10-18 09:44:52 -03:00
John Johansen
9d14d6ebfb Merge abstractions/samba: allow use of /run/lock/samba
Some distros use /run/lock/samba as the Samba lock directory, so allow
that in the samba abstraction in addition to /run/samba.

MR: https://gitlab.com/apparmor/apparmor!805
Acked-by: John Johansen <john.johansen@canonical.com>
2021-10-16 07:10:09 +00:00
John Johansen
8db7e70395 Merge Add profile for samba-bgqd
... and some rules in the smbd profile to execute it and send it a term
signal.

samba-bgqd is (quoting its manpage) "an internal helper program
performing asynchronous printing-related jobs."

samba-bgqd was added in Samba 4.15.

Fixes: https://bugzilla.opensuse.org/show_bug.cgi?id=1191532
MR: https://gitlab.com/apparmor!807
Acked-by: John Johansen <john.johansen@canonical.com>
2021-10-16 07:02:34 +00:00
Christian Boltz
85e53a5d04 Add profile for samba-bgqd
... and some rules in the smbd profile to execute it and send it a term
signal.

samba-bgqd is (quoting its manpage) "an internal helper program
performing asynchronous printing-related jobs."

samba-bgqd was added in Samba 4.15.

Fixes: https://bugzilla.opensuse.org/show_bug.cgi?id=1191532
2021-10-15 22:06:05 +02:00
Cameron Nemo
f5c9003d41 abstractions/samba: allow use of /run/lock/samba
Some distros use /run/lock/samba as the Samba lock directory, so allow
that in the samba abstraction in addition to /run/samba.
2021-10-05 22:51:18 -07:00
Steve Beattie
a24cda5ae1 binutils/aa-features-abi: fix a couple of minor issues
A small patch set to fix two issues with binutils/aa-features-abi:

1. The `aa-features-abi -f` short argument was not added to the
   `getopt_long()` set of short arguments, resulting in the command
   incorrectly failing when passed -f

2. Due to variable shadowing the file descriptor for the `--file`
   argument was not being autoclosed.

- binutils/aa-features-abi: make -f short arg actually be accepted
- binutils/aa-features-abi: fix failure to close fd due to shadowed
  var decl

Signed-off-by: Steve Beattie <steve.beattie@canonical.com>
Acked-by: John Johansen <john.johansen@canonical.com>
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/804
2021-09-27 13:09:17 -07:00
Steve Beattie
ffc6529bef binutils/aa-features-abi: fix failure to close fd due to shadowed var decl
The variable used to store the file descriptor for the --file ended up
being declared twice, resulting in the autoclose attribute attached to
the first declaration being removed by the shadowed second declaration.
Fix this by converting the second declaration to just be an assignment,
as was intended.

strace output before:

  [...]
  ) = 1925
  close(1)                                = 0
  exit_group(0)                           = ?
  +++ exited with 0 +++

strace output after removing shadow declaration:

  ) = 1925
  close(1)                                = 0
  close(3)                                = 0
  exit_group(0)                           = ?
  +++ exited with 0 +++

(File descriptor 3 is what is returned by the open() call on the
 --file argument.)

Signed-off-by: Steve Beattie <steve.beattie@canonical.com>
Acked-by: John Johansen <john.johansen@canonical.com>
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/804
2021-09-27 13:07:11 -07:00
Steve Beattie
8137beb265 binutils/aa-features-abi: make -f short arg actually be accepted
The aa-features-abi -f short argument was not added to the
getopt_long() set of short arguments, resulting in the command
incorrectly failing like so:

  $ ./aa-features-abi -f /etc/apparmor.d/abi/3.0
  ./aa-features-abi: invalid option -- 'f'
  USAGE: ./aa-features-abi [OPTIONS] <SOURCE> [OUTPUT OPTIONS]
  [...]

The long --file option works as expected.

Fix this by adding f to the set of short arguments passed to
getopt_long().

Signed-off-by: Steve Beattie <steve.beattie@canonical.com>
Acked-by: John Johansen <john.johansen@canonical.com>
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/804
2021-09-27 13:05:59 -07:00
Christian Boltz
b0bc0d5323 Merge branch 'fix-lexer' into 'master'
parser: Fix unknown state condition RLIMIT_MODEINCLDE

See merge request apparmor/apparmor!803

Acked-by: Christian Boltz for all branches
2021-09-24 11:26:21 +00:00
John Johansen
dc7755e544 parser: Fix unknown state condition RLIMIT_MODEINCLDE
The parser is broken on RLIMIT parsing when receiving unexpected input
because the shared state for this specifies RLIMIT_MODEINCLUDE which
is an unknown start condition resulting in the following warning

  parser_lex.l:745: undeclared start condition RLIMIT_MODEINCLUDE

and also means RLIMIT and INCLUDE are not properly handled

Signed-off-by: John Johansen <john.johansen@canonical.com>
2021-09-24 00:48:27 -07:00
John Johansen
0700b47df8 Merge aa-unconfined: Improve fallback handling to attr/current
If /proc/*/attr/apparmor/current exists, only read that - instead of
falling back to /proc/*/attr/current if a process is for example
unconfined so that read_proc_current returns None.

Fixes: https://gitlab.com/apparmor/apparmor/-/issues/199
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/801
Acked-by: John Johansen <john.johansen@canonical.com>
2021-09-18 20:44:48 +00:00
Christian Boltz
f39d5c7c09 aa-unconfined: Improve fallback handling to attr/current
If /proc/*/attr/apparmor/current exists, only read that - instead of
falling back to /proc/*/attr/current if a process is for example
unconfined so that read_proc_current returns None.

Fixes: https://gitlab.com/apparmor/apparmor/-/issues/199
2021-09-18 19:02:56 +02:00
John Johansen
3b6257edea Merge dnsmasq: allow paths for podman dnsname plugin
The dnsname plugin in podman needs access to some files in
/run/containers/cni/dnsname/*/

This is also documented upstream:
https://github.com/containers/dnsname/blob/main/README_PODMAN.md
but nobody thought about telling us to just update the profile :-/

Fixes: https://bugzilla.opensuse.org/show_bug.cgi?id=1190271
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/800
Acked-by: John Johansen <john.johansen@canonical.com>
2021-09-16 21:33:02 +00:00
Christian Boltz
254ebacbd8 dnsmasq: allow paths for podman dnsname plugin
The dnsname plugin in podman needs access to some files in
/run/containers/cni/dnsname/*/

This is also documented upstream:
https://github.com/containers/dnsname/blob/main/README_PODMAN.md
but nobody thought about telling us to just update the profile :-/

Fixes: https://bugzilla.opensuse.org/show_bug.cgi?id=1190271
2021-09-16 23:10:38 +02:00
John Johansen
c37586cd11 Merge Avoid aa-notify crash on log events without operation=
Some STATUS log events trigger a crash in aa-notify because the log
line doesn't have operation=. Examples are:

    type=AVC msg=audit(1630913351.586:4): apparmor="STATUS" info="AppArmor Filesystem Enabled" pid=1 comm="swapper/0"

    type=AVC msg=audit(1630913352.610:6): apparmor="STATUS" info="AppArmor sha1 policy hashing enabled" pid=1 comm="swapper/0"

Fix this by not looking at log events without operation=

Also add one of the example events as libapparmor testcase.

Fixes: https://gitlab.com/apparmor/apparmor/-/issues/194
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/797
Acked-by: John Johansen <john.johansen@canonical.com>
2021-09-13 23:02:15 +00:00
John Johansen
92d5bec86e Merge libapparmor: fix debug build of log parsing
Fix log parsing for void Linux default log format.


Fixes: https://gitlab.com/apparmor/apparmor/-/issues/196
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/799
Georgia Garcia <georgia.garcia@canonical.com>
2021-09-13 22:58:28 +00:00
John Johansen
b32b898a9a libapparmor: fix log parsing for socklogd
The default log format for void linux is not handled by current log
parsing. The following example message results in an invalid record
error.

2021-09-11T20:57:41.91645 kern.notice: [  469.180605] audit: type=1400 audit(1631392703.952:3): apparmor="ALLOWED" operation="mkdir" profile="/usr/bin/kak" name="/run/user/1000/kakoune/" pid=2545 comm="kak" requested_mask="c" denied_mask="c" fsuid=1000 ouid=1000

This log message fails on parsing

  kern.notice:

which differs from the expect syslog format of
  host_name kernel:

Fixes: https://gitlab.com/apparmor/apparmor/-/issues/196
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/799
Signed-off-by: John Johansen <john.johansen@canonical.com>
2021-09-13 15:04:06 -07:00
John Johansen
1192dae561 libapparmor: fix memory leaks in logparsing
bison reports the follow warnings on the parser

/home/jj/apparmor/apparmor-jjohansen.git/libraries/libapparmor/src/grammar.y:245.48-62: warning: unused value: $4 [-Wother]
 	| syslog_date TOK_ID TOK_SYSLOG_KERNEL TOK_DMESG_STAMP TOK_AUDIT TOK_COLON key_type audit_id audit_user_msg_partial_tail
                                                ^^^^^^^^^^^^^^^
/home/jj/apparmor/apparmor-jjohansen.git/libraries/libapparmor/src/grammar.y:247.48-62: warning: unused value: $4 [-Wother]
 	| syslog_date TOK_ID TOK_SYSLOG_KERNEL TOK_DMESG_STAMP TOK_AUDIT TOK_COLON key_type audit_id audit_user_msg_tail
                                                ^^^^^^^^^^^^^^^
which it turns out are memory leaks.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/799
Signed-off-by: John Johansen <john.johansen@canonical.com>
2021-09-12 23:11:39 -07:00
John Johansen
4fe5387b69 libapparmor: fix debug build of log parsing
When building with YYDEBUG=1 the following failure occurs

grammar.y:49:46: error: unknown type name ‘no_debug_unused_’; did you mean ‘debug_unused_’?
 void aalogparse_error(unused_ void *scanner, no_debug_unused_ char const *s)
                                              ^~~~~~~~~~~~~~~~
                                              debug_unused_
g

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/799
Signed-off-by: John Johansen <john.johansen@canonical.com>
2021-09-12 23:11:31 -07:00
Christian Boltz
88595722f6 Avoid aa-notify crash on log events without operation=
Some STATUS log events trigger a crash in aa-notify because the log
line doesn't have operation=. Examples are:

    type=AVC msg=audit(1630913351.586:4): apparmor="STATUS" info="AppArmor Filesystem Enabled" pid=1 comm="swapper/0"

    type=AVC msg=audit(1630913352.610:6): apparmor="STATUS" info="AppArmor sha1 policy hashing enabled" pid=1 comm="swapper/0"

Fix this by not looking at log events without operation=

Also add one of the example events as libapparmor testcase.

Fixes: https://gitlab.com/apparmor/apparmor/-/issues/194
2021-09-06 16:54:33 +02:00
John Johansen
d11f2d5923 Merge Include local customization
The current setup for the profile sanitized_helper does not include a local
profile for adjustments.

Fixes: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=990499
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/796
Acked-by: John Johansen <john.johansen@canonical.com>
2021-09-03 11:59:12 +00:00
Shai4she
de5966671f Include local customization, cf. https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=990499 2021-09-03 08:27:02 +00:00
Steve Beattie
4559a2997c utils: Add new python versions to logprof.conf
Adding everything up to 3.19 should make the file future-proof for a
while ;-)

Fixes: https://gitlab.com/apparmor/apparmor/-/issues/193
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/795
Acked-by: Steve Beattie <steve.beattie@canonical.com>
2021-08-26 17:43:43 +00:00
Georgia Garcia
c8ff8799cc Merge cleanup imports from apparmor.common
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/794
Acked-by: Georgia Garcia <georgia.garcia@canonical.com>
2021-08-25 21:58:08 +00:00
Christian Boltz
b570e6134c Add new python versions to logprof.conf
Adding everything up to 3.19 should make the file future-proof for a
while ;-)

Fixes: https://gitlab.com/apparmor/apparmor/-/issues/193
2021-08-25 13:50:28 +02:00
Christian Boltz
0ee225b498 import hasher from apparmor.common
... instead of indirectly using it via apparmor.aa
2021-08-24 22:48:19 +02:00
Christian Boltz
c09e0b6ef3 import is_skippable_file from apparmor.common
... instead of indirectly using it via apparmor.aa
2021-08-24 22:47:39 +02:00
Christian Boltz
8b2fe01c7d aa-easyprof: use AppArmorException from apparmor.common
... instead of keeping an own version of it witht the exact same code
and a TODO note to use the one from common.

Also adjust the aa-easyprof tests to directly import AppArmorException
from apparmor.common.
2021-08-24 22:35:59 +02:00
Christian Boltz
79e7a204cf import AppArmorException from apparmor.common
... instead of indirectly using the one imported into apparmor.aa
2021-08-24 22:31:11 +02:00
Christian Boltz
7f64902f24 aa-unconfined: import specific items from apparmor.common
... instead of importing the whole apparmor.common
2021-08-24 22:20:27 +02:00
John Johansen
7711baae4a Merge aa-decode: use grep -E instead of egrep
egrep and fgrep are deprecated and will print a warning in the next grep release (3.8)

https://git.savannah.gnu.org/cgit/grep.git/commit/?id=a9515624709865d480e3142fd959bccd1c9372d1

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/792
Acked-by: John Johansen <john.johansen@canonical.com>
2021-08-24 08:29:04 +00:00
John Johansen
c258976ff8 Merge utils: use internal which implementation
* removes runtime dependency on which
* fixes aa-unconfined when ss is installed outside {/usr,}/bin

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/784
Signed-off-by: Michal Vasilek <michal.vasilek@nic.cz>
Acked-by: John Johansen <john.johansen@canonical.com>
2021-08-24 08:23:29 +00:00
Michal Vasilek
e8f3a1b878 aa-decode: use grep -E instead of egrep
egrep and fgrep are deprecated and will print a warning in the next grep
release (3.8)

https://git.savannah.gnu.org/cgit/grep.git/commit/?id=a9515624709865d480e3142fd959bccd1c9372d1
Signed-off-by: Michal Vasilek <michal.vasilek@nic.cz>
2021-08-24 10:16:29 +02:00
Michal Vasilek
c31d49234f utils: use internal which implementation
* removes runtime dependency on which
* fixes aa-unconfined when ss is installed outside {/usr,}/bin

Signed-off-by: Michal Vasilek <michal.vasilek@nic.cz>
2021-08-24 09:29:32 +02:00
John Johansen
1a190f2e30 Merge aa-remove-unknown: Drop superfluous $0 parameter from usage()
$0 is always the name of the script, even if using it inside a function.
Therefore use $0 directly, and no longer hand it over as a parameter.

Also `chmod +x aa-remove-unknown` to make in-tree testing easier.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/785
Acked-by: John Johansen <john.johansen@canonical.com>
2021-08-21 07:43:49 +00:00
John Johansen
5068f54cf1 Merge ProfileStorage: Store empty xattrs as empty string
... instead of None.

This avoids the need to allow type changes (None vs. str).

Also adjust the tests accordingly.

While on it, simplify the tests for attachment.

attachment is always a str, therefore adjust the test to expect an empty
str ('') instead of None - and later converting that None to ''.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/786
Acked-by: John Johansen <john.johansen@canonical.com>
2021-08-20 21:55:22 +00:00
John Johansen
572c342a2b Merge SeverityVarsTest: Make order of variable replacements constant
... using [] instead of {}

This should keep the order of checking (and therefore code coverage)
constant, and should fix the randomly appearing partial coverage in
severity.py handle_variable_rank(). In some random cases (depending in
which order the replacements were done and checked for their severity),
the coverage report indicated that the 'elif' condition was never false.

Note: This is only "coverage cosmetics". In "real users", it doesn't
matter in which order the variable replacements are checked because the
result doesn't depend on the ordering.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/790
Acked-by: John Johansen <john.johansen@canonical.com>
2021-08-20 21:52:23 +00:00
Christian Boltz
4fd7bcc289 Merge branch 'fix-video-abstraction' into 'master'
add a missing slash at the end of the sys rule

See merge request apparmor/apparmor!791

Acked-by: Christian Boltz <apparmor@cboltz.de> for 2.12..master
2021-08-20 18:16:03 +00:00
Mikhail Morfikov
b3dcd02dff add a missing slash at the end of the sys rule 2021-08-20 00:38:14 +02:00
Christian Boltz
d4b17ef904 SeverityVarsTest: Make order of variable replacements constant
... using [] instead of {}

This should keep the order of checking (and therefore code coverage)
constant, and should fix the randomly appearing partial coverage in
severity.py handle_variable_rank(). In some random cases (depending in
which order the replacements were done and checked for their severity),
the coverage report indicated that the 'elif' condition was never false.

Note: This is only "coverage cosmetics". In "real users", it doesn't
matter in which order the variable replacements are checked because the
result doesn't depend on the ordering.
2021-08-19 12:52:56 +02:00
Alex Murray
516733950e regression tests: fix aa_policy_cache when using system parser
When using the system parser ${parser_config} will be empty and so if this
is quoted when passed as  argument to the parser then this gets in
interpreted as the name of a file to be compiled and hence the parser just
prints:

File  not found, skipping...
File  not found, skipping...
File  not found, skipping...
...

for all the aa_policy_cache tests - instead fix this by just not quoting
this argument as suggested by cboltz.

This fixes the regression tests to run to completion without error when
USE_SYSTEM=1 is set.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/788
Signed-off-by: Alex Murray <alex.murray@canonical.com>
Acked-by: Christian Boltz <apparmor@cboltz.de>
2021-08-19 11:02:10 +09:30
Christian Boltz
131ae8425b Merge branch 'cboltz-typo' into 'master'
Fix typo in manpage

Closes #192

See merge request apparmor/apparmor!789

Acked-by: Acked-by: Seth Arnold <seth.arnold@canonical.com> for all branches
2021-08-17 18:25:51 +00:00
Christian Boltz
1459f49b7a Fix typo in manpage
Fixes: https://gitlab.com/apparmor/apparmor/-/issues/192
2021-08-17 19:43:53 +02:00
Christian Boltz
8cecc14d2d aa-remove-unknown: Drop superfluous $0 parameter from usage()
$0 is always the name of the script, even if using it inside a function.
Therefore use $0 directly, and no longer hand it over as a parameter.
2021-08-16 19:59:34 +02:00
Christian Boltz
169d305b2b chmod +x aa-remove-unknown 2021-08-16 19:59:34 +02:00
Christian Boltz
e69f46ac3f ProfileStorage: simplify tests for attachment
attachment is always a str, therefore adjust the test to expect an empty
str ('') instead of None - and later converting that None to ''.
2021-08-16 19:59:05 +02:00
Christian Boltz
337ebcd032 ProfileStorage: Store empty xattrs as empty string
... instead of None.

This avoids the need to allow type changes (None vs. str).

Also adjust the tests accordingly.
2021-08-16 19:59:02 +02:00
Georgia Garcia
bbe52a1eec Merge CI: always collect test artifacts
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/787

Acked-by: Georgia Garcia <georgia.garcia@canonical.com>
2021-08-16 13:51:12 +00:00
Christian Boltz
266ac13e10 CI: always collect test artifacts
The default is to collect them on success, but that's not helpful to
debug failure cases.
2021-08-15 16:28:35 +02:00
John Johansen
a79e800ebe Merge libapparmor:fix error value returned from features_lookup functions.
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/780
Acked-by: John Johansen <john.johansen@canonical.com>
2021-08-13 20:49:53 +00:00
John Johansen
31fda3eee7 Merge Update abstractions/python and profiles for python 3.10
Add support for python 3.10 in abstractions and profiles.

Fixes: https://gitlab.com/apparmor/apparmor/-/issues/187
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/783
Acked-by: John Johansen <john.johansen@canonical.com>
2021-08-13 20:13:59 +00:00
Steve Beattie
0db428a67b Revert "regression tests: fix aa_policy_cache when using system parser"
This reverts merge request !782
2021-08-12 06:59:41 +00:00
Steve Beattie
8d0b48df12 regression tests: fix aa_policy_cache when using system parser
Merge branch 'fix-policy-cache-regression-tests' into 'master'

When using the system parser ${parser_config} will be empty and so if this
is unconditionally passed as an argument to the parser then this gets in
interpreted as the name of a file to be compiled and hence the parser just
prints:

File  not found, skipping...
File  not found, skipping...
File  not found, skipping...
...

for all the aa_policy_cache tests - instead fix this to pass a single args
argument to the parser which will only include parser_config if it is not
empty.

This fixes the regression tests to run to completion without error when
USE_SYSTEM=1 is set.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/782
Signed-off-by: Alex Murray <alex.murray@canonical.com>
Acked-by: Steve Beattie <steve@nxnw.org>
2021-08-12 05:32:07 +00:00
Christian Boltz
ea7b201ba4 Update abstractions/python and profiles for python 3.10
Fixes: https://gitlab.com/apparmor/apparmor/-/issues/187
2021-08-11 21:37:40 +02:00
Alex Murray
0f2a33e7fb regression tests: fix aa_policy_cache when using system parser
When using the system parser ${parser_config} will be empty and so if this
is unconditionally passed as an argument to the parser then this gets in
interpreted as the name of a file to be compiled and hence the parser just
prints:

File  not found, skipping...
File  not found, skipping...
File  not found, skipping...
...

for all the aa_policy_cache tests - instead fix this to pass a single args
argument to the parser which will only include parser_config if it is not
empty.

This fixes the regression tests to run to completion without error when
USE_SYSTEM=1 is set.

Signed-off-by: Alex Murray <alex.murray@canonical.com>
2021-08-11 18:02:36 +09:30
John Johansen
bbdd563955 library: bump version number to stay in sync with 3.0.2 release
Signed-off-by: John Johansen <john.johansen@canonical.com>
2021-08-05 22:26:59 -07:00
John Johansen
8dce557f01 bump Version to indicate dev branch
Signed-off-by: John Johansen <john.johansen@canonical.com>
2021-08-05 22:25:47 -07:00
Georgia Garcia
656a48b900 tests: check for loopback module on pivot_root test
mount -o loop fails when the loopback module is not loaded with
permission denied. Add a check if /dev/loop0 exists. If not, load
the loop module.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/781
Signed-off-by: Georgia Garcia <georgia.garcia@canonical.com>
Acked-by: Christian Boltz <apparmor@cboltz.de>
2021-08-03 10:09:55 -03:00
Mingjun.Yang
348bb8b3d7 libapparmor:fix error value returned from features_lookup functions. 2021-07-31 11:21:47 +08:00
John Johansen
3f46d96aca libapparmor: fix comments about kernel exporte interfaces
Some basic fixes to comments, that were found after !713 was merged.

Fixes: https://gitlab.com/apparmor/apparmor/-/merge_requests/713
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/777
Signed-off-by: John Johansen <john.johansen@canonical.com>
Acked-by: Christian Boltz <apparmor@cboltz.de>
2021-07-22 14:24:00 -07:00
John Johansen
29215b4784 Merge libapparmor: Adjust stacking interface check
libapparmor performs a test for the new stacking interface, however
how it does this test is problematic as it requires all confined
tasks to be given read access to the task introspection interface.
This results in tasks needing to be given read access to the interface
even if they don't need it. Making it possible for tasks to discover
their confinement even if they are not supposed to be able to.
Instead change the check to using state on the parent directory.
This will generate a getattr request instead of read and make it
on the directory instead of on any interface file that could be
used to obtain information.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/713
Signed-off-by: John Johansen john.johansen@canonical.com
Acked-by: Timeout
2021-07-21 15:44:23 -07:00
John Johansen
a98469eb09 [7/7] abstractions: Make "available" readable as part of the enabled api
Understacking AppArmor if it is not the major LSM may set the enabled
field to false, to keep userspace from hitting the old shared proc
interfaces. The parameter "available" is added to indicate apparmor
is available but not present on the older interfaces.

Fixes: https://gitlab.com/apparmor/apparmor/-/issues/150
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/713
Signed-off-by: John Johansen <john.johansen@canonical.com>
2021-07-21 14:31:44 -07:00
John Johansen
c60fc809a9 [6/7] parser: update the parser to add interface rules for change_X
For change_hat and change_profile instead of a single interface
rule we need to add some readonly interfaces for discovery and
the new and old proc interface for writing.

Consolidate into a single shared routine.

Fixes: https://gitlab.com/apparmor/apparmor/-/issues/150
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/713
Signed-off-by: John Johansen <john.johansen@canonical.com>
2021-07-21 14:31:44 -07:00
John Johansen
35e58273e6 [5/7] libapparmor: rework trying original interface if new interface fails
Adjust the interface check and fallback. Unfortunately there is no
solution that will fix all failure cases. Instead try to minimize
the failure cases and bias towards failures that don't cause a
regression under an old parser/policy.

Note: In cases where we absolutely know the interface should not
      be accessed fail those accesses imediately instead of relying
      on what ever LSM active to handle it.

While we are at it document the interfaces and failure cases.

Fixes: https://gitlab.com/apparmor/apparmor/-/issues/150
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/713
Signed-off-by: John Johansen <john.johansen@canonical.com>
2021-07-21 14:31:44 -07:00
John Johansen
d0c4fc7d68 [4/7] libapparmor: fix available and enabled checks
Make it easier to separate errors from an actual answer, and ensure
we do a fallback check if there was an error.

Also fix the error code returned from aa_is_enabled() which got
broken by the addition of the private_enabled() check.

Finally make sure the private enabled error code is documented.

Fixes: https://gitlab.com/apparmor/apparmor/-/issues/150
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/713
Signed-off-by: John Johansen <john.johansen@canonical.com>
2021-07-21 14:31:44 -07:00
John Johansen
3fb4c4b876 [3/7] libapparmor: Fix AppArmor private interface availability check
The parameter that is landing upstream in "available" not
"private_enabled".

Also set the correct variable, as previously we were not.

Note: that skipping checking available for the private apparmor
proc interfaces is okay, as the dedicated apparmor interfaces will
fail correctly if available is False.

This just gives a clear way for userspace to query this info without
having to resort to error codes that access to the private interfaces
would return.

Fixes: https://gitlab.com/apparmor/apparmor/-/issues/150
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/713
Signed-off-by: John Johansen <john.johansen@canonical.com>
2021-07-21 14:31:44 -07:00
John Johansen
6c4ed2af8d [2/7] libapparmor: Adjust stacking interface check
libapparmor performs a test for the new stacking interface, however
how it does this test is problematic as it requires all confined
tasks to be given read access to the task introspection interface.

This results in tasks needing to be given read access to the interface
even if they don't need it. Making it possible for tasks to discover
their confinement even if they are not supposed to be able to.

Instead change the check to using stat on the parent directory.
This will generate a getattr request instead of read and make it
on the directory instead of on any interface file that could be
used to obtain information.

Fixes: https://gitlab.com/apparmor/apparmor/-/issues/150
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/713
Signed-off-by: John Johansen <john.johansen@canonical.com>
2021-07-21 14:31:44 -07:00
John Johansen
0be67ec840 [1/7] libapparmor: fix check for asprintf failure in proc init fn()
The fn() handling proc base address init is not checking for asprintf
failure. Fix it.

Fixes: https://gitlab.com/apparmor/apparmor/-/issues/150
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/713
Signed-off-by: John Johansen <john.johansen@canonical.com>
2021-07-21 14:31:44 -07:00
John Johansen
d8ec3dafb7 Merge allow Prometheus metrics end-point in dovecot/stats
Patch by Michael Ströder <michael@stroeder.com>

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/776
Acked-by: John Johansen <john@jjmx.net>
2021-07-21 19:28:41 +00:00
Christian Boltz
f3dd0d1911 allow Prometheus metrics end-point in dovecot/stats
Patch by Michael Ströder <michael@stroeder.com>
2021-07-19 22:36:28 +02:00
Jon Tourville
598131696e Merge Parser check fix
This resolves an issue in the parser's job handling when running on a machine with >8 CPU cores. The test library was updated to resolve failures in the caching tests caused by the features directory entries being unsorted in the tests.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/775
Acked-by: John Johansen [john@jjmx.net](mailto:john@jjmx.net)
2021-07-19 20:01:57 +00:00
Jon Tourville
efe39e7590 parser: fix comment for jobs_max default value 2021-07-19 13:53:09 -05:00
John Johansen
710bf66e51 Merge Allow reading /etc/login.defs.d/ in abstraction/authentication
This directory can include login.defs config sniplets in openSUSE
Tumbleweed.

References: https://bugzilla.opensuse.org/show_bug.cgi?id=1188296

See also
https://en.opensuse.org/openSUSE:Packaging_UsrEtc#pam.2Fpam-config

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/774
Acked-by: John Johansen <john.johansen@canonical.com>
2021-07-16 22:07:34 +00:00
Jon Tourville
e82a23dfe4 parser: sort feature directory entries in to match libapparmor's directory traversal 2021-07-16 08:57:57 -05:00
Christian Boltz
b6b89478aa Allow reading /etc/login.defs.d/ in abstraction/authentication
This directory can include login.defs config sniplets in openSUSE
Tumbleweed.

References: https://bugzilla.opensuse.org/show_bug.cgi?id=1188296

See also
https://en.opensuse.org/openSUSE:Packaging_UsrEtc#pam.2Fpam-config
2021-07-15 13:04:44 +02:00
John Johansen
3d1232e640 parser: fix cache time stamp check to include dir time stamps
Currently for directory includes the directory timestamp is ignored.
This is wrong as operations like removing a file from the dir won't
be considered in the timestamp check.

Fix this by updating the timestamp check to include the included
directories timestamp.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/760
Signed-off-by: John Johansen <john@jjmx.net>
Acked-by: Georgia Garcia  <georgia.garcia@canonical.com>
2021-07-13 18:08:55 -07:00
Christian Boltz
f466e80d18 Merge branch 'cboltz-gcrypt' into 'master'
add abstractions/crypto, allowing reading @{etc_ro}/gcrypt/random.conf r, and move several rules around

See merge request apparmor/apparmor!772

Acked-by: John Johansen <john.johansen@canonical.com>
2021-07-13 21:52:25 +00:00
Christian Boltz
b5241282e8 move @{PROC}/sys/crypto/fips_enabled r, rule
... from openssl to crypto abstraction
2021-07-13 21:56:29 +02:00
Christian Boltz
ba8087927f Move crypto-policies rules from ssl_certs to crypto
No additional include rule needed since crypto is included in base.
2021-07-13 21:56:29 +02:00
Christian Boltz
534a6d3057 move @{PROC}/sys/crypto/* permissions from base to crypto 2021-07-13 21:56:29 +02:00
Christian Boltz
9830031314 Add crypto abstraction and include it in base
crypto allows reading /etc/gcrypt/random.conf, which is possibly needed
for all programs that use libgcrypt.

Reported by darix, he has seen it with vivaldi.
2021-07-13 21:56:29 +02:00
Christian Boltz
4e8ca5696e Merge branch 'cboltz-test-profiles' into 'master'
Test if active and extra profiles can be parsed by the tools

See merge request apparmor/apparmor!677

Acked-by: John Johansen <john.johansen@canonical.com>
2021-07-13 19:51:27 +00:00
Christian Boltz
26d7c13f94 Add option to skip reading specific profiles
If a profile uses features not supported by the tools yet, add a
skiplist to (hopefully temporarily) exclude it from the tests.

This is meant to avoid blocking usage of new features in profiles.

When doing a release, the skip lists should be empty.
2021-07-13 21:09:36 +02:00
Christian Boltz
b02c59a730 Test if active and extra profiles can be parsed by the tools
The added test makes sure that the python code can parse all profiles
shipped with AppArmor. If this fails, read_profiles() /
read_inactive_profiles() will raise an exception.

Checking for the number of read profiles is mostly done to ensure
*something* is read (to make sure an empty or non-existing directory
won't make the test useless).
2021-07-13 21:09:36 +02:00
Christian Boltz
92883d7e6c Fix extra profiles path in utils/test/logprof.conf 2021-07-13 21:09:35 +02:00
Christian Boltz
bacfe785fe Merge branch 'cboltz-ci-artifacts' into 'master'
Generate and keep html in utils coverage-regression

See merge request apparmor/apparmor!771

Acked-by: Georgia Garcia  <georgia.garcia@canonical.com>
2021-07-13 18:07:29 +00:00
Christian Boltz
8d9e2489a2 Generate and keep html in utils coverage-regression
We sometimes have random coverage changes that are not reproducible and
therefore hard to debug.

Generate html coverage as part of make coverage-regression, and keep the
resulting utils/test/htmlcov/ as artifact to make debugging easier.

coverage-html needs JS files from various libjs-* packages, install them
in before_script
2021-07-13 18:40:59 +02:00
Jon Tourville
5910b50926 parser: correctly calculate max number of jobs 2021-07-12 10:09:16 -05:00
Georgia Garcia
bf59925a6b tests: disable file query test for kernels before 4.4
The file query test on query_label.sh fails on kernels
before 4.4 because of the lack of support. Since there
is no feature file to examine for this feature, we
need to check for the kernel version.

Signed-off-by: Georgia Garcia <georgia.garcia@canonical.com>
2021-07-02 17:20:01 -03:00
Georgia Garcia
12957eba4d parser: CAP_AUDIT_READ is only available after Linux 3.16
The parser was not compiling on older versions of Ubuntu
(trusty) because the capability CAP_AUDIT_READ that was
defined on base_cap_names.h was not available until
kernel version 3.16.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/767
Signed-off-by: Georgia Garcia <georgia.garcia@canonical.com>
Acked-by: John Johansen <john.johansen@canonical.com>
2021-07-02 17:05:19 -03:00
John Johansen
8c8da7c67d parser: move ifdefs for capabilities to single common file
Unfortunately the parser was doing ifdef checks for capabilities
in two places. Move all the capability ifdefs into capability.h

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/768
Signed-off-by: John Johansen <john.johansen@canonical.com>
Acked-by: Georgia Garcia  <georgia.garcia@canonical.com>
2021-07-02 12:48:47 -07:00
John Johansen
e6e112fba1 tests: regression: fix test failure due to mmap semantic changes
The regression tests are failing on some older kernels due to
commit 9f834ec18defc369d73ccf9e87a2790bfa05bf46 being cherry-picked
back to them without the corresponding apparmor patch
34c426acb75cc21bdf84685e106db0c1a3565057.

This means we can not rely on a simple features/flag check to determine
how the kernel is behaving with regard to mmap. Since this test is
not concerned with testing mmap, instead of adding a more complex
conditional simplify by always adding the m permission.

Fixes: https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1830984
Signed-off-by: John Johansen <john.johansen@canonical.com>
Acked-by: Georgia Garcia  <georgia.garcia@canonical.com>
2021-07-01 14:15:02 -07:00
John Johansen
db94b436dd Merge Fix crash caused by ask_exec()
ask_exec still uses aa[profile][hat], therefore
- use full_profile when accessing hashlog
- correctly split the merged profile name to profile and hat
- avoid accidently initializing non-existing aa[profile][hat]

This fixes a regression from converting lots of code to use flat
profile//hat array keys.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/763
Acked-by: John Johansen <john@jjmx.net>
2021-06-30 06:36:55 +00:00
John Johansen
80ae7491c4 Merge Make 'transitions' a dict instead of Hasher
It's used like a plain dict, therefore no further code changes are
needed.

Also simplify generating the 'context' key that is used with
'transitions'.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/764
Acked-by: John Johansen <john@jjmx.net>
2021-06-30 06:33:28 +00:00
Christian Boltz
93bd9a1d5b Merge branch 'cboltz-crypto-policies' into 'master'
abstractions/ssl_certs: allow reading crypto policies

See merge request apparmor/apparmor!720

Acked-by: Seth Arnold <seth.arnold@canonical.com>
2021-06-29 12:41:40 +00:00
Christian Boltz
13a8221622 abstractions/ssl_certs: allow reading crypto policies
See https://gitlab.com/redhat-crypto/fedora-crypto-policies for details.

Reported by darix and also my own audit.log - the actual denial was for
/usr/share/crypto-policies/DEFAULT/openssl.txt.

Also allow the /etc/crypto-policies/ counterpart.

(I'm aware that the crypto policies are not really certificates, but
since they are used by several crypto libraries, ssl_certs is probably
the best place for them even if the filename doesn't match.)
2021-06-28 22:04:08 +02:00
Georgia Garcia
458a981b62 tests: fix i18n.sh regression test on arm64
The following errors are happening on the regression tests
of i18n.sh on arm64 hirsute/impish:

Error: open failed. Test 'i18n (194) OPEN (octal) "/tmp/sdtest.3654-6536-J2ZwFM/file__post" RW' was expected to 'pass'. Reason for failure 'FAIL: open /tmp/sdtest.3654-6536-J2ZwFM/file__post failed - Permission denied'
...

The cause is a bash bug handling UTF-8 on subshells.

Fixes: https://bugs.launchpad.net/apparmor/+bug/1932331
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/765

Signed-off-by: Georgia Garcia <georgia.garcia@canonical.com>
Acked-by: John Johansen <john.johansen@canonical.com>
2021-06-28 15:30:33 -03:00
Christian Boltz
5aa35195f4 Make 'transitions' a dict instead of Hasher
It's used like a plain dict, therefore no further code changes are
needed.

Also simplify generating the 'context' key that is used with
'transitions'.
2021-06-27 21:37:22 +02:00
Christian Boltz
755b5d11e1 Fix crash caused by ask_exec()
ask_exec still uses aa[profile][hat], therefore
- use full_profile when accessing hashlog
- correctly split the merged profile name to profile and hat
- avoid accidently initializing non-existing aa[profile][hat]

This fixes a regression from converting lots of code to use flat
profile//hat array keys.
2021-06-27 21:21:53 +02:00
Georgia Garcia
9ff713957c Add README on tests regarding single test execution
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/761

Signed-off-by: Georgia Garcia <georgia.garcia@canonical.com>
Acked-by: John Johansen <john.johansen@canonical.com>
2021-06-22 12:15:18 +00:00
Georgia Garcia
f46dd62aa0 Merge branch 'profile-check' into 'master'
profiles: Fix config dir on make check

Closes #177

See merge request apparmor/apparmor!762
2021-06-21 19:41:28 +00:00
Georgia Garcia
644d36003c profiles: Fix config dir on make check
The check-logprof test in the profiles Makefile specifies
the configuration directory as --configdir ../utils/test,
but when aa-logprof looks for severity.db in the configdir,
it cannot find it.

This fix points the configdir to utils. Note that the
logprof.conf on utils uses the configuration for files
created during the libapparmor installation on the system.

Fixes: https://gitlab.com/apparmor/apparmor/-/issues/177
Signed-off-by: Georgia Garcia <georgia.garcia@canonical.com>
2021-06-21 14:20:34 +00:00
John Johansen
9fb1398b63 Merge remove always-True write_flags parameter from write_piece() and get_header()
All the calling code (directly or indirectly) uses write_flags=True,
therefore drop the parameter to simplify the code.

See the individual commits for details. Also, reviewing the individual commits is probably easier than reviewing the full diff (especially the test changes).

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/759
Acked-by: John Johansen <john@jjmx.net>
2021-05-25 10:16:33 +00:00
Christian Boltz
5d8f66c9e3 get_header() tests: drop write_flags, add xattrs
Drop unused write_flags parameter from AaTest_get_header and
AaTest_get_header_01. This is a cleanup for the previous commit.

While on it, add xattrs parameter to AaTest_get_header, and add two
tests with non-empty xattrs.
2021-05-25 11:31:10 +02:00
Christian Boltz
6e6b94ab57 get_header(): remove always-True write_flags parameter
All the calling code (directly or indirectly) uses write_flags=True,
therefore drop the parameter to simplify the code.

A few tests called get_header() with write_flags=False. Adjust or drop
those tests.

Note: to keep the diff readable, the test changes are as small as
possible. The next commit will cleanup the now-superfluous write_flags
values in the tests.
2021-05-25 11:31:10 +02:00
Christian Boltz
a7b44cb1ac write_piece(): remove always-True write_flags parameter
All the calling code (directly or indirectly) uses write_flags=True,
therefore drop the parameter to simplify the code.
2021-05-25 11:31:08 +02:00
John Johansen
c07a5bb3d3 Merge change_profile_flags(): use ProfileStorage.parse()
... instead of "manually" creating a ProfileStorage object

Also preserve profile keyword and comment in ProfileStorage.parse()

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/758
Acked-by: John Johansen <john@jjmx.net>
2021-05-25 08:55:15 +00:00
Christian Boltz
2351bf74bf change_profile_flags(): use ProfileStorage.parse()
... instead of "manually" creating a ProfileStorage object
2021-05-24 14:50:52 +02:00
Christian Boltz
b7e9928941 Preserve profile keyword and comment in ProfileStorage.parse() 2021-05-24 14:50:46 +02:00
John Johansen
e00e3fed85 Merge When changing flags, use correct amount of whitespace
.. instead of preserving the original leading whitespace.

This change affects the behaviour of aa-complain, aa-enforce and aa-audit.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/757
Acked-by: John Johansen <john@jjmx.net>
2021-05-24 10:21:07 +00:00
John Johansen
18ad8e94a8 Merge Merge hat parsing into ProfileStorage.parse()
... and into parse_profile_start_line() (which is used by
ProfileStorage.parse()).

With this change, the section handling RE_PROFILE_HAT_DEF in
parse_profile_data() becomes superfluous.

A nice side effect is that two simple_tests parse failures get
accidently ;-) fixed.

Also preserve 'hat' keyword in ProfileStorage instead of always writing hats as '^hat'.

When writing a profile, prepending '^' or 'hat' to a hat name moves from
aa.py write_piece() to ProfileStorage.get_header().

Finally, extend cleanprof_test.* with 'hat bar {...}'.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/756
Acked-by: John Johansen <john@jjmx.net>
2021-05-24 10:18:35 +00:00
John Johansen
ea57aaa617 Merge abstractions/php: support PHP 8
Fixes: https://bugzilla.opensuse.org/show_bug.cgi?id=1186267
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/755
Acked-by: John Johansen <john@jjmx.net>
2021-05-24 10:07:21 +00:00
Christian Boltz
f0a445dd7d When changing flags, use correct amount of whitespace
.. instead of preserving the original leading whitespace.

This change affects the behaviour of aa-complain, aa-enforce and aa-audit.
2021-05-23 19:00:06 +02:00
Christian Boltz
97aece024a Preserve 'hat' keyword in ProfileStorage
... instead of always writing hats as '^hat'.

When writing a profile, prepending '^' or 'hat' to a hat name moves from
aa.py write_piece() to ProfileStorage.get_header().

Also extend cleanprof_test.* with 'hat bar {...}'.
2021-05-23 18:19:28 +02:00
Christian Boltz
6f15bea74c Merge hat parsing into ProfileStorage.parse()
... and into parse_profile_start_line() (which is used by
ProfileStorage.parse()).

With this change, the section handling RE_PROFILE_HAT_DEF in
parse_profile_data() becomes superfluous.

A nice side effect is that two simple_tests parse failures get
accidently ;-) fixed.
2021-05-23 17:52:03 +02:00
Christian Boltz
5853f52233 abstractions/php: support PHP 8
References: https://bugzilla.opensuse.org/show_bug.cgi?id=1186267
2021-05-21 22:50:54 +02:00
John Johansen
0325ba06da Merge ProfileStorage: change 'profile' to 'is_hat', and move parse_profile_start{,_to_storage}() into ProfileStorage
The 'profile' flag means "this profile is a profile or a child profile, but not a hat". Since that's true for most cases, rename the flag to 'is_hat'.

Note that `'profile' == True` translates to `'is_hat' == False`

Also adjust all code to switch from 'profile' to 'is_hat'.

Further down the commit list,

* move parse_profile_start{,_to_storage}() into ProfileStorage
* merge parse_profile_start() into parse()
* add some missing tests

See the individual commits for details.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/754
Acked-by: John Johansen <john@jjmx.net>
2021-05-16 23:46:34 +00:00
Christian Boltz
055ca8f857 Add a test to ensure nested childs cause an Exception
... and add some tests for other error conditions that don't imply
nested childs, so that the intended failure gets tested.
(This is probably a leftover of the `hat == profile` -> `hat = None`
(while not in a hat/child profile) change.)
2021-05-16 18:15:03 +02:00
Christian Boltz
42fe65de71 ProfileStorage: merge parse_profile_start() into parse()
... which avoids handing several values around.

Also adjust the tests so that only the end result (of parse() gets
tested.
2021-05-16 18:15:03 +02:00
Christian Boltz
1642fea228 Move parse_profile_start{,_to_storage}() into ProfileStorage
... and make them class functions of ProfileStorage.

parse_profile_start_to_storage() gets renamed to parse().

Also move the tests for parse_profile_start() and
parse_profile_start_to_storage() to test-profile-storage.py.
2021-05-16 18:15:03 +02:00
Christian Boltz
2a97d6b6bc ProfileStorage: change 'profile' to 'is_hat'
The 'profile' flag means "this profile is a profile or a child profile,
but not a hat". Since that's true for most cases, rename the flag to
'is_hat'.

Note that `'profile' == True` translates to `'is_hat' == False`

Also adjust all code to switch from 'profile' to 'is_hat'.
2021-05-16 18:15:03 +02:00
John Johansen
52de1a226f Merge Update postfix profiles
... with paths and needed permissions seen on latest Tumbleweed

I propose these additions for 3.0 and master.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/753
Acked-by: John Johansen <john@jjmx.net>
2021-05-10 08:15:52 +00:00
John Johansen
adee3e5a4c Merge parse_profile_start(): get rid of pps_set_profile
This value is True if we are in a child profile (not: hat), but that's information we get "for free", so there's no need to hand it around. Besides that, it was wrongly set to False for main profiles (which are not hats).

Remove the pps_set_profile return value from parse_profile_start(), and always assume True unless we were parsing a hat. For completeness, explicitely set it to False when parsing a hat.

To make sure child profiles and hats don't get mixed up, add a child profile to cleanprof_test.{in,out}.

test-libapparmor-test_multi.py always interpreted foo//bar as being a hat, therefore explicitely mark them as such. (Technically not really needed since this is the default, but it helps to make things clear.)

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/751
Acked-by: John Johansen <john@jjmx.net>
2021-05-10 08:14:18 +00:00
Christian Boltz
d78db0502f Update postfix profiles
with paths and needed permissions seen on latest Tumbleweed
2021-05-09 17:45:13 +02:00
John Johansen
33a53c2664 Merge Fix comment wording in file_cache.h
Fixes: https://gitlab.com/apparmor/apparmor/-/merge_requests/743
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/752
Acked-by: John Johansen <john.johansen@canonical.com>
2021-05-02 09:40:17 +00:00
Christian Boltz
e31015a11a Fix comment wording in file_cache.h
This fixes https://gitlab.com/apparmor/apparmor/-/merge_requests/743#note_562522101
2021-05-02 11:29:41 +02:00
Christian Boltz
e1af0cdeca parse_profile_start(): get rid of pps_set_profile
This value is True if we are in a child profile (not: hat), but that's
information we get "for free", so there's no need to hand it around.
Besides that, it was wrongly set to False for main profiles (which are
not hats).

Remove the pps_set_profile return value from parse_profile_start(), and
always assume True unless we were parsing a hat. For completeness,
explicitely set it to False when parsing a hat.

To make sure child profiles and hats don't get mixed up, add a child
profile to cleanprof_test.{in,out}.

test-libapparmor-test_multi.py always interpreted foo//bar as being
a hat, therefore explicitely mark them as such. (Technically not really
needed since this is the default, but it helps to make things clear.)
2021-04-28 21:22:08 +02:00
Steve Beattie
92c76e04fe tests: add a test with recursive include in preamble
... just to be sure that the recursion check works everywhere ;-)


MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/750
Acked-By: Steve Beattie <steve@nxnw.org>
See merge request apparmor/apparmor!750
2021-04-28 14:23:53 +00:00
Christian Boltz
f0221f4bca Add a test with recursive include in preamble 2021-04-28 13:32:08 +02:00
John Johansen
74bc4275a5 parser: Fix invalid reference to name in attachment warning
The name var is being improperly used in a warning. Not only is
it being used after it is freed, it also never had the correct value
as the "name" variable contained the value being used as the base
attachment.

Signed-off-by: John Johansen <john.johansen@canonical.com>
Acked-by: time out
2021-04-27 21:06:21 -07:00
John Johansen
be0d2fa947 parser: fix filter slashes for profile attachments
The parser is failing to properly filter the slashes in the profile
attachment after variable expansion. Causing matche failures when
multiple slashes occur.

Fixes: https://gitlab.com/apparmor/apparmor/-/issues/154
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/727
Reported-by: Mikhail Morfikov <mmorfikov@gmail.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>
Acked-by: time out
2021-04-27 21:06:05 -07:00
John Johansen
71bf9e132f Merge parser: add include dedup cache to handle include loops
Profile includes can be setup to loop and expand in a pathalogical manner that causes build failures. Fix this by caching which includes have already been seen in a given profile context.

In addition this can speed up some profile compiles, that end up re-including common abstractions. By not only deduping the files being included but skipping the need to reprocess and dedup the rules within the include.

Fixes: https://bugzilla.suse.com/show_bug.cgi?id=1184779
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/743
Acked-by: Steve Beattie <steve.beattie@canonical.com>
2021-04-28 04:00:54 +00:00
Steve Beattie
c00b0d325b parser: add a simple one-level recursive include test
This adds a recursive include that otherwise parses correctly, to check
that the parser handles one-level recursion loop acceptably. When the
utils can support it, we should have tests that exercise deeper levels
of looping, e.g. include a -> include b -> include c -> include a or
deeper.

Without the fix in
https://gitlab.com/apparmor/apparmor/-/merge_requests/743, the parser
does fail due to hitting its file descriptor limit.

(The test at

  https://gitlab.com/apparmor/apparmor/-/blob/master/parser/tst/simple_tests/include_tests/recursive.sd

includes itself, which will result in a recursive profile definition
which isn't accepted by the parser.)

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/743
Signed-off-by: Steve Beattie <steve.beattie@canonical.com>
Signed-off-by: John Johansen <john.johansen@canonical.com>
2021-04-27 20:27:33 -07:00
John Johansen
7dcf013bca parser: add include dedup cache to handle include loops
Profile includes can be setup to loop and expand in a pathalogical
manner that causes build failures. Fix this by caching which includes
have already been seen in a given profile context.

In addition this can speed up some profile compiles, that end up
re-including common abstractions. By not only deduping the files
being included but skipping the need to reprocess and dedup the
rules within the include.

Fixes: https://bugzilla.suse.com/show_bug.cgi?id=1184779
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/743
Signed-off-by: John Johansen <john.johansen@canonical.com>
Acked-by: Steve Beattie <steve.beattie@canonical.com>
2021-04-27 20:26:57 -07:00
John Johansen
a7816e1a8f Merge Rework internal profile storage and handling in the aa-* tools to use merged profile names instead of [profile][hat]
Change the tools to use merged profile names (`var['foo//bar']`) instead of the profile/hat layout (`var[profile][hat]`) in many places. Also storage gets moved to ProfileList instead of using a hasher.

Already changed places (in this MR) are parsing profiles, writing profiles, handling and storing of extra profiles, log handling and asking the user about profile additions.

Remaining usage of the `var[profile][hat]` layout are the `aa` and `original_aa` hashers, they'll be replaced in a separate MR.

See the individual commits for details. I'd also recommend to do the review on the individual commits, because the big diff is probably unreadable ;-)

While this is a big chain of changes, each commit contains working code, converting between the two storage layouts with `split_to_merged()` and `merged_to_split()` as needed, with merged layout "bubbling up" in more and more functions.

The long-term goal of these changes is to enable support for nested child profiles in the tools, but - one step after the other ;-)

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/736
Acked-by: John Johansen <john.johansen@canonical.com>
2021-04-27 10:16:58 +00:00
John Johansen
bf70a8e4ec Merge get_new_profile_filename(): use better variable name
The function decides on the filename of a profile, therefore use 'filename' as variable name instead of the somewhat confusing 'profile' and 'full_profilename'.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/749
Acked-by: John Johansen <john.johansen@canonical.com>
2021-04-27 00:37:51 +00:00
John Johansen
ea61100ab6 Merge .gitignore: Add aa-features-abi and utils coverage files
I propose this addition for master and 3.0 (to keep the file in sync, and because most additions \[except `utils/test/coverage-report.txt`\] already make sense in 3.0)

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/748
Acked-by: John Johansen <john.johansen@canonical.com>
2021-04-27 00:33:34 +00:00
John Johansen
a0844f194e Merge Rewrite gen-dbus in python
The generated files are exactly the same.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/747
Acked-by: John Johansen <john.johansen@canonical.com>
2021-04-27 00:31:42 +00:00
Christian Boltz
54eb2baae7 get_new_profile_filename(): use better variable name
The function decides on the filename of a profile, therefore use
'filename' as variable name instead of the somewhat confusing 'profile'
and 'full_profilename'.
2021-04-25 20:35:37 +02:00
Christian Boltz
5c0609453c .gitignore: Add aa-features-abi and utils coverage files 2021-04-25 20:10:48 +02:00
Christian Boltz
2b00d21e2e Rewrite gen-dbus in python
The generated files are exactly the same.
2021-04-25 18:31:38 +02:00
John Johansen
8aa15c7fbe Merge Detect endless #include loop when parsing profiles
If an include file includes itsself (for example if local/foo has '#include <local/foo>'), print a warning instead of calling load_include() again and again.

This fixes a crash when hitting such a case: RecursionError: maximum recursion depth exceeded while calling a Python object

Fixes: https://bugzilla.suse.com/show_bug.cgi?id=1184779 for the tools. The parser will also need a fix.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/742
Acked-by: John Johansen <john.johansen@canonical.com>
2021-04-21 20:06:49 +00:00
Mikhail Morfikov
92e27f5566 abstractions: Add trash abstraction
I noticed that some apps have support for moving files to trash, but
currently there's no abstraction that would provide rules to make this
action possible.

Fixes: https://gitlab.com/apparmor/apparmor/-/issues/160
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/738
Signed-off-by: John Johansen <john.johansen@canonical.com>
Acked-by: Christian Boltz <apparmor@cboltz.de>
2021-04-21 13:01:43 -07:00
John Johansen
cf809ea928 parser: Fix make DEBUG=1
When building the parser with DEBUG=1 enabled the build fails with
the following error and warnings

    In file included from parser_main.c:47:0:
    parser_main.c: In function ‘void auto_tune_parameters()’:
     parser_main.c:1421:35: error: ‘estimate_jobs’ was not declared in this scope
        PDEBUG("Auto tune: --jobs=%d", estimate_jobs);
                                   ^
    parser.h:201:37: note: in definition of macro ‘PDEBUG’
      fprintf(stderr, "parser: " fmt, ## args); \
                                     ^~~~
    parser_main.c:1421:35: note: suggested alternative: ‘estimated_jobs’
        PDEBUG("Auto tune: --jobs=%d", estimate_jobs);
                                   ^
    parser.h:201:37: note: in definition of macro ‘PDEBUG’
      fprintf(stderr, "parser: " fmt, ## args); \
                                     ^~~~
    parser.h:201:41: warning: format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘long int’ [-Wformat=]
      fprintf(stderr, "parser: " fmt, ## args); \
                                         ^
    parser_main.c:1428:5: note: in expansion of macro ‘PDEBUG’
         PDEBUG("Auto tune: --jobs=%d", jobs);
     ^~~~~~
    Makefile:234: recipe for target 'parser_main.o' failed

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/745
Signed-off-by: John Johansen <john.johansen@canonical.com>
Acked-by: Christian Boltz <apparmor@cboltz.de>
2021-04-21 12:57:05 -07:00
Christian Boltz
30323a2ded Detect endless #include loop when parsing profiles
If an include file includes itsself (for example if local/foo has
'#include <local/foo>'), print a warning instead of calling
load_include() again and again.

This fixes a crash when hitting such a case:
    RecursionError: maximum recursion depth exceeded while calling a Python object

Fixes: https://bugzilla.suse.com/show_bug.cgi?id=1184779 for the tools.
The parser will also need a fix.
2021-04-16 00:00:02 +02:00
Christian Boltz
e54b13a97a write_piece(): use merged profile names
... and adjust the callers accordingly.

While on it, simplify the write_piece() code that prepends '^' to hats a bit.
2021-04-15 12:53:08 +02:00
Christian Boltz
0e5dca1083 serialize_profile(): use merged profile names in parameter
... and adjust all callers accordingly.
2021-04-15 12:53:08 +02:00
Christian Boltz
0802f34b35 deduplicate code in read_profile() and autodep()
if a profile doesn't have an attachment specified and the profile name
starts with '/', set the attachment to the profile name. This allows to
have one add_profile() call instead of two very similar ones.
2021-04-15 12:53:08 +02:00
Christian Boltz
8f84e125fd simplify logic in read_profile()
exit early if profile_data is empty (which means we did read an empty
file). This allows to simplify the if conditions to "if active_profile:"
and "else:".
2021-04-15 12:53:08 +02:00
Christian Boltz
e04c8151bb autodep(): use merged profile names
This means getting rid of several merged_to_split() and
split_to_merged() calls.
2021-04-15 12:53:08 +02:00
Christian Boltz
5cf7a28130 change get_profile() to return merged profile names
... and adjust its only caller accordingly.
2021-04-15 12:53:08 +02:00
Christian Boltz
5a68d96c11 extend create_new_profile() tests to cover required hats 2021-04-15 12:53:08 +02:00
Christian Boltz
c65206f16c create_new_profile(): use and return merged profile names
... and adjust all callers and the tests.

For bonus points ;-) this also removes a hasher usage, and extends the
test to check that only the expected profile gets created.
2021-04-15 12:53:08 +02:00
Christian Boltz
286761271b Store extra profiles in 'extra_profiles' ProfileList
... instead of the 'extras' hasher.

Also adjust all code that previously used 'extras' to use
'extra_profiles'. This affects get_profile() and read_profile().
2021-04-15 12:53:08 +02:00
Christian Boltz
179168f566 ProfileList: add get_profile_and_childs()
... and a test for it
2021-04-15 12:53:08 +02:00
Christian Boltz
b1a1b5dc1b ProfileList: allow storing actual profile data
Add a prof_storage parameter to add_profile() to hand over the actual
profile data/rules as ProfileStorage.

Also adjust several tests to hand over a (dummy) ProfileStorage object.

Note: For now, the parameter is optional because it needs some more changes
in aa.py to be really useable. This will change in a later commit.
2021-04-15 12:53:08 +02:00
Christian Boltz
ba53ff3045 Change ask_the_questions() to work with merged profile names
... instead of converting log_dict to traditional [profile][hat] layout
in do_logprof_pass().

A nice side effect is that we get sorting the main profile before its
hats for free and can remove the sorting code.

Also update a comment in ask_rule_questions().

Finally, adjust aa-mergeprof so that it hands over a merged log_dict (using
split_to_merged())
2021-04-15 12:53:08 +02:00
Christian Boltz
a20865008f collapse_log(): return merged profile names
... instead of the old [profile][hat] structure.

This needs changes in do_logprof_pass() when calling ask_the_questions()
(using merged_to_split() for now).

Also adjust test-libapparmor-test_multi.py logfile_to_profile() to
expect the merged structure.
2021-04-15 12:53:08 +02:00
Christian Boltz
bd3b62a8a1 Change collapse_log to internally use merged profile names
... and convert them back to the [profile][hat] layout at the end so
that callers still get the expected result.

As a side effect, log_dict no longer needs to be a hasher().
2021-04-15 12:53:08 +02:00
Christian Boltz
338a7774f1 parse_profile_data(): return merged profile names
... instead of the old [profile][hat] structure.

This needs changes in read_profile() (now using the merged profile name)
and attach_profile_data() (using merged_to_split() for now).

Also adjust test-aa.py to expect the merged structure.
2021-04-15 12:53:08 +02:00
Christian Boltz
d3816b5bcf add split_to_merged()
... to convert a traditional compat['foo']['bar'] to a profile['foo//bar'] list
2021-04-15 12:53:08 +02:00
Christian Boltz
64a261f5ba parse_profile_data(): use merged profile names internally
Change parse_profile_data() to internally use merged profile names
(`foo//bar`) instead of separate profile and hat, and only split it up
again to the [profile][hat] layout at the very end with
merged_to_split().

A nice side effect is that we get rid of a hasher() usage.

parse_profile_data() also gets changed to use `hat = None` (instead of
`hat = profile`) if not inside a child profile. As a result,
parse_profile_start() and one of its tests need a small change.

Besides that small change, calling code should not see a difference, and
the tests also stay working.
2021-04-15 12:53:08 +02:00
Christian Boltz
24e0631bd2 Add combine_profname() to combine profile name parts into joint name
... and add some tests for it.
2021-04-15 12:53:07 +02:00
Christian Boltz
4642d4c9c3 add merged_to_split()
... and a little test for it.

This function is meant to convert a merged foo['profile//hat'] to
old-style foo_compat['profile']['hat'].
2021-04-15 12:53:05 +02:00
John Johansen
472383a429 Merge Increase include and abi rule test coverage to 100%
... by adding some tests.

MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/741
Acked-by: John Johansen <john.johansen@canonical.com>
2021-04-14 22:36:01 +00:00
Christian Boltz
86edd48487 Increase include and abi rule test coverage to 100%
... by adding some tests.
2021-04-15 00:24:38 +02:00
Mikhail Morfikov
f19f9ae1fa abstractions: update video abstraction
the video abstraction currently it only contains the following rules:

  @{sys}/class/video4linux r,
  @{sys}/class/video4linux/** r,

Judging by the v4l path, this abstraction should be used whenever some
app wants to use for instance a webcam or other USB cameras to stream
video usually in chat apps. I was testing some apps, and it looks like
the following rules are needed to make the video streaming possible:

Fixes: https://gitlab.com/apparmor/apparmor/-/issues/159
MR: https://gitlab.com/apparmor/apparmor/-/merge_requests/740
Signed-off-by: John Johansen <john.johansen@canonical.com>
2021-04-14 14:51:09 -07:00
247 changed files with 5476 additions and 3862 deletions

31
.gitignore vendored
View File

@@ -4,6 +4,8 @@ binutils/aa-enabled
binutils/aa-enabled.1
binutils/aa-exec
binutils/aa-exec.1
binutils/aa-features-abi
binutils/aa-features-abi.1
binutils/aa-status
binutils/aa-status.8
binutils/cJSON.o
@@ -12,6 +14,7 @@ parser/po/*.mo
parser/af_names.h
parser/cap_names.h
parser/generated_cap_names.h
parser/generated_af_names.h
parser/tst_lib
parser/tst_misc
parser/tst_regex
@@ -157,6 +160,7 @@ libraries/libapparmor/swig/perl/libapparmor_wrap.c
libraries/libapparmor/swig/perl/libapparmor_wrap.o
libraries/libapparmor/swig/perl/pm_to_blib
libraries/libapparmor/swig/python/LibAppArmor.py
libraries/libapparmor/swig/python/LibAppArmor.egg-info/
libraries/libapparmor/swig/python/build/
libraries/libapparmor/swig/python/libapparmor_wrap.c
libraries/libapparmor/swig/python/Makefile
@@ -173,7 +177,7 @@ libraries/libapparmor/swig/ruby/LibAppArmor_wrap.c
libraries/libapparmor/swig/ruby/LibAppArmor_wrap.o
libraries/libapparmor/swig/ruby/Makefile
libraries/libapparmor/swig/ruby/Makefile.in
libraries/libapparmor/swig/ruby/Makefile.new
libraries/libapparmor/swig/ruby/Makefile.bak
libraries/libapparmor/swig/ruby/Makefile.ruby
libraries/libapparmor/swig/ruby/mkmf.log
libraries/libapparmor/testsuite/.deps
@@ -201,14 +205,22 @@ utils/*.tmp
utils/po/*.mo
utils/apparmor/*.pyc
utils/apparmor/rule/*.pyc
utils/apparmor.egg-info/
utils/build/
utils/htmlcov/
utils/test/common_test.pyc
utils/test/.coverage
utils/test/coverage-report.txt
utils/test/htmlcov/
utils/vim/apparmor.vim
utils/vim/apparmor.vim.5
utils/vim/apparmor.vim.5.html
utils/vim/pod2htmd.tmp
tests/regression/apparmor/*.o
tests/regression/apparmor/aa_policy_cache
tests/regression/apparmor/access
tests/regression/apparmor/at_secure
tests/regression/apparmor/attach_disconnected
tests/regression/apparmor/changehat
tests/regression/apparmor/changehat_fail
tests/regression/apparmor/changehat_fork
@@ -223,6 +235,10 @@ tests/regression/apparmor/chgrp
tests/regression/apparmor/chmod
tests/regression/apparmor/chown
tests/regression/apparmor/clone
tests/regression/apparmor/dbus_eavesdrop
tests/regression/apparmor/dbus_message
tests/regression/apparmor/dbus_service
tests/regression/apparmor/dbus_unrequested_reply
tests/regression/apparmor/deleted
tests/regression/apparmor/env_check
tests/regression/apparmor/environ
@@ -233,7 +249,10 @@ tests/regression/apparmor/fchdir
tests/regression/apparmor/fchgrp
tests/regression/apparmor/fchmod
tests/regression/apparmor/fchown
tests/regression/apparmor/fd_inheritance
tests/regression/apparmor/fd_inheritor
tests/regression/apparmor/fork
tests/regression/apparmor/introspect
tests/regression/apparmor/link
tests/regression/apparmor/link_subset
tests/regression/apparmor/mkdir
@@ -244,15 +263,20 @@ tests/regression/apparmor/net_raw
tests/regression/apparmor/open
tests/regression/apparmor/openat
tests/regression/apparmor/pipe
tests/regression/apparmor/pivot_root
tests/regression/apparmor/ptrace
tests/regression/apparmor/ptrace_helper
tests/regression/apparmor/pwrite
tests/regression/apparmor/query_label
tests/regression/apparmor/readdir
tests/regression/apparmor/rename
tests/regression/apparmor/rw
tests/regression/apparmor/socketpair
tests/regression/apparmor/swap
tests/regression/apparmor/symlink
tests/regression/apparmor/syscall_chroot
tests/regression/apparmor/syscall_ioperm
tests/regression/apparmor/syscall_iopl
tests/regression/apparmor/syscall_mknod
tests/regression/apparmor/syscall_mlockall
tests/regression/apparmor/syscall_ptrace
@@ -264,10 +288,15 @@ tests/regression/apparmor/syscall_setscheduler
tests/regression/apparmor/syscall_sysctl
tests/regression/apparmor/sysctl_proc
tests/regression/apparmor/tcp
tests/regression/apparmor/transition
tests/regression/apparmor/unix_fd_client
tests/regression/apparmor/unix_fd_server
tests/regression/apparmor/unix_socket
tests/regression/apparmor/unix_socket_client
tests/regression/apparmor/unlink
tests/regression/apparmor/uservars.inc
tests/regression/apparmor/xattrs
tests/regression/apparmor/xattrs_profile
tests/regression/apparmor/coredump
**/__pycache__/
*.orig

View File

@@ -1,9 +1,5 @@
---
image: ubuntu:latest
before_script:
- export DEBIAN_FRONTEND=noninteractive && apt-get update -qq && apt-get install --no-install-recommends -y build-essential apache2-dev autoconf automake bison dejagnu flex libpam-dev libtool perl liblocale-gettext-perl pkg-config python-all-dev python3-all-dev pyflakes3 ruby-dev swig lsb-release python3-coverage python3-notify2 python3-psutil zlib1g-dev
- lsb_release -a
- uname -a
# XXX - add a deploy stage to publish man pages, docs, and coverage
# reports
@@ -12,45 +8,131 @@ stages:
- build
- test
.ubuntu-before_script:
before_script:
- export DEBIAN_FRONTEND=noninteractive
- apt-get update -qq
- apt-get install --no-install-recommends -y gcc perl liblocale-gettext-perl linux-libc-dev lsb-release make
- lsb_release -a
- uname -a
.install-c-build-deps: &install-c-build-deps
- apt-get install --no-install-recommends -y build-essential apache2-dev autoconf automake bison dejagnu flex libpam-dev libtool pkg-config python3-all-dev python3-setuptools ruby-dev swig zlib1g-dev
build-all:
stage: build
extends:
- .ubuntu-before_script
artifacts:
name: ${CI_COMMIT_REF_NAME}-${CI_COMMIT_SHA}
expire_in: 30 days
untracked: true
paths:
- libraries/libapparmor/
- parser/
- binutils/
- utils/
- changehat/mod_apparmor/
- changehat/pam_apparmor/
- profiles/
- libraries/libapparmor/
- parser/
- binutils/
- utils/
- changehat/mod_apparmor/
- changehat/pam_apparmor/
- profiles/
script:
- cd libraries/libapparmor && ./autogen.sh && ./configure --with-perl --with-python --prefix=/usr && make && cd ../.. || { cat config.log ; exit 1 ; }
- make -C parser
- make -C binutils
- make -C utils
- make -C changehat/mod_apparmor
- make -C changehat/pam_apparmor
- make -C profiles
- *install-c-build-deps
- cd libraries/libapparmor && ./autogen.sh && ./configure --with-perl --with-python --prefix=/usr && make && cd ../.. || { cat config.log ; exit 1 ; }
- make -C parser
- make -C binutils
- make -C utils
- make -C changehat/mod_apparmor
- make -C changehat/pam_apparmor
- make -C profiles
test-all:
test-libapparmor:
stage: test
needs: ["build-all"]
extends:
- .ubuntu-before_script
script:
- make -C libraries/libapparmor check
- make -C parser check
- make -C binutils check
- make -C utils check
- make -C utils/test coverage-regression
- make -C changehat/mod_apparmor check
- make -C profiles check-parser
- make -C profiles check-abstractions.d
- *install-c-build-deps
- make -C libraries/libapparmor check
test-parser:
stage: test
needs: ["build-all"]
extends:
- .ubuntu-before_script
script:
- *install-c-build-deps
- make -C parser check
test-binutils:
stage: test
needs: ["build-all"]
extends:
- .ubuntu-before_script
script:
- make -C binutils check
test-utils:
stage: test
needs: ["build-all"]
extends:
- .ubuntu-before_script
script:
- apt-get install --no-install-recommends -y libc6-dev libjs-jquery libjs-jquery-throttle-debounce libjs-jquery-isonscreen libjs-jquery-tablesorter pyflakes3 python3-coverage python3-notify2 python3-psutil python3-setuptools
# See apparmor/apparmor#221
- make -C parser/tst gen_dbus
- make -C parser/tst gen_xtrans
- make -C utils check
- make -C utils/test coverage-regression
artifacts:
paths:
- utils/test/htmlcov/
when: always
test-mod-apparmor:
stage: test
needs: ["build-all"]
extends:
- .ubuntu-before_script
script:
- make -C changehat/mod_apparmor check
test-profiles:
stage: test
needs: ["build-all"]
extends:
- .ubuntu-before_script
script:
- make -C profiles check-parser
- make -C profiles check-abstractions.d
shellcheck:
stage: test
needs: []
extends:
- .ubuntu-before_script
script:
- apt-get install --no-install-recommends -y file shellcheck xmlstarlet
- shellcheck --version
- './tests/bin/shellcheck-tree --format=checkstyle
| xmlstarlet tr tests/checkstyle2junit.xslt
> shellcheck.xml'
artifacts:
when: always
reports:
junit: shellcheck.xml
# Disabled due to aa-logprof dependency on /sbin/apparmor_parser existing
# - make -C profiles check-profiles
# - make -C profiles check-profiles
# test-pam_apparmor:
# - stage: test
# - script:
# - cd changehat/pam_apparmor && make check
include:
- template: SAST.gitlab-ci.yml
- template: Secret-Detection.gitlab-ci.yml
variables:
SAST_EXCLUDED_ANALYZERS: "eslint,flawfinder,semgrep,spotbugs"
SAST_BANDIT_EXCLUDED_PATHS: "*/tst/*, */test/*"

10
.shellcheckrc Normal file
View File

@@ -0,0 +1,10 @@
# Don't follow source'd scripts
disable=SC1090
disable=SC1091
# dash supports 'local'
disable=SC2039
disable=SC3043
# dash supports 'echo -n'
disable=SC3037

View File

@@ -124,7 +124,7 @@ static char **parse_args(int argc, char **argv)
{"stdout", no_argument, 0, ARG_STDOUT},
};
while ((opt = getopt_long(argc, argv, "+dvhxl:w:", long_opts, NULL)) != -1) {
while ((opt = getopt_long(argc, argv, "+dvhxf:l:w:", long_opts, NULL)) != -1) {
switch (opt) {
case 'd':
opt_debug = true;
@@ -181,7 +181,7 @@ int main(int argc, char **argv)
error("failed to extract features abi from the kernel");
}
if (opt_file) {
int in = open(opt_file, O_RDONLY);
in = open(opt_file, O_RDONLY);
if (in == -1)
error("failed to open file '%s'", opt_file);
rc = aa_features_new_from_file(&features, in);

View File

@@ -135,7 +135,16 @@ static int get_profiles(struct profile **profiles, size_t *n) {
while (getline(&line, &len, fp) != -1) {
struct profile *_profiles;
autofree char *status = NULL;
autofree char *name = strdup(aa_splitcon(line, &status));
autofree char *name = NULL;
char *tmpname = aa_splitcon(line, &status);
if (!tmpname) {
dfprintf(stderr, "Error: failed profile name split of '%s'.\n", line);
ret = AA_EXIT_INTERNAL_ERROR;
// skip this entry and keep processing
continue;
}
name = strdup(tmpname);
if (status)
status = strdup(status);

View File

@@ -1 +1 @@
3.0.0
3.0.98

View File

@@ -70,6 +70,10 @@ AppArmor extensions to the system are not available.
AppArmor is available on the system but has been disabled at boot.
=item B<EBUSY>
AppArmor is available but only via private interfaces.
=item B<ENOENT>
AppArmor is available (and maybe even enforcing policy) but the interface is

View File

@@ -66,17 +66,17 @@ variable to configure. See ``configure --help'' for reference.
fi
#
# Check if you have distutils, else fail
# Check if you have setuptools, else fail
#
AC_MSG_CHECKING([for the distutils Python package])
ac_distutils_result=`$PYTHON -c "import distutils" 2>&1`
if test -z "$ac_distutils_result"; then
AC_MSG_CHECKING([for the setuptools Python package])
ac_setuptools_result=`$PYTHON -c "import setuptools" 2>&1`
if test -z "$ac_setuptools_result"; then
AC_MSG_RESULT([yes])
else
AC_MSG_RESULT([no])
AC_MSG_ERROR([cannot import Python module "distutils".
AC_MSG_ERROR([cannot import Python module "setuptools".
Please check your Python installation. The error was:
$ac_distutils_result])
$ac_setuptools_result])
PYTHON_VERSION=""
fi
@@ -88,8 +88,8 @@ $ac_distutils_result])
PYTHON_CPPFLAGS=`$PYTHON_CONFIG --includes`
fi
if test -z "$PYTHON_CPPFLAGS"; then
python_path=`$PYTHON -c "import sys; import distutils.sysconfig;\
sys.stdout.write('%s\n' % distutils.sysconfig.get_python_inc());"`
python_path=`$PYTHON -c "import sys; import sysconfig;\
sys.stdout.write('%s\n' % sysconfig.get_path('include'));"`
if test -n "${python_path}"; then
python_path="-I$python_path"
fi
@@ -108,8 +108,8 @@ sys.stdout.write('%s\n' % distutils.sysconfig.get_python_inc());"`
if test -z "$PYTHON_LDFLAGS"; then
# (makes two attempts to ensure we've got a version number
# from the interpreter)
py_version=`$PYTHON -c "import sys; from distutils.sysconfig import *; \
sys.stdout.write('%s\n' % ''.join(get_config_vars('VERSION')))"`
py_version=`$PYTHON -c "import sys; import sysconfig; \
sys.stdout.write('%s\n' % ''.join(sysconfig.get_config_vars('VERSION')))"`
if test "$py_version" == "[None]"; then
if test -n "$PYTHON_VERSION"; then
py_version=$PYTHON_VERSION
@@ -119,8 +119,8 @@ sys.stdout.write("%s\n" % sys.version[[:3]])"`
fi
fi
PYTHON_LDFLAGS=`$PYTHON -c "import sys; from distutils.sysconfig import *; \
sys.stdout.write('-L' + get_python_lib(0,1) + ' -lpython\n')"`$py_version`$PYTHON -c \
PYTHON_LDFLAGS=`$PYTHON -c "import sys; import sysconfig; \
sys.stdout.write('-L' + sysconfig.get_path('stdlib') + ' -lpython\n')"`$py_version`$PYTHON -c \
"import sys; sys.stdout.write('%s' % getattr(sys,'abiflags',''))"`
fi
AC_MSG_RESULT([$PYTHON_LDFLAGS])
@@ -131,8 +131,8 @@ sys.stdout.write('-L' + get_python_lib(0,1) + ' -lpython\n')"`$py_version`$PYTHO
#
AC_MSG_CHECKING([for Python site-packages path])
if test -z "$PYTHON_SITE_PKG"; then
PYTHON_SITE_PKG=`$PYTHON -c "import sys; import distutils.sysconfig; \
sys.stdout.write('%s\n' % distutils.sysconfig.get_python_lib(0,0));"`
PYTHON_SITE_PKG=`$PYTHON -c "import sys; import sysconfig; \
sys.stdout.write('%s\n' % sysconfig.get_path('purelib'));"`
fi
AC_MSG_RESULT([$PYTHON_SITE_PKG])
AC_SUBST([PYTHON_SITE_PKG])
@@ -146,8 +146,8 @@ sys.stdout.write('%s\n' % distutils.sysconfig.get_python_lib(0,0));"`
PYTHON_EXTRA_LIBS=''
fi
if test -z "$PYTHON_EXTRA_LIBS"; then
PYTHON_EXTRA_LIBS=`$PYTHON -c "import sys; import distutils.sysconfig; \
conf = distutils.sysconfig.get_config_var; \
PYTHON_EXTRA_LIBS=`$PYTHON -c "import sys; import sysconfig; \
conf = sysconfig.get_config_var; \
sys.stdout.write('%s %s %s\n' % (conf('BLDLIBRARY'), conf('LOCALMODLIBS'), conf('LIBS')))"`
fi
AC_MSG_RESULT([$PYTHON_EXTRA_LIBS])
@@ -162,8 +162,8 @@ sys.stdout.write('%s %s %s\n' % (conf('BLDLIBRARY'), conf('LOCALMODLIBS'), conf(
PYTHON_EXTRA_LDFLAGS=''
fi
if test -z "$PYTHON_EXTRA_LDFLAGS"; then
PYTHON_EXTRA_LDFLAGS=`$PYTHON -c "import sys; import distutils.sysconfig; \
conf = distutils.sysconfig.get_config_var; \
PYTHON_EXTRA_LDFLAGS=`$PYTHON -c "import sys; import sysconfig; \
conf = sysconfig.get_config_var; \
sys.stdout.write('%s\n' % conf('LINKFORSHARED'))"`
fi
AC_MSG_RESULT([$PYTHON_EXTRA_LDFLAGS])

View File

@@ -27,7 +27,7 @@ INCLUDES = $(all_includes)
# http://www.gnu.org/software/libtool/manual/html_node/Libtool-versioning.html
#
AA_LIB_CURRENT = 9
AA_LIB_REVISION = 0
AA_LIB_REVISION = 2
AA_LIB_AGE = 8
SUFFIXES = .pc.in .pc
@@ -38,7 +38,7 @@ include $(COMMONDIR)/Make.rules
BUILT_SOURCES = grammar.h scanner.h af_protos.h
AM_LFLAGS = -v
AM_YFLAGS = -d -p aalogparse_
AM_CFLAGS = -Wall $(EXTRA_WARNINGS) -fPIC
AM_CFLAGS = -Wall $(EXTRA_WARNINGS) -fPIC -flto-partition=none
AM_CPPFLAGS = -D_GNU_SOURCE -I$(top_srcdir)/include/
scanner.h: scanner.l
$(LEX) -v $<

View File

@@ -194,6 +194,8 @@ static int features_dir_cb(int dirfd, const char *name, struct stat *st,
if (features_snprintf(fst, "%s {", name) == -1)
return -1;
/* Handle symlink here. See _aa_dirat_for_each in private.c */
if (S_ISREG(st->st_mode)) {
ssize_t len;
size_t remaining;
@@ -664,7 +666,7 @@ static const char *features_lookup(aa_features *features, const char *str)
/* Empty strings are not accepted. Neither are leading '/' chars. */
if (!str || str[0] == '/')
return false;
return NULL;
/**
* Break @str into an array of components. For example,
@@ -677,7 +679,7 @@ static const char *features_lookup(aa_features *features, const char *str)
/* At least one valid token is required */
if (!num_components)
return false;
return NULL;
/* Ensure that all components are valid and found */
for (i = 0; i < num_components; i++) {

View File

@@ -38,7 +38,7 @@
#if (YYDEBUG != 0)
#define debug_unused_ /* nothing */
#else
#define no_debug_unused_ unused_
#define debug_unused_ unused_
#endif
aa_log_record *ret_record;
@@ -46,7 +46,7 @@ aa_log_record *ret_record;
/* Since we're a library, on any errors we don't want to print out any
* error messages. We should probably add a debug interface that does
* emit messages when asked for. */
void aalogparse_error(unused_ void *scanner, no_debug_unused_ char const *s)
void aalogparse_error(unused_ void *scanner, debug_unused_ char const *s)
{
#if (YYDEBUG != 0)
printf("ERROR: %s\n", s);
@@ -186,6 +186,7 @@ aa_record_event_type lookup_aa_event(unsigned int type)
%token TOK_KEY_FLAGS
%token TOK_KEY_SRCNAME
%token TOK_SOCKLOGD_KERNEL
%token TOK_SYSLOG_KERNEL
%token TOK_SYSLOG_USER
@@ -232,24 +233,28 @@ dmesg_type: TOK_DMESG_STAMP TOK_AUDIT TOK_COLON key_type audit_id key_list
{ ret_record->version = AA_RECORD_SYNTAX_V2; free($1); }
;
syslog_id: TOK_ID TOK_SYSLOG_KERNEL { free($1); }
| TOK_SOCKLOGD_KERNEL { }
;
syslog_type:
syslog_date TOK_ID TOK_SYSLOG_KERNEL audit_id key_list
{ ret_record->version = AA_RECORD_SYNTAX_V2; free($2); }
| syslog_date TOK_ID TOK_SYSLOG_KERNEL key_type audit_id key_list
{ ret_record->version = AA_RECORD_SYNTAX_V2; free($2); }
| syslog_date TOK_ID TOK_SYSLOG_KERNEL TOK_DMESG_STAMP audit_id key_list
{ ret_record->version = AA_RECORD_SYNTAX_V2; free($2); free($4); }
| syslog_date TOK_ID TOK_SYSLOG_KERNEL TOK_DMESG_STAMP key_type audit_id key_list
{ ret_record->version = AA_RECORD_SYNTAX_V2; free($2); free($4); }
syslog_date syslog_id audit_id key_list
{ ret_record->version = AA_RECORD_SYNTAX_V2; }
| syslog_date syslog_id key_type audit_id key_list
{ ret_record->version = AA_RECORD_SYNTAX_V2; }
| syslog_date syslog_id TOK_DMESG_STAMP audit_id key_list
{ ret_record->version = AA_RECORD_SYNTAX_V2; free($3); }
| syslog_date syslog_id TOK_DMESG_STAMP key_type audit_id key_list
{ ret_record->version = AA_RECORD_SYNTAX_V2; free($3); }
/* needs update: hard newline in handling mutiline log messages */
| syslog_date TOK_ID TOK_SYSLOG_KERNEL TOK_DMESG_STAMP TOK_AUDIT TOK_COLON key_type audit_id audit_user_msg_partial_tail
{ ret_record->version = AA_RECORD_SYNTAX_V2; free($2); }
| syslog_date TOK_ID TOK_SYSLOG_KERNEL TOK_DMESG_STAMP TOK_AUDIT TOK_COLON key_type audit_id audit_user_msg_tail
{ ret_record->version = AA_RECORD_SYNTAX_V2; free($2); }
| syslog_date TOK_ID TOK_SYSLOG_KERNEL TOK_DMESG_STAMP TOK_AUDIT TOK_COLON key_type audit_id key_list
{ ret_record->version = AA_RECORD_SYNTAX_V2; free($2); free($4); }
| syslog_date TOK_ID TOK_SYSLOG_KERNEL TOK_AUDIT TOK_COLON key_type audit_id key_list
{ ret_record->version = AA_RECORD_SYNTAX_V2; free($2); }
| syslog_date syslog_id TOK_DMESG_STAMP TOK_AUDIT TOK_COLON key_type audit_id audit_user_msg_partial_tail
{ ret_record->version = AA_RECORD_SYNTAX_V2; free($3); }
| syslog_date syslog_id TOK_DMESG_STAMP TOK_AUDIT TOK_COLON key_type audit_id audit_user_msg_tail
{ ret_record->version = AA_RECORD_SYNTAX_V2; free($3); }
| syslog_date syslog_id TOK_DMESG_STAMP TOK_AUDIT TOK_COLON key_type audit_id key_list
{ ret_record->version = AA_RECORD_SYNTAX_V2; free($3); }
| syslog_date syslog_id TOK_AUDIT TOK_COLON key_type audit_id key_list
{ ret_record->version = AA_RECORD_SYNTAX_V2; }
| syslog_date TOK_ID TOK_SYSLOG_USER key_list
{ ret_record->version = AA_RECORD_SYNTAX_V2; free($2); }
;

View File

@@ -43,10 +43,137 @@
__asm__ (".symver " #real "," #name "@" #version)
#define default_symbol_version(real, name, version) \
__asm__ (".symver " #real "," #name "@@" #version)
#define DLLEXPORT __attribute__((visibility("default"),externally_visible))
#define UNCONFINED "unconfined"
#define UNCONFINED_SIZE strlen(UNCONFINED)
/*
* AppArmor kernel interfaces. Potentially used by this code to
* implement the various library functions.
*
*
* /sys/module/apparmor/parameters/ *
*
* Available on all kernels, some options may not be available and policy
* may block access.
* audit - normal,quiet_denied,quiet,noquiet,all
* debug (bool) - turn on debug messages if enabled during compile
* hash_policy (bool) - provide a hash of loaded policy
* logsyscall (bool) - ignored
* paranoid_load (bool) - whether full policy checks are done. Should only
* be disabled for embedded device kernels
* audit_header (bool) - include "apparmor=<mode> in messages"
* enabled (bool) - whether apparmor is enabled. This can be
* different than whether apparmor is available.
* See virtualization and LSM stacking.
* lock_policy (bool) - one way trigger. Once set policy can not be
* loaded, replace, removed.
* mode - global policy namespace control of whether
* apparmor is in "enforce", "complain"
* path_max - maximum path size. Can always be read but
* can only be set on some kernels.
*
* securityfs/apparmor - usually mounted at /sys/kernel/security/apparmor/ *
* .access - transactional interface used to query kernel
* .ns_level - RO policy namespace level of current task
* .ns_name - RO current policy namespace of current task
* .ns_stacked - RO boolean if stacking is in use with the namespace
* .null - special device file used to redirect closed fds to
* profiles - RO virtualized text list of visible loaded profiles
* .remove - WO names of profiles to remove
* .replace - WO binary policy to replace (will load if not present)
* .load - WO binary policy to load (will fail if already present)
* revision - RO unique incrementing revision number for policy
* .stacked - RO boolean if label is currently stacked
* features/ - RO feature set supported by kernel
* policy/ - RO policy loaded into kernel
*
*
* /proc/<tid>/attr/apparmor/ *
* New proc attr interface compatible with LSM stacking. Available even
* when LSM stacking is not in use.
* current - see /proc/<tid>/attr/current
* exec - see /proc/<tid>/attr/exec
* prev - see /proc/<tid>/attr/prev
*
* /proc/<tid>/attr/ * Old proc attr interface shared between LSMs goes
* to first registered LSM that wants the proc interface, but can be
* virtualized by setting the display LSM. So if LSM stacking is in
* use this interface may belong to another LSM. Use
* /proc/<tid>/attr/apparmor/ *
* first if possible, and do NOT use if
* /sys/module/apparmor/parameters/enabled=N.
* Note: older version of the library only used this interface and did not
* check if it was available. Which could lead to weird failures if
* another LSM has claimed it. This version of the library tries to
* fix this problem, but unfortunately it is impossible to completely
* address, because access to interfaces required to determine
* whether apparmor owns the interface may be restricted, either
* by existing apparmor policy that has not been updated to use the
* new interface or by another LSM.
* current - current confinement
* display - LSM stacking. Which LSM currently owns the interface.
* exec - label to switch to at exec
* fscreate - unused by apparmor
* keycreate - unused by apparmor
* prev - when in HAT set to parent label
* sockcreate - unused by apparmor
*
*
* Below /proc/ interface combinations are documented on how the library
* currently behaves and how it used to behave. This serves to document
* known failure points as we can not entirely fix this mess.
* Note: userspace applications using the interface directly have all
* the issues/failures of AppArmor 2.x unless they have specifically
* been updated to deal with this mess.
*
*
* AppArmor 2.x Lib
*
* LSM AA sys sys proc/ proc/ user
* Stk | Blt | LSM | enabl | avail | aa/ | * | space |
* ----+-----+-------+-------+-------+-------+-------+-------+--------+
* N | N | - | - | - | - | N | AA2.x | - |
* N | N | other | - | - | - | N | AA2.x | FAIL |
* N | N | other |denied | - | - | N | AA2.x | FAIL |
* N | Y | - | N | - | - | N | AA2.x | - |
* N | Y | other | - | - | - | N | AA2.x | FAIL |
* N | Y | AA | - | - | - | Y | AA2.x | PASS |
* Y | N | - | - | - | - | N | AA2.x | - |
* Y | N | other | - | - | - | N | AA2.x | FAIL |
* Y | Y | - | N | - | - | N | AA2.x | - |
* Y | Y | other | - | - | - | N | AA2.x | FAIL |
* Y | Y | AA | - | - | - | Y | AA2.x | PASS |
* Y | Y | major | - | - | - | Y | AA2.x | PASS |
* Y | Y | minor | - | - | - | N | AA2.x | FAIL |
*
*
* AppArmor 3.x Lib - adds stacking support.
*
* Will FAIL in a few cases because it can not determine if apparmor
* is enabled and has control of the old interface. Not failing in these
* cases where AppArmor is available will result in regressions where
* the library will not work correctly with old kernels. In these
* cases its better that apparmor userspace is not used.
*
* AppArmor 3.x will avoid the failure cases if any of enabled, avail
* or the new proc interfaces are available to the task. AppArmor 3.x
* will also automatically add permissions to access the new proc
* interfaces so change_hat and change_profile won't experience these
* failures, it will only happen for confined applications hitting the
* interfaces and not using change_hat or change_profile.
*
* LSM AA sys sys proc/ proc/
* Stk | Blt | LSM | enabl | avail | aa/ | * |
* ----+-----+-------+-------+-------+-------+-------+-----------------
* Y/N | N | other | denied| NA | NA | Y | old interface avail
* Y/N | Y | other | denied| NA | NA | Y | old interface avail
* Y | Y | minor | denied| NA | NA | Y | old interface avail
* Y | Y | minor | denied| NA | denied| Y | old interface avail
* Y/N | Y | minor | denied| denied| denied| Y | old interface avail
*/
/**
* aa_find_mountpoint - find where the apparmor interface filesystem is mounted
* @mnt: returns buffer with the mountpoint string
@@ -93,25 +220,34 @@ int aa_find_mountpoint(char **mnt)
return rc;
}
// done as a macro so we can paste the param
/**
* pararm_check_base - return boolean value for PARAM
* PARAM: parameter to check
*
* Returns: 1 == Y
* 0 == N
* <0 == error
*
* done as a macro so we can paste the param
*/
#define param_check_base(PARAM) \
({ \
int rc, fd; \
fd = open("/sys/module/apparmor/parameters/" PARAM, O_RDONLY); \
if (fd == -1) { \
rc = errno; \
rc = -errno; \
} else { \
char buffer[2]; \
int size = read(fd, &buffer, 2); \
rc = errno; \
rc = -errno; \
close(fd); \
errno = rc; \
errno = -rc; \
if (size > 0) { \
if (buffer[0] == 'Y') \
rc = 0; \
rc = 1; \
else \
rc = ECANCELED; \
rc = 0; \
} \
} \
(rc); \
@@ -130,31 +266,37 @@ static void param_check_enabled_init_once(void)
static int param_check_enabled()
{
if (pthread_once(&param_enabled_ctl, param_check_enabled_init_once) == 0)
if (pthread_once(&param_enabled_ctl, param_check_enabled_init_once) == 0 && param_enabled >= 0)
return param_enabled;
/* fallback if not initialized OR we recorded an error when
* initializing.
*/
return param_check_base("enabled");
}
static int is_enabled(void)
{
return !param_check_enabled();
return param_check_enabled() == 1;
}
static void param_check_private_enabled_init_once(void)
{
param_enabled = param_check_base("private_enabled");
param_private_enabled = param_check_base("available");
}
static int param_check_private_enabled()
{
if (pthread_once(&param_private_enabled_ctl, param_check_private_enabled_init_once) == 0)
if (pthread_once(&param_private_enabled_ctl, param_check_private_enabled_init_once) == 0 && param_private_enabled >= 0)
return param_private_enabled;
return param_check_base("private_enabled");
/* fallback if not initialized OR we recorded an error when
* initializing.
*/
return param_check_base("available");
}
static int is_private_enabled(void)
{
return !param_check_private_enabled();
return param_check_private_enabled() == 1;
}
/**
@@ -174,15 +316,17 @@ int aa_is_enabled(void)
bool private = false;
rc = param_check_enabled();
if (rc) {
if (rc == ENOENT)
errno = ENOSYS;
else
errno = rc;
if (rc < 1) {
if (!is_private_enabled()) {
if (rc == 0)
errno = ECANCELED;
else if (rc == -ENOENT)
errno = ENOSYS;
else
errno = -rc;
if (!is_private_enabled())
return 0;
}
/* actually available but only on private interfaces */
private = true;
}
@@ -228,41 +372,91 @@ static inline pid_t aa_gettid(void)
*/
static pthread_once_t proc_attr_base_ctl = PTHREAD_ONCE_INIT;
static const char *proc_attr_base_old = "/proc/%d/attr/%s";
static const char *proc_attr_new_dir = "/proc/%d/attr/apparmor/";
static const char *proc_attr_base_stacking = "/proc/%d/attr/apparmor/%s";
static const char *proc_attr_base_unavailable = "/proc/%d/attr/apparmor/unavailable/%s";
static const char *proc_attr_base;
static const char *proc_attr_base = NULL;
static int proc_stacking_present = -1; /* unknown */
static void proc_attr_base_init_once(void)
{
autofree char *tmp;
/* if we fail we just fall back to the default value */
if (asprintf(&tmp, "/proc/%d/attr/apparmor/current", aa_gettid())) {
autoclose int fd = open(tmp, O_RDONLY);
if (fd != -1) {
if (asprintf(&tmp, proc_attr_new_dir, aa_gettid()) > 0) {
struct stat sb;
if (stat(tmp, &sb) == 0) {
proc_attr_base = proc_attr_base_stacking;
proc_stacking_present = 1;
return;
}
}
if (!is_enabled() && is_private_enabled()) {
/* new stacking interfaces aren't available and apparmor
* is disabled, but available. do not use the
* /proc/<pid>/attr/ * interfaces as they could be
* in use by another LSM
*/
proc_attr_base = proc_attr_base_unavailable;
} else if (errno == ENOENT) {
/* no stacking - try falling back */
proc_stacking_present = 0;
} else if (errno == EACCES) {
/* the dir exists, but access is denied */
proc_stacking_present = 1;
proc_attr_base = proc_attr_base_stacking;
} /* else
denied by policy, or other error try falling back */
} else {
/* failed allocation - proc_attr_base stays NULL */
return;
}
proc_attr_base = proc_attr_base_old;
/* check for new interface failed, see if we can fallback */
if (param_check_enabled() == 0) {
/* definate NO (not just an error) on enabled. Do not fall
* back to old shared proc interface
*
* First try an alternate check for private proc interface
*/
int enabled = param_check_private_enabled();
if (enabled == 1) {
/* the private interface exists and we can't
* fallback so just keep trying on the new
* interface.
*/
proc_attr_base = proc_attr_base_stacking;
} else if (enabled == 0) {
/* definite NO - no interface available */
proc_attr_base = proc_attr_base_unavailable;
} else {
/* error can't determine, proc_attr_base stays NULL */
}
} else if (param_check_enabled() == 1) {
/* apparmor is enabled, we can use the old interface */
proc_attr_base = proc_attr_base_old;
} else if (errno != EACCES) {
/* this shouldn't happen unless apparmor is not builtin
* or proc isn't mounted
*/
proc_attr_base = proc_attr_base_unavailable;
} /* else
denied by policy - proc_attr_base stays NULL */
return;
}
static char *procattr_path(pid_t pid, const char *attr)
{
char *path = NULL;
const char *tmp;
/* TODO: rework this with futex or userspace RCU so we can update
* the base value instead of continually using the same base
* after we have hit an error
*/
/* ignore failure, we just fallback to the default value */
(void) pthread_once(&proc_attr_base_ctl, proc_attr_base_init_once);
if (asprintf(&path, proc_attr_base, pid, attr) > 0)
if (proc_attr_base)
tmp = proc_attr_base;
else if (proc_stacking_present)
/* couldn't determine during init */
tmp = proc_attr_base_stacking;
else
/* couldn't determine during init and no stacking */
tmp = proc_attr_base_old;
if (asprintf(&path, tmp, pid, attr) > 0)
return path;
return NULL;
}
@@ -278,8 +472,8 @@ static int procattr_open(pid_t tid, const char *attr, int flags)
}
fd = open(tmp, flags);
free(tmp);
/* Test is we can fallback to a different interface this is ugly.
* If only the old interface is available:
/* Test is we can fallback to the old interface (this is ugly).
* If we haven't tried the old interface already
* proc_attr_base == proc_attr_base_old - no fallback
* else if is_enabled()
* apparmor is available on the old interface
@@ -289,7 +483,7 @@ static int procattr_open(pid_t tid, const char *attr, int flags)
* old interface where is_enabled() is only successful if
* the old interface is available to apparmor.
*/
if (fd == -1 && errno == EACCES && proc_attr_base != proc_attr_base_old && is_enabled()) {
if (fd == -1 && tmp != proc_attr_base_old && param_check_enabled() != 0) {
if (asprintf(&tmp, proc_attr_base_old, tid, attr) < 0)
return -1;
fd = open(tmp, flags);
@@ -631,7 +825,7 @@ int aa_change_onexec(const char *profile)
}
/* create an alias for the old change_hat@IMMUNIX_1.0 symbol */
extern typeof((__change_hat)) __old_change_hat __attribute__((alias ("__change_hat")));
DLLEXPORT extern typeof((__change_hat)) __old_change_hat __attribute__((alias ("__change_hat")));
symbol_version(__old_change_hat, change_hat, IMMUNIX_1.0);
default_symbol_version(__change_hat, change_hat, APPARMOR_1.0);
@@ -1029,7 +1223,7 @@ int query_label(uint32_t mask, char *query, size_t size, int *allowed,
/* export multiple aa_query_label symbols to compensate for downstream
* releases with differing symbol versions. */
extern typeof((query_label)) __aa_query_label __attribute__((alias ("query_label")));
DLLEXPORT extern typeof((query_label)) __aa_query_label __attribute__((alias ("query_label")));
symbol_version(__aa_query_label, aa_query_label, APPARMOR_1.1);
default_symbol_version(query_label, aa_query_label, APPARMOR_2.9);

View File

@@ -6,14 +6,14 @@
IMMUNIX_1.0 {
global:
change_hat;
change_hat; __old_change_hat;
local:
*;
};
APPARMOR_1.0 {
global:
change_hat;
change_hat; __change_hat;
parse_record;
free_record;
local:
@@ -24,7 +24,7 @@ APPARMOR_1.1 {
global:
aa_is_enabled;
aa_find_mountpoint;
aa_change_hat;
aa_change_hat; __old_change_hat;
aa_change_hatv;
aa_change_hat_vargs;
aa_change_profile;
@@ -37,7 +37,7 @@ APPARMOR_1.1 {
free_record;
aa_getprocattr_raw;
aa_getprocattr;
aa_query_label;
aa_query_label; __aa_query_label;
# no more symbols here, please
@@ -47,7 +47,7 @@ APPARMOR_1.1 {
APPARMOR_2.9 {
global:
aa_query_label;
aa_query_label; query_label;
local:
*;
} APPARMOR_1.1;

View File

@@ -45,6 +45,8 @@ struct aa_policy_cache {
static int clear_cache_cb(int dirfd, const char *path, struct stat *st,
void *data unused)
{
/* Handle symlink here. See _aa_dirat_for_each in private.c */
if (S_ISREG(st->st_mode)) {
/* remove regular files */
return unlinkat(dirfd, path, 0);

View File

@@ -452,7 +452,8 @@ int _aa_overlaydirat_for_each(int dirfd[], int n, void *data,
*
* The cb function is called with the DIR in use and the name of the
* file in that directory. If the file is to be opened it should
* use the openat, fstatat, and related fns.
* use the openat, fstatat, and related fns. If the file is a symlink
* _aa_dirat_for_each currently tries to traverse it for the caller
*
* Returns: 0 on success, else -1 and errno is set to the error code
*/
@@ -485,14 +486,34 @@ int _aa_dirat_for_each(int dirfd, const char *name, void *data,
autofree struct dirent *dir = namelist[i];
struct stat my_stat;
if (rc)
continue;
if (fstatat(cb_dirfd, dir->d_name, &my_stat, 0)) {
if (fstatat(cb_dirfd, dir->d_name, &my_stat, AT_SYMLINK_NOFOLLOW)) {
PDEBUG("stat failed for '%s': %m\n", dir->d_name);
rc = -1;
continue;
}
/* currently none of the callers handle symlinks, and this
* same basic code was applied to each. So for this patch
* just drop it here.
*
* Going forward we need to start handling symlinks as
* they have meaning.
* In the case of
* cache: they act as a place holder for files that have been
* combined into a single binary. This enables the
* file based cache lookup time find that relation
* and dedup, so multiple loads aren't done.
* profiles: just a profile in an alternate location, but
* should do dedup detection when doing dir reads
* so we don't double process.
*/
if (S_ISLNK(my_stat.st_mode)) {
/* just traverse the symlink */
if (fstatat(cb_dirfd, dir->d_name, &my_stat, 0)) {
PDEBUG("symlink target stat failed for '%s': %m\n", dir->d_name);
rc = -1;
continue;
}
}
if (cb(cb_dirfd, dir->d_name, &my_stat, data)) {
PDEBUG("dir_for_each callback failed for '%s'\n",

View File

@@ -172,6 +172,7 @@ audit "audit"
ip_addr [a-f[:digit:].:]{3,}
/* syslog tokens */
socklogd_kernel kern.notice{colon}
syslog_kernel kernel{colon}
syslog_user [[:alnum:]_-]+\[[[:digit:]]+\]{colon}
syslog_yyyymmdd {digit}{4}{minus}{digit}{2}{minus}{digit}{2}
@@ -351,6 +352,7 @@ yy_flex_debug = 0;
{key_flags} { BEGIN(safe_string); return(TOK_KEY_FLAGS); }
{key_srcname} { BEGIN(safe_string); return(TOK_KEY_SRCNAME); }
{socklogd_kernel} { BEGIN(dmesg_timestamp); return(TOK_SOCKLOGD_KERNEL); }
{syslog_kernel} { BEGIN(dmesg_timestamp); return(TOK_SYSLOG_KERNEL); }
{syslog_user} { return(TOK_SYSLOG_USER); }
{syslog_month} { yylval->t_str = strdup(yytext); return(TOK_DATE_MONTH); }
@@ -365,6 +367,7 @@ yy_flex_debug = 0;
<hostname>{
{ws}+ { /* eat whitespace */ }
{socklogd_kernel} { BEGIN(dmesg_timestamp); return(TOK_SOCKLOGD_KERNEL); }
{syslog_hostname} { yylval->t_str = strdup(yytext); BEGIN(INITIAL); return(TOK_ID); }
}

View File

@@ -21,7 +21,7 @@ install-exec-local:
clean-local:
if test -x "$(PYTHON)"; then $(PYTHON) setup.py clean; fi
rm -rf build
rm -rf build LibAppArmor.egg-info
if test $(top_srcdir) != $(top_builddir) ; then rm -f libapparmor_wrap.c ; fi
endif

View File

@@ -1,6 +1 @@
import sys
if sys.version_info[0] >= 3:
from LibAppArmor.LibAppArmor import *
else:
from .LibAppArmor import *
from LibAppArmor.LibAppArmor import *

View File

@@ -1,4 +1,4 @@
from distutils.core import setup, Extension
from setuptools import setup, Extension
import string
setup(name = 'LibAppArmor',

View File

@@ -10,8 +10,7 @@ test_python.py: test_python.py.in $(top_builddir)/config.status
CLEANFILES = test_python.py
# bah, how brittle is this?
PYTHON_DIST_BUILD_PATH = '$(builddir)/../build/$$($(PYTHON) -c "import distutils.util; import platform; print(\"lib.%s-%s\" %(distutils.util.get_platform(), platform.python_version()[:3]))")'
PYTHON_DIST_BUILD_PATH = '$(builddir)/../build/$$($(PYTHON) buildpath.py)'
TESTS = test_python.py
TESTS_ENVIRONMENT = \

View File

@@ -0,0 +1,10 @@
#!/usr/bin/python3
# the build path has changed in setuptools 61.2
import sys
import sysconfig
import setuptools
if tuple(map(int,setuptools.__version__.split("."))) >= (61, 2):
identifier = sys.implementation.cache_tag
else:
identifier = "%d.%d" % sys.version_info[:2]
print("lib.%s-%s" % (sysconfig.get_platform(), identifier))

View File

@@ -9,7 +9,9 @@ LibAppArmor_wrap.c : $(srcdir)/../SWIG/libapparmor.i
MOSTLYCLEANFILES=LibAppArmor_wrap.c
Makefile.ruby: extconf.rb
mv Makefile Makefile.bak
PREFIX=$(prefix) $(RUBY) $< --with-LibAppArmor-include=$(top_srcdir)/include
mv Makefile.bak Makefile
LibAppArmor.so: LibAppArmor_wrap.c Makefile.ruby
$(MAKE) -fMakefile.ruby
@@ -22,7 +24,7 @@ install-exec-local: Makefile.ruby
clean-local:
if test -f Makefile.ruby; then $(MAKE) -fMakefile.ruby clean; fi
rm -f Makefile.ruby Makefile.new
rm -f Makefile.ruby Makefile.bak
rm -f *.o *.so *.log
endif

View File

@@ -2,16 +2,8 @@
require 'mkmf'
# hack 1: ruby black magic to write a Makefile.new instead of a Makefile
alias open_orig open
def open(path, mode=nil, perm=nil)
path = 'Makefile.new' if path == 'Makefile'
if block_given?
open_orig(path, mode, perm) { |io| yield(io) }
else
open_orig(path, mode, perm)
end
end
# hack 1: Before extconf.rb gets called, Makefile gets backed up, and
# restored afterwards (see Makefile.am)
if ENV['PREFIX']
prefix = CONFIG['prefix']
@@ -27,7 +19,7 @@ if find_library('apparmor', 'parse_record', '../../src/.libs') and
# hack 2: strip all rpath references
open('Makefile.ruby', 'w') do |out|
IO.foreach('Makefile.new') do |line|
IO.foreach('Makefile') do |line|
out.puts line.gsub(/-Wl,-R'[^']*'/, '')
end
end

View File

@@ -0,0 +1 @@
audit.log:type=AVC msg=audit(1630913351.586:4): apparmor="STATUS" info="AppArmor Filesystem Enabled" pid=1 comm="swapper/0"

View File

@@ -0,0 +1,3 @@
START
File: status-filesystem-enabled.in
Event type: AA_RECORD_INVALID

View File

@@ -0,0 +1 @@
2021-09-11T20:57:41.91645 kern.notice: [ 469.180605] audit: type=1400 audit(1631392703.952:3): apparmor="ALLOWED" operation="mkdir" profile="/usr/sbin/sshd" name="/run/user/1000/kakoune/" pid=2545 comm="sshd" requested_mask="c" denied_mask="c" fsuid=1000 ouid=1000

View File

@@ -0,0 +1,15 @@
START
File: testcase_socklogd_mkdir.in
Event type: AA_RECORD_ALLOWED
Audit ID: 1631392703.952:3
Operation: mkdir
Mask: c
Denied Mask: c
fsuid: 1000
ouid: 1000
Profile: /usr/sbin/sshd
Name: /run/user/1000/kakoune/
Command: sshd
PID: 2545
Epoch: 1631392703
Audit subid: 3

View File

@@ -0,0 +1,4 @@
/usr/sbin/sshd {
owner /run/user/1000/kakoune/ w,
}

View File

@@ -60,7 +60,7 @@ WARNINGS = -Wall
CXX_WARNINGS = ${WARNINGS} ${EXTRA_WARNINGS}
CPP_WARNINGS =
ifndef CFLAGS
CFLAGS = -g -O2 -pipe
CFLAGS = -g -O2 -pipe -flto-partition=none
ifdef DEBUG
CFLAGS += -pg -D DEBUG
@@ -102,7 +102,7 @@ SRCS = parser_common.c parser_include.c parser_interface.c parser_lex.c \
af_rule.cc af_unix.cc policy_cache.c default_features.c
HDRS = parser.h parser_include.h immunix.h mount.h dbus.h lib.h profile.h \
rule.h common_optarg.h signal.h ptrace.h network.h af_rule.h af_unix.h \
policy_cache.h
policy_cache.h file_cache.h
TOOLS = apparmor_parser
OBJECTS = $(patsubst %.cc, %.o, $(SRCS:.c=.o))
@@ -215,10 +215,10 @@ apparmor_parser: $(OBJECTS) $(AAREOBJECTS) $(LIBAPPARMOR_A)
$(CXX) $(LDFLAGS) $(EXTRA_CFLAGS) -o $@ $(OBJECTS) $(LIBS) \
${LEXLIB} $(AAREOBJECTS) $(AARE_LDFLAGS) $(AALIB)
parser_yacc.c parser_yacc.h: parser_yacc.y parser.h profile.h
parser_yacc.c parser_yacc.h: parser_yacc.y parser.h profile.h file_cache.h
$(YACC) $(YFLAGS) -o parser_yacc.c parser_yacc.y
parser_lex.c: parser_lex.l parser_yacc.h parser.h profile.h mount.h dbus.h policy_cache.h
parser_lex.c: parser_lex.l parser_yacc.h parser.h profile.h mount.h dbus.h policy_cache.h file_cache.h
$(LEX) ${LEXFLAGS} -o$@ $<
parser_lex.o: parser_lex.c parser.h parser_yacc.h
@@ -230,13 +230,13 @@ parser_misc.o: parser_misc.c parser.h parser_yacc.h profile.h cap_names.h $(APPA
parser_yacc.o: parser_yacc.c parser_yacc.h $(APPARMOR_H)
$(CXX) $(EXTRA_CFLAGS) -c -o $@ $<
parser_main.o: parser_main.c parser.h parser_version.h policy_cache.h libapparmor_re/apparmor_re.h $(APPARMOR_H)
parser_main.o: parser_main.c parser.h parser_version.h policy_cache.h file_cache.h libapparmor_re/apparmor_re.h $(APPARMOR_H)
$(CXX) $(EXTRA_CFLAGS) -c -o $@ $<
parser_interface.o: parser_interface.c parser.h profile.h libapparmor_re/apparmor_re.h
$(CXX) $(EXTRA_CFLAGS) -c -o $@ $<
parser_include.o: parser_include.c parser.h parser_include.h
parser_include.o: parser_include.c parser.h parser_include.h file_cache.h
$(CXX) $(EXTRA_CFLAGS) -c -o $@ $<
parser_merge.o: parser_merge.c parser.h profile.h
@@ -257,7 +257,7 @@ parser_policy.o: parser_policy.c parser.h parser_yacc.h profile.h
parser_alias.o: parser_alias.c parser.h profile.h
$(CXX) $(EXTRA_CFLAGS) -c -o $@ $<
parser_common.o: parser_common.c parser.h
parser_common.o: parser_common.c parser.h file_cache.h
$(CXX) $(EXTRA_CFLAGS) -c -o $@ $<
mount.o: mount.cc mount.h parser.h immunix.h rule.h
@@ -307,10 +307,18 @@ parser_version.h: Makefile
# as well as the filtering that occurs for network protocols that
# apparmor should not mediate.
af_names.h: ../common/list_af_names.sh
../common/list_af_names.sh | LC_ALL=C sed -n -e 's/[ \t]\?AF_MAX[ \t]\+[0-9]\+,//g' -e 's/[ \t]\+\?AF_\([A-Z0-9_]\+\)[ \t]\+\([0-9]\+\),/#ifndef AF_\1\n# define AF_\1 \2\n#endif\nAA_GEN_NET_ENT("\L\1", \UAF_\1)\n/pg' > $@
../common/list_af_names.sh | LC_ALL=C sed -n -e 's/AF_MAX[ \t]\+\([0-9]\+\),\?.*/\n#define AA_AF_MAX \1\n/p' >> $@
# cat $@
generated_af_names.h: ../common/list_af_names.sh
../common/list_af_names.sh > $@
af_names.h: generated_af_names.h base_af_names.h
cat base_af_names.h | diff -u - generated_af_names.h | grep -v '^.AF_MAX' | grep '^\+[^+]' ; \
if [ $$? -eq 1 ] ; then \
cat base_af_names.h | LC_ALL=C sed -n -e 's/[ \t]\?AF_MAX[ \t]\+[0-9]\+,//g' -e 's/[ \t]\+\?AF_\([A-Z0-9_]\+\)[ \t]\+\([0-9]\+\),/#ifndef AF_\1\n# define AF_\1 \2\n#endif\nAA_GEN_NET_ENT("\L\1", \UAF_\1)\n/pg' > $@ ; \
cat base_af_names.h | LC_ALL=C sed -n -e 's/AF_MAX[ \t]\+\([0-9]\+\),\?.*/\n#define AA_AF_MAX \1\n/p' >> $@ ; \
else \
echo "Error: new AF names detected; please update base_af_names.h with values from generated_af_names.h" ; \
exit 1 ; \
fi
generated_cap_names.h: /usr/include/linux/capability.h
../common/list_capabilities.sh | LC_ALL=C sed -n -e "s/[ \\t]\\?CAP_\\([A-Z0-9_]\\+\\)/\{\"\\L\\1\", \\UCAP_\\1, NO_BACKMAP_CAP, CAPFLAG_BASE_FEATURE\},\\n/pg" > $@
@@ -411,6 +419,7 @@ install-indep: indep
install -m 755 -d ${DESTDIR}/var/lib/apparmor
install -m 755 -d $(APPARMOR_BIN_PREFIX)
install -m 755 rc.apparmor.functions $(APPARMOR_BIN_PREFIX)
install -m 755 profile-load $(APPARMOR_BIN_PREFIX)
$(MAKE) -C po install NAME=${NAME} DESTDIR=${DESTDIR}
$(MAKE) install_manpages DESTDIR=${DESTDIR}
@@ -434,7 +443,7 @@ clean: pod_clean
rm -f $(YACC_C_FILES)
rm -f parser_version.h
rm -f $(NAME)*.tar.gz $(NAME)*.tgz
rm -f af_names.h
rm -f af_names.h generated_af_names.h
rm -f cap_names.h generated_cap_names.h
rm -rf techdoc.aux techdoc.out techdoc.log techdoc.pdf techdoc.toc techdoc.txt techdoc/
$(MAKE) -s -C $(AAREDIR) clean

View File

@@ -148,7 +148,7 @@ capabilities(7))
B<NETWORK RULE> = [ I<QUALIFIERS> ] 'network' [ I<DOMAIN> ] [ I<TYPE> | I<PROTOCOL> ]
B<DOMAIN> = ( 'unix' | 'inet' | 'ax25' | 'ipx' | 'appletalk' | 'netrom' | 'bridge' | 'atmpvc' | 'x25' | 'inet6' | 'rose' | 'netbeui' | 'security' | 'key' | 'netlink' | 'packet' | 'ash' | 'econet' | 'atmsvc' | 'rds' | 'sna' | 'irda' | 'pppox' | 'wanpipe' | 'llc' | 'ib' | 'mpls' | 'can' | 'tipc' | 'bluetooth' | 'iucv' | 'rxrpc' | 'isdn' | 'phonet' | 'ieee802154' | 'caif' | 'alg' | 'nfc' | 'vsock' | 'kcm' | 'qipcrtr' | 'smc' | 'xdp' ) ','
B<DOMAIN> = ( 'unix' | 'inet' | 'ax25' | 'ipx' | 'appletalk' | 'netrom' | 'bridge' | 'atmpvc' | 'x25' | 'inet6' | 'rose' | 'netbeui' | 'security' | 'key' | 'netlink' | 'packet' | 'ash' | 'econet' | 'atmsvc' | 'rds' | 'sna' | 'irda' | 'pppox' | 'wanpipe' | 'llc' | 'ib' | 'mpls' | 'can' | 'tipc' | 'bluetooth' | 'iucv' | 'rxrpc' | 'isdn' | 'phonet' | 'ieee802154' | 'caif' | 'alg' | 'nfc' | 'vsock' | 'kcm' | 'qipcrtr' | 'smc' | 'xdp' | 'mctp' ) ','
B<TYPE> = ( 'stream' | 'dgram' | 'seqpacket' | 'rdm' | 'raw' | 'packet' )
@@ -842,7 +842,7 @@ and other operations that are typically reserved for the root user.
AppArmor supports simple coarse grained network mediation. The network
rule restrict all socket(2) based operations. The mediation done is
a course grained check on whether a socket of a given type and family
a coarse-grained check on whether a socket of a given type and family
can be created, read, or written. There is no mediation based of port
number or protocol beyond tcp, udp, and raw. Network netlink(7) rules may
only specify type 'dgram' and 'raw'.

View File

@@ -71,6 +71,13 @@ fi
case "$1" in
start)
if [ -x /usr/bin/systemd-detect-virt ] && \
systemd-detect-virt --quiet --container && \
! is_container_with_internal_policy; then
aa_log_daemon_msg "Not starting AppArmor in container"
aa_log_end_msg 0
exit 0
fi
apparmor_start
rc=$?
;;
@@ -79,6 +86,13 @@ case "$1" in
rc=$?
;;
restart|reload|force-reload)
if [ -x /usr/bin/systemd-detect-virt ] && \
systemd-detect-virt --quiet --container && \
! is_container_with_internal_policy; then
aa_log_daemon_msg "Not starting AppArmor in container"
aa_log_end_msg 0
exit 0
fi
apparmor_restart
rc=$?
;;

46
parser/base_af_names.h Normal file
View File

@@ -0,0 +1,46 @@
AF_UNSPEC 0,
AF_UNIX 1,
AF_INET 2,
AF_AX25 3,
AF_IPX 4,
AF_APPLETALK 5,
AF_NETROM 6,
AF_BRIDGE 7,
AF_ATMPVC 8,
AF_X25 9,
AF_INET6 10,
AF_ROSE 11,
AF_NETBEUI 13,
AF_SECURITY 14,
AF_KEY 15,
AF_NETLINK 16,
AF_PACKET 17,
AF_ASH 18,
AF_ECONET 19,
AF_ATMSVC 20,
AF_RDS 21,
AF_SNA 22,
AF_IRDA 23,
AF_PPPOX 24,
AF_WANPIPE 25,
AF_LLC 26,
AF_IB 27,
AF_MPLS 28,
AF_CAN 29,
AF_TIPC 30,
AF_BLUETOOTH 31,
AF_IUCV 32,
AF_RXRPC 33,
AF_ISDN 34,
AF_PHONET 35,
AF_IEEE802154 36,
AF_CAIF 37,
AF_ALG 38,
AF_NFC 39,
AF_VSOCK 40,
AF_KCM 41,
AF_QIPCRTR 42,
AF_SMC 43,
AF_XDP 44,
AF_MCTP 45,
AF_MAX 46,

View File

@@ -19,8 +19,29 @@
#ifndef __AA_CAPABILITY_H
#define __AA_CAPABILITY_H
#include <cstdint>
#include <linux/capability.h>
#define NO_BACKMAP_CAP 0xff
#ifndef CAP_AUDIT_WRITE
#define CAP_AUDIT_WRITE 29
#endif
#ifndef CAP_AUDIT_CONTROL
#define CAP_AUDIT_CONTROL 30
#endif
#ifndef CAP_SETFCAP
#define CAP_SETFCAP 31
#endif
#ifndef CAP_MAC_OVERRIDE
#define CAP_MAC_OVERRIDE 32
#endif
#ifndef CAP_AUDIT_READ
#define CAP_AUDIT_READ 37
#endif
#ifndef CAP_PERFMON
#define CAP_PERFMON 38
#endif

52
parser/file_cache.h Normal file
View File

@@ -0,0 +1,52 @@
/*
* Copyright (c) 2021
* Canonical, Ltd. (All rights reserved)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of version 2 of the GNU General Public
* License published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, contact Canonical Ltd.
*/
#ifndef __AA_FILE_CACHE_H
#define __AA_FILE_CACHE_H
#include <set>
#include <string>
using namespace std;
/* TODO: have includecache be a frontend for file cache, don't just
* store name.
*/
class IncludeCache_t {
public:
set<string> cache;
IncludeCache_t() = default;
virtual ~IncludeCache_t() = default;
/* return true if in set */
bool find(const char *name) {
return cache.find(name) != cache.end();
}
bool insert(const char *name) {
pair<set<string>::iterator,bool> res = cache.insert(name);
if (res.second == false) {
return false;
}
/* inserted */
return true;
}
};
#endif /* __AA_FILE_CACHE_H */

View File

@@ -183,7 +183,7 @@ int strn_escseq(const char **pos, const char *chrs, size_t n)
if (strchr(chrs, c))
return c;
/* unsupported escap sequence, backup to return that char */
/* unsupported escape sequence, backup to return that char */
pos--;
return -1;
}

View File

@@ -599,9 +599,9 @@ public:
int min_match_len()
{
if (contains_oob()) {
return 0;
}
/* Inverse match does not match any oob char at this time
* so only count characters
*/
return 1;
}

View File

@@ -32,6 +32,7 @@
#include <sys/apparmor.h>
#include "file_cache.h"
#include "immunix.h"
#include "libapparmor_re/apparmor_re.h"
#include "libapparmor_re/aare_rules.h"
@@ -353,6 +354,8 @@ extern char *profile_ns;
extern char *current_filename;
extern FILE *ofile;
extern int read_implies_exec;
extern IncludeCache_t *g_includecache;
extern void pwarnf(bool werr, const char *fmt, ...) __attribute__((__format__(__printf__, 2, 3)));
extern void common_warn_once(const char *name, const char *msg, const char **warned_name);

View File

@@ -20,6 +20,7 @@
#include <stdarg.h>
#include "parser.h"
#include "file_cache.h"
/* Policy versioning is determined by a combination of 3 values:
* policy_version: version of txt policy
@@ -95,6 +96,8 @@ char *current_filename = NULL;
FILE *ofile = NULL;
IncludeCache_t *g_includecache;
#ifdef FORCE_READ_IMPLIES_EXEC
int read_implies_exec = 1;
#else

View File

@@ -151,7 +151,7 @@ void parse_default_paths(void)
add_search_dir(basedir);
}
FILE *search_path(char *filename, char **fullpath)
FILE *search_path(char *filename, char **fullpath, bool *skip)
{
FILE *newf = NULL;
char *buf = NULL;
@@ -161,15 +161,27 @@ FILE *search_path(char *filename, char **fullpath)
perror("asprintf");
exit(1);
}
if (g_includecache->find(buf)) {
/* hit do not want to re-include */
*skip = true;
return NULL;
}
newf = fopen(buf, "r");
if (newf && fullpath)
*fullpath = buf;
else
free(buf);
buf = NULL;
if (newf)
if (newf) {
/* ignore failing to insert into cache */
(void) g_includecache->insert(buf);
if (fullpath)
*fullpath = buf;
else
free(buf);
break;
}
free(buf);
buf = NULL;
}
*skip = false;
return newf;
}

View File

@@ -27,7 +27,7 @@ extern void init_base_dir(void);
extern void set_base_dir(char *dir);
extern void parse_default_paths(void);
extern int do_include_preprocessing(char *profilename);
FILE *search_path(char *filename, char **fullpath);
FILE *search_path(char *filename, char **fullpath, bool *skip);
extern void push_include_stack(char *filename);
extern void pop_include_stack(void);

View File

@@ -44,6 +44,7 @@
#include "parser_yacc.h"
#include "lib.h"
#include "policy_cache.h"
#include "file_cache.h"
#ifdef PDEBUG
#undef PDEBUG
@@ -134,10 +135,19 @@ static int include_dir_cb(int dirfd unused, const char *name, struct stat *st,
if (is_blacklisted(name, path))
return 0;
if (g_includecache->find(path)) {
PDEBUG("skipping reinclude of \'%s\' in \'%s\'\n", path,
d->filename);
return 0;
}
/* Handle symlink here. See _aa_dirat_for_each in private.c */
if (S_ISREG(st->st_mode)) {
if (!(yyin = fopen(path,"r")))
yyerror(_("Could not open '%s' in '%s'"), path, d->filename);
PDEBUG("Opened include \"%s\" in \"%s\"\n", path, d->filename);
(void) g_includecache->insert(path);
update_mru_tstamp(yyin, path);
push_include_stack(path);
yypush_buffer_state(yy_create_buffer(yyin, YY_BUF_SIZE));
@@ -151,16 +161,29 @@ void include_filename(char *filename, int search, bool if_exists)
FILE *include_file = NULL;
struct stat my_stat;
autofree char *fullpath = NULL;
bool cached;
if (search) {
if (preprocess_only)
include_file = search_path(filename, &fullpath, &cached);
if (!include_file && cached) {
goto skip;
} else if (preprocess_only) {
fprintf(yyout, "\n\n##included <%s>\n", filename);
include_file = search_path(filename, &fullpath);
} else if (!include_file && preprocess_only) {
fprintf(yyout, "\n\n##failed include <%s>\n", filename);
}
} else if (g_includecache->find(filename)) {
/* duplicate entry skip */
goto skip;
} else {
if (preprocess_only)
fprintf(yyout, "\n\n##included \"%s\"\n", filename);
fullpath = strdup(filename);
include_file = fopen(fullpath, "r");
if (include_file)
/* ignore failure to insert into cache */
(void) g_includecache->insert(filename);
}
if (!include_file) {
@@ -181,6 +204,7 @@ void include_filename(char *filename, int search, bool if_exists)
yypush_buffer_state(yy_create_buffer( yyin, YY_BUF_SIZE ));
} else if (S_ISDIR(my_stat.st_mode)) {
struct cb_struct data = { fullpath, filename };
update_mru_tstamp(include_file, fullpath);
fclose(include_file);
include_file = NULL;
if (dirat_for_each(AT_FDCWD, fullpath, &data, include_dir_cb)) {
@@ -188,6 +212,13 @@ void include_filename(char *filename, int search, bool if_exists)
" '%s' in '%s'"), fullpath, filename);;
}
}
return;
skip:
if (preprocess_only)
fprintf(yyout, "\n\n##skipped duplicate include <%s>\n", filename);
return;
}
static char *lsntrim(char *s, int l)
@@ -712,7 +743,7 @@ include/{WS} {
}
}
<INITIAL,SUB_ID,SUB_ID_WS,SUB_VALUE,LIST_VAL_MODE,EXTCOND_MODE,LIST_COND_VAL,LIST_COND_PAREN_VAL,LIST_COND_MODE,EXTCONDLIST_MODE,ASSIGN_MODE,NETWORK_MODE,CHANGE_PROFILE_MODE,MOUNT_MODE,DBUS_MODE,SIGNAL_MODE,PTRACE_MODE,UNIX_MODE,RLIMIT_MODEINCLUDE,INCLUDE_EXISTS,ABI_MODE>{
<INITIAL,SUB_ID,SUB_ID_WS,SUB_VALUE,LIST_VAL_MODE,EXTCOND_MODE,LIST_COND_VAL,LIST_COND_PAREN_VAL,LIST_COND_MODE,EXTCONDLIST_MODE,ASSIGN_MODE,NETWORK_MODE,CHANGE_PROFILE_MODE,MOUNT_MODE,DBUS_MODE,SIGNAL_MODE,PTRACE_MODE,UNIX_MODE,RLIMIT_MODE,INCLUDE,INCLUDE_EXISTS,ABI_MODE>{
(.|\n) {
DUMP_PREPROCESS;
/* Something we didn't expect */

View File

@@ -50,6 +50,7 @@
#include "common_optarg.h"
#include "policy_cache.h"
#include "libapparmor_re/apparmor_re.h"
#include "file_cache.h"
#define OLD_MODULE_NAME "subdomain"
#define PROC_MODULES "/proc/modules"
@@ -84,13 +85,13 @@ int mru_skip_cache = 1;
/* for jobs_max and jobs
* LONG_MAX : no limit
* LONG_MIN : auto = detect system processing cores
* n : use that number of processes/threads to compile policy
* -n : multiply by the number of CPUs to compile policy
*/
#define JOBS_AUTO LONG_MIN
#define DEFAULT_JOBS_MAX -8
#define DEFAULT_ESTIMATED_JOB_SIZE (50 * 1024 * 1024)
long estimated_job_size = DEFAULT_ESTIMATED_JOB_SIZE;
long jobs_max = -DEFAULT_JOBS_MAX; /* 8 * cpus */
long jobs_max = DEFAULT_JOBS_MAX; /* 8 * cpus */
long jobs = JOBS_AUTO; /* default: number of processor cores */
long njobs = 0;
long jobs_scale = 0; /* number of chance to resample online
@@ -1035,6 +1036,8 @@ void reset_parser(const char *filename)
aa_features_unref(policy_features);
policy_features = NULL;
clear_cap_flag(CAPFLAG_POLICY_FEATURE);
delete g_includecache;
g_includecache = new IncludeCache_t();
}
int test_for_dir_mode(const char *basename, const char *linkdir)
@@ -1418,14 +1421,14 @@ static void auto_tune_parameters(void)
} else if (estimated_jobs < ncpus) {
/* --jobs=estimate_jobs */
jobs = estimated_jobs;
PDEBUG("Auto tune: --jobs=%d", estimate_jobs);
PDEBUG("Auto tune: --jobs=%ld", estimated_jobs);
} else {
long long n = estimated_jobs / ncpus;
if (n < -DEFAULT_JOBS_MAX) {
/* --jobs=cpus*n */
jobs = -n;
PDEBUG("Auto tune: --jobs=%d", jobs);
PDEBUG("Auto tune: --jobs=%ld", jobs);
}
}
} else {
@@ -1447,6 +1450,8 @@ static int profile_dir_cb(int dirfd unused, const char *name, struct stat *st,
{
int rc = 0;
/* Handle symlink here. See _aa_dirat_for_each in private.c */
if (!S_ISDIR(st->st_mode) && !is_blacklisted(name, NULL)) {
struct dir_cb_data *cb_data = (struct dir_cb_data *)data;
autofree char *path = NULL;
@@ -1469,6 +1474,8 @@ static int binary_dir_cb(int dirfd unused, const char *name, struct stat *st,
{
int rc = 0;
/* Handle symlink here. See _aa_dirat_for_each in private.c */
if (!S_ISDIR(st->st_mode) && !is_blacklisted(name, NULL)) {
struct dir_cb_data *cb_data = (struct dir_cb_data *)data;
autofree char *path = NULL;
@@ -1661,7 +1668,7 @@ int main(int argc, char *argv[])
if ((retval = dirat_for_each(AT_FDCWD, profilename,
&cb_data, cb))) {
last_error = errno;
PDEBUG("Failed loading profiles from %s\n",
PERROR("There was an error while loading profiles from %s\n",
profilename);
if (abort_on_error)
break;

View File

@@ -29,6 +29,7 @@
#include <errno.h>
#include <sys/apparmor.h>
#include "lib.h"
#include "parser.h"
#include "profile.h"
#include "parser_yacc.h"
@@ -145,6 +146,56 @@ void add_entry_to_policy(Profile *prof, struct cod_entry *entry)
prof->entries = entry;
}
static bool add_proc_access(Profile *prof, const char *rule)
{
/* FIXME: should use @{PROC}/@{PID}/attr/{apparmor/,}{current,exec} */
struct cod_entry *new_ent;
/* allow probe for new interfaces */
char *buffer = strdup("/proc/*/attr/apparmor/");
if (!buffer) {
PERROR("Memory allocation error\n");
return FALSE;
}
new_ent = new_entry(buffer, AA_MAY_READ, NULL);
if (!new_ent) {
free(buffer);
PERROR("Memory allocation error\n");
return FALSE;
}
add_entry_to_policy(prof, new_ent);
/* allow probe if apparmor is enabled for the old interface */
buffer = strdup("/sys/module/apparmor/parameters/enabled");
if (!buffer) {
PERROR("Memory allocation error\n");
return FALSE;
}
new_ent = new_entry(buffer, AA_MAY_READ, NULL);
if (!new_ent) {
free(buffer);
PERROR("Memory allocation error\n");
return FALSE;
}
add_entry_to_policy(prof, new_ent);
/* allow setting on new and old interfaces */
buffer = strdup(rule);
if (!buffer) {
PERROR("Memory allocation error\n");
return FALSE;
}
new_ent = new_entry(buffer, AA_MAY_WRITE, NULL);
if (!new_ent) {
free(buffer);
PERROR("Memory allocation error\n");
return FALSE;
}
add_entry_to_policy(prof, new_ent);
return TRUE;
}
#define CHANGEPROFILE_PATH "/proc/*/attr/{apparmor/,}{current,exec}"
void post_process_file_entries(Profile *prof)
{
struct cod_entry *entry;
@@ -170,22 +221,11 @@ void post_process_file_entries(Profile *prof)
}
/* if there are change_profile rules, this implies that we need
* access to /proc/self/attr/current
* access to some /proc/ interfaces
*/
if (cp_mode & AA_CHANGE_PROFILE) {
/* FIXME: should use @{PROC}/@{PID}/attr/{apparmor/,}{current,exec} */
struct cod_entry *new_ent;
char *buffer = strdup("/proc/*/attr/{apparmor/,}{current,exec}");
if (!buffer) {
PERROR("Memory allocation error\n");
if (!add_proc_access(prof, CHANGEPROFILE_PATH))
exit(1);
}
new_ent = new_entry(buffer, AA_MAY_WRITE, NULL);
if (!new_ent) {
PERROR("Memory allocation error\n");
exit(1);
}
add_entry_to_policy(prof, new_ent);
}
}
@@ -202,19 +242,13 @@ void post_process_rule_entries(Profile *prof)
*/
static int profile_add_hat_rules(Profile *prof)
{
struct cod_entry *entry;
/* don't add hat rules if not hat or profile doesn't have hats */
if (!prof->flags.hat && prof->hat_table.empty())
return 0;
/* add entry to hat */
entry = new_entry(strdup(CHANGEHAT_PATH), AA_MAY_WRITE, NULL);
if (!entry)
if (!add_proc_access(prof, CHANGEHAT_PATH))
return ENOMEM;
add_entry_to_policy(prof, entry);
return 0;
}

View File

@@ -468,20 +468,26 @@ static int process_profile_name_xmatch(Profile *prof)
{
std::string tbuf;
pattern_t ptype;
const char *name;
char *name;
struct cond_entry *entry;
const char *xattr_value;
/* don't filter_slashes for profile names */
if (prof->attachment)
if (prof->attachment) {
name = prof->attachment;
else
name = local_name(prof->name);
} else {
/* don't filter_slashes for profile names, do on attachment */
name = strdup(local_name(prof->name));
if (!name)
return FALSE;
}
filter_slashes(name);
ptype = convert_aaregex_to_pcre(name, 0, glob_default, tbuf,
&prof->xmatch_len);
if (ptype == ePatternBasic)
prof->xmatch_len = strlen(name);
if (!prof->attachment)
free(name);
if (ptype == ePatternInvalid) {
PERROR(_("%s: Invalid profile name '%s' - bad regular expression\n"), progname, name);
@@ -505,6 +511,7 @@ static int process_profile_name_xmatch(Profile *prof)
list_for_each(prof->altnames, alt) {
int len;
tbuf.clear();
filter_slashes(alt->name);
ptype = convert_aaregex_to_pcre(alt->name, 0,
glob_default,
tbuf, &len);
@@ -516,7 +523,7 @@ static int process_profile_name_xmatch(Profile *prof)
}
if (prof->xattrs.list) {
if (!(features_supports_domain_xattr && kernel_supports_oob)) {
warn_once_xattr(name);
warn_once_xattr(prof->name);
free_cond_entry_list(prof->xattrs);
goto build;
}

View File

@@ -44,20 +44,6 @@
#include <netinet/in.h>
#include <arpa/inet.h>
#include <linux/capability.h>
#ifndef CAP_AUDIT_WRITE
#define CAP_AUDIT_WRITE 29
#endif
#ifndef CAP_AUDIT_CONTROL
#define CAP_AUDIT_CONTROL 30
#endif
#ifndef CAP_SETFCAP
#define CAP_SETFCAP 31
#endif
#ifndef CAP_MAC_OVERRIDE
#define CAP_MAC_OVERRIDE 32
#endif
#define CIDR_32 htonl(0xffffffff)
#define CIDR_24 htonl(0xffffff00)
@@ -220,6 +206,7 @@ void add_local_entry(Profile *prof);
struct cond_entry_list cond_entry_list;
int boolean;
struct prefixes prefix;
IncludeCache_t *includecache;
}
%type <id> TOK_ID
@@ -334,9 +321,17 @@ opt_id: { /* nothing */ $$ = NULL; }
opt_id_or_var: { /* nothing */ $$ = NULL; }
| id_or_var { $$ = $1; }
profile_base: TOK_ID opt_id_or_var opt_cond_list flags TOK_OPEN rules TOK_CLOSE
profile_base: TOK_ID opt_id_or_var opt_cond_list flags TOK_OPEN
{
Profile *prof = $6;
/* mid rule action
* save current cache, restore at end of block
*/
$<includecache>$ = g_includecache;
g_includecache = new IncludeCache_t();
}
rules TOK_CLOSE
{
Profile *prof = $7;
bool self_stack = false;
if (!prof) {
@@ -387,6 +382,10 @@ profile_base: TOK_ID opt_id_or_var opt_cond_list flags TOK_OPEN rules TOK_CLOSE
post_process_file_entries(prof);
post_process_rule_entries(prof);
prof->flags.debug(cerr);
/* restore previous blocks include cache */
delete g_includecache;
g_includecache = $<includecache>6;
$$ = prof;
};
@@ -1775,12 +1774,17 @@ static int abi_features_base(struct aa_features **features, char *filename, bool
autofclose FILE *f = NULL;
struct stat my_stat;
char *fullpath = NULL;
bool cached;
if (search) {
if (strcmp(filename, "kernel") == 0)
return aa_features_new_from_kernel(features);
f = search_path(filename, &fullpath);
PDEBUG("abi lookup '%s' -> '%s' f %p\n", filename, fullpath, f);
f = search_path(filename, &fullpath, &cached);
PDEBUG("abi lookup '%s' -> '%s' f %p cached %d\n", filename, fullpath, f, cached);
if (!f && cached) {
*features = NULL;
return 0;
}
} else {
f = fopen(filename, "r");
PDEBUG("abi relpath '%s' f %p\n", filename, f);
@@ -1809,10 +1813,15 @@ static void abi_features(char *filename, bool search)
yyerror(_("failed to find features abi '%s': %m"), filename);
}
if (policy_features) {
if (!aa_features_is_equal(tmp_features, policy_features)) {
pwarn(WARN_ABI, _("%s: %s features abi '%s' differs from policy declared feature abi, using the features abi declared in policy\n"), progname, current_filename, filename);
if (tmp_features) {
if (!aa_features_is_equal(tmp_features, policy_features)) {
pwarn(WARN_ABI, _("%s: %s features abi '%s' differs from policy declared feature abi, using the features abi declared in policy\n"), progname, current_filename, filename);
}
aa_features_unref(tmp_features);
}
aa_features_unref(tmp_features);
} else if (!tmp_features) {
/* skipped reinclude, but features not set */
yyerror(_("failed features abi not set but include cache skipped\n"));
} else {
/* first features abi declaration */
policy_features = tmp_features;

52
parser/profile-load Executable file
View File

@@ -0,0 +1,52 @@
#!/bin/sh
# profile-load
#
# ----------------------------------------------------------------------
# Copyright (c) 2010-2015 Canonical, Ltd.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public
# License published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, contact Canonical, Ltd.
# ----------------------------------------------------------------------
#
# Helper for loading an AppArmor profile in pre-start scripts.
[ -z "$1" ] && exit 1 # require a profile name
. /lib/apparmor/rc.apparmor.functions
# do not load in a container
if [ -x /usr/bin/systemd-detect-virt ] && \
systemd-detect-virt --quiet --container && \
! is_container_with_internal_policy; then
exit 0
fi
[ -d /rofs/etc/apparmor.d ] && exit 0 # do not load if running liveCD
profile=/etc/apparmor.d/"$1"
[ -e "$profile" ] || exit 0 # skip when missing profile
module=/sys/module/apparmor
[ -d $module ] || exit 0 # do not load without AppArmor in kernel
[ -x /sbin/apparmor_parser ] || exit 0 # do not load without parser
aafs=/sys/kernel/security/apparmor
[ -d $aafs ] || exit 0 # do not load if unmounted
[ -w $aafs/.load ] || exit 1 # fail if cannot load profiles
params=$module/parameters
[ -r $params/enabled ] || exit 0 # do not load if missing
read -r enabled < $params/enabled || exit 1 # if this fails, something went wrong
[ "$enabled" = "Y" ] || exit 0 # do not load if disabled
/sbin/apparmor_parser -r -W "$profile" || exit 0 # LP: #1058356

View File

@@ -1,117 +0,0 @@
#!/bin/sh
# ----------------------------------------------------------------------
# Copyright (c) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007
# NOVELL (All rights reserved)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public
# License published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, contact Novell, Inc.
# ----------------------------------------------------------------------
# rc.apparmor by Steve Beattie
#
# /etc/init.d/apparmor
#
# chkconfig: 2345 01 99
# description: AppArmor rc file. This rc script inserts the apparmor \
# module and runs the parser on the /etc/apparmor.d/ \
# directory.
#
### BEGIN INIT INFO
# Provides: apparmor
# Required-Start:
# Required-Stop:
# Default-Start: 3 4 5
# Default-Stop: 0 1 2 6
# Short-Description: AppArmor initialization
# Description: AppArmor rc file. This rc script inserts the apparmor
# module and runs the parser on the /etc/apparmor.d/
# directory.
### END INIT INFO
APPARMOR_FUNCTIONS=/lib/apparmor/rc.apparmor.functions
aa_action() {
STRING=$1
shift
$*
rc=$?
if [ $rc -eq 0 ] ; then
aa_log_success_msg $"$STRING "
else
aa_log_failure_msg $"$STRING "
fi
return $rc
}
aa_log_success_msg() {
[ -n "$1" ] && echo -n $1
echo ": done."
}
aa_log_warning_msg() {
[ -n "$1" ] && echo -n $1
echo ": Warning."
}
aa_log_failure_msg() {
[ -n "$1" ] && echo -n $1
echo ": Failed."
}
aa_log_skipped_msg() {
[ -n "$1" ] && echo -n $1
echo ": Skipped."
}
usage() {
echo "Usage: $0 {start|stop|restart|try-restart|reload|force-reload|status|kill}"
}
# source apparmor function library
if [ -f "${APPARMOR_FUNCTIONS}" ]; then
. ${APPARMOR_FUNCTIONS}
else
aa_log_failure_msg "Unable to find AppArmor initscript functions"
exit 1
fi
test -x ${PARSER} || exit 0 # by debian policy
case "$1" in
start)
apparmor_start
rc=$?
;;
stop)
apparmor_stop
rc=$?
;;
restart|reload|force-reload)
apparmor_restart
rc=$?
;;
try-restart)
apparmor_try_restart
rc=$?
;;
kill)
apparmor_kill
rc=$?
;;
status)
apparmor_status
rc=$?
;;
*)
usage
exit 1
;;
esac
exit $rc

View File

@@ -68,7 +68,7 @@ is_apparmor_present() {
# something like `systemd-detect-virt --container`.
#
# The only known container environments capable of supporting internal policy
# are LXD and LXC environment.
# are LXD and LXC environments, and Windows Subsystem for Linux.
#
# Returns 0 if the container environment is capable of having its own internal
# policy and non-zero otherwise.
@@ -90,6 +90,12 @@ is_container_with_internal_policy() {
local ns_stacked
local ns_name
# WSL needs to be detected explicitly
if [ -x /usr/bin/systemd-detect-virt ] && \
[ "$(systemd-detect-virt --container)" = "wsl" ]; then
return 0
fi
if ! [ -f "$ns_stacked_path" ] || ! [ -f "$ns_name_path" ]; then
return 1
fi
@@ -111,37 +117,6 @@ is_container_with_internal_policy() {
return 0
}
# This set of patterns to skip needs to be kept in sync with
# AppArmor.pm::isSkippableFile()
# returns 0 if profile should NOT be skipped
# returns 1 on verbose skip
# returns 2 on silent skip
skip_profile() {
local profile="$1"
if [ "${profile%.rpmnew}" != "$profile" ] || \
[ "${profile%.rpmsave}" != "$profile" ] || \
[ "${profile%.orig}" != "$profile" ] || \
[ "${profile%.rej}" != "$profile" ] || \
[ "${profile%\~}" != "$profile" ] ; then
return 1
fi
# Silently ignore the dpkg, pacman, and xbps files
if [ "${profile%.dpkg-new}" != "$profile" ] || \
[ "${profile%.dpkg-old}" != "$profile" ] || \
[ "${profile%.dpkg-dist}" != "$profile" ] || \
[ "${profile%.dpkg-bak}" != "$profile" ] || \
[ "${profile%.dpkg-remove}" != "$profile" ] || \
[ "${profile%.pacsave}" != "$profile" ] || \
[ "${profile%.pacnew}" != "$profile" ] ; then
return 2
fi
if echo "$profile" | grep -E -q '^.+\.new-[0-9\.]+_[0-9]+$'; then
return 2
fi
return 0
}
__parse_profiles_dir() {
local parser_cmd="$1"
local profile_dir="$2"
@@ -157,41 +132,11 @@ __parse_profiles_dir() {
return 1
fi
# Note: the parser automatically skips files that match skip_profile()
# when we pass it a directory, but not when we pass it an individual
# profile. So we need to use skip_profile only in the latter case,
# as long as the parser is in sync' with skip_profile().
"$PARSER" $PARSER_OPTS "$parser_cmd" -- "$profile_dir" || {
# FIXME: once the parser properly handles broken profiles
# (LP: #1377338), remove the following code and the
# skip_profile() function. For now, if the parser returns
# an error, just run it again separately on each profile.
for profile in "$profile_dir"/*; do
skip_profile "$profile"
skip=$?
if [ "$skip" -eq 2 ]; then
# Ignore skip status == 2 (silent skip)
continue
elif [ "$skip" -ne 0 ] ; then
aa_log_skipped_msg "$profile"
logger -t "AppArmor(init)" -p daemon.warn \
"Skipping profile $profile"
continue
fi
if [ ! -f "$profile" ] ; then
continue
fi
echo "$profile"
done | \
# Use xargs to parallelize calls to the parser over all CPUs
xargs -n1 -d"\n" --max-procs="$(getconf _NPROCESSORS_ONLN)" \
"$PARSER" $PARSER_OPTS "$parser_cmd" --
if [ $? -ne 0 ]; then
status=1
aa_log_failure_msg "At least one profile failed to load"
fi
}
# shellcheck disable=SC2086
if ! "$PARSER" $PARSER_OPTS "$parser_cmd" -- "$profile_dir"; then
status=1
aa_log_failure_msg "At least one profile failed to load"
fi
return "$status"
}
@@ -215,7 +160,6 @@ parse_profiles() {
# run the parser on all of the apparmor profiles
if [ ! -f "$PARSER" ]; then
aa_log_failure_msg "AppArmor parser not found"
aa_log_action_end 1
exit 1
fi
@@ -227,41 +171,6 @@ parse_profiles() {
return "$STATUS"
}
profiles_names_list() {
# run the parser on all of the apparmor profiles
if [ ! -f "$PARSER" ]; then
aa_log_failure_msg "- AppArmor parser not found"
exit 1
fi
for profile_dir in $PROFILE_DIRS; do
if [ ! -d "$profile_dir" ]; then
aa_log_warning_msg "- Profile directory not found: $profile_dir"
continue
fi
for profile in "$profile_dir"/*; do
if skip_profile "$profile" && [ -f "$profile" ] ; then
LIST_ADD=$("$PARSER" -N "$profile" )
if [ $? -eq 0 ]; then
echo "$LIST_ADD"
fi
fi
done
done
}
failstop_system() {
level=$(runlevel | cut -d" " -f2)
if [ "$level" -ne "1" ] ; then
aa_log_failure_msg "- could not start AppArmor. Changing to runlevel 1"
telinit 1;
return 255;
fi
aa_log_failure_msg "- could not start AppArmor."
return 255
}
is_apparmor_loaded() {
if ! is_securityfs_mounted ; then
mount_securityfs
@@ -309,7 +218,7 @@ apparmor_start() {
fi
# if there is anything in the profiles file don't load
if ! read -r line < "$SFS_MOUNTPOINT/profiles"; then
if ! read -r _ < "$SFS_MOUNTPOINT/profiles"; then
parse_profiles load
else
aa_log_skipped_msg ": already loaded with profiles."
@@ -357,7 +266,7 @@ remove_profiles() {
}
apparmor_stop() {
aa_log_daemon_msg "Unloading AppArmor profiles "
aa_log_daemon_msg "Unloading AppArmor profiles"
remove_profiles
rc=$?
aa_log_end_msg "$rc"

View File

@@ -1,125 +0,0 @@
#!/bin/sh
# ----------------------------------------------------------------------
# Copyright (c) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007
# NOVELL (All rights reserved)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public
# License published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, contact Novell, Inc.
# ----------------------------------------------------------------------
# rc.apparmor by Steve Beattie
#
# /etc/init.d/apparmor
#
# chkconfig: 2345 01 99
# description: AppArmor rc file. This rc script inserts the apparmor \
# module and runs the parser on the /etc/apparmor.d/ \
# directory.
#
### BEGIN INIT INFO
# Provides: apparmor
# Required-Start:
# Required-Stop:
# Default-Start: 3 4 5
# Default-Stop: 0 1 2 6
# Short-Description: AppArmor initialization
# Description: AppArmor rc file. This rc script inserts the apparmor
# module and runs the parser on the /etc/apparmor.d/
# directory.
### END INIT INFO
APPARMOR_FUNCTIONS=/lib/apparmor/rc.apparmor.functions
# source function library
if [ -f /etc/init.d/functions ]; then
. /etc/init.d/functions
elif [ -f /etc/rc.d/init.d/functions ]; then
. /etc/rc.d/init.d/functions
elif [ -f /lib/lsb/init-functions ]; then
. /lib/lsb/init-functions
else
exit 0
fi
usage() {
echo "Usage: $0 {start|stop|restart|try-restart|reload|force-reload|status|kill}"
}
aa_log_success_msg() {
echo -n "$*"
success
echo
}
aa_log_warning_msg() {
echo -n "$*"
warning
echo
}
aa_log_skipped_msg() {
echo -n "$*"
warning
echo
}
aa_log_failure_msg() {
echo -n "$*"
failure
echo
}
aa_action() {
STRING=$1
shift
action "${STRING} " "$@"
return $?
}
# source apparmor function library
if [ -f "${APPARMOR_FUNCTIONS}" ]; then
. ${APPARMOR_FUNCTIONS}
else
aa_log_failure_msg "Unable to find AppArmor initscript functions"
exit 1
fi
case "$1" in
start)
apparmor_start
rc=$?
;;
stop)
apparmor_stop
rc=$?
;;
restart|reload|force-reload)
apparmor_restart
rc=$?
;;
try-restart)
apparmor_try_restart
rc=$?
;;
kill)
apparmor_kill
rc=$?
;;
status)
apparmor_status
rc=$?
;;
*)
usage
exit 1
;;
esac
exit $rc

View File

@@ -17,8 +17,8 @@ endif
all: tests
.PHONY: tests error_output gen_dbus gen_xtrans parser_sanity caching minimize equality valgrind
tests: error_output caching minimize equality parser_sanity
.PHONY: tests error_output gen_dbus gen_xtrans parser_sanity caching minimize equality dirtest valgrind
tests: error_output caching minimize equality dirtest parser_sanity
GEN_TRANS_DIRS=simple_tests/generated_x/ simple_tests/generated_perms_leading/ simple_tests/generated_perms_safe/ simple_tests/generated_dbus
@@ -29,7 +29,7 @@ $(GEN_TRANS_DIRS):
mkdir $@
gen_dbus: $(GEN_TRANS_DIRS)
./gen-dbus.pl
./gen-dbus.py
error_output: $(PARSER)
LANG=C ./errors.py -p "$(PARSER)" $(PYTEST_ARG)
@@ -46,6 +46,9 @@ minimize: $(PARSER)
equality: $(PARSER)
LANG=C APPARMOR_PARSER="$(PARSER) $(PARSER_ARGS)" ./equality.sh
dirtest: $(PARSER)
LANG=C APPARMOR_PARSER="$(PARSER) $(PARSER_ARGS)" ./dirtest.sh
valgrind: $(PARSER) gen_xtrans gen_dbus
LANG=C ./valgrind_simple.py -p "$(PARSER) $(PARSER_ARGS)" -v simple_tests

View File

@@ -17,7 +17,6 @@
from argparse import ArgumentParser
import os
import platform
import shutil
import time
import tempfile
@@ -73,13 +72,13 @@ class AAParserCachingCommon(testlib.AATestTemplate):
self.cmd_prefix = [config.parser, '--config-file=./parser.conf', '--base', self.tmp_dir, '--skip-kernel-load']
if not self.is_apparmorfs_mounted():
self.cmd_prefix += ['-M', './features_files/features.all']
self.cmd_prefix.extend(('-M', './features_files/features.all'))
# Otherwise get_cache_dir() will try to create /var/cache/apparmor
# and will fail when the test suite is run as non-root.
self.cmd_prefix += [
self.cmd_prefix.extend((
'--cache-loc', os.path.join(self.tmp_dir, 'cache')
]
))
# create directory for cached blobs
# NOTE: get_cache_dir() requires cmd_prefix to be fully initialized
@@ -98,7 +97,8 @@ class AAParserCachingCommon(testlib.AATestTemplate):
shutil.rmtree(self.tmp_dir)
def get_cache_dir(self, create=False):
cmd = [config.parser, '--print-cache-dir'] + self.cmd_prefix
cmd = [config.parser, '--print-cache-dir']
cmd.extend(self.cmd_prefix)
rc, report = self.run_cmd(cmd)
if rc != 0:
if "unrecognized option '--print-cache-dir'" not in report:
@@ -146,14 +146,11 @@ class AAParserCachingCommon(testlib.AATestTemplate):
class AAParserBasicCachingTests(AAParserCachingCommon):
def setUp(self):
super(AAParserBasicCachingTests, self).setUp()
def test_no_cache_by_default(self):
'''test profiles are not cached by default'''
cmd = list(self.cmd_prefix)
cmd.extend(['-q', '-r', self.profile])
cmd.extend(('-q', '-r', self.profile))
self.run_cmd_check(cmd)
self.assert_path_exists(os.path.join(self.cache_dir, PROFILE), expected=False)
@@ -161,7 +158,7 @@ class AAParserBasicCachingTests(AAParserCachingCommon):
'''test profiles are not cached with --skip-cache'''
cmd = list(self.cmd_prefix)
cmd.extend(['-q', '--write-cache', '--skip-cache', '-r', self.profile])
cmd.extend(('-q', '--write-cache', '--skip-cache', '-r', self.profile))
self.run_cmd_check(cmd)
self.assert_path_exists(os.path.join(self.cache_dir, PROFILE), expected=False)
@@ -169,7 +166,7 @@ class AAParserBasicCachingTests(AAParserCachingCommon):
'''test profiles are cached when requested'''
cmd = list(self.cmd_prefix)
cmd.extend(['-q', '--write-cache', '-r', self.profile])
cmd.extend(('-q', '--write-cache', '-r', self.profile))
self.run_cmd_check(cmd)
self.assert_path_exists(os.path.join(self.cache_dir, PROFILE))
@@ -177,7 +174,7 @@ class AAParserBasicCachingTests(AAParserCachingCommon):
'''test features file is written when caching'''
cmd = list(self.cmd_prefix)
cmd.extend(['-q', '--write-cache', '-r', self.profile])
cmd.extend(('-q', '--write-cache', '-r', self.profile))
self.run_cmd_check(cmd)
self.assert_path_exists(os.path.join(self.cache_dir, PROFILE))
self.assert_path_exists(os.path.join(self.cache_dir, '.features'))
@@ -188,7 +185,7 @@ class AAParserBasicCachingTests(AAParserCachingCommon):
self.require_apparmorfs()
cmd = list(self.cmd_prefix)
cmd.extend(['-q', '--write-cache', '-r', self.profile])
cmd.extend(('-q', '--write-cache', '-r', self.profile))
self.run_cmd_check(cmd)
self.assert_path_exists(os.path.join(self.cache_dir, PROFILE))
self.assert_path_exists(os.path.join(self.cache_dir, '.features'))
@@ -200,26 +197,26 @@ class AAParserAltCacheBasicTests(AAParserBasicCachingTests):
'''Same tests as above, but with an alternate cache location specified on the command line'''
def setUp(self):
super(AAParserAltCacheBasicTests, self).setUp()
super().setUp()
alt_cache_loc = tempfile.mkdtemp(prefix='aa-alt-cache', dir=self.tmp_dir)
os.chmod(alt_cache_loc, 0o755)
self.unused_cache_loc = self.cache_dir
self.cmd_prefix.extend(['--cache-loc', alt_cache_loc])
self.cmd_prefix.extend(('--cache-loc', alt_cache_loc))
self.cache_dir = self.get_cache_dir()
def tearDown(self):
if len(os.listdir(self.unused_cache_loc)) > 0:
self.fail('original cache dir \'%s\' not empty' % self.unused_cache_loc)
super(AAParserAltCacheBasicTests, self).tearDown()
super().tearDown()
class AAParserCreateCacheBasicTestsCacheExists(AAParserBasicCachingTests):
'''Same tests as above, but with create cache option on the command line and the cache already exists'''
def setUp(self):
super(AAParserCreateCacheBasicTestsCacheExists, self).setUp()
super().setUp()
self.cmd_prefix.append('--create-cache-dir')
@@ -227,7 +224,7 @@ class AAParserCreateCacheBasicTestsCacheNotExist(AAParserBasicCachingTests):
'''Same tests as above, but with create cache option on the command line and cache dir removed'''
def setUp(self):
super(AAParserCreateCacheBasicTestsCacheNotExist, self).setUp()
super().setUp()
shutil.rmtree(self.cache_dir)
self.cmd_prefix.append('--create-cache-dir')
@@ -237,7 +234,7 @@ class AAParserCreateCacheAltCacheTestsCacheNotExist(AAParserBasicCachingTests):
alt cache specified, and cache dir removed'''
def setUp(self):
super(AAParserCreateCacheAltCacheTestsCacheNotExist, self).setUp()
super().setUp()
shutil.rmtree(self.cache_dir)
self.cmd_prefix.append('--create-cache-dir')
@@ -245,7 +242,7 @@ class AAParserCreateCacheAltCacheTestsCacheNotExist(AAParserBasicCachingTests):
class AAParserCachingTests(AAParserCachingCommon):
def setUp(self):
super(AAParserCachingTests, self).setUp()
super().setUp()
r = testlib.filesystem_time_resolution()
self.mtime_res = r[1]
@@ -253,28 +250,14 @@ class AAParserCachingTests(AAParserCachingCommon):
def _generate_cache_file(self):
cmd = list(self.cmd_prefix)
cmd.extend(['-q', '--write-cache', '-r', self.profile])
cmd.extend(('-q', '--write-cache', '-r', self.profile))
self.run_cmd_check(cmd)
self.assert_path_exists(self.cache_file)
def _assertTimeStampEquals(self, time1, time2):
'''Compare two timestamps to ensure equality'''
# python 3.2 and earlier don't support writing timestamps with
# nanosecond resolution, only microsecond. When comparing
# timestamps in such an environment, loosen the equality bounds
# to compensate
# Reference: https://bugs.python.org/issue12904
(major, minor, _) = platform.python_version_tuple()
if (int(major) < 3) or ((int(major) == 3) and (int(minor) <= 2)):
self.assertAlmostEquals(time1, time2, places=5)
else:
self.assertEqual(time1, time2)
def _set_mtime(self, path, mtime):
atime = os.stat(path).st_atime
os.utime(path, (atime, mtime))
self._assertTimeStampEquals(os.stat(path).st_mtime, mtime)
self.assertEqual(os.stat(path).st_mtime, mtime)
def test_cache_loaded_when_exists(self):
'''test cache is loaded when it exists, is newer than profile, and features match'''
@@ -282,7 +265,7 @@ class AAParserCachingTests(AAParserCachingCommon):
self._generate_cache_file()
cmd = list(self.cmd_prefix)
cmd.extend(['-v', '-r', self.profile])
cmd.extend(('-v', '-r', self.profile))
self.run_cmd_check(cmd, expected_string='Cached reload succeeded')
def test_cache_not_loaded_when_skip_arg(self):
@@ -291,7 +274,7 @@ class AAParserCachingTests(AAParserCachingCommon):
self._generate_cache_file()
cmd = list(self.cmd_prefix)
cmd.extend(['-v', '--skip-cache', '-r', self.profile])
cmd.extend(('-v', '--skip-cache', '-r', self.profile))
self.run_cmd_check(cmd, expected_string='Replacement succeeded for')
def test_cache_not_loaded_when_skip_read_arg(self):
@@ -300,7 +283,7 @@ class AAParserCachingTests(AAParserCachingCommon):
self._generate_cache_file()
cmd = list(self.cmd_prefix)
cmd.extend(['-v', '--skip-read-cache', '-r', self.profile])
cmd.extend(('-v', '--skip-read-cache', '-r', self.profile))
self.run_cmd_check(cmd, expected_string='Replacement succeeded for')
def test_cache_not_loaded_when_features_differ(self):
@@ -311,7 +294,7 @@ class AAParserCachingTests(AAParserCachingCommon):
testlib.write_file(self.cache_dir, '.features', 'monkey\n')
cmd = list(self.cmd_prefix)
cmd.extend(['-v', '-r', self.profile])
cmd.extend(('-v', '-r', self.profile))
self.run_cmd_check(cmd, expected_string='Replacement succeeded for')
def test_cache_writing_does_not_overwrite_features_when_features_differ(self):
@@ -322,7 +305,7 @@ class AAParserCachingTests(AAParserCachingCommon):
features_file = testlib.write_file(self.cache_dir, '.features', 'monkey\n')
cmd = list(self.cmd_prefix)
cmd.extend(['-v', '--write-cache', '--skip-bad-cache', '-r', self.profile])
cmd.extend(('-v', '--write-cache', '--skip-bad-cache', '-r', self.profile))
self.run_cmd_check(cmd, expected_string='Replacement succeeded for')
self.assert_path_exists(features_file)
# ensure that the features does *not* match the current features set
@@ -334,7 +317,7 @@ class AAParserCachingTests(AAParserCachingCommon):
testlib.write_file(self.cache_dir, '.features', 'monkey\n')
cmd = list(self.cmd_prefix)
cmd.extend(['-v', '--write-cache', '--skip-bad-cache', '-r', self.profile])
cmd.extend(('-v', '--write-cache', '--skip-bad-cache', '-r', self.profile))
self.run_cmd_check(cmd, expected_string='Replacement succeeded for')
self.assert_path_exists(self.cache_file, expected=False)
@@ -349,7 +332,7 @@ class AAParserCachingTests(AAParserCachingCommon):
new_features_file = new_file + '/.features';
cmd = list(self.cmd_prefix)
cmd.extend(['-v', '--write-cache', '-r', self.profile])
cmd.extend(('-v', '--write-cache', '-r', self.profile))
self.run_cmd_check(cmd, expected_string='Replacement succeeded for')
self.assert_path_exists(features_file)
self.assert_path_exists(new_features_file)
@@ -362,7 +345,7 @@ class AAParserCachingTests(AAParserCachingCommon):
orig_stat = os.stat(cache_file)
cmd = list(self.cmd_prefix)
cmd.extend(['-v', '--write-cache', '-r', self.profile])
cmd.extend(('-v', '--write-cache', '-r', self.profile))
self.run_cmd_check(cmd, expected_string='Replacement succeeded for')
self.assert_path_exists(cache_file)
stat = os.stat(cache_file)
@@ -378,7 +361,7 @@ class AAParserCachingTests(AAParserCachingCommon):
check_file = testlib.write_file(self.cache_dir, 'monkey', 'monkey\n')
cmd = list(self.cmd_prefix)
cmd.extend(['-v', '--write-cache', '-r', self.profile])
cmd.extend(('-v', '--write-cache', '-r', self.profile))
self.run_cmd_check(cmd, expected_string='Replacement succeeded for')
self.assert_path_exists(check_file, expected=False)
@@ -416,7 +399,7 @@ class AAParserCachingTests(AAParserCachingCommon):
orig_stat = os.stat(self.cache_file)
cmd = list(self.cmd_prefix)
cmd.extend(['-v', '-r', self.profile])
cmd.extend(('-v', '-r', self.profile))
self.run_cmd_check(cmd, expected_string='Replacement succeeded for')
stat = os.stat(self.cache_file)
@@ -434,7 +417,7 @@ class AAParserCachingTests(AAParserCachingCommon):
orig_stat = os.stat(self.cache_file)
cmd = list(self.cmd_prefix)
cmd.extend(['-v', '-r', self.profile])
cmd.extend(('-v', '-r', self.profile))
self.run_cmd_check(cmd, expected_string='Replacement succeeded for')
stat = os.stat(self.cache_file)
@@ -452,12 +435,12 @@ class AAParserCachingTests(AAParserCachingCommon):
orig_stat = os.stat(self.cache_file)
cmd = list(self.cmd_prefix)
cmd.extend(['-v', '-r', '-W', self.profile])
cmd.extend(('-v', '-r', '-W', self.profile))
self.run_cmd_check(cmd, expected_string='Replacement succeeded for')
stat = os.stat(self.cache_file)
self.assertNotEqual(orig_stat.st_ino, stat.st_ino)
self._assertTimeStampEquals(profile_mtime, stat.st_mtime)
self.assertEqual(profile_mtime, stat.st_mtime)
def test_abstraction_newer_rewrites_cache(self):
'''test cache is rewritten if abstraction is newer'''
@@ -469,12 +452,12 @@ class AAParserCachingTests(AAParserCachingCommon):
orig_stat = os.stat(self.cache_file)
cmd = list(self.cmd_prefix)
cmd.extend(['-v', '-r', '-W', self.profile])
cmd.extend(('-v', '-r', '-W', self.profile))
self.run_cmd_check(cmd, expected_string='Replacement succeeded for')
stat = os.stat(self.cache_file)
self.assertNotEqual(orig_stat.st_ino, stat.st_ino)
self._assertTimeStampEquals(abstraction_mtime, stat.st_mtime)
self.assertEqual(abstraction_mtime, stat.st_mtime)
def test_parser_newer_uses_cache(self):
'''test cache is not skipped if parser is newer'''
@@ -489,7 +472,7 @@ class AAParserCachingTests(AAParserCachingCommon):
cmd = list(self.cmd_prefix)
cmd[0] = new_parser
cmd.extend(['-v', '-r', self.profile])
cmd.extend(('-v', '-r', self.profile))
self.run_cmd_check(cmd, expected_string='Cached reload succeeded for')
def _purge_cache_test(self, location):
@@ -497,7 +480,7 @@ class AAParserCachingTests(AAParserCachingCommon):
cache_file = testlib.write_file(self.cache_dir, location, 'monkey\n')
cmd = list(self.cmd_prefix)
cmd.extend(['-v', '--purge-cache', '-r', self.profile])
cmd.extend(('-v', '--purge-cache', '-r', self.profile))
self.run_cmd_check(cmd)
# no message is output
self.assert_path_exists(cache_file, expected=False)
@@ -520,27 +503,27 @@ class AAParserAltCacheTests(AAParserCachingTests):
check_orig_cache = True
def setUp(self):
super(AAParserAltCacheTests, self).setUp()
super().setUp()
alt_cache_loc = tempfile.mkdtemp(prefix='aa-alt-cache', dir=self.tmp_dir)
os.chmod(alt_cache_loc, 0o755)
self.orig_cache_dir = self.cache_dir
self.cmd_prefix.extend(['--cache-loc', alt_cache_loc])
self.cmd_prefix.extend(('--cache-loc', alt_cache_loc))
self.cache_dir = self.get_cache_dir(create=True)
self.cache_file = os.path.join(self.cache_dir, PROFILE)
def tearDown(self):
if self.check_orig_cache and len(os.listdir(self.orig_cache_dir)) > 0:
self.fail('original cache dir \'%s\' not empty' % self.orig_cache_dir)
super(AAParserAltCacheTests, self).tearDown()
super().tearDown()
def test_cache_purge_leaves_original_cache_alone(self):
'''test cache purging only touches alt cache'''
# skip tearDown check to ensure non-alt cache is empty
self.check_orig_cache = False
filelist = [PROFILE, '.features', 'monkey']
filelist = (PROFILE, '.features', 'monkey')
for f in filelist:
testlib.write_file(self.orig_cache_dir, f, 'monkey\n')

73
parser/tst/dirtest.sh Executable file
View File

@@ -0,0 +1,73 @@
#!/bin/sh
#
# Copyright (c) 2022
# Canonical, Ltd. (All rights reserved)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public
# License published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, contact Canonical Ltd.
#
# simple test to ensure dir is being iterated as expected
# yes this needs to be improved and reworked
# passed in by Makefile
#APPARMOR_PARSER="${APPARMOR_PARSER:-../apparmor_parser}"
do_tst() {
local msg="$1"
local expected="$2"
local rc=0
shift 2
#global tmpdir
${APPARMOR_PARSER} "$@" > "$tmpdir/out.unsorted" 2>/dev/null
rc=$?
LC_ALL=C sort "$tmpdir/out.unsorted" > "$tmpdir/out"
if [ $rc -ne 0 ] && [ "$expected" != "fail" ] ; then
echo "failed: expected \"$expected\" but parser returned error"
return 1
fi
if [ $rc -eq 0 ] && [ "$expected" = "fail" ] ; then
echo "succeeded unexpectedly: expected \"$expected\" but parser returned success"
return 1
fi
if ! diff -q "$tmpdir/out" dirtest/dirtest.out ; then
echo "failed: expected \"$expected\" but output comparison failed"
diff -u dirtest/dirtest.out "$tmpdir/out"
return 1
fi
return 0
}
tmpdir=$(mktemp -d "$tmpdir.XXXXXXXX")
chmod 755 "$tmpdir"
export tmpdir
rc=0
# pass - no parser errors and output matches
# error - parser error and output matches
# fail - comparison out parser output failed
do_tst "good dir list" pass -N dirtest/gooddir/ || rc=1
do_tst "bad link in dir" fail -N dirtest/badlink/ || rc=1
do_tst "bad profile in dir" fail -N dirtest/badprofile/ || rc=1
rm -rf "$tmpdir"
if [ $rc -eq 0 ] ; then
echo "PASS"
fi
exit $rc

View File

@@ -0,0 +1 @@
foo

View File

@@ -0,0 +1 @@
../goodtarget

View File

@@ -0,0 +1,2 @@
profile a_profile {
}

View File

@@ -0,0 +1,2 @@
profile b_profile {
}

View File

@@ -0,0 +1,3 @@
profile bad_profile {
file
}

View File

@@ -0,0 +1 @@
../goodtarget

View File

@@ -0,0 +1,2 @@
profile a_profile {
}

View File

@@ -0,0 +1,2 @@
profile b_profile {
}

View File

@@ -0,0 +1,3 @@
a_profile
b_profile
good_target

View File

@@ -0,0 +1 @@
../goodtarget

View File

@@ -0,0 +1,2 @@
profile a_profile {
}

View File

@@ -0,0 +1,2 @@
profile b_profile {
}

View File

@@ -0,0 +1,2 @@
profile good_target {
}

View File

@@ -630,7 +630,18 @@ verify_binary_equality "link rules slash filtering" \
/t { link @{FOO}//foo -> /mnt/bar, }" \
"@{FOO}=/dev/
@{BAR}=/mnt/
/t { link @{FOO}/foo -> @{BAR}/bar, }" \
/t { link @{FOO}/foo -> @{BAR}/bar, }"
verify_binary_equality "attachment slash filtering" \
"/t /bin/foo { }" \
"/t /bin//foo { }" \
"@{BAR}=/bin/
/t @{BAR}/foo { }" \
"@{FOO}=/foo
/t /bin/@{FOO} { }" \
"@{BAR}=/bin/
@{FOO}=/foo
/t @{BAR}/@{FOO} { }"
if [ $fails -ne 0 ] || [ $errors -ne 0 ]
then

View File

@@ -36,9 +36,9 @@ class AAErrorTests(testlib.AATestTemplate):
else:
self.assertEqual(rc, 0, report)
ignore_messages = [
ignore_messages = (
'Cache read/write disabled: interface file missing. (Kernel needs AppArmor 2.4 compatibility patch.)\n',
]
)
for ign in ignore_messages:
if ign in outerr:
outerr = outerr.replace(ign, '')
@@ -73,7 +73,7 @@ class AAErrorTests(testlib.AATestTemplate):
)
def test_deprecation1(self):
self.cmd_prefix.extend(['--warn=deprecated'])
self.cmd_prefix.append('--warn=deprecated')
self._run_test(
'errors/deprecation1.sd',
"Warning from errors/deprecation1.sd (errors/deprecation1.sd line 6): The use of file paths as profile names is deprecated. See man apparmor.d for more information\n",
@@ -81,7 +81,7 @@ class AAErrorTests(testlib.AATestTemplate):
)
def test_deprecation2(self):
self.cmd_prefix.extend(['--warn=deprecated'])
self.cmd_prefix.append('--warn=deprecated')
self._run_test(
'errors/deprecation2.sd',
"Warning from errors/deprecation2.sd (errors/deprecation2.sd line 6): The use of file paths as profile names is deprecated. See man apparmor.d for more information\n",

View File

@@ -1,167 +0,0 @@
#!/usr/bin/perl
#
# Copyright (c) 2013
# Canonical, Ltd. (All rights reserved)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public
# License published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, contact Canonical Ltd.
#
use strict;
use Locale::gettext;
use POSIX;
setlocale(LC_MESSAGES, "");
my $count=0;
my $prefix="simple_tests/generated_dbus";
my @quantifier = ("", "deny", "audit");
my @session = ("", "bus=session", "bus=system", "bus=accessibility");
my @path = ("", "path=/foo/bar", "path=\"/foo/bar\"");
my @interface = ("", "interface=com.baz", "interface=\"com.baz\"");
my @member = ("", "member=bar", "member=\"bar\"");
my @name = ("", "name=com.foo", "name=\"com.foo\"");
my @peer = map { "peer=($_)" } (@name, "label=/usr/bin/app",
"label=\"/usr/bin/app\"",
"name=com.foo label=/usr/bin/app",
"name=\"com.foo\" label=\"/usr/bin/app\"");
# @msg_perms are the permissions that are related to sending and receiving
# messages. @svc_perms are the permissions related to services.
my @base_msg_perms = ("r", "w", "rw", "read", "receive", "write", "send");
my @msg_perms = ("", @base_msg_perms, (map { "($_)" } @base_msg_perms),
"(write, read)", "(send receive)", "(send read)",
"(receive write)");
gen_files("message-rules", "PASS", \@quantifier, \@msg_perms, \@session,
[""], \@path, \@interface, \@member, \@peer);
gen_files("service-rules", "PASS", \@quantifier, ["bind"], \@session,
\@name, [""], [""], [""], [""]);
gen_files("eavesdrop-rules", "PASS", \@quantifier, ["eavesdrop"], \@session,
[""], [""], [""], [""], [""]);
gen_file("sloppy-formatting", "PASS", "", "(send , receive )", "bus=session",
"", "path =\"/foo/bar\"", "interface = com.foo", " member=bar",
"peer =( label= /usr/bin/app name =\"com.foo\")");
gen_file("sloppy-formatting", "PASS", "", "bind", "bus =session",
"name= com.foo", "", "", "", "");
gen_file("sloppy-formatting", "PASS", "", "eavesdrop", "bus = system",
"", "", "", "", "");
# Don't use the first element, which is empty, from each array since all empty
# conditionals would PASS but we want all FAILs
shift @msg_perms;
shift @name;
shift @path;
shift @interface;
shift @member;
shift @peer;
gen_files("message-incompat", "FAIL", \@quantifier, \@msg_perms, \@session,
\@name, [""], [""], [""], [""]);
gen_files("service-incompat", "FAIL", \@quantifier, ["bind"], \@session,
\@name, \@path, [""], [""], [""]);
gen_files("service-incompat", "FAIL", \@quantifier, ["bind"], \@session,
\@name, [""], \@interface, [""], [""]);
gen_files("service-incompat", "FAIL", \@quantifier, ["bind"], \@session,
\@name, [""], [""], \@member, [""]);
gen_files("service-incompat", "FAIL", \@quantifier, ["bind"], \@session,
\@name, [""], [""], [""], \@peer);
gen_files("eavesdrop-incompat", "FAIL", \@quantifier, ["eavesdrop"], \@session,
\@name, \@path, \@interface, \@member, \@peer);
gen_files("pairing-unsupported", "FAIL", \@quantifier, ["send", "bind"],
\@session, ["name=sn", "label=sl"], [""], [""], [""],
["peer=(name=pn)", "peer=(label=pl)"]);
# missing bus= prefix
gen_file("bad-formatting", "FAIL", "", "send", "session", "", "", "", "", "");
# incorrectly formatted permissions
gen_files("bad-perms", "FAIL", [""], ["send receive", "(send", "send)"],
["bus=session"], [""], [""], [""], [""], [""]);
# invalid permissions
gen_files("bad-perms", "FAIL", [""],
["a", "x", "Ux", "ix", "m", "k", "l", "(a)", "(x)"], [""], [""],
[""], [""], [""], [""]);
gen_file("duplicated-conditionals", "FAIL", "", "bus=1 bus=2");
gen_file("duplicated-conditionals", "FAIL", "", "name=1 name=2");
gen_file("duplicated-conditionals", "FAIL", "", "path=1 path=2");
gen_file("duplicated-conditionals", "FAIL", "", "interface=1 interface=2");
gen_file("duplicated-conditionals", "FAIL", "", "member=1 member=2");
gen_file("duplicated-conditionals", "FAIL", "", "peer=(name=1) peer=(name=2)");
gen_file("duplicated-conditionals", "FAIL", "", "peer=(label=1) peer=(label=2)");
gen_file("duplicated-conditionals", "FAIL", "", "peer=(name=1) peer=(label=2)");
print "Generated $count dbus tests\n";
sub print_rule($$$$$$$$$) {
my ($file, $quantifier, $perms, $session, $name, $path, $interface, $member, $peer) = @_;
print $file " ";
print $file " ${quantifier}" if ${quantifier};
print $file " dbus";
print $file " ${perms}" if ${perms};
print $file " ${session}" if ${session};
print $file " ${name}" if ${name};
print $file " ${path}" if ${path};
print $file " ${interface}" if ${interface};
print $file " ${member}" if ${member};
print $file " ${peer}" if ${peer};
print $file ",\n";
}
sub gen_file($$$$$$$$$$) {
my ($test, $xres, $quantifier, $perms, $session, $name, $path, $interface, $member, $peer) = @_;
my $file;
unless (open $file, ">${prefix}/$test-$count.sd") {
print("couldn't open $test\n");
exit 1;
}
print $file "#\n";
print $file "#=DESCRIPTION ${test}\n";
print $file "#=EXRESULT ${xres}\n";
print $file "#\n";
print $file "/usr/bin/foo {\n";
print_rule($file, $quantifier, $perms, $session, $name, $path, $interface,
$member, $peer);
print $file "}\n";
close($file);
$count++;
}
sub gen_files($$$$$$$$$$) {
my ($test, $xres, $quantifiers, $perms, $sessions, $names, $paths, $interfaces, $members, $peers) = @_;
foreach my $quantifier (@{$quantifiers}) {
foreach my $perm (@{$perms}) {
foreach my $session (@{$sessions}) {
foreach my $name (@{$names}) {
foreach my $path (@{$paths}) {
foreach my $interface (@{$interfaces}) {
foreach my $member (@{$members}) {
foreach my $peer (@{$peers}) {
gen_file($test, $xres, $quantifier, $perm, $session, $name,
$path, $interface, $member, $peer);
}
}
}
}
}
}
}
}
}

157
parser/tst/gen-dbus.py Executable file
View File

@@ -0,0 +1,157 @@
#!/usr/bin/python3
#
# Copyright (c) 2013 Canonical, Ltd. (All rights reserved)
# Copyright (c) 2021 Christian Boltz
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public
# License published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, contact Canonical Ltd.
#
from testlib import write_file
def get_rule (quantifier, perms, session, name, path, interface, member, peer):
result = ' '
for part in (quantifier, 'dbus', perms, session, name, path, interface, member, peer):
if part:
result += ' %s' % part
result += ',\n'
return result
def gen_file(test, xres, quantifier, perms, session, name, path, interface, member, peer):
global count
content = ''
content += '#\n'
content += '#=DESCRIPTION %s\n' % test
content += '#=EXRESULT %s\n' % xres
content += '#\n'
content += '/usr/bin/foo {\n'
content += get_rule(quantifier, perms, session, name, path, interface, member, peer)
content += '}\n'
write_file('simple_tests/generated_dbus', '%s-%s.sd' % (test, count), content)
count += 1
def gen_files (test, xres, quantifiers, perms, sessions, names, paths, interfaces, members, peers):
for quantifier in quantifiers:
for perm in perms:
for session in sessions:
for name in names:
for path in paths:
for interface in interfaces:
for member in members:
for peer in peers:
gen_file(test, xres, quantifier, perm, session, name, path, interface, member, peer)
count=0
quantifier = ('', 'deny', 'audit')
session = ('', 'bus=session', 'bus=system', 'bus=accessibility')
path = ['', 'path=/foo/bar', 'path="/foo/bar"']
interface = ['', 'interface=com.baz', 'interface="com.baz"']
member = ['', 'member=bar', 'member="bar"']
name = ['', 'name=com.foo', 'name="com.foo"']
peer = [
'peer=()',
'peer=(name=com.foo)',
'peer=(name="com.foo")',
'peer=(label=/usr/bin/app)',
'peer=(label="/usr/bin/app")',
'peer=(name=com.foo label=/usr/bin/app)',
'peer=(name="com.foo" label="/usr/bin/app")',
]
# msg_perms are the permissions that are related to sending and receiving
# messages.
msg_perms = [
'',
'r',
'w',
'rw',
'read',
'receive',
'write',
'send',
'(r)',
'(w)',
'(rw)',
'(read)',
'(receive)',
'(write)',
'(send)',
'(write, read)',
'(send receive)',
'(send read)',
'(receive write)',
]
empty_tup = ('',)
gen_files('message-rules', 'PASS', quantifier, msg_perms, session,
empty_tup, path, interface, member, peer)
gen_files('service-rules', 'PASS', quantifier, ['bind'], session,
name, empty_tup, empty_tup, empty_tup, empty_tup)
gen_files('eavesdrop-rules', 'PASS', quantifier, ['eavesdrop'], session,
empty_tup, empty_tup, empty_tup, empty_tup, empty_tup)
gen_file('sloppy-formatting', 'PASS', '', '(send , receive )', 'bus=session',
'', 'path ="/foo/bar"', 'interface = com.foo', ' member=bar',
'peer =( label= /usr/bin/app name ="com.foo")')
gen_file('sloppy-formatting', 'PASS', '', 'bind', 'bus =session',
'name= com.foo', '', '', '', '')
gen_file('sloppy-formatting', 'PASS', '', 'eavesdrop', 'bus = system',
'', '', '', '', '')
# Don't use the empty element from each array since all empty conditionals would PASS but we want all FAILs
msg_perms.remove('')
name.remove('')
path.remove('')
interface.remove('')
member.remove('')
peer.remove('peer=()')
gen_files('message-incompat', 'FAIL', quantifier, msg_perms, session, name, empty_tup, empty_tup, empty_tup, empty_tup)
gen_files('service-incompat', 'FAIL', quantifier, ('bind',), session, name, path, empty_tup, empty_tup, empty_tup)
gen_files('service-incompat', 'FAIL', quantifier, ('bind',), session, name, empty_tup, interface, empty_tup, empty_tup)
gen_files('service-incompat', 'FAIL', quantifier, ('bind',), session, name, empty_tup, empty_tup, member, empty_tup)
gen_files('service-incompat', 'FAIL', quantifier, ('bind',), session, name, empty_tup, empty_tup, empty_tup, peer)
gen_files('eavesdrop-incompat', 'FAIL', quantifier, ('eavesdrop',), session, name, path, interface, member, peer)
gen_files('pairing-unsupported', 'FAIL', quantifier, ('send', 'bind'),
session, ('name=sn', 'label=sl'), empty_tup, empty_tup, empty_tup,
('peer=(name=pn)', 'peer=(label=pl)'))
# missing bus= prefix
gen_file('bad-formatting', 'FAIL', '', 'send', 'session', '', '', '', '', '')
# incorrectly formatted permissions
gen_files('bad-perms', 'FAIL', empty_tup, ('send receive', '(send', 'send)'),
('bus=session',), empty_tup, empty_tup, empty_tup, empty_tup, empty_tup)
# invalid permissions
gen_files('bad-perms', 'FAIL', empty_tup,
('a', 'x', 'Ux', 'ix', 'm', 'k', 'l', '(a)', '(x)'), empty_tup, empty_tup,
empty_tup, empty_tup, empty_tup, empty_tup)
gen_file('duplicated-conditionals', 'FAIL', '', 'bus=1 bus=2', '', '', '', '', '', '')
gen_file('duplicated-conditionals', 'FAIL', '', 'name=1 name=2', '', '', '', '', '', '')
gen_file('duplicated-conditionals', 'FAIL', '', 'path=1 path=2', '', '', '', '', '', '')
gen_file('duplicated-conditionals', 'FAIL', '', 'interface=1 interface=2', '', '', '', '', '', '')
gen_file('duplicated-conditionals', 'FAIL', '', 'member=1 member=2', '', '', '', '', '', '')
gen_file('duplicated-conditionals', 'FAIL', '', 'peer=(name=1) peer=(name=2)', '', '', '', '', '', '')
gen_file('duplicated-conditionals', 'FAIL', '', 'peer=(label=1) peer=(label=2)', '', '', '', '', '', '')
gen_file('duplicated-conditionals', 'FAIL', '', 'peer=(name=1) peer=(label=2)', '', '', '', '', '', '')
print('Generated %s dbus tests' % count)

View File

@@ -120,8 +120,8 @@ def gen_file (name, xres, leading1, qual1, rule1, perm1, target1, leading2, qual
#
# will conflict
#
# NOTE: conflict tests don't tests leading permissions or using unsafe keywords
# It is assumed that there are extra tests to verify 1 to 1 coorispondance
# NOTE: conflict tests don't test leading permissions or using unsafe keywords
# It is assumed that there are extra tests to verify 1 to 1 correspondance
def gen_files(name, rule1, rule2, default):
perms = gen_list()
@@ -172,7 +172,7 @@ def gen_leading_perms (name, rule1, rule2):
gen_file(file, "PASS", 0, q, rule1, i, t, 1, q, rule2, i, t)
# test for rules with leading safe or unsafe keywords.
# check they are equivalent to their counter part,
# check they are equivalent to their counterpart,
# or if $invert that they properly conflict with their counterpart
def gen_safe_perms(name, xres, invert, rule1, rule2):
perms = gen_list()

View File

@@ -0,0 +1,8 @@
#
#=DESCRIPTION abi testing - empty/cut-off rule
#=EXRESULT FAIL
abi "
/does/not/exist {
}

View File

@@ -0,0 +1,8 @@
#
#=DESCRIPTION abi testing - empty/cut-off rule
#=EXRESULT FAIL
abi ",
/does/not/exist {
}

View File

@@ -0,0 +1,8 @@
#
#=DESCRIPTION abi testing - empty/cut-off rule
#=EXRESULT FAIL
abi ""
/does/not/exist {
}

View File

@@ -0,0 +1,8 @@
#
#=DESCRIPTION abi testing - empty/cut-off rule
#=EXRESULT FAIL
abi "",
/does/not/exist {
}

View File

@@ -0,0 +1,8 @@
#
#=DESCRIPTION abi testing - empty/cut-off rule
#=EXRESULT FAIL
abi <
/does/not/exist {
}

View File

@@ -0,0 +1,8 @@
#
#=DESCRIPTION abi testing - empty/cut-off rule
#=EXRESULT FAIL
abi <,
/does/not/exist {
}

View File

@@ -0,0 +1,8 @@
#
#=DESCRIPTION abi testing - empty/cut-off rule
#=EXRESULT FAIL
abi <>
/does/not/exist {
}

View File

@@ -0,0 +1,8 @@
#
#=DESCRIPTION abi testing - empty/cut-off rule
#=EXRESULT FAIL
abi <>,
/does/not/exist {
}

View File

@@ -0,0 +1,7 @@
#
#=DESCRIPTION includes testing - recursive include should not fail
#=EXRESULT PASS
#
/does/not/exist {
#include <includes/recursive.include>
}

View File

@@ -0,0 +1,10 @@
#
#=DESCRIPTION includes testing - recursive include should not fail
#=EXRESULT PASS
#
#include <includes/recursive.preamble>
/does/not/exist {
/foo r,
}

View File

@@ -0,0 +1,6 @@
# helper for include_tests/recursive_2.sd
/foo rw,
#include <includes/recursive.include>
/no/such/path r,

View File

@@ -0,0 +1,4 @@
# helper for include_tests/recursive_3.sd
#include <includes/recursive.preamble>

View File

@@ -86,7 +86,7 @@ class AATestTemplate(unittest.TestCase, metaclass=AANoCleanupMetaClass):
(rc, out, outerr) = self._run_cmd(command, input, stderr, stdout, stdin, timeout)
report = out + outerr
return [rc, report]
return rc, report
def _run_cmd(self, command, input=None, stderr=subprocess.PIPE, stdout=subprocess.PIPE,
stdin=None, timeout=120):
@@ -96,7 +96,7 @@ class AATestTemplate(unittest.TestCase, metaclass=AANoCleanupMetaClass):
sp = subprocess.Popen(command, stdin=stdin, stdout=stdout, stderr=stderr,
close_fds=True, preexec_fn=subprocess_setup, universal_newlines=True)
except OSError as e:
return [127, str(e)]
return 127, str(e), ''
timeout_communicate = TimeoutFunction(sp.communicate, timeout)
out, outerr = (None, None)
@@ -115,7 +115,7 @@ class AATestTemplate(unittest.TestCase, metaclass=AANoCleanupMetaClass):
if outerr is None:
outerr = ''
return (rc, out, outerr)
return rc, out, outerr
# Timeout handler using alarm() from John P. Speno's Pythonic Avocado
@@ -180,7 +180,7 @@ def read_features_dir(path):
if not os.path.exists(path) or not os.path.isdir(path):
return result
for name in os.listdir(path):
for name in sorted(os.listdir(path)):
entry = os.path.join(path, name)
result += '%s {' % name
if os.path.isfile(entry):

View File

@@ -13,12 +13,12 @@
# TODO
# - finish adding suppressions for valgrind false positives
from argparse import ArgumentParser # requires python 2.7 or newer
from argparse import ArgumentParser
import os
import sys
import tempfile
import unittest
import testlib
from tempfile import NamedTemporaryFile
DEFAULT_TESTDIR = "./simple_tests/vars"
VALGRIND_ERROR_CODE = 151
@@ -42,8 +42,8 @@ class AAParserValgrindTests(testlib.AATestTemplate):
self.maxDiff = None
def _runtest(self, testname, config):
parser_args = ['-Q', '-I', config.testdir, '-M', './features_files/features.all']
failure_rc = [VALGRIND_ERROR_CODE, testlib.TIMEOUT_ERROR_CODE]
parser_args = ('-Q', '-I', config.testdir, '-M', './features_files/features.all')
failure_rc = (VALGRIND_ERROR_CODE, testlib.TIMEOUT_ERROR_CODE)
command = [config.valgrind]
command.extend(VALGRIND_ARGS)
command.append(config.parser)
@@ -65,13 +65,10 @@ def find_testcases(testdir):
def create_suppressions():
'''generate valgrind suppressions file'''
with NamedTemporaryFile("w+", suffix='.suppressions', prefix='aa-parser-valgrind', delete=False) as temp_file:
temp_file.write(VALGRIND_SUPPRESSIONS)
return temp_file.name
handle, name = tempfile.mkstemp(suffix='.suppressions', prefix='aa-parser-valgrind')
os.close(handle)
handle = open(name,"w+")
handle.write(VALGRIND_SUPPRESSIONS)
handle.close()
return name
def main():
rc = 0

View File

@@ -41,13 +41,13 @@ ifdef USE_SYSTEM
LOGPROF?=aa-logprof
else
# PYTHON_DIST_BUILD_PATH based on libapparmor/swig/python/test/Makefile.am
PYTHON_DIST_BUILD_PATH = ../libraries/libapparmor/swig/python/build/$$($(PYTHON) -c "import distutils.util; import platform; print(\"lib.%s-%s\" %(distutils.util.get_platform(), platform.python_version()[:3]))")
PYTHON_DIST_BUILD_PATH = ../libraries/libapparmor/swig/python/build/$$($(PYTHON) -c "import sysconfig; print(\"lib.%s-%s\" %(sysconfig.get_platform(), sysconfig.get_python_version()))")
LIBAPPARMOR_PATH=../libraries/libapparmor/src/.libs/
LD_LIBRARY_PATH=$(LIBAPPARMOR_PATH):$(PYTHON_DIST_BUILD_PATH)
PYTHONPATH=../utils/:$(PYTHON_DIST_BUILD_PATH)
PARSER?=../parser/apparmor_parser
# use ../utils logprof
LOGPROF?=LD_LIBRARY_PATH=$(LD_LIBRARY_PATH) PYTHONPATH=$(PYTHONPATH) $(PYTHON) ../utils/aa-logprof --configdir ../utils/test/
LOGPROF?=LD_LIBRARY_PATH=$(LD_LIBRARY_PATH) PYTHONPATH=$(PYTHONPATH) $(PYTHON) ../utils/aa-logprof --configdir ../utils/
endif
# $(PWD) is wrong when using "make -C profiles" - explicitly set it here to get the right value

View File

@@ -6,6 +6,10 @@
include <abstractions/nameservice>
# Allow other processes to read our /proc entries
ptrace (readby),
# Allow other processes to trace us by default
ptrace (tracedby),
# Allow unconfined processes to send us signals by default
signal (receive) peer=unconfined,
# Allow apache to send us signals by default

View File

@@ -15,5 +15,6 @@ abi <abi/3.0>,
include <abstractions/apparmor_api/find_mountpoint>
@{sys}/module/apparmor/parameters/enabled r,
@{sys}/module/apparmor/parameters/available r,
# TODO: add alternate apparmorfs interface for enabled

View File

@@ -2,7 +2,7 @@
#
# Copyright (C) 2002-2009 Novell/SUSE
# Copyright (C) 2009-2012 Canonical Ltd
# Copyright (C) 2019 Christian Boltz
# Copyright (C) 2019-2021 Christian Boltz
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public
@@ -36,6 +36,8 @@
# SuSE's pwdutils are different:
@{etc_ro}/default/passwd r,
@{etc_ro}/login.defs r,
@{etc_ro}/login.defs.d/ r,
@{etc_ro}/login.defs.d/*.defs r,
# nis
include <abstractions/nis>

View File

@@ -12,6 +12,7 @@
abi <abi/3.0>,
include <abstractions/crypto>
# (Note that the ldd profile has inlined this file; if you make
# modifications here, please consider including them in the ldd
@@ -104,9 +105,6 @@
# glibc's *printf protections read the maps file
@{PROC}/@{pid}/{maps,auxv,status} r,
# libgcrypt reads some flags from /proc
@{PROC}/sys/crypto/* r,
# some applications will display license information
/usr/share/common-licenses/** r,

View File

@@ -0,0 +1,26 @@
# vim:syntax=apparmor
# ------------------------------------------------------------------
#
# Copyright (C) 2002-2009 Novell/SUSE
# Copyright (C) 2009-2011 Canonical Ltd.
# Copyright (C) 2021 Christian Boltz
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public
# License published by the Free Software Foundation.
#
# ------------------------------------------------------------------
abi <abi/3.0>,
@{etc_ro}/gcrypt/random.conf r,
@{PROC}/sys/crypto/fips_enabled r,
# libgcrypt reads some flags from /proc
@{PROC}/sys/crypto/* r,
# crypto policies used by various libraries
/etc/crypto-policies/*/*.txt r,
/usr/share/crypto-policies/*/*.txt r,
include if exists <abstractions/crypto.d>

View File

@@ -51,13 +51,6 @@
/{,usr/}bin/which rix,
# Deny DBus
# for GTK error message dialog, not required exo-open to work.
deny dbus send
bus=session
path=/org/gtk/vfs/mounttracker,
# System files
/etc/xdg/{,xdg-*/}xfce4/helpers.rc r,

View File

@@ -0,0 +1,55 @@
# vim:syntax=apparmor
# ------------------------------------------------------------------
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public
# License published by the Free Software Foundation.
#
# ------------------------------------------------------------------
abi <abi/3.0>,
/usr/share/themes/{,**} r,
/usr/share/gtksourceview-[0-9]*/{,**} r,
/usr/share/gtk-2.0/ r,
/usr/share/gtk-2.0/gtkrc r,
/usr/share/gtk-{3,4}.0/ r,
/usr/share/gtk-{3,4}.0/settings.ini r,
/etc/gtk-2.0/ r,
/etc/gtk-2.0/gtkrc r,
/etc/gtk-{3,4}.0/ r,
/etc/gtk-{3,4}.0/*.conf r,
/etc/gtk/gtkrc r,
owner @{HOME}/.themes/{,**} r,
owner @{HOME}/.local/share/themes/{,**} r,
owner @{HOME}/.gtk r,
owner @{HOME}/.gtkrc r,
owner @{HOME}/.gtkrc-2.0 r,
owner @{HOME}/.gtk-bookmarks r,
owner @{HOME}/.config/gtkrc r,
owner @{HOME}/.config/gtkrc-2.0 r,
owner @{HOME}/.config/gtk-{3,4}.0/ rw,
owner @{HOME}/.config/gtk-{3,4}.0/settings.ini r,
owner @{HOME}/.config/gtk-{3,4}.0/bookmarks r,
owner @{HOME}/.config/gtk-{3,4}.0/gtk.css r,
# for gtk file dialog
owner @{HOME}/.config/gtk-2.0/ rw,
owner @{HOME}/.config/gtk-2.0/gtkfilechooser.ini* rw,
# .Xauthority file required for X connections
owner @{HOME}/.Xauthority r,
# Xsession errors file
owner @{HOME}/.xsession-errors w,
# Include additions to the abstraction
include if exists <abstractions/gtk.d>

View File

@@ -16,5 +16,14 @@
owner @{HOME}/.config/ibus/bus/ rw,
owner @{HOME}/.config/ibus/bus/* rw,
# abstract path in ibus >= 1.5.22 uses $XDG_CACHE_HOME (ie, @{HOME}/.cache)
# This should use this, but due to LP: #1856738 we cannot
#unix (connect, receive, send)
# type=stream
# peer=(addr="@@{HOME}/.cache/ibus/dbus-*"),
unix (connect, receive, send)
type=stream
peer=(addr="@/home/*/.cache/ibus/dbus-*"),
# Include additions to the abstraction
include if exists <abstractions/ibus.d>

View File

@@ -10,6 +10,8 @@
# (src/intel/perf/gen_perf.c, load_oa_metrics())
@{PROC}/sys/dev/i915/perf_stream_paranoid r,
@{sys}/devices/pci[0-9]*/**/{revision,config} r,
# User files
owner @{HOME}/.cache/ w, # if user clears all caches
owner @{HOME}/.cache/mesa_shader_cache/ rw,

View File

@@ -24,6 +24,7 @@
@{run}/systemd/userdb/io.systemd.DynamicUser rw, # systemd-exec users
@{run}/systemd/userdb/io.systemd.Home rw, # systemd-home dirs
@{run}/systemd/userdb/io.systemd.NameServiceSwitch rw, # UNIX/glibc NSS
@{run}/systemd/userdb/io.systemd.Machine rw, # systemd-machined
@{PROC}/sys/kernel/random/boot_id r,

View File

@@ -11,9 +11,9 @@
abi <abi/3.0>,
/etc/ssl/openssl.cnf r,
/etc/ssl/{engdef,engines}.d/ r,
/etc/ssl/{engdef,engines}.d/*.cnf r,
/usr/share/ssl/openssl.cnf r,
@{PROC}/sys/crypto/fips_enabled r,
# Include additions to the abstraction
include if exists <abstractions/openssl.d>

View File

@@ -13,26 +13,25 @@
abi <abi/3.0>,
# shared snippets for config files
/etc/php{,5,7}/**/ r,
/etc/php{,5,7}/**.ini r,
/etc/php{,5,7,8}/** r,
# Xlibs
/usr/X11R6/lib{,32,64}/lib*.so* mr,
# php extensions
/usr/lib{64,}/php{,5,7}/*/*.so mr,
/usr/lib{64,}/php{,5,7,8}/*/*.so mr,
# ICU (unicode support) data tables
/usr/share/icu/*/*.dat r,
# php session mmap socket
/var/lib/php{,5,7}/session_mm_* rwlk,
/var/lib/php{,5,7,8}/session_mm_* rwlk,
# file based session handler
/var/lib/php{,5,7}/sess_* rwlk,
/var/lib/php{,5,7}/sessions/* rwlk,
/var/lib/php{,5,7,8}/sess_* rwlk,
/var/lib/php{,5,7,8}/sessions/* rwlk,
# php libraries
/usr/share/php{,5,7}/ r,
/usr/share/php{,5,7}/** mr,
/usr/share/php{,5,7,8}/ r,
/usr/share/php{,5,7,8}/** mr,
# MySQL extension
/usr/share/mysql/** r,

View File

@@ -12,18 +12,17 @@
abi <abi/3.0>,
/usr/lib{,32,64}/python{2.[4-7],3.[0-9]}/**.{pyc,so} mr,
/usr/lib{,32,64}/python{2.[4-7],3.[0-9]}/**.{egg,py,pth} r,
/usr/lib{,32,64}/python{2.[4-7],3.[0-9]}/{site,dist}-packages/ r,
/usr/lib{,32,64}/python3.[0-9]/lib-dynload/*.so mr,
/usr/local/lib{,32,64}/python{2.[4-7],3,3.[0-9]}/**.{pyc,so} mr,
/usr/local/lib{,32,64}/python{2.[4-7],3,3.[0-9]}/**.{egg,py,pth} r,
/usr/local/lib{,32,64}/python{2.[4-7],3,3.[0-9]}/{site,dist}-packages/ r,
/usr/local/lib{,32,64}/python3.[0-9]/lib-dynload/*.so mr,
/usr/{local/,}lib{,32,64}/python{2.[4-7],3,3.[0-9],3.1[0-9]}/**.{pyc,so,so.*[0-9]} mr,
/usr/{local/,}lib{,32,64}/python{2.[4-7],3,3.[0-9],3.1[0-9]}/**.{egg,py,pth} r,
/usr/{local/,}lib{,32,64}/python{2.[4-7],3,3.[0-9],3.1[0-9]}/{site,dist}-packages/ r,
/usr/{local/,}lib{,32,64}/python{2.[4-7],3,3.[0-9],3.1[0-9]}/{site,dist}-packages/**/ r,
/usr/{local/,}lib{,32,64}/python{2.[4-7],3,3.[0-9],3.1[0-9]}/{site,dist}-packages/*.dist-info/{METADATA,namespace_packages.txt} r,
/usr/{local/,}lib{,32,64}/python{2.[4-7],3,3.[0-9],3.1[0-9]}/{site,dist}-packages/*.VERSION r,
/usr/{local/,}lib{,32,64}/python{2.[4-7],3,3.[0-9],3.1[0-9]}/{site,dist}-packages/*.egg-info/PKG-INFO r,
/usr/{local/,}lib{,32,64}/python3.{1,}[0-9]/lib-dynload/*.so mr,
# Site-wide configuration
/etc/python{2.[4-7],3.[0-9]}/** r,
/etc/python{2.[4-7],3.[0-9],3.1[0-9]}/** r,
# shared python paths
/usr/share/{pyshared,pycentral,python-support}/** r,
@@ -36,7 +35,7 @@
/usr/lib/wx/python/*.pth r,
# python build configuration and headers
/usr/include/python{2.[4-7],3.[0-9]}*/pyconfig.h r,
/usr/include/python{2.[4-7],3.[0-9],3.1[0-9]}*/pyconfig.h r,
# Include additions to the abstraction
include if exists <abstractions/python.d>

Some files were not shown because too many files have changed in this diff Show More