Package: advocate
AdvocateAdvocate is a set of tools based around therequests libraryfor safely making
HTTP requests on behalf of a third party. Specifically, it aims to prevent
common techniques that enableSSRF attacks.Advocate was inspired byfin1te’s SafeCurl project.InstallationpipinstalladvocateAdvocate is officially supported on CPython 2.7+, CPython 3.4+ and PyPy 2. PyPy 3 may work as well, but
you’ll need a copy of the ipaddress module from elsewhere.See it in actionIf you want to try out Advocate to see what kind of things it catches, there’s atest site up on advocate.saynotolinux.com.ExamplesAdvocate is more-or-less a drop-in replacement for requests. In most cases you can just replace “requests” with
“advocate” where necessary and be good to go:>>>importadvocate>>>printadvocate.get("http://google.com/")<Response[200]>Advocate also provides a subclassedrequests.Sessionwith sane defaults for
validation already set up:>>>importadvocate>>>sess=advocate.Session()>>>printsess.get("http://google.com/")<Response[200]>>>>printsess.get("http://localhost/")advocate.exceptions.UnacceptableAddressException:('localhost',80)All of the wrapped request functions accept avalidatorkwarg where you
can set additional rules:>>>importadvocate>>>validator=advocate.AddrValidator(hostname_blacklist={"*.museum",})>>>printadvocate.get("http://educational.MUSEUM/",validator=validator)advocate.exceptions.UnacceptableAddressException:educational.MUSEUMIf you require more advanced rules than the defaults, but don’t want to have to pass
the validator kwarg everywhere, there’sRequestsAPIWrapper. You can
define a wrapper in a common file and import it instead of advocate:>>>fromadvocateimportAddrValidator,RequestsAPIWrapper>>>fromadvocate.packagesimportipaddress>>>dougs_advocate=RequestsAPIWrapper(AddrValidator(ip_blacklist={...# Contains data incomprehensible to mere mortals...ipaddress.ip_network("42.42.42.42/32")...}))>>>printdougs_advocate.get("http://42.42.42.42/")advocate.exceptions.UnacceptableAddressException:('42.42.42.42',80)Other than that, you can do just about everything with Advocate that you can
with an unwrapped requests. Advocate passes requests’ test suite with the
exception of tests that requireSession.mount().Conditionally bypassing protectionIf you want to allow certain users to bypass Advocate’s restrictions, just
use plain ‘ol requests by doing something like:ifuser=="mr_skeltal":requests_module=requestselse:requests_module=advocateresp=requests_module.get("http://example.com/doot_doot")requests-futures supportA thin wrapper aroundrequests-futuresis provided to ease writing async-friendly code:>>>fromadvocate.futuresimportFuturesSession>>>sess=FuturesSession()>>>fut=sess.get("http://example.com/")>>>fut<Futureat0x10c717f28state=finishedreturnedResponse>>>>fut.result()<Response[200]>You can do basically everything you can do with regularFuturesSessions andadvocate.Sessions:>>>fromadvocateimportAddrValidator>>>fromadvocate.futuresimportFuturesSession>>>sess=FuturesSession(max_workers=20,validator=AddrValidator(hostname_blacklist={"*.museum"}))>>>fut=sess.get("http://anice.museum/")>>>fut<Futureat0x10c696668state=running>>>>fut.result()Traceback(mostrecentcalllast):# [...]advocate.exceptions.UnacceptableAddressException:anice.museumWhen should I use Advocate?Any time you’re fetching resources over HTTP for / from someone you don’t trust!When should I not use Advocate?That’s a tough one. There are a few cases I can think of where I wouldn’t:When good, safe support for IPv6 is importantWhen internal hosts use globally routable addresses and you can’t guess their prefix to blacklist it ahead of timeYou already have a good handle on network security within your networkActually, if you’re comfortable enough with Squid and network security, you should set up a secured Squid instance on a segregated subnet
and proxy through that instead. Advocate attempts to guess whether an address references an internal host
and block access, but it’s definitely preferable to proxy through a host can’t access anything internal in the first place!Of course, if you’re writing an app / library that’s meant to be usable OOTB on other people’s networks, Advocate + a user-configurable
blacklist is probably the safer bet.This seems like it’s been done beforeThere’ve been a few similar projects, but in my opinion Advocate’s approach is the best because:It sees URLs the same as the underlying HTTP libraryParsing URLs is hard, and no two URL parsers seem to behave exactly the same. The tiniest
differences in parsing between your validator and the underlying HTTP library can lead
to vulnerabilities. For example, differences between PHP’sparse_urland cURL’s
URL parserallowed a blacklist bypass in SafeCurl.Advocate doesn’t do URL parsing at all, and lets requests handle it. Advocate only looks at the
address requests actually tries to open a socket to.It deals with DNS rebindingTwo consecutive calls tosocket.getaddrinfoaren’t guaranteed to return the same
info, depending on the system configuration. If the “safe” looking record TTLs between
the verification lookup and the lookup for actually opening the socket, we may end
up connecting to a very different server than the one we OK’d!Advocate gets around this by only using onegetaddrinfocall for both verification
and connecting the socket. In pseudocode:defconnect_socket(host,port):forresinsocket.getaddrinfo(host,port):# where `res` will be a tuple containing the IP for the hostifnotis_blacklisted(res):# ... connect the socket using `res`SeeWikipedia’s article on DNS rebinding attacksfor more info.It handles redirects sanelyMost of the other SSRF-prevention libs cover this, but I’ve seen a lot
of sample code online that doesn’t. Advocate will catch it since it inspectseveryconnection attempt the underlying HTTP lib makes.TODOProper IPv6 Support?Advocate’s IPv6 support is still a work-in-progress, since I’m not
that familiar with the spec, and there are so many ways to tunnel IPv4 over IPv6,
as well as other non-obvious gotchas. IPv6 records are ignored by default
for now, but you can enable by using anAddrValidatorwithallow_ipv6=True.It should mostly work as expected, but Advocate’s approach might not even make sense with
most IPv6 deployments, seeIssue #3for
more info.If you can think of any improvements to the IPv6 handling, please submit an issue or PR!CaveatsThis is beta-quality software, the API might change without warning!mount()ing other adapters is disallowed to prevent Advocate’s validating adapters from being clobbered.Advocate does not, and might never support the use of HTTP proxies.Proper IPv6 support is still a WIP as noted above.Acknowledgementshttps://github.com/fin1te/safecurlfor inspirationhttps://github.com/kennethreitz/requestsfor the lovely requests modulehttps://bitbucket.org/kwi/py2-ipaddressfor the backport of ipaddresshttps://github.com/hakobe/paranoidhttpa similar project targeting golanghttps://github.com/uber-common/paranoid-requesta similar project targeting Nodehttp://search.cpan.org/~tsibley/LWP-UserAgent-Paranoid/a similar project targeting Perl 5