Linux Security Modules

はじめに

第41章はじめに

このビデオでは、この章で説明するトピックの概要を簡単に説明します。


学習目標
この章の終わりまでに、次のことができるようになります。

Linux Security Modules（LSM）フレームワークの仕組みとデプロイ方法を理解できます。
使用可能なさまざまなLSM実装をリストできます。
SELinuxの主な機能を説明できます。
利用可能なさまざまなモードとポリシーを説明できます。
コンテキストの重要性と、それらの取得と設定の方法を把握できます。
重要なSELinuxユーティリティ プログラムの使用方法を知ることができます。
AppArmorにある程度熟知できます。


Linux Security Modules

Linux Security Modules（LSM）とは
最新のコンピュータ システムはセキュリティで保護する必要がありますが、そのセキュリティ要件は、データの機密性、アカウントを持つユーザーの数、外部ネットワークへの露出、法的要件、その他の要因によって異なります。適切なセキュリティ制御を使用可能にする責任は、アプリケーション設計者とLinuxカーネル開発者とメンテナにあります。もちろん、ユーザーも適切な手順に従う必要があります。しかし、適切に実行されているシステムでは、非特権ユーザーは、システムをセキュリティ侵害にさらすことがないように、操作権限が非常に限られているはずです。このセクションでは、LinuxカーネルがLinux Security Modulesフレームワークを使用してセキュリティを強化する方法、特にSELinuxを中心に説明します。目的は、カーネルに対して行われたさまざまな要求に対して、強制的なアクセス制御を実装することです。それは次の方法で行います。

カーネルへの変更を最小限に抑えます
カーネルでのオーバーヘッドを最小化にします
異なる実装に対して、柔軟性と選択を許可します。各実装は自己完結型のLSM（Linux Security Modules）として提供されます。

基本的な考え方は、システムコールをフックすることです。強化された権限の作業を実行するために、アプリケーションがカーネル（システム）モードへの移行を要求するときに、コードを挿入します。このコードは、パーミッションが有効であること、悪意のある意図から保護されていることなどの確認を行います。これは、システムコールがカーネルによって実行される前後に、セキュリティ関連の機能ステップを呼び出す形で行われます。


LSMの選択
長い間、LSMの実装された唯一の強化されたセキュリティ モデルはSELinuxでした。2001年に、このプロジェクトが最初にアップストリームでカーネルに直接組み込まれたとき、セキュリティを強化するアプローチを1つだけ使用することに反対がありました。

その結果、SELinuxの代替モジュールを使用できるLSMアプローチが採用されました。2003年に開発され、Linuxカーネルに組み込まれました。

現在のLSMで実装されるものは次のとおりです。

SELinux
AppArmor
Smack
Tomoyo

Linuxカーネルの同じ部分を変更する可能性があるため、一度に使用できるLSMは1つだけです。

ユーザーの利用度の多い順に、最初にSELinuxを説明し、次にAppArmorを説明します。


SELinuxの概要
SELinuxはもともと米国NSA（National Security Administration）によって開発されたもので、非常に長い間RHELに不可欠な機能でした。

運用という観点から見ると、SELinuxは、プロセスがシステム上のどのファイル、ディレクトリ、ポート、およびその他のアイテムにアクセスできるかを決定する、セキュリティ ルールのセットです。

3種類の概念要素で機能します。

各ボックスをクリックして展開し、SELinuxが機能する3種類の概念要素について学習します。

SELinuxの概念要素

コンテキスト
コンテキストは、ファイル、プロセス、およびポートのラベルです。コンテキストの例として、SELinuxユーザー、ロール、タイプがあります。

ルール
ルールは、コンテキスト、プロセス、ファイル、ポート、ユーザーなどの観点からアクセス制御を記述したものです。

ポリシー
ポリシーは、SELinuxが行うシステム全体のアクセス制御の判断が何かを記述するルール セットです。

SELinuxコンテキストは、ユーザー、プロセス、ファイル、およびポートが相互に対話する方法を定義するルールによって使用される名前です。デフォルトのポリシーはアクセスを拒否することであるため、システムで許されるアクションを記述するためにルールが使用されます。

追加のオンライン ドキュメントとして、SELinux User's and Administrator's Guideがあります。


