2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

macOSのsandbox-execをためしてみた

Posted at

1. もっとも手軽 ― 組み込みプロファイルで実行

macOS には no-networkstrict などの組み込みプロファイルが用意されています。

# ネットワークを禁止した状態で curl を試す(失敗するはず)
sandbox-exec -n no-network /usr/bin/curl https://example.com
  • -n <name> で組み込みプロファイル名を指定
  • no-network はすべてのネットワークアクセスを拒否します

2. 独自プロファイルをファイルで書いて実行

1️⃣ プロファイルを書く(例: allow_ls.sb

;; allow_ls.sb
(version 1)

(deny default)                 ; まず全部拒否
(allow process-exec            ; /bin/ls の実行を許可
       (equal "/bin/ls"))
(allow file-read*              ; ~/tmp だけ読み取り/書き込み可
       file-write*
       (regex "^/Users/leo/tmp"))

2️⃣ コマンドを走らせる

sandbox-exec -f allow_ls.sb /bin/ls /Users/leo/tmp

ポイント

説明
(deny default) まずは全て拒否 ― “ホワイトリスト方式” で書き始めるのが鉄則
(allow process-exec …) 実行できるバイナリをピンポイントで許可
(allow file-read* file-write* …) 読み書きパスを正規表現で限定

3. 即席ワンライナーでプロファイルを渡す

ファイルに書かずに ヒアドキュメント で済ませる方法です。

sandbox-exec -p \
'(version 1)
 (deny default)
 (allow file-read*
        (literal "/etc/hosts"))' \
/bin/cat /etc/hosts

4. 便利な開発テクニック

テクニック 使いどころ
(debug deny) を一番上に書く sandbox で拒否されたときのログを詳しく出す
(with no-log ...) を併用 ログが多すぎる場面で絞り込みたいとき
環境変数 SANDBOX_DEBUG_INFORMATION=YES syslog から sandbox の違反原因を確認

よくあるハマりどころ

  1. パス指定の落とし穴
    • /bin/ls を許可しても実行実体が /usr/bin/ls なら拒否されます
    • which ls で正確なパスを確認しましょう
  2. GUI アプリには別 API
    • GUI アプリのサンドボックスは App Sandbox(Entitlement ベース)で、sandbox-exec は CLI 向けです
  3. macOS Ventura 以降の制限
    • SIP (System Integrity Protection) や EndpointSecurity 連携で挙動が変わる場合があります

まとめ

  • sandbox-exec は “deny default” で書き始める のが安全
  • テキストファイルに Scheme ライク なポリシーを書いて -f で渡す
  • ネットワーク禁止など軽い試験なら 組み込みプロファイル が手っ取り早い

これで macOS 上での簡易サンドボックス実行が試せます。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?