Debian/GNU Linux で Tor プロキシを立てる

Posted by
ぴろり
Posted at
2012/08/07 18:10
Trackbacks
関連記事 (0)
Post Comment
コメントできます
Category
開発メモ カテゴリ

 Tor (トーア、The Onion Router) は、ネットワークの接続経路を匿名化するための規格であると同時に、そのリファレンス実装でもあります。Tor では、P2P 技術を利用し、接続ごとにランダムに選択された複数のノードを経由して目的のサーバへ接続することで、その接続元を追跡されにくくしています。今回、自宅の Debian サーバに Tor プロキシ サーバを建ててみました。

このエントリーをはてなブックマークに追加  

前置き

 Tor Project で配布されているパッケージをインストールすることで Tor ネットワークを利用できるようになりますが、所有しているマシンが多いと、マシンごとに都度インストールするのが面倒です。そこで、24 時間運転の Linux サーバに Tor プロキシを 1 台建てて、クライアントからはこのプロキシを参照するようにしました。

覚書き

 サーバの環境は以下の通り。

# uname -a
Linux mizuho 2.6.26-2-amd64 #1 SMP Sun Mar 4 21:48:06 UTC 2012 x86_64 GNU/Linux
# cat /etc/debian_version
5.0.10
# free
             total       used       free     shared    buffers     cached
Mem:       3097760    1563348    1534412          0     325088     383492

 ソースをダウンロードしてビルドしてみる。

# cd
# mkdir src
# cd src
# wget https://www.torproject.org/dist/tor-0.2.2.37.tar.gz
...
# tar zxfv tor-0.2.2.37.tar.gz
...
# cd tor-*

 簡単に ./configure && make すればいいみたいだけれど、一応、設定オプションを見てみる。

# ./configure --help
`configure' configures this package to adapt to many kinds of systems.

Usage: ./configure [OPTION]... [VAR=VALUE]...

To assign environment variables (e.g., CC, CFLAGS...), specify them as
VAR=VALUE.  See below for descriptions of some of the useful variables.

Defaults for the options are specified in brackets.

Configuration:
  -h, --help              display this help and exit
      --help=short        display options specific to this package
      --help=recursive    display the short help of all the included packages
  -V, --version           display version information and exit
  -q, --quiet, --silent   do not print `checking ...' messages
      --cache-file=FILE   cache test results in FILE [disabled]
  -C, --config-cache      alias for `--cache-file=config.cache'
  -n, --no-create         do not create output files
      --srcdir=DIR        find the sources in DIR [configure dir or `..']

Installation directories:
  --prefix=PREFIX         install architecture-independent files in PREFIX
                          [/usr/local]
  --exec-prefix=EPREFIX   install architecture-dependent files in EPREFIX
                          [PREFIX]