SELinuxモード
SELinuxは、3つのモードのいずれかで実行できます。

クリックして各ボックスを展開し、3つのSELinuxモードの詳細をご覧ください。

SELinuxモード

Enforcing
すべてのSELinuxコードは有効であり、ポリシーに従ってアクセスは拒否されます。すべての違反を監査しログに記録します。

Permissive
SELinuxコードは有効ですが、アクセスを拒否せず、enforcingモードでは拒否される動作については監査と警告のみが行われます。

Disabled
SELinux カーネルとアプリケーション コードを完全に無効にし、システムを保護しません。

これらのモードはファイル（通常は/etc/selinux/config）で選択（および説明）され、その場所はディストリビューションによって異なります（多くの場合、/etc/sysconfig/selinuxもしくはそこからリンクされています）。ファイルは読むだけで内容がわかるように自己文書化されています。sestatusユーティリティは、現在のモードとポリシーを表示します。

SELinuxモード：Enforcing

SELinuxモード：Permissive

現在のモードを確認または設定するには、getenforceとsetenforceを使用します。

$ getenforce
Disabled

$ sudo setenforce Permissive
$ getenforce
Permissive

setenforceを使用して、システムの稼働中にenforcingモードとpermissiveモードを臨機応変に切り替えることができます。ただし、disabledモードの切り替えは、この方法では行えません。setenforceでは、permissiveモードとenforcingモードを切り替えることができますが、SELinuxを完全に無効にすることはできません。SELinuxを無効にするには、少なくとも2つの異なる方法があります。

構成ファイル
SELinuxの構成ファイル（通常は/etc/selinux/config）を編集し、SELINUX=disabledを設定します。これはデフォルトの方法であり、SELinuxを恒久的に無効にするために使用するべきです。
カーネル パラメータ
再起動時にselinux=0をカーネル パラメータ リストに追加します。
ただし、SELinuxを再度有効にする可能性のあるシステムでは、SELinuxを無効にすることはお勧めできません。SELinuxを無効にするのではなく、permissiveモードを使用することをお勧めします。これにより、時間のかかるファイルシステム全体の再ラベル付けを回避できます。


SELinuxポリシー
同じ構成ファイル（通常である/etc/sysconfig/selinux）にSELinuxポリシーを設定します。複数のポリシーを定義できますが、一度にアクティブにできるのは1つだけです。ポリシーを変更するには、システムの再起動とファイルシステムの内容の時間のかかる再ラベル付けが必要になる場合があります。各ポリシーは、/etc/selinux/[SELINUXTYPE]の下にインストールされるファイルに設定されています。

クリックして各カードを反転し、最も一般的なSELinuxポリシーについて学習します。

targeted
SELinuxはターゲットとなるプロセスを制限されたドメインで実行します。デフォルトのポリシーです。ユーザー プロセスとinitプロセスは対象外です。SELinuxは、すべてのプロセスにメモリ制限を適用します。これにより、バッファ オーバーフロー攻撃に対する脆弱性が軽減されます。

minimum
選択されたプロセスのみが保護される、targetedポリシーの一種です。

MLS
マルチレベル セキュリティ（Multi-Level Security:MLS）は一番制限がきついポリシーです。すべてのプロセスは、特定のポリシーを持つきめ細かいセキュリティ ドメインに置かれます。


コンテキスト ユーティリティ
前述したように、コンテキストはファイル、ディレクトリ、ポート、プロセスに適用されるラベルです。これらのラベルは、アクセス ルールを記述するために使用されます。SELinuxコンテキストは4つあります。

ユーザー
ロール
タイプ
レベル。

ここでは、最も一般的に使用されるコンテキストのtypeに注目します。ラベルの命名規則により、kernel_tのように、type コンテキストのラベルは_tで終わる必要があります。

-Zオプションを使用して、コンテキストを表示するには以下を実行します。

$ ls -Z
$ ps auZ

chconコマンドを使用して、コンテキストを変更する場合は以下です。

$ chcon -t etc_t somefile
$ chcon --reference somefile so


SELinuxと標準コマンド
lsやpsなどの多くの標準コマンド ラインのコマンドは、SELinuxをサポートするように拡張され、マニュアル ページに詳細な説明が追加されました。パラメータZは次のように標準のコマンド ライン ツールに渡されます。

