diff --git a/src/realtime/expose/upstream.cpp b/src/realtime/expose/upstream.cpp index b7669d2..8db87c8 100644 --- a/src/realtime/expose/upstream.cpp +++ b/src/realtime/expose/upstream.cpp @@ -1,4 +1,8 @@ #include "realtime/expose/upstream.h" +#include +#include +#include +#include namespace molo::realtime::expose { namespace { UpstreamScheme SchemeOf(const std::string& s){ @@ -51,19 +55,45 @@ const UpstreamEntry* UpstreamTable::Route(const std::string& path) const{ if(!best||e.prefix.size()>best->prefix.size())best=&e; } return best; } +namespace { +// RFC1918 + loopback + link-local, checked on the real numeric address +// (host byte order), never on substrings of the input string. +bool IsPrivateOrLoopbackV4(std::uint32_t addr){ + std::uint8_t b0=static_cast(addr>>24); + std::uint8_t b1=static_cast(addr>>16); + if(b0==127)return true; // 127.0.0.0/8 + if(b0==10)return true; // 10.0.0.0/8 + if(b0==172&&b1>=16&&b1<=31)return true; // 172.16.0.0/12 + if(b0==192&&b1==168)return true; // 192.168.0.0/16 + if(b0==169&&b1==254)return true; // 169.254.0.0/16 (link-local) + return false; +} +bool IsPrivateOrLoopbackV6(const in6_addr& a){ + if(IN6_IS_ADDR_LOOPBACK(&a))return true; // ::1 + if(IN6_IS_ADDR_LINKLOCAL(&a))return true; // fe80::/10 + if(IN6_IS_ADDR_V4MAPPED(&a)){ + std::uint32_t v4; + std::memcpy(&v4,&a.s6_addr[12],sizeof(v4)); + return IsPrivateOrLoopbackV4(ntohl(v4)); + } + return false; +} +} // namespace bool UpstreamHostAllowed(const std::string& host, bool allow_public){ if(allow_public)return true; - std::string h=host; - if(h=="localhost"||h=="127.0.0.1"||h=="::1"||h=="::ffff:127.0.0.1")return true; - if(h.rfind("127.",0)==0)return true; - if(h.rfind("10.",0)==0)return true; - if(h.rfind("192.168.",0)==0)return true; - if(h.rfind("172.",0)==0){ - int n=0; size_t d=h.find('.',4); - try{n=std::stoi(h.substr(4,d==std::string::npos?std::string::npos:d-4));}catch(...){return false;} - if(n>=16&&n<=31)return true; + if(host=="localhost")return true; + // Only a real IP-address literal can be judged private/loopback. A + // hostname that merely looks like one (e.g. "10.evil.com") must never be + // accepted via string matching: if it does not parse as a literal IP, + // it is not guaranteed-private, regardless of what it starts with. + in_addr a4{}; + if(inet_pton(AF_INET,host.c_str(),&a4)==1){ + return IsPrivateOrLoopbackV4(ntohl(a4.s_addr)); + } + in6_addr a6{}; + if(inet_pton(AF_INET6,host.c_str(),&a6)==1){ + return IsPrivateOrLoopbackV6(a6); } - if(h.rfind("169.254.",0)==0||h.rfind("fe80",0)==0||h.rfind("FE80",0)==0)return true; return false; } } // namespace molo::realtime::expose