By default, `make install' will install all the files in
`/usr/local/bin', `/usr/local/lib' etc.  You can specify
an installation prefix other than `/usr/local' using `--prefix',
for instance `--prefix=$HOME'.

For better control, use the options below.

Fine tuning of the installation directories:
  --bindir=DIR            user executables [EPREFIX/bin]
  --sbindir=DIR           system admin executables [EPREFIX/sbin]
  --libexecdir=DIR        program executables [EPREFIX/libexec]
  --sysconfdir=DIR        read-only single-machine data [PREFIX/etc]
  --sharedstatedir=DIR    modifiable architecture-independent data [PREFIX/com]
  --localstatedir=DIR     modifiable single-machine data [PREFIX/var]
  --libdir=DIR            object code libraries [EPREFIX/lib]
  --includedir=DIR        C header files [PREFIX/include]
  --oldincludedir=DIR     C header files for non-gcc [/usr/include]
  --datarootdir=DIR       read-only arch.-independent data root [PREFIX/share]
  --datadir=DIR           read-only architecture-independent data [DATAROOTDIR]
  --infodir=DIR           info documentation [DATAROOTDIR/info]
  --localedir=DIR         locale-dependent data [DATAROOTDIR/locale]
  --mandir=DIR            man documentation [DATAROOTDIR/man]
  --docdir=DIR            documentation root [DATAROOTDIR/doc/PACKAGE]
  --htmldir=DIR           html documentation [DOCDIR]
  --dvidir=DIR            dvi documentation [DOCDIR]
  --pdfdir=DIR            pdf documentation [DOCDIR]
  --psdir=DIR             ps documentation [DOCDIR]

Program names:
  --program-prefix=PREFIX            prepend PREFIX to installed program names
  --program-suffix=SUFFIX            append SUFFIX to installed program names
  --program-transform-name=PROGRAM   run sed PROGRAM on installed program names

System types:
  --build=BUILD     configure for building on BUILD [guessed]
  --host=HOST       cross-compile to build programs to run on HOST [BUILD]

Optional Features:
  --disable-option-checking  ignore unrecognized --enable/--with options
  --disable-FEATURE       do not include FEATURE (same as --enable-FEATURE=no)
  --enable-FEATURE[=ARG]  include FEATURE [ARG=yes]
  --disable-buf-freelists disable freelists for buffer RAM
  --enable-openbsd-malloc Use malloc code from openbsd. Linux only
  --enable-instrument-downloads
                          Instrument downloads of directory resources etc.
  --enable-static-openssl Link against a static openssl library. Requires
                          --with-openssl-dir
  --enable-static-libevent
                          Link against a static libevent library. Requires
                          --with-libevent-dir
  --enable-static-zlib    Link against a static zlib library. Requires
                          --with-zlib-dir
  --disable-transparent   disable transparent proxy support
  --disable-asciidoc      don't use asciidoc (disables building of manpages)
  --disable-threads       disable multi-threading support
  --enable-gcc-warnings   enable verbose warnings
  --enable-gcc-warnings-advisory
                          enable verbose warnings, excluding -Werror
  --enable-gcc-hardening  enable compiler security checks
  --enable-linker-hardening
                          enable linker security fixups
  --enable-local-appdata  default to host local application data paths on
                          Windows
  --disable-dependency-tracking  speeds up one-time build
  --enable-dependency-tracking   do not reject slow dependency extractors
  --disable-largefile     omit support for large files

Optional Packages:
  --with-PACKAGE[=ARG]    use PACKAGE [ARG=yes]
  --without-PACKAGE       do not use PACKAGE (same as --with-PACKAGE=no)
  --with-tor-user=NAME    Specify username for tor daemon
  --with-tor-group=NAME   Specify group name for tor daemon
  --with-libevent-dir=PATH    Specify path to libevent installation
  --with-ssl-dir=PATH    Obsolete alias for --with-openssl-dir
  --with-openssl-dir=PATH    Specify path to openssl installation
  --with-zlib-dir=PATH    Specify path to zlib installation
  --with-dmalloc          Use debug memory allocation library.
  --with-tcmalloc         Use tcmalloc memory allocation library.
  --with-syslog-facility=LOG syslog facility to use (default=LOG_DAEMON)

Some influential environment variables:
  CC          C compiler command
  CFLAGS      C compiler flags
  LDFLAGS     linker flags, e.g. -L if you have libraries in a
              nonstandard directory 
  LIBS        libraries to pass to the linker, e.g. -l
  CPPFLAGS    (Objective) C/C++ preprocessor flags, e.g. -I if
              you have headers in a nonstandard directory 
  CPP         C preprocessor

Use these variables to override the choices made by `configure' or to help
it to find libraries and programs with nonstandard names/locations.

Report bugs to the package provider.

 このステップは必要なくて好みの問題なんだけど、tor ユーザを作っておくことに。ユーザを作ったら、設定オプションを指定して ./configure する。

# adduser \
	--system \
	--no-create-home \
	--disabled-password \
	--disabled-login \
	--ingroup daemon \
	tor
# ./configure \
	--with-tor-user=tor \
	--with-tor-group=daemon
...

 ./configure の途中、必要なライブラリが無いと怒られたのでインストールしておく。libevent は、汎用的なイベント通知のフレームワークっぽいライブラリで、memcached などでも使われているそうな。へぇ~。

# apt-get install libevent-dev

 ./configure が終わったら make して完了。設定ファイルをちょこちょこっと弄る。

# cd /usr/local/etc/tor
# cp torrc.sample torrc
# vi torrc

### デーモンとして動作するよう設定
RunAsDaemon 1