$ ps axZ
LABEL PID TTY STAT TIME COMMAND
system_u:system_r:init_t:s0 1 ? Ss 0:04 /usr/lib/systemd/systemd --switched-root ...
system_u:system_r:kernel_t:s0 2 ? S 0:00 [kthreadd]...unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 2305 ? D 0:00 sshd: peter@pts/0unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 2306 pts/0 Ss 0:00 -bash
...
system_u:system_r:httpd_t:s0 7490 ? Ss 0:00 /usr/sbin/httpd -DFOREGROUND
system_u:system_r:httpd_t:s0 7491 ? S 0:00 /usr/sbin/httpd -DFOREGROUND...

$ ls -Z /home/ /tmp/
/home/:
drwx------. peter peter unconfined_u:object_r:user_home_dir_t:s0 peter/tmp/:
-rwx------. root root system_u:object_r:initrc_tmp_t:s0 ks-script-c4ENhg
drwx------. root root system_u:object_r:tmp_t:s0 systemd-private-0ofSvO
-rw-------. root root system_u:object_r:initrc_tmp_t:s0 yum.log

SELinuxをサポートするために拡張されたツールには他に、cp、mv、mkdirがあります。

SELinuxを無効にした場合、これらのユーティリティの関連フィールドには有用な情報が表示されていないことに注意してください。


コンテキストの継承
新しく作成されたファイルは、親ディレクトリからコンテキストを継承しますが、ファイルを移動すると、保存されているのは移動前のソース ディレクトリのコンテキストであるため、移動後のディレクトリで実行などを行うと問題を引き起こす可能性があります。

前の例で言えば、ファイルを/tmpから/home/peterに移動してもtmpfileのコンテキストは変更されません。

$ cd /tmp/
$ touch tmpfile
$ ls -Z tmpfile
-rw-rw-r--. peter peter unconfined_u:object_r:user_tmp_t:s0 tmpfile

$ cd
$ touch homefile
$ ls -Z homefile
-rw-rw-r--. peter peter unconfined_u:object_r:user_home_t:s0 homefile

$ mv /tmp/tmpfile .
$ ls -Z
-rw-rw-r--. peter peter unconfined_u:object_r:user_home_t:s0 homefile
-rw-rw-r--. peter peter unconfined_u:object_r:user_tmp_t:s0 tmpfile

ファイルの移動でSELinuxの問題が発生する典型的な例は、httpdサーバーのDocumentRootディレクトリにファイルを移動する場合です。SELinux対応システムでは、ウェブ サーバーは正しいコンテキスト ラベルを持つファイルにのみアクセスできます。/tmpにファイルを作成し、それをDocumentRootディレクトリに移動した場合、そのファイルのSELinuxコンテキストが調整されるまで、httpdサーバーからファイルにアクセスできなくなります。


restorecon
restoreconは、親ディレクトリの設定に基づいてファイル コンテキストをリセットします。次の例では、restoreconはホーム ディレクトリのすべてのファイルのデフォルト ラベルを再帰的にリセットします。

$ ls -Z
-rw-rw-r--. peter peter unconfined_u:object_r:user_home_t:s0 homefile
-rw-rw-r--. peter peter unconfined_u:object_r:user_tmp_t:s0 tmpfile

$ restorecon -Rv /home/peter
restorecon reset /home/peter/tmpfile context \
unconfined_u:object_r:user_tmp_t:s0->unconfined_u:object_r:user_home_t:s0

$ ls -Z
-rw-rw-r--. peter peter unconfined_u:object_r:user_home_t:s0 homefile
-rw-rw-r--. peter peter unconfined_u:object_r:user_home_t:s0 tmpfile

tmpfileのコンテキストは、ホーム ディレクトリで作成されたファイルのデフォルト コンテキストにリセットされていることに注目してください。タイプがuser_tmp_tからuser_home_tに変更されました。


semanage
別の課題として、新しく作成されたディレクトリのデフォルト コンテキストの設定方法があります。semanage fcontext（policycoreutils-pythonパッケージで提供）は、ファイルおよびディレクトリのデフォルト コンテキストの変更と表示ができます。semanage fcontextはデフォルト設定のみを変更することに注意してください。既存のオブジェクトにすぐには適用されません。これには、その後restoreconを実行する必要があります。例えば、

