Navigation Menu

Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Getting Source IP Behind Proxy #21582

Closed
BrennanConroy opened this issue May 7, 2020 · 6 comments
Closed

Getting Source IP Behind Proxy #21582

BrennanConroy opened this issue May 7, 2020 · 6 comments
Labels
area-middleware Includes: URL rewrite, redirect, response cache/compression, session, and other general middlesware Author: Migration Bot 🤖 The issue was created by a issue mover bot. The author may not be the actual author. Needs: Author Feedback The author of this issue needs to respond in order for us to continue investigating this issue.

Comments

@BrennanConroy
Copy link
Member

From @SonoranBrian on Thursday, May 7, 2020 12:17:38 AM

I have a .Net Core application running in a docker container as my backend service. Clients connect to the backend through HAProxy -> Kestrel -> .Net Core Service

I'm trying to capture the user's IP address, but am unable to get the true client IP.

startup.cs

public void ConfigureServices(IServiceCollection services)
        {
            // Proxy Forwarded Headers
            services.Configure<ForwardedHeadersOptions>(options =>
            {
                options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
                options.KnownNetworks.Add(new IPNetwork(IPAddress.Parse("::ffff:172.21.0.2"), 104));
            });
        }

---------------------------------------------

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseStaticFiles();
            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto,
                ForwardLimit = 2
            });
            app.UseRouting();
            app.UseCors("CorsPolicy");
            app.UseAuthentication();
            app.UseAuthorization();
       }

Getting the client IP (Signalr)

// Extract user IP
        public IPAddress getIp(HubCallerContext cntxt)
        {
            // Return the Context IP address
            if (cntxt != null)
            {
                HttpContext request = cntxt.GetHttpContext();
                if (request != null)
                {
                    return request.Connection.RemoteIpAddress;
                }
                else
                {
                    return IPAddress.Parse("1.1.1.1");
                }
            }
            else
            {
                return IPAddress.Parse("0.0.0.0");
            }

The IP address captured is ::ffff:XXX.XX.X.X (The X representing our HA Proxy server, not the client IP)

I've also tried manually setting the HAProxy forwarded IP to 1.1.1.1: http-request set-header X-Forwarded-For 1.1.1.1 but this still shows as the HAProxy's internal IP and not the forced 1.1.1.1.

In HAProxy if I try to enable send-proxy I receive the following error:

Server example-backend/example_backend is DOWN, reason: Layer7 wrong status, code: 505, info: "HTTP Version Not Supported", check duration: 1ms. 0 active and 0 backup servers left. 0 sessions active, 0 requeued, 0 remaining in queue.

Any help is greatly appreciated!

Copied from original issue: SignalR/SignalR#4470

@ghost ghost added the Author: Migration Bot 🤖 The issue was created by a issue mover bot. The author may not be the actual author. label May 7, 2020
@BrennanConroy
Copy link
Member Author

@Tratcher any ideas?

@Tratcher
Copy link
Member

Tratcher commented May 7, 2020

What version of AspNetCore is this? We've made a few fixes around ::ffff: IPs.

Check these troubleshooting steps and share the request headers before UseForwardedHeaders.

@SonoranBrian
Copy link

SonoranBrian commented May 7, 2020

@Tratcher I'm currently running .Net Core 3.1.1

With logging enabled:

Request Method: GET
Request Scheme: http
Request Path: /
Request Headers:
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Accept-Encoding: gzip
Accept-Language: en-US,en;q=0.9
Cookie: __stripe_mid=487b288e-b892-4602-ace1-44c110780f0e; __cfduid=d77b3afab37f9f0318b67e00c49008a5e1586393279
Host: api.example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36
Upgrade-Insecure-Requests: 1
cf-ipcountry: US
cf-ray: 58fcef91fea2f58d-SEA
x-forwarded-proto: https,https
cf-visitor: {"scheme":"https"}
sec-fetch-site: none
sec-fetch-mode: navigate
sec-fetch-user: ?1
sec-fetch-dest: document
cf-request-id: 0291f40f390000f58d7c99e200000001
cf-connecting-ip: 159.118.XXX.XXX // My IP
cdn-loop: cloudflare
x-forwarded-port: 443
x-forwarded-for: 162.158.XXX.XX,162.158.XXX.XX

Request RemoteIp: ::ffff:172.21.X.X

I also see I forgot to preface, everything is also running behind Cloudflare as well.

@SonoranBrian
Copy link

SonoranBrian commented May 7, 2020

With the logging enabled, I could see my real IP was in the cf-connecting-ip from Cloudflare.

I modified my SignalR getIp() method as follows:

// Extract user IP
        public IPAddress getIp(HubCallerContext cntxt)
        {
            // Return the Context IP address
            if (cntxt != null)
            {
                HttpContext httpContext = cntxt.GetHttpContext();
                if (httpContext != null)
                {
                    IPAddress clientIp;
                    IPAddress.TryParse(httpContext.Request.Headers["cf-connecting-ip"], out clientIp);
                    return clientIp;

This now allows me to get the proper IP from cloudflare. I should be able to also modify my HAProxy configuration to set the default x-forwarded-for header to the header from cloudflare as well.

EDIT:
By changing around my HAProxy config, I can see the logging shows the x-forwarded-for IP correctly. For some reason, the RemoteIP is still incorrect, as shown in the logging:

x-forwarded-for: 159.118.XXX.XXX
cf-connecting-ip: 159.118.XXX.XXX
x-forwarded-port: 443

Request RemoteIp: ::ffff:172.21.0.2

@Tratcher
Copy link
Member

Tratcher commented May 7, 2020

FYI d36dcca added mitigations for ::ffff: addresses back in 2.2 or 3.0, you shouldn't need to specify that prefix anymore.

Oh I see the issue, you're defining ForwardedHeadersOptions twice, once in ConfigureServices and once in Configure. These don't stack, the later options are the ones used and they don't have KnownNetworks set. Change Configure to this: app.UseForwardedHeaders();

@Tratcher Tratcher added the Needs: Author Feedback The author of this issue needs to respond in order for us to continue investigating this issue. label May 8, 2020
@ghost
Copy link

ghost commented May 12, 2020

This issue has been automatically marked as stale because it has been marked as requiring author feedback but has not had any activity for 4 days. It will be closed if no further activity occurs within 3 days of this comment. If it is closed, feel free to comment when you are able to provide the additional information and we will re-investigate.

See our Issue Management Policies for more information.

@ghost ghost closed this as completed May 15, 2020
@dotnet dotnet locked as resolved and limited conversation to collaborators Jun 14, 2020
@amcasey amcasey added area-middleware Includes: URL rewrite, redirect, response cache/compression, session, and other general middlesware and removed area-runtime labels Jun 2, 2023
This issue was closed.
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
area-middleware Includes: URL rewrite, redirect, response cache/compression, session, and other general middlesware Author: Migration Bot 🤖 The issue was created by a issue mover bot. The author may not be the actual author. Needs: Author Feedback The author of this issue needs to respond in order for us to continue investigating this issue.
Projects
None yet
Development

No branches or pull requests

6 participants