2008年8月4日星期一

编程方式更改Tor身份——Switch TOR to a new identity

Tor 俗称洋葱路由器,用于防范流量过滤、嗅探分析,可以实现匿名对外连接、匿名隐藏服务。Tor 的代理一般在2-5层左右,加密程度也比较高。在一些需要使用代理的项目中用Tor 替代常用的代理服务器,有两个显著的好处:一是安全,二是可用代理非常多而且可靠性也很高。

在程序中使用Tor 的一个关键问题就是如何在程序中强制Tor 使用新的身份(切换代理),如果不能在程序中更换身份那使用Tor 的意义也就不大了。

Tor 默认HTTP代理端口是8118,Socket代理端口是9050,控制端口是9051。我们可以通过向Tor 控制端口发送命令来强制Tor 使用新的身份。

下面有三段代码,分别由shell、php和c#实现切换Tor 使用新的身份。

shell代码片段:
spawn telnet 127.0.0.1 9051
expect "Escape character is'^]'."
send "AUTHENTICATE\r"
expect "250 OK"
send "signal NEWNYM\r"
expect "250 OK"
send "quit\r"

php版本:
/** * Switch Tor to a new identity. **/
function tor_new_identity($tor_ip='127.0.0.1', $control_port='9051', $auth_code='')
{
$fp = fsockopen($tor_ip, $control_port, $errno, $errstr, 30);
if (!$fp) return false; //can't connect to the control port
fputs($fp, "AUTHENTICATE $auth_code\r\n");
$response = fread($fp, 1024);
list($code, $text) = explode(' ', $response, 2);
if ($code != '250')
return false; //authentication failed

//send the request to for new identity
fputs($fp, "signal NEWNYM\r\n");
$response = fread($fp, 1024);
list($code, $text) = explode(' ', $response, 2);
if ($code != '250') return false; //signal failed
fclose($fp); return true;
}
?>

c#版本代码片段:
TcpClient client = new TcpClient();
client.Connect("127.0.0.1", Convert.ToInt32(9051));
NetworkStream stream = client.GetStream();
byte[] cmd = null;
string strCmd = string.Format("AUTHENTICATE \"{0}\"\r\n",password);
cmd = System.Text.Encoding.Default.GetBytes(strCmd);
stream.Write(cmd, 0, cmd.Length);
byte[] buffer = new byte[2];
int count = 0;
string strResponse = "";
count = stream.Read(buffer, 0, buffer.Length);
strResponse += System.Text.Encoding.Default.GetString(buffer, 0, count);
while (count != 0 && stream.DataAvailable)
{
count = stream.Read(buffer, 0, buffer.Length);
strResponse += System.Text.Encoding.Default.GetString(buffer, 0, count);
if (count < buffer.Length)
break;
}
if (strResponse.IndexOf("250") == -1)
{
MessageBox.Show("AUTHENTICATE Fail!");
return;
}
buffer = new byte[1024];
strCmd = "signal NEWNYM\r\n";
cmd = System.Text.Encoding.Default.GetBytes(strCmd);
stream.Write(cmd, 0, cmd.Length);
strResponse = "";
count = stream.Read(buffer, 0, buffer.Length);
strResponse += System.Text.Encoding.Default.GetString(buffer, 0, count);
while (count != 0 && stream.DataAvailable)
{
count = stream.Read(buffer, 0, buffer.Length);
strResponse += System.Text.Encoding.Default.GetString(buffer, 0, count);
if (count < buffer.Length)
break;
}
if (strResponse.IndexOf("250") == 1)
MessageBox.Show("Switch Identity OK!");

参考文章地址:
http:// linux.chinaunix.net/bbs/thread-1014409-1-1.html
http:// w-shadow.com/blog/2008/06/20/tor-how-to-new-identity-with-php
http:// www.cnblogs.com/sxlfybb/archive/2008/07/07/1237662.html

1 comments:

wangbode 说...

那个php的部分好像不行啊,我试了好久都不行,难道这里的tor是装在linux环境下的?