[root@rhel7 /]# mkdir /virtualHosts
[root@rhel7 /]# ls -Z
...
drwxr-xr-x. root root unconfined_u:object_r:default_t:s0 virtualHosts

[root@rhel7 /]# semanage fcontext -a -t httpd_sys_content_t /virtualHosts
[root@rhel7 /]# ls -Z
...
drwxr-xr-x. root root unconfined_u:object_r:default_t:s0 virtualHosts

[root@rhel7 /]# restorecon -RFv /virtualHosts
restorecon reset /virtualHosts context unconfined_u:object_r:default_t:s0->system_u:object_r:httpd_sys_content_t:s0

[root@rhel7 /]# ls -Z
drwxr-xr-x. root root system_u:object_r:httpd_sys_content_t:s0 virtualHosts

したがって、default_tからhttpd_sys_content_tへのコンテキストの変更は、restoreconの実行後に適用されます。


SELinuxのブール値の使い方
SELinuxポリシーの挙動は、ポリシーを書き換えなくても実行時に設定できます。これは、有効化と無効化ができるポリシー パラメータであるSELinuxのブール値を設定することにより実現できます。

getsebool　-　ブール値を見ます。
setsebool　-　ブール値を設定します。
semanage boolean -i　-　恒久的なブール設定を表示します。

以下のスクリーンショットで、現在の状態や簡単な説明を含め、現在のポリシーのすべてのブール値を一覧表示するために必要な操作を確認できます。

$ setsebool allow_ftpd_anon_write on
$ getsebool allow_ftpd_anon_write
  allow_ftpd_anon_write -> on
$ semanage boolean -l | grep allow_ftpd_anon_write
$ allow_ftpd_anon_write -> off

恒久的な設定ではないことに注意してください。

$ setsebool -P allow_ftpd_anon_write on
$ semanage boolean -l | grep allow_ftpd_anon_write
  allow_ftpd_anon_write -> on

恒久的な設定になりました。

semanageの使用例


SELinuxアクセスの監視
SELinuxには、実行時に問題を収集し、これらの問題をログに記録し、同じ問題の再発を防ぐソリューションを提案するツール群が付属しています。これらのユーティリティは、setroubleshoot-serverパッケージで提供されます。それらの使用例を次に示します。

[root@rhel7 ~]# echo 'File created at /root' > rootfile
[root@rhel7 ~]# mv rootfile /var/www/html/
[root@rhel7 ~]# wget -O - localhost/rootfile
--2014-11-21 13:42:04-- http://localhost/rootfile
Resolving localhost (localhost)... ::1, 127.0.0.1
Connecting to localhost (localhost)|::1|:80... connected.
HTTP request sent, awaiting response... 403 Forbidden
2014-11-21 13:42:04 ERROR 403: Forbidden.

[root@rhel7 ~]# tail /var/log/messages
Nov 21 13:42:04 rhel7 setroubleshoot: Plugin Exception restorecon
Nov 21 13:42:04 rhel7 setroubleshoot: SELinux is preventing /usr/sbin/httpd from getattr access on the file .
....
Nov 21 13:42:04 rhel7 python: SELinux is preventing /usr/sbin/httpd from getattr access on the file .
....
Do allow this access for now by executing
# grep httpd /var/log/audit/audit.log | audit2allow -M mypol
# semodule -i mypol.pp

Additional Information:
Source Context system_u:system_r:httpd_t:s0
Target Context unconfined_u:object_r:admin_home_t:s0
Target Objects [ file ]
Source httpd
Source Path /usr/sbin/httpd
....


AppArmor
AppArmorは、SELinuxに代わるLSMです。2006年以降、Linuxカーネルにサポートが組み込まれています。SUSE、Ubuntu、およびその他のディストリビューションで使用されています。

AppArmorとは:

強制アクセス制御（Mandatory Access Control：MAC）を提供します。
管理者は、セキュリティ プロファイルを、機能を制限するプログラムに関連付けることができます。
SELinuxよりも（すべてではありませんが、一部では）使いやすいと考えられています。
ファイルシステムでの対応は不要です（セキュリティ ラベルは不要）。

