El Capitanでtsocksを使う

コマンドを実行するとき,必ずSOCKSプロキシを通るようにするためのツールtsocksというものがあって,Linuxではもちろん,OSX Mavericksでも動くのでよく使っていました.

ところが,先日El Capitanにアップデートした途端動かなくなり,いろいろ調べてるうちに解決したのでそのメモ.

OSXでのインストール方法

標準のhomebrewには含まれておらず,homebrew用のスクリプトを用意してやる必要があります.

norisu0313.hatenablog.com

ここを参考に,

github.com

に含まれているスクリプト/usr/local/Library/Formula/に配置します.

~$ cat -> /usr/local/Library/Formula/tsocks.rb
require 'formula'

class Tsocks < Formula
  # The original is http://tsocks.sourceforge.net/
  # This GitHub repo is a maintained fork with OSX support
  homepage 'http://github.com/pc/tsocks'
  head 'https://github.com/pc/tsocks.git'

  depends_on 'autoconf' => :build if MacOS.xcode_version.to_f >= 4.3

  def install
    system "autoconf", "-v"
    system "./configure", "--prefix=#{prefix}", "--disable-debug", "--disable-dependency-tracking", "--with-conf=#{config_file}"

    inreplace("tsocks") { |bin| bin.change_make_var! "LIBDIR", lib }

    system "make"
    system "make install"

    etc.install "tsocks.conf.simple.example" => "tsocks.conf" unless config_file.exist?
  end

  def test
    puts 'Your current public ip is:'
    ohai `curl -sS ifconfig.me 2>&1`.chomp
    puts "If your correctly configured #{config_file}, this should show the ip you have trough the proxy"
    puts 'Your ip through the proxy is:'
    ohai `tsocks curl -sS ifconfig.me 2>&1`.chomp
  end

  def config_file
    etc / 'tsocks.conf'
  end
end
[EOF]
~$

tsocksのしくみ

tsocksのソースコードを読むとわかるのですが,ライブラリ関数のフックを用いてこの機能を実現しています.LinuxならLD_PRELOAD, OSXならDYLD_INSERT_LIBRARIESおよびDYLD_FORCE_FLAT_NAMESPACEといった具合です.tsocks本体のスクリプト環境変数に共有ライブラリを追加するためのラッパーで,実際には生成されたlibtsocksというライブラリが仕事をしています.

El Capitanでの問題

どうやらSystem Integrity Protection (SIP) が悪さ (セキュリティ的には良い挙動ですが) をしているらしく,DYLD_INSERT_LIBRARIESによるフックが無効化されていました.
SIPの無効化はリカバリーモードでcsrutil disableとか打つと良いのですが,影響を及ぼさないシステム保護まで解除してしまうため,必要なものだけを無効化します.

~$ csrutil disable
~$ csrutil enable --without debug

これによってApple InternalDebugging Restrictionsのみが無効化され,fsなどの保護は生きたままになります.

~$ csrutil status
System Integrity Protection status: enabled (Custom Configuration).

Configuration:
    Apple Internal: disabled
    Kext Signing: enabled
    Filesystem Protections: enabled
    Debugging Restrictions: disabled
    DTrace Restrictions: enabled
    NVRAM Protections: enabled

This is an unsupported configuration, likely to break in the future and leave your machine in an unknown state.

これでtsocksが使えるようになります.

~$ ssh -fND 1080 home
~$ tsocks curl 192.168.1.X