### 実行ユーザを変更
User tor

### SOCKS プロキシの待ち受けポートを設定
SocksListenAddress 192.168.1.201:9050
### プロキシは LAN 内のマシンからのみ接続可能
SocksPolicy accept 192.168.1.0/24
SocksPolicy reject *

 設定ファイルの修正が完了したら、設定ファイルに間違いがないか一応チェックしてみる。

# tor --verify-config
# tor

 以上で SOCKS プロキシとして Tor ネットワークを利用できるようになるはず。ブラウザのプロキシ設定を Debian サーバに向けさせて、チェックページを開いてみる。プロキシが有効/無効の時で表示が変われば OK。

 もし、Tor のブリッジとして参加したいのであれば、以下の設定も追加で行うとよい。同時に ORPort で指定したポートをルータ側で開放しておく必要がある。

### ブリッジの待ち受けポート
ORPort 9051

### ブリッジの問い合わせ情報など
Nickname pirolix
Address home.magicvox.net
ContactInfo Piroli YUKARINOMIYA <webmaster@magicvox.net>

### ブリッジで占有されるネットワーク帯域を設定できる
RelayBandwidthRate 64 KB  # Throttle traffic to 100KB/s (800Kbps)
RelayBandwidthBurst 128 KB # But allow bursts up to 200KB/s (1600Kbps)

 Tor は接続元を隠蔽するだけで通信内容は暗号化されないので、SSH や HTTPS と併せて使う必要がある。

 その他、torrc で指定できるディレクティブの一覧は以下で取得できる(アルファベット順でソート済み)