AppArmorは、強制アクセス制御（ Mandatory Access Control：MAC）を提供することにより、従来の UNIXの任意アクセス制御（Discretionary Access Control ：DAC）モデルを補完します。

手動でプロファイルを指定することに加えて、AppArmorには学習モードが含まれています。このモードでは、プロファイルの違反はログに記録されますが、阻止はされません。このログは、プログラムの一般的な動作に基づいていて、プロファイルに変換できます。


状態の確認
AppArmorを採用しているディストリビューションは、デフォルトでAppArmorを有効にしてロードすることが多いです。Linuxカーネルでも同様に有効にする必要があります。ただし、一度に実行できるLSMは1つだけです。

AppArmorカーネル モジュールが利用可能である場合、systemdが装備されたシステムでは次のことができます。

$ sudo systemctl [start|stop|restart|status] apparmor

これにより操作の現在の状態を変更または照会できます。もしくは以下を実行すると、

​$ sudo systemctl [enable|disable} apparmor

起動時にロードする／しないを決めることができます。

現在の状態を確認するには、次を実行します。

$ sudo apparmor_status
apparmor module is loaded.
25 profiles are loaded.
25 profiles are in enforce mode.
    /sbin/dhclient
...

プロファイルとプロセスは、enforceモードまたはcomplainモードのどちらかに属します。これは、SELinuxのenforcingモードとpermissiveモードに類似しています。モードについては次で説明します。プロセスでは、PIDのリストが表示されることに注意してください。

$ ps aux | grep libvirtd
root      787  0.0  0.9  527200  35936  ?       Ssl  10:54  0:00  /usr/sbin/libvirtd
student​  3346  0.0  0.0   13696   2204  pts/16  S+   11:42  0:00  grep --color=auto libvirtd


モードとプロファイル
プロファイルは、システム上で/usr/bin/evinceなどのパス名を持つ実行可能プログラムの使用方法を制限します。

プロセスは、次の2つのモードのいずれかで実行できます。

Enforceモード
ポリシー遵守は強制され、アプリケーションが制限されている方法で動作するのを防ぎます。試行された違反は、システム ログ ファイルに報告されます。これがデフォルトのモードです。aa-enforceを使用して、プロファイルをこのモードに設定できます。

Complainモード
ポリシーは遵守の強制はありませんが、試行されたポリシー違反は報告されます。これは学習モードとも呼ばれます。aa-complainを使用して、プロファイルをこのモードに設定できます。

Linuxディストリビューションには、あらかじめパッケージ化されたプロファイルが付属しており、通常は、その特定のパッケージがインストールされたときにプロファイルが一緒にインストールされます。もしくは、apparmor-profilesなどのAppArmorパッケージと一緒にプロファイルがインストールされます。これらのプロファイルは/etc/apparmor.dに保存されます。

新しいソフトウェアをインストールするときには、パッケージ内の実行可能ファイルに固有の、新しいプロファイルを作成できます。

システムにインストールされるAppArmorプロファイルは、選択したソフトウェア パッケージによって異なります。たとえば、あるUbuntuシステムの場合：

student@ubuntu: /etc/apparmor.d$ ls​
abstractions  usr.lib.dovecot.anvil   usr.lib.telepathy
apache2.d     usr.lib.dovecot.auth    usr.sbin.avahi-daemon
bin.ping      usr.lib.dovecot.config  usr.sbin.cups-brows
...

man apparmor.dを実行することで、これらのファイルに何が入るかについての完全なドキュメントを取得できます。


AppArmorユーティリティ
AppArmorには、監視と制御のための管理ユーティリティが数多くあります。たとえば、OpenSUSEシステムの場合：

$ rpm -qil apparmor-utils | grep bin​
/usr/bin/aa-easyprof
/usr/sbin/aa-audit
/usr/sbin/aa-autodep
/usr/​sbin/aa-cleanprof
/usr/sbin/aa-complain
/usr/sbin/aa-decode
/usr/sbin/aa-disable
/usr/sbin/aa-enforce
/usr/sbin/aa-exec
....
/usr/sbin/complain
/usr/sbin/decode
/usr/sbin/disable
/usr/sbin/enforce
....

