Python Twisted: restricting access by IP address

非 Y 不嫁゛ 提交于 2019-12-01 09:11:10

问题


What would be the best method to restrict access to my XMLRPC server by IP address? I see the class CGIScript in web/twcgi.py has a render method that is accessing the request... but I am not sure how to gain access to this request in my server. I saw an example where someone patched twcgi.py to set environment variables and then in the server access the environment variables... but I figure there has to be a better solution.

Thanks.


回答1:


When a connection is established, a factory's buildProtocol is called to create a new protocol instance to handle that connection. buildProtocol is passed the address of the peer which established the connection and buildProtocol may return None to have the connection closed immediately.

So, for example, you can write a factory like this:

from twisted.internet.protocol import ServerFactory

class LocalOnlyFactory(ServerFactory):
    def buildProtocol(self, addr):
        if addr.host == "127.0.0.1":
            return ServerFactory.buildProtocol(self, addr)
        return None

And only local connections will be handled (but all connections will still be accepted initially since you must accept them to learn what the peer address is).

You can apply this to the factory you're using to serve XML-RPC resources. Just subclass that factory and add logic like this (or you can do a wrapper instead of a subclass).

iptables or some other platform firewall is also a good idea for some cases, though. With that approach, your process never even has to see the connection attempt.




回答2:


Okay, another answer is to get the ip address from the transport, inside any protocol:

d = self.transport.getHost () ; print d.type, d.host, d.port

Then use the value to filter it in any way you want.




回答3:


I'd use a firewall on windows, or iptables on linux.



来源:https://stackoverflow.com/questions/1273297/python-twisted-restricting-access-by-ip-address

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!