当前位置: 移动技术网 > IT编程>开发语言>其他编程 > 使用HTTP_X_FORWARDED_FOR获取客户端IP的严重后果

使用HTTP_X_FORWARDED_FOR获取客户端IP的严重后果

2017年12月08日  | 移动技术网IT编程  | 我要评论
在web开发中.我们可能都习惯使用下面的代码来获取客户端的ip地址:
c#代码
复制代码 代码如下:

//优先取得代理ip
string ip = request.servervariables["http_x_forwarded_for"];
if (string.isnullorempty(ip)) {
//没有代理ip则直接取连接客户端ip
ip = request.servervariables["remote_addr"];
}

上面代码看来起是正常的.可惜这里却隐藏了一个隐患!!因为"http_x_forwarded_for"这个值是通过获取http头的"x_forwarded_for"属性取得.所以这里就提供给恶意破坏者一个办法:可以伪造ip地址!!
下面是测试代码:
复制代码 代码如下:

httpwebrequest request = (httpwebrequest)httpwebrequest.create("http://localhost/ip.aspx");
request.headers.add("x_forwarded_for", "0.0.0.0");
httpwebresponse response = (httpwebresponse)request.getresponse();
streamreader stream = new streamreader(response.getresponsestream());
string ip = stream.readtoend();
stream.close();
response.close();
request = null;

"ip.aspx"文件代码:
复制代码 代码如下:

response.clear();
//优先取得代理ip
string ip = request.servervariables["http_x_forwarded_for"];
if (string.isnullorempty(ip))
{
//没有代理ip则直接取客户端ip
ip = request.servervariables["remote_addr"];
}
response.write(ip);
response.end();

这样.当测试代码中去访问ip.aspx文件时."string ip = stream.readtoend();"这段代码取到的ip数据就是"0.0.0.0"!!!!(呵.在真实情况下.这样的ip地址肯定不是我们想要的结果.而在有些投票系统中限制一个ip只能投1次票时,如果也是用类似的代码取得对方ip然后再判断的话.呵呵.限制就失效咯)...

或者如果你用上面代码获取ip地址后后面又不再进行数据判断的话也许还能更进一步进行数据破坏!!
比如你用类似上面的代码中获取ip地址就直接有这样的sql语句:
string sql = "insert into (ip) value ('" + ip + "')";
那么也许破坏者还可以进行sql注入进行数据破坏!!

这样看来利用"http_x_forwarded_for"这个属性获取客户端ip的方法就不再可取了.-_-# 但如果不用这种方法.那么那些真正使用了代理服务器的人.我们又不能再获取到他们的真实ip地址(因为某些代理服务器会在"x_forwarded_for"这个http头里加上访问用户真正的ip地址).呵.现实就是这样,某种东西都有有得必有失...

最后,我的建议是不要再使用上面的方法去获取客户端ip.即是不要再理会代理情况.你的建议又是怎样呢???

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网