これらのユーティリティの多くは、短い名前を指定しても長い名前を指定しても呼び出すことができます。以下に例を示します。

linux-llgn:/etc/apparmor.d # ls -l /usr/sbin/*complain
-rwxr-xr-x 1 root root 1442 Oct 25 07:37 /usr/sbin/aa-complain*
lrwxrwxrwx 1 ​root root 11 Nov 11 13:02 /usr/sbin/complain -> aa-complain*
linux-llgn:/etc/apparmor.d #

表：AppArmorユーティリティ

プログラム	用途
apparmor_status	すべてのプロファイルおよびプロファイルを含むプロセスのステータスを表示します
apparmor_notify（aa-notify） 	AppArmorのログ メッセージの概要を表示します
complain		特定のプロファイルをcomplainモードに設定します
enforce		指定したプロファイルを強制モードに設定します
disable		現在のカーネルから指定されたプロファイルをアンロードし、システム起動時にロードされないようにします
logprof（aa-logprof）	ログ ファイルをスキャンし、既存のプロファイルでカバーされていないAppArmorイベントが記録されている場合は考慮に入れる方法を提案し、承認されている場合は制限するように変更して再ロードします。
easyprof（aa-easyprof）　プログラムの基本的なAppArmorプロファイルの生成を支援します。簡易なインターフェイスを提供します。


演習

課題 41.1: SELinux：コンテキスト

🚩
以下のPDFドキュメントに埋め込まれた外部URLにアクセスする場合は、常に右クリックして新しいタブまたはウィンドウで開いてください。直接クリックしてURLを開こうとすると、コース ウィンドウ／タブが閉じます。

Exercise 41.1: SELinux: Contexts

Please Note

This exercise can only be performed on a system (such as RHEL) where SELinux is installed.  While it is possible to install on Debian-based distributions, such as Ubuntu, it is not the easiest task and it is not often done.

1.  Verify SELinux is enabled and in enforcing mode, by executing getenforce and sestatus. If not, edit /etc/selinux/config, reboot, and check again.

2.  Install  the httpd package  (if  not  already  present)  which  provides  the Apache web  server,  and  then  verify  that  it  is working:

$ sudo yum install  httpd
$ elinks http:/localhost

(You can also use lynx or elinks etc. as the browser, or use your graphical browser such as firefox or chrome, in this and succeeding steps.)

3.  As superuser, create a small file in /var/www/html:

$ sudo sh -c "echo file1 > /var/www/html/file1.html"

4.  Verify you can see it:

$ elinks -dump http://localhost/file1.html
file1

Now create another small file in root’s home directory and move it to /var/www/html.  (Do not copy it, move it!)  Then try and view it:

$ sudo cd /root
$ sudo sh -c "echo file2 > file2.html"
$ sudo mv file2.html /var/www.html
$ elinks -dump http://localhost/file2.html
Forbidden

You don't have permission to access /file2.html on this server.

5.  Examine the security contexts:

$ cd  /var/www/html
$ ls -Z file*html
-rw-r--r--. root root unconfined_u:object_r:httpd_sys_content_t:s0 file1.html
-rw-r--r--. root root unconfined_u:object_r:admin_home_t:s0 file2.html

6.  Change the offending context and view again:

$ sudo chcon -t httpd_sys_content_t file2.html
$ elinks http://localhost/file2.html
file2


課題 41.2: apparmorセキュリティを使う
🚩
以下のPDFドキュメントに埋め込まれた外部URLにアクセスする場合は、常に右クリックして新しいタブまたはウィンドウで開いてください。直接クリックしてURLを開こうとすると、コース ウィンドウ／タブが閉じます。

Exercise 41.2: Exploring apparmor security

Please Note

This exercise can only be performed on a system (such asUbuntu) where AppArmor is installed.The below was tested on Ubuntu, but should work on other AppArmor-enabled systems, such as OpenSUSE, where the apt commands should be replaced by zypper.

On Ubuntu,  the /bin/ping utility  runs  with  SUID  enabled.   For  this  exercise,  we  will  copy ping to ping-x and  adjust  the capabilities so the program functions.Then we will build an AppArmor profile, install and verify that nothing has changed.  Modifying the AppArmor profile and adding capabilities will allow the program more functionality.

