Once a process is running under apparmor, changing the profile is as simple as updating the profile and reloading it. Initially getting it into apparmor normally requires a restart, but sometimes you just don’t want to restart the daemon.
Lets say that you’ve deployed a production service and managed to not actually enable the apparmor profile that you wrote for it. Now you want to enable it without a restart, since a restart would be disruptive (and would involve admitting that you didn’t actually deploy it under apparmor like you claimed…)
In order to have a binary name for use in our example, let’s call our program “/usr/sbin/inspircd”. Throughout the following text, my input is in red.
Create the apparmor profile and make it active
(Actually creating the profile is beyond the scope of this process.)
apparmor_parser -r /etc/apparmor.d/usr.sbin.inspircd.
Make sure we have gdb
apt-get install gdb
Find the process
ps auxf | grep /usr/sbin/inspircd
(For our example, we will use pid 22143)
Confine the process
If we could do this from outside of the process, this would be trivial. Then again, there are sound reasons for why only the process itself is permitted to change its profile.
What we want to do here is call: aa_change_profile(“/usr/sbin/inspircd”) from within the process, but it is nearly certain that aa_change_profile is not in the symbol table for our daemon. So we do it the hard way, by doing what aa_change_profile does: write a particular string to /proc/self/attr/current (the 32 in the write call is the length of the string: no trailing null is needed.)
(Note that while we are in gdb, the process is stopped in the debugger, and users might tend to notice this… I pasted all 5 lines of text into the debugger, which meant that I was stopped in the debugger for under 2 seconds.)
# gdb -p 22143
(gdb) call open("/proc/self/attr/current",2)
$1 = 13
(gdb) call write($1,"changeprofile /usr/sbin/inspircd",32)
$2 = 32
(gdb) call close($1)
$3 = 0
A debugging session is active.
Inferior 1 [process 22143] will be detached.
Quit anyway? (y or n) y
Detaching from program: /usr/sbin/inspircd, process 22143
And now we have a happily confined process, no file descriptors leaked, no daemon restart, and only a second or so of interruption masquerading as lagginess.