# tor --list-torrc-options
AccelDir
AccelName
AccountingMax
AccountingStart
Address
AllowDotExit
AllowInvalidNodes
AllowNonRFC953Hostnames
AllowSingleHopCircuits
AllowSingleHopExits
AlternateBridgeAuthority
AlternateDirAuthority
AlternateHSAuthority
AssumeReachable
AuthDirBadDir
AuthDirBadExit
AuthDirFastGuarantee
AuthDirGuardBWGuarantee
AuthDirInvalid
AuthDirListBadDirs
AuthDirListBadExits
AuthDirMaxServersPerAddr
AuthDirMaxServersPerAuthAddr
AuthDirReject
AuthDirRejectUnlisted
AuthoritativeDirectory
AutomapHostsOnResolve
AutomapHostsSuffixes
AvoidDiskWrites
BandwidthBurst
BandwidthRate
Bridge
BridgeAuthoritativeDir
BridgePassword
BridgeRecordUsageByCountry
BridgeRelay
CellStatistics
CircuitBuildTimeout
CircuitIdleTimeout
CircuitPriorityHalflife
CircuitStreamTimeout
ClientDNSRejectInternalAddresses
ClientOnly
ClientRejectInternalAddresses
ConnLimit
ConsensusParams
ConstrainedSockSize
ConstrainedSockets
ContactInfo
ControlListenAddress
ControlPort
ControlPortFileGroupReadable
ControlPortWriteToFile
ControlSocket
ControlSocketsGroupWritable
CookieAuthFile
CookieAuthFileGroupReadable
CookieAuthentication
DNSListenAddress
DNSPort
DataDirectory
DirAllowPrivateAddresses
DirListenAddress
DirPolicy
DirPort
DirPortFrontPage
DirReqStatistics
DirServer
DisableAllSwap
DownloadExtraInfo
EnforceDistinctSubnets
EntryNodes
EntryStatistics
ExcludeExitNodes
ExcludeNodes
ExcludeSingleHopRelays
ExitNodes
ExitPolicy
ExitPolicyRejectPrivate
ExitPortStatistics
ExtraInfoStatistics
FallbackNetworkstatusFile
FascistFirewall
FastFirstHopPK
FetchDirInfoEarly
FetchDirInfoExtraEarly
FetchHidServDescriptors
FetchServerDescriptors
FetchUselessDescriptors
FetchV2Networkstatus
FirewallPorts
GeoIPFile
GiveGuardFlagTo_CVE_2011_2768_VulnerableRelays
HSAuthoritativeDir
HTTPProxy
HTTPProxyAuthenticator
HTTPSProxy
HTTPSProxyAuthenticator
HardwareAccel
HashedControlPassword
HidServAuth
HidServDirectoryV2
HiddenServiceAuthorizeClient
HiddenServiceDir
HiddenServicePort
HiddenServiceVersion
KeepalivePeriod
LearnCircuitBuildTimeout
Log
LogMessageDomains
LongLivedPorts
MapAddress
MaxAdvertisedBandwidth
MaxCircuitDirtiness
MaxOnionsPending
MinUptimeHidServDirectoryV2
MyFamily
NATDListenAddress
NATDPort
NamingAuthoritativeDirectory
NewCircuitPeriod
Nickname
NodeFamily
NumCPUs
NumEntryGuards
ORListenAddress
ORPort
OutboundBindAddress
PerConnBWBurst
PerConnBWRate
PidFile
PreferTunneledDirConns
ProtocolWarnings
PublishHidServDescriptors
PublishServerDescriptor
ReachableAddresses
ReachableDirAddresses
ReachableORAddresses
RecommendedClientVersions
RecommendedServerVersions
RecommendedVersions
RefuseUnknownExits
RejectPlaintextPorts
RelayBandwidthBurst
RelayBandwidthRate
RendPostPeriod
RephistTrackTime
RunAsDaemon
SafeLogging
SafeSocks
ServerDNSAllowBrokenConfig
ServerDNSAllowNonRFC953Hostnames
ServerDNSDetectHijacking
ServerDNSRandomizeCase
ServerDNSResolvConfFile
ServerDNSSearchDomains
ServerDNSTestAddresses
ShutdownWaitLength
Socks4Proxy
Socks5Proxy
Socks5ProxyPassword
Socks5ProxyUsername
SocksListenAddress
SocksPolicy
SocksPort
SocksTimeout
StrictNodes
TestSocks
TestingAuthDirTimeToLearnReachability
TestingEstimatedDescriptorPropagationTime
TestingTorNetwork
TestingV3AuthInitialDistDelay
TestingV3AuthInitialVoteDelay
TestingV3AuthInitialVotingInterval
TrackHostExits
TrackHostExitsExpire
TransListenAddress
TransPort
TunnelDirConns
UpdateBridgesFromAuthority
UseBridges
UseEntryGuards
User
V1AuthoritativeDirectory
V2AuthoritativeDirectory
V3AuthDistDelay
V3AuthNIntervalsValid
V3AuthUseLegacyKey
V3AuthVoteDelay
V3AuthVotingInterval
V3AuthoritativeDirectory
V3BandwidthsFile
VersioningAuthoritativeDirectory
VirtualAddrNetwork
VoteOnHidServDirectoriesV2
WarnPlaintextPorts
WarnUnsafeSocks
_UsingTestNetworkDefaults
__AllDirActionsPrivate
__DisablePredictedCircuits
__HashedControlSessionPassword
__LeaveStreamsUnattached
__OwningControllerProcess
__ReloadTorrcOnSIGHUP

使用例

 試しに、BitTorrent クライアントの一つである BitComet に Tor プロキシを利用すると、ファイルのダウンロードを匿名で行うことができるようになる。BitComet の通信設定において、SOCKS5 プロキシを選択し、先に構築した Tor プロキシ サーバのアドレスとポート番号を設定するだけでよい。
 ただし、違法な使途で匿名通信を行うために Tor を利用するのは好ましいことではない。Tor を匿名 BitTorrent のために使うのは止めよう - P2P とかその辺のお話にあるように、違法ファイルのアップロードやダウンロードに関する警告によって Tor ノードが停止されてしまえば、匿名通信を本当に必要としている人がその恩恵に与れなくなるだろう(2012/08/30 追記)

このエントリーをはてなブックマークに追加  



関連記事/トラックバック

関連記事/トラックバックはまだありません

この記事にトラックバックを送るには?

コメントを投稿する

 
 (必須, 匿名可, 公開, トリップが使えます)
 (必須, 匿名可, 非公開, Gravatar に対応しています)
 (必須)
スパム コメント防止のため「投稿確認」欄に ランダムな数字 CAPTCHAについて を入力してから送信してください。お手数ですがご協力のほど宜しくお願いいたします。