1.  Make sure all necessary packages are installed:
student@ubuntu: ̃$ sudo apt install apparm*

2.  Create a copy ofping (called ping-x) and verify it has no initial special permissions or capabilities.  Furthermore, it cannot work when executed by student, a normal user:

student@ubuntu: ̃$ sudo cp /bin/ping /bin/ping-x
student@ubuntu: ̃$ sudo ls -l /bin/ping-x

-rwxr-xr-x 1 root root 64424 Oct 17 10:12 /bin/ping-x

student@ubuntu: ̃$ sudo getcap /bin/ping-x
student@ubuntu: ̃$

student@ubuntu: ̃$ ping-x -c3 -4 127.0.0.1
ping: socket: Operation not permitted

3.  Set the capabilities and re-try ping-x:

student@ubuntu: ̃$ sudo setcap cap_net_raw+ep  /bin/ping-x
student@ubuntu: ̃$ ping-x  -c3 -4 127.0.0.1
PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.092 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.093 ms
64 bytes from 127.0.0.1: icmp_seq=3 ttl=64 time=0.086 ms

--- 127.0.0.1 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2034ms
rtt min/avg/max/mdev = 0.086/0.090/0.093/0.008 ms

The modifiedping-x program now functions normally.

4.  Verify there is no pre-existing AppArmor profile for ping-x, but there is a profile forping.  Determine the status of the current ping program:

student@ubuntu: ̃$ sudo aa-status

The output from aa-status is long, so we can grep for the interesting lines:

student@ubuntu: ̃$ sudo aa-status | grep -e "ˆ[[:alnum:]]" -e ping
apparmor module is loaded.
87 profiles are loaded.
51 profiles are in enforce mode.
ping
36 profiles are in complain mode.
17 processes have profiles defined.
6 processes are in enforce mode.
11 processes are in complain mode.
0 processes are unconfined but have a profile defined.

We can see ping has a profile that is loaded and enabled for enforcement.

5.  Next we will construct a new profile for ping-x. This step requires two terminal windows.
The first window (window1) will be running the aa-genprof command.  This will generate a AppArmor profile by scan-ning /var/log/syslog for AppArmor errors.
The second window (window2) will be used to run ping-x. (See the manpage for aa-genprof for additional information.)
Inwindow1:

student@ubuntu: ̃$ sudo aa-genprof /bin/ping-x
Writing updated profile for /bin/ping-x.
Setting /bin/ping-x to complain mode.

Before you begin, you may wish to check if a 
profile already exists for the application you
wish to confine. See the following wiki page for
more information:
http://wiki.apparmor.net/index.php/Profiles

Please start the application to be profiled in
another window and exercise its functionality now.

Once completed, select the "Scan" option below in
order to scan the system logs for AppArmor events.

For each AppArmor event, you will be given the
opportunity to choose whether the access should be
allowed or denied.

Profiling: /bin/ping-x

[(S)can system log for AppArmor events] / (F)inish

Inwindow2:

student@ubuntu: ̃$ ping-x  -c3 -4 127.0.0.1
PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.099 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.120 ms
64 bytes from 127.0.0.1: icmp_seq=3 ttl=64 time=0.114 ms

--- 127.0.0.1 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2041ms
rtt min/avg/max/mdev = 0.099/0.111/0.120/0.008 ms

Inwindow1:

The command ping-x has completed, we must now instruct aa-genprof to scan for the required information to be added to the profile. It may require several scans to collect all of the information for the profile.Enter S to scan:

Reading log entries from /var/log/syslog.
Updating AppArmor profiles in /etc/apparmor.d.
Complain-mode changes:

Profile:    /bin/ping-x
Capability: net_raw
Severity:   8

[1 - capability net_raw,]
(A)llow / [(D)eny] / (I)gnore / Audi(t) / Abo(r)t / (F)inish

Enter A to allow the capability:

Adding capability net_raw, to profile.

Profile:        /bin/ping-x
Network Family: inet
Socket Type:    raw

[1 - network inet raw,]
(A)llow / [(D)eny] / (I)gnore / Audi(t) / Abo(r)t / (F)inish

