【问题标题】:Detect if AWS Server is behind a Load Balancer or not检测 AWS 服务器是否在负载均衡器后面
【发布时间】:2015-11-11 06:12:18
【问题描述】:

目前,同一个网站在两个不同的服务器配置和两个不同的 URL 下运行。

  • 位于负载平衡器后面的 IIS 服务器群
  • 具有弹性 IP 的单个 IIS 服务器

为方便起见,最好在所有服务器上运行相同的代码,因为这样可以简化部署过程。

我知道我可以这样做:

if (string.Equals(HttpContext.Current.Request.Headers["X-Forwarded-Proto"], "https"))

这会检查负载平衡器是否转发了“https”数据。但是,我想做的只是检测负载均衡器是否存在。

我要写的必备:if(LoadBalancerExists) { do this stuff }

有人知道怎么做吗?

【问题讨论】:

  • 在负载均衡器上添加规则以添加自定义http标头?然后阅读它。
  • 如何添加自定义 http 标头?
  • 有什么理由不能简单地将其作为配置设置并在部署脚本中进行设置?
  • 目前不存在部署脚本,因为我目前正在测试,也许这是更好的方法。
  • 在启动时,获取当前EC2实例的实例ID,然后调用API描述ELB,然后查看您的实例ID是否注册到ELB。

标签: c# asp.net amazon-web-services load-balancing


【解决方案1】:

事实证明,如果负载均衡器不存在Request.Headers["X-Forwarded-Proto"] == null

如果确实存在Request.Headers["X-Forwarded-Proto"] == 'http' or 'https'

快速解决方案:if(Request.Headers["X-Forwarded-Proto"] == null) { do stuff }

更新的解决方案增加了安全性,因为标头可以被欺骗:

ClientIP = Request.UserHostAddress;
Subnet = <enter your aws CIDR subnet address>;    // e.g. 172.0.0.0
Mask = <enter your aws VPC address>;              // e.g. 255.255.0.0

// Verify header
if(Request.Headers["X-Forwarded-Proto"] == null) {
    // Verify that ClientIP i.e. the LoadBalancer's IP is inside of our subnet.
    if(IsAddressOnSubnet(ClientAddress, Subnet, Mask)) {
        // do some stuff
    }
}

protected bool IsAddressOnSubnet(IPAddress Address, IPAddress Subnet, IPAddress Mask)
{
    try
    {
        Byte[] addressOctets = Address.GetAddressBytes();
        Byte[] subnetOctets = Mask.GetAddressBytes();
        Byte[] networkOctets = Subnet.GetAddressBytes();

        return
            ((networkOctets[0] & subnetOctets[0]) == (addressOctets[0] & subnetOctets[0])) &&
            ((networkOctets[1] & subnetOctets[1]) == (addressOctets[1] & subnetOctets[1])) &&
            ((networkOctets[2] & subnetOctets[2]) == (addressOctets[2] & subnetOctets[2])) &&
            ((networkOctets[3] & subnetOctets[3]) == (addressOctets[3] & subnetOctets[3]));
    }
    catch (System.Exception ex)
    {
        return false;
    }
}

感谢 Michael-sqlbot 指出安全问题。

这个aws reference很有用。

感谢 Спасибо,检测 IP 地址在子网 here 上的参考! Прекрасное решение!。

【讨论】:

  • 记住这些标头可能被欺骗,一个潜在的更具确定性的测试将是标头是否存在并且连接的客户端 IP 在私有 IP 地址内分配给 ELB 子网的范围。如果两者都为真,则来自 ELB,如果 IP 测试为假,则不是,无论标头是否存在。
  • @Michael-sqlbot 我如何test that the connected client IP is inside the private IP address ranges assigned to the subnets of the ELB
  • C# 不是我的专长。也许像HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"]
  • @Michael-sqlbot 这是一个外部站点,客户端 ip 可以是任何东西,或者我不明白客户端 ip 是什么意思。
  • 如果请求来自 ELB,则客户端 IP 应该是来自 ELB 子网之一的私有 IP,否则不是。
猜你喜欢
  • 1970-01-01
  • 2020-10-22
  • 2012-08-05
  • 2014-12-18
  • 2016-10-13
  • 2013-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多