EnterAto allow the network family:

Adding network inet raw, to profile.

Profile:        /bin/ping-x
Network Family: inet
Socket Type:    dgram

[1 - #include <abstractions/nameservice>]
2 - network inet dgram,
(A)llow / [(D)eny] / (I)gnore / Audi(t) / Abo(r)t / (F)inish

Enter A to add the socket type datagram to the profile:

Adding #include <abstractions/nameservice> to profile.

= Changed Local Profiles =

The following local profiles were changed. Would you like to save them?

[1 - /bin/ping-x]
(S)ave Changes / Save Selec(t)ed Profile / [(V)iew Changes] / View Changes b/w (C)lean profiles / Abo(r)t

Enter S to save the new profile:

Writing updated profile for /bin/ping-x.

Profiling: /bin/ping-x

[(S)can system log for AppArmor events] / (F)inish

EnterFto finish:

Setting /bin/ping-x to enforce mode.
Reloaded AppArmor profiles in enforce mode.
Please consider contributing your new profile!
See the following wiki page for more information:
http://wiki.apparmor.net/index.php/Profiles

Finished generating profile for /bin/ping-x.

6.  View the created profile, which has been stored in/etc/appamor.d/bin.ping-x.

student@ubuntu: ̃$ sudo cat /etc/apparmor.d/bin.ping-x
# Last Modified: Tue Oct 17 11:30:47 2017
#include <tunables/global>

/bin/ping-x {
#include <abstractions/base>
#include <abstractions/nameservice>

capability net_raw,
network inet raw,

/bin/ping-x mr,
/lib/x86_64-linux-gnu/ld-*.so mr,}

7.  The aa-genproc utility installs and activates the new policy so it should be ready to use, and the policies can be reloaded on demand with the systemctl reload apparmor command.  To avoid any potential issues, and verify the changes will survive, reboot the system.

Once the system has restarted, as the user student, verify ping-xstill functions with the new profile enabled. Ping the localhost by ip address:

student@ubuntu: ̃$ ping-x -c3 -4 127.0.0.1
PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.057 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.043 ms
64 bytes from 127.0.0.1: icmp_seq=3 ttl=64 time=0.095 ms
--- 127.0.0.1 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2027ms
rtt min/avg/max/mdev = 0.043/0.065/0.095/0.021 ms

8.  This should work as expected.  The profile is very specific, and AppArmor will not allow functionality outside of the specified parameters. To verify AppArmor is protecting this application, try to ping the IPV6 localhost address.
This should fail:

student@ubuntu: ̃$ ping-x -c3  -6 ::1
ping: socket: Permission denied

(Note, the-6 option means use only IPv6and::1 is the local host in IPv6.)
The output indicates there is a socket issue. If the system log is examined it will be discovered that our ping-x program has no access to IPv6 within AppArmor:

766:104): apparmor="DENIED" operation="create" profile="/bin/ping-x"
pid=2709 comm="ping-x" family="inet6" sock_type="raw" protocol=58
requested_mask="create" denied_mask="create

9.  To correct this deficiency, re-run aa-genprof as we did earlier, and in window 2, ping the IPv6 loopback and append the additional options


知識チェック

「第41章 - Linux Security Modules」を完遂しました。おめでとうございます。このクイズに答えて、これまでに学んだ概念の理解度をチェックしてください。

クイズ開始

問題 41.1
SELinuxのPermissiveモードとEnforcingモードの違いを、より適切に説明している文章は次のうちどれですか？

A. SELinuxのEnforcingモードは、アクセスできるプロセスのみを制限し、ネットワーク ポートには影響しません。
B. SELinuxのEnforcingモードは、明示的に許可されているもの以外のすべてへのアクセスを拒否します。
C. SELinuxのEnforcingモードとPermissiveモードは似ていますが、Permissiveモードはエラーをログに記録します。
D. SELinuxのPermissiveモードは、明示的に許可されているもの以外のすべてへのアクセスを拒否します。

問題 41.2
現在のディレクトリのデフォルト コンテキストに一致するようにファイル コンテキストをリセットするには、SELinuxのどのツールを使用すればよいですか？

A. restorecon
B. semanage
C. setsebol
